text
stringlengths
15
59.8k
meta
dict
Q: How to make VSCode integrated terminal run the same Conda Python interpreter as Terminal.app? I have miniconda installed with automatic base environment activation using /usr/bash in the Terminal.app. When I first open Terminal.app and run python the correct interpreter inside the base environment is run, say Python3.8. Inside VSCode (without necessarily having opened it using something like code .) I have the integrated terminal, which opens bash as expected. The prompt is in fact the same as when I open Terminal.app: say (base) $. However, if I run python, MacOS's system Python2.7 is activated, instead of conda's Python. The only way I've found to actually run the Python interpreter from within conda's base environment, automatically and consistently with Terminal.app, is to run conda deactivate, then conda activate again. In fact, if I search for Python executables in the environment, by typing python then clicking tab from within the first initialization of the integrated bash terminal, the results include executables that are only available within conda's base environment, which leads me to believe that I have that environment truly activated. Furthermore, if I use the Select Python Interpreter in VSCode and choose the base environment, when I activate the integrated terminal it will run source ~/opt/miniconda3/bin/activate base, and even then if I run python, conda's Python interpreter is ignored, and I will get MacOS's Python2.7. I have tried setting both python.pythonPath and python.condaPath options to the default base Python in settings.json, with no success. Somehow VSCode is activating conda's environment, as expected, but is overwriting the python command to the system's default Python2.7, instead of the environment's default Python3.8. How do I get VSCode to run the Python interpreter consistently with the conda's base environment, like Terminal.app does?
{ "language": "en", "url": "https://stackoverflow.com/questions/67344254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What can I use as a blank Request URL for Sms? In order for a number to receive Sms messages, it appears I must enter a value for the Request URL associated with the number. However I do not need to notified of messages in a callback. I'm wondering what value I can put in here that will basically do nothing but still allow me to retrieving messages via the polling mechanism? Thanks, Dan A: Twilio developer evangelist here. You can use a URL that responds with an empty <Response> TwiML element. If you don't have a server to host that on, you could use http://twimlets.com. This link ought to do the trick: http://twimlets.com/echo?Twiml=%3CResponse%3E%3C%2FResponse%3E&
{ "language": "en", "url": "https://stackoverflow.com/questions/27002463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to identify a column in mysql when I have 2 with same name I'm using this PHP code to get my sql query which joins 2 tables ... both table have the same "size" field, but the results is not the same in both... code: mysql_query("SELECT * FROM cart INNER JOIN tbl_product ON tbl_product.product_id = cart.product_id WHERE .......) or die(mysql_error()); The result of this query shows me Cart_id, member_id, product_id, size, .... and a second size 1 of the size comes the cart table and 1 from the product table.. then I try to retrieve my data while($data2 = mysql_fetch_array( $data)) { $size= $data2['size']; But I get the second size in my result and I need the first one.. I need the cart.size ... how can I do this ? A: Name the columns explicitly in your SELECT statement, and assign ALIASes to the columns with identical names: SELECT cart.id_col, cart.size AS CartSize, ttbl_product.size AS ProductSize FROM cart INNER JOIN tbl_product ON tbl_product.product_id = cart.product_id WHERE ....... then extract the value for ProductSize from the results. If you don't need the cart size, you can eliminate it from the list of columns return and leave out the ALIAS, as you'll only have a single Size column in the results: SELECT cart.id_col, ttbl_product.size FROM cart INNER JOIN tbl_product ON tbl_product.product_id = cart.product_id WHERE ....... In general, it's a good idea to explicitly name the columns you want in your SELECT statement as it makes it clearer what you're getting back, it will fail sooner if you are trying to get a column that's not there (when the SELECT executes, not when you try to retrieve the column value from the result set), and can lead to better performance if you're only interested in a small-ish subset of the available columns. A: A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name [...] This is a basic feature of the SELECT statement in SQL. Please consult the manual: http://dev.mysql.com/doc/refman/5.0/en/select.html A: Use SQL aliases. For examle: SELECT a.a AS aa, b.a AS ba FROM tbl1 AS a, tbl2 AS b A: Change SELECT * to SELECT [fields] where you manually specify which fields you need. If you only need one then there's nothing left to do. If you need both then you can use an alias for the fields like this: SELECT p.size AS product_size, c.size AS cart_size FROM ... Then they will be available in your array as keys product_size and cart_size. A: Try this: mysql_query("SELECT cart.size as cartsize, tbl_product.size as productsize, ... FROM cart INNER JOIN tbl_product ON tbl_product.product_id = cart.product_id WHERE ...) or die(mysql_error()); But if you don't work on some legacy code you don't want to rewrite completely use PDO instead, like suggested in first the comment. A: Several comments to begin with: * *I suggest to move away from mysql_* as soon as you can *Try not to use the * operator in your select statements As for your question, use an alias for the two columns, I also like to give my tables a simpler alias (makes the query more concise): SELECT t1.id, t1.size AS cart_size, t2.size AS product_size FROM cart t1 INNER JOIN tbl_product t2 ON t1.product_id = t2.product_id Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/27138824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery 1.7.1 slider not working except on homepage I have tried to place the slider on every page on this website: http://atripathi.com It works on the homepage, but doesn't work on any of the other pages (About, Services, etc.) I know it's probably an easy fix, but I can't get it at the moment. Thank you for any help or suggestions! A: Looks like the original suggestion above is correct. I'm seeing slider javascript includes at the top of your homepage that aren't on the other pages. Generally, a good way of troubleshooting is to make copies of both pages, index-c.php and about-c.php perhaps, and start removing everything that isn't pertinent to the trouble you're having (other HTML, css includes, etc.) until you get down to only the slider on the page. Once you've done that, you might notice that the one page is slightly different than the other, making it work. You can copy back and forth until it does. The other possibility is that there's a relative path problem somewhere, because your one page is inside a folder (though I'm guessing you have a .htaccess redirect to a root folder page)? So if all else fails, move the reduced about-c.php to the root folder and see if that then works. If so, you know it's a path problem. Hope these suggestions help. A: I see that jQuery is being included on all your pages but the cycle plugin is only included on the home page. You should be able to update your template(s) to fix this.
{ "language": "en", "url": "https://stackoverflow.com/questions/10076627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I load a shared object in C++? I have a shared object (a so - the Linux equivalent of a Windows dll) that I'd like to import and use with my test code. I'm sure it's not this simple ;) but this is the sort of thing I'd like to do.. #include "headerforClassFromBlah.h" int main() { load( "blah.so" ); ClassFromBlah a; a.DoSomething(); } I assume that this is a really basic question but I can't find anything that jumps out at me searching the web. A: It depends on the platform. To do it at runtime, on Linux, you use dlopen, on windows, you use LoadLibrary. To do it at compile time, on windows you export the function name using dllexport and dllimport. On linux, gcc exports all public symbols so you can just link to it normally and call the function. In both cases, typically this requires you to have the name of the symbol in a header file that you then #include, then you link to the library using the facilities of your compiler. A: There are two ways of loading shared objects in C++ For either of these methods you would always need the header file for the object you want to use. The header will contain the definitions of the classes or objects you want to use in your code. Statically: #include "blah.h" int main() { ClassFromBlah a; a.DoSomething(); } gcc yourfile.cpp -lblah Dynamically (In Linux): #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> int main(int argc, char **argv) { void *handle; double (*cosine)(double); char *error; handle = dlopen ("libm.so", RTLD_LAZY); if (!handle) { fprintf (stderr, "%s\n", dlerror()); exit(1); } dlerror(); /* Clear any existing error */ cosine = dlsym(handle, "cos"); if ((error = dlerror()) != NULL) { fprintf (stderr, "%s\n", error); exit(1); } printf ("%f\n", (*cosine)(2.0)); dlclose(handle); return 0; } *Stolen from dlopen Linux man page The process under windows or any other platform is the same, just replace dlopen with the platforms version of dynamic symbol searching. For the dynamic method to work, all symbols you want to import/export must have extern'd C linkage. There are some words Here about when to use static and when to use dynamic linking. A: You need to #include any headers associated with the shared library to get the declrarations of things like ClassFromBlah. You then need to link against the the .so - exactly how you do this depends on your compiler and general instalation, but for g++ something like: g++ myfile.cpp -lblah will probably work. A: It is -l that link the archive file like libblah.a or if you add -PIC to gcc you will get a 'shared Object' file libblah.so (it is the linker that builds it). I had a SUN once and have build this types of files. The files can have a revision number that must be exact or higher (The code can have changed due to a bug). but the call with parameters must be the same like the output.
{ "language": "en", "url": "https://stackoverflow.com/questions/1142103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Generic controller in MVC Can you explain to me the point of a controller when all it does it return a view? Have I missed the point here? I've come across a situation when trying to build a rudimentary CMS where the user can create views (stored in the database), but of course as they are user created, the controller's don't exist. So is there another way to serve them? Thanks for any help, I'm still trying to get to grips with MVC fully! A: Can you explain to me the point of a controller when all it does it return a view? Who said that all a controller does is to return a view? A controller does lots of other things. For example it could receive the user input under the form of an action parameters, check whether the ModelState.IsValid, do some processing on the Model and then return a View which is the whole point of the MVC pattern. I've come across a situation when trying to build a rudimentary CMS where the user can create views (stored in the database), but of course as they are user created, the controller's don't exist. So is there another way to serve them? Yes, of course. You could use a custom virtual path provider by implementing the VirtualPathProvider class.
{ "language": "en", "url": "https://stackoverflow.com/questions/10795771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bootstrap override kajiki I want to override this table: <table py:attrs="w.attrs" cellpadding="0" cellspacing="1" border="0"> <thead py:if="w.columns"> <tr> <th py:for="i, col in enumerate(w.columns)" class="col_${i}" py:content="col.title"/> </tr> </thead> <tbody> <tr py:for="i, row in enumerate(w.value)" class="${i%2 and 'odd' or 'even'}"> <td py:for="col in w.columns" align="${col.get_option('align', None)}" class="${col.get_option('css_class', None)}" py:content="col.get_field(row, displays_on='genshi')"/> </tr> </tbody> </table> with a Bootstrap table (striped-table). I already tried to edit directly the tags, but it didn't work. How can I do? A: In Bootstrap 4, you need to add the classes table table-striped to your table. Here's a working example: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td>Apple</td> <td>@youtube</td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Orange</td> <td>@facebook</td> </tr> <tr> <th scope="row">3</th> <td>Larry</td> <td>Banana</td> <td>@twitter</td> </tr> </tbody> </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/48504935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to fix Uncaught TypeError: Cannot read properties of null (reading 'remove')? I'm doing an ecommerce as a project and I'm trying to finish up the function to delete items from the cart. I think I'm close to making it work but I get the "Uncaught TypeError". I understand why this error happens, but I haven't been able to recognize how to fix it. I think the problem is in the line "let fila = document.querySelector(${products.id})", but I don't get why ${products.id} is a problem. Any help would be amazing. Thanks. function retrieveCart() { let cart = JSON.parse(localStorage.getItem("cart")); let container = document.querySelector("#cartItems") carrito.forEach(products => { let fila = `<div class="itemBoxCart p-4" id=${products.id}> <div class="card h-100 shadow"> <div class="card-body p-4"> <div class="text-center"> <h5>${products.name}</h5> <div class="d-flex justify-content-center small text-warning mb-2"> <div class="bi-star-fill"></div> </div> <span class="text-muted text-decoration-line-through"></span> ${products.price} <button id="deleteItem" class="btn btn-outline-dark mt-auto">Delete</button> </div> </div> </div> </div>` container.innerHTML += fila }); } retrieveCart() // DELETE ITEMS const deleteItems = () => { let buttonDelete = document.querySelectorAll("#deleteItem"); for (const deleteItem of buttonDelete) { deleteItem.addEventListener("click", ()=> { const newCart = cart.filter(productos => productos.id != deleteItem.id); let aDelete = cart.indexOf(newCart,0) cart.splice(aDelete,1) localStorage.setItem('cart', JSON.stringify(newCart)); let fila = document.querySelector(`${products.id}`) fila.remove() }); } } deleteItems();
{ "language": "en", "url": "https://stackoverflow.com/questions/74061678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sort XML file structure representation recursively by name - foders first I am trying to sort a XML representation of a file system structure. I have tried using a XSLT to sort, but cannot get it o work completely. The XML is generated using PHP FilesystemIterator, and I want to sort recursively by: * *Folders first in alphabetical ascending order *Files last in alphabetical ascending order Hoever, I cannot quite get it to work as intended. My original XML: <rows parent="0"> <row id="1" sortOrder="1" isFolder="true" fileName="BFolder"> <cell image="folder.gif">BFolder</cell> <row id="2" sortOrder="2" fileName="Moved.jpg"> <cell>Moved.jpg</cell> </row> <row id="3" sortOrder="2" fileName="MFile.mp4"> <cell>MFile.mp4</cell> </row> <row id="4" sortOrder="2" fileName="AFile.jpg"> <cell>AFile.jpg</cell> </row> <row id="5" sortOrder="1" isFolder="true" fileName="Movies"> <cell image="folder.gif">Movies</cell> <row id="6" sortOrder="2" fileName="Sfile.mp4"> <cell>SFile.mp4</cell> </row> <row id="23" sortOrder="1" isFolder="true" fileName="974"> <cell image="folder.gif">974</cell> <row id="24" sortOrder="2" fileName="Vägguttag.jpeg"> <cell>Vägguttag.jpeg</cell> </row> <row id="25" sortOrder="2" fileName="VU.jpeg"> <cell>VU.jpeg</cell> </row> </row> </row> <row id="14" sortOrder="2" fileName="004.png"> <cell>004.png</cell> </row> <row id="15" sortOrder="2" fileName="003.png"> <cell>003.png</cell> </row> </row> <row id="10" sortOrder="2" fileName="BB.pdf"> <cell>BB.pdf</cell> </row> <row id="16" sortOrder="2" fileName="BA.pdf"> <cell>BA.pdf</cell> </row> <row id="17" sortOrder="2" fileName="C.js"> <cell>C.js</cell> </row> <row id="1" sortOrder="1" isFolder="true" fileName="AFolder"> <cell image="folder.gif">Renamed</cell> </row> </rows> I would like it sorted like this: <rows parent="0"> <row id="1" sortOrder="1" isFolder="true" fileName="AFolder"> <cell image="folder.gif">Renamed</cell> </row> <row id="1" sortOrder="1" isFolder="true" fileName="BFolder"> <cell image="folder.gif">BFolder</cell> <row id="5" sortOrder="1" isFolder="true" fileName="Movies"> <cell image="folder.gif">Movies</cell> <row id="23" sortOrder="1" isFolder="true" fileName="974"> <cell image="folder.gif">974</cell> <row id="25" sortOrder="2" fileName="1.jpeg"> <cell>1.jpeg</cell> </row> <row id="24" sortOrder="2" fileName="2.jpeg"> <cell>2.jpeg</cell> </row> </row> <row id="6" sortOrder="2" fileName="Sfile.mp4"> <cell>SFile.mp4</cell> </row> </row> <row id="15" sortOrder="2" fileName="003.png"> <cell>003.png</cell> </row> <row id="14" sortOrder="2" fileName="004.png"> <cell>004.png</cell> </row> <row id="4" sortOrder="2" fileName="AFile.jpg"> <cell>AFile.jpg</cell> </row> <row id="3" sortOrder="2" fileName="MFile.mp4"> <cell>MFile.mp4</cell> </row> <row id="2" sortOrder="2" fileName="Moved.jpg"> <cell>Moved.jpg</cell> </row> </row> <row id="16" sortOrder="2" fileName="BA.pdf"> <cell>BA.pdf</cell> </row> <row id="10" sortOrder="2" fileName="BB.pdf"> <cell>BB.pdf</cell> </row> <row id="17" sortOrder="2" fileName="C.js"> <cell>C.js</cell> </row> </rows> The XSLT i have tried: <xsl:template match="node() | @*"> <xsl:copy> <xsl:apply-templates select="node() | @*"/> </xsl:copy> </xsl:template> <xsl:template match="/*"> <xsl:copy> <xsl:apply-templates select="@*"/> <xsl:apply-templates select="*"> <xsl:sort select="@sortOrder" data-type="text" order="ascending"/> <xsl:sort select="@fileName" data-type="text" order="ascending"/> </xsl:apply-templates> </xsl:copy> </xsl:template> A: The solution is simple: remove the / from <xsl:template match="/*"> to get <xsl:template match="*"> Otherwise you'd only sort the elements at the root node level. A: You were close, but your second template only matched the root element. Change it like this: <xsl:template match="rows|row"> <xsl:copy> <xsl:apply-templates select="@*"/> <xsl:apply-templates select="*"> <xsl:sort select="@sortOrder" data-type="text" order="ascending"/> <xsl:sort select="@fileName" data-type="text" order="ascending"/> </xsl:apply-templates> </xsl:copy> </xsl:template>
{ "language": "en", "url": "https://stackoverflow.com/questions/45243621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ProGuard optimization passes 5 rule skipped on generating build in Android studio 3.4.1 suddenly Proguard optimisation passes 5 was working correctly and build did the passes at all five levels (refer below log), however suddenly Gradle skips (without any warning) the ProGuard optimization passes (log shown below) Environment consists of Android Studio 3.4.1, Gradle plug in 3.4.1 and ProGuard 6.0.3. R8 is disabled in gradle.properties and useProguard is enabled in app module build.gradle. App is on Java platform. Tried below options suggested in other SO posts (not related to ProGuard optimisation), but there is no success. remove .gradle folder. invalidated cache in Android studio tried changing Gradle plugin to 3.3.1 Working Proguard Optimization Gradle log Shrinking... Printing usage to ... Removing unused program classes and class elements... Original number of program classes: 7098 Final number of program classes: 5859 Optimizing (pass 1/5)... Optimizing (pass 2/5)... Optimizing (pass 3/5)... Optimizing (pass 4/5)... Optimizing (pass 5/5)... Shrinking... Removing unused program classes and class elements... Original number of program classes: 5815 Final number of program classes: 5815 Obfuscating... Skipped optimisation Gradle log Shrinking... Printing usage to ... Removing unused program classes and class elements... Original number of program classes: 7415 Final number of program classes: 6151 Obfuscating... Tried upgrading Android Studio to 3.5 version by disabling R8, but same issue persists. Even tried the same on multiple machines. There is no SO post for this type of issue. Please assist. A: Found the solution for me - in build.gradle I changed this line: proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' to this: proguardFiles 'proguard-rules.pro' i.e. take out the proguard-android.txt portion out. This was based on this answer which stated that If you don't want to optimize, use the proguard-android.txt configuration file instead of this one, which turns off the optimization flags Not sure it's what you had, but worth a shot. Also, I'd make sure you understand whether you're on R8 (the new minifier) or actually Proguard, which is rapidly transitioning out Cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/58520839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CakePHP Containable behaviour not working as expected I'm trying to retrieve specific fields from a model that is 2 levels deep. Im using the container behaviour but the bottom level is not being retrieved properly. Heres the code: $this->Review->Behaviors->attach('Containable'); $latestReviews = $this->Review->find('all', array( 'contain' => array( 'Business' => array( 'fields' => array('Business.name'), 'BusinessType' => array( 'fields' => array('BusinessType.url') ) ), ), 'fields' => array('overall'), )); And the Array it is returning: array( (int) 0 => array( 'Review' => array( 'overall' => '2' ), 'Business' => array( 'name' => 'Business Name', 'business_type_id' => '1', 'id' => '2012' ) )) However rather than give me the business type id I want it to return me the BusinessType url field. Can anyone see where Im going wrong? Im sure this is inline with the CakePHP documentation. A: Quoting the manual: When using ‘fields’ and ‘contain’ options - be careful to include all foreign keys that your query directly or indirectly requires. A: I think you should remove the 'fields' option and the model name in the fields lists: $this->Review->Behaviors->attach('Containable'); $latestReviews = $this->Review->find('all', array( 'contain' => array( 'Business' => array( 'fields' => array('name'), 'BusinessType' => array( 'fields' => array('url') ) ) ))); A: Using the 3.x version : If you have limited the fields you are loading with select() but also want to load fields off of contained associations, you can pass the association object to select(): // Select id & title from articles, but all fields off of Users. $query = $articles->find() ->select(['id', 'title']) ->select($articles->Users) ->contain(['Users']); The $articles is the equivalent for $this->Review in the question
{ "language": "en", "url": "https://stackoverflow.com/questions/13055926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I test a component that fetches data from an external API? I'm trying to test a component that fetches data from Axios and it keeps giving me an error that the data fetched is undefined. I'm using jest and react testing library and also mocking Axios. The test result shows the Axios mock has been called but it keeps returning an undefined result. This is the code: const lyricData = { message: { body: { lyrics: { lyric: "Do you love the rain, does it make you dance", lyrics_copyright: 'Lyrics powered by www.musixmatch.com. This Lyrics is NOT for Commercial use and only 30% of the lyrics are returned.', } }, } }; afterEach(cleanup); const props = { tracks: [ { track: { track_id: 181987382, artist_name: 'sama', tracks: 'Hold my Liquor' } } ] }; it('loads and displays lyric', async () => { axiosMock.get.mockResolvedValue({ data: lyricData }); const url = `https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/track.lyrics.get?format=json&callback=callback&track_id=181987382&apikey=${process.env.REACT_APP_API_KEY}`; const { getByTestId, getByTitle } = render(<Lyrics {...props} />); const loading = getByTestId('loading'); const title = getByTitle('Next Lyric'); expect(loading).toBeInTheDocument(); expect(title).toBeInTheDocument(); const resolvedValue = await waitForElement(() => getByTestId('lyrics')); expect(resolvedValue).toBeInTheDocument(); expect(axiosMock.get).toHaveBeenCalledTimes(1); expect(axiosMock.get).toHaveBeenCalledWith(url); }); it keeps saying lyricData.lyric in the component below is undefined const [lyrics, setLyrics] = useState(); const [copyright, setCopyRight] = useState(); const [count, setCount] = useState(0); const trackName = tracks[count]; const trackId = trackIds[count]; const classes = useStyles(); const rand = randomNumber(trackIds.length); useEffect(() => { const getLyrics = async (id) => { const lyricData = await generateLyric(id); setLyrics(lyricData.lyric); setCopyRight(lyricData.lyrics_copyright); }; if (trackId) getLyrics(trackId); }, [trackId, trackIds]); This is the generate lyric function: export const generateLyric = async (trackId) => { const sanitizeLyrics = (lyric) => { const noNewLines = lyric.replace('/\n/g', ' '); const truncateLyric = noNewLines .split(' ') .splice(5, 55) .join(' '); return truncateLyric; }; const url = `https://api.musixmatch.com/ws/1.1/track.lyrics.get?format=json&callback=callback&track_id=${trackId}&apikey=${process.env.REACT_APP_API_KEY}`; try { const { result } = await getApiData(url); const { lyrics_body, lyrics_copyright } = result.message.body.lyrics; const lyric = sanitizeLyrics(lyrics_body); return { lyric, lyrics_copyright }; } catch (error) { console.error(error); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/58486214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Appcompatactivity with Android Studio In a recent Android Developer blog appcompatactivity is introduced. In the video it is said that if using Android Studio the min SDK is specified as 7, Android Studio automatically switches to appcompatactivity. However I've not been able to get this to work. In Android Studio v1.1 actionbaractivity was used which seems to have changed back to activity in Android Studio v1.2. What am I missing?
{ "language": "en", "url": "https://stackoverflow.com/questions/29980189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Embedd hyperlink in one column of details DataTables rows This is a follow on question from SO Question From the accepted response I was able to get the table working as shown in the JS Fiddle below `var data = {"data":[{"student_name":"jack","subjects":{"math":{"cat1_grade":"30","cat2_grade":"39","cat3_grade":"38"},"english":{"cat1_grade":"30","cat2_grade":"39","cat3_grade":"38"},"swahili":{"cat1_grade":"30","cat2_grade":"39","cat3_grade":"38"}},"subject1_average":"35","subject2_average":"26","subject3_average":"59"}]}; /* Formatting function for row details - modify as you need */ function format ( d ) { // `d` is the original data object for the row var header = false; var detail_table = $("<table></table>",{ "cellpadding":"5", "cellspacing": "0", "border": "0", "style":"padding-left:50px;" }); var tbody = $("<tbody></tbody>"); detail_table.append(tbody); $.each(d.subjects, function(k, v){ var tbody_row = $("<tr></tr>").append($("<td></td>",{"text": k})); if(!header){ var thead = $("<thead></thead>"); var thead_row = $("<tr></tr>") thead_row.append($("<th></th>",{"text":" "})); $.each(v, function(a, b){ thead_row.append($("<th></th>",{"text":a})); tbody_row.append($("<td></td>",{"text":b})); }); thead.append(thead_row); detail_table.append(thead); header = true; }else{ $.each(v, function(a, b){ tbody_row.append($("<td></td>",{"text":b})); }); } tbody.append(tbody_row); }); return detail_table; } $(document).ready(function() { var table = $('#example').DataTable( { "ajax": { "url": '/echo/js/?js=' + encodeURIComponent(JSON.stringify(data)), }, "columns": [ { "className": 'details-control', "orderable": false, "data": null, "defaultContent": '' }, { "data": "student_name" }, { "data": "subject1_average" }, { "data": "subject2_average" }, { "data": "subject3_average" } ], "order": [[1, 'asc']] } ); // Add event listener for opening and closing details $('#example tbody').on('click', 'td.details-control', function () { var tr = $(this).closest('tr'); var row = table.row( tr ); if ( row.child.isShown() ) { // This row is already open - close it row.child.hide(); tr.removeClass('shown'); } else { // Open this row row.child( format(row.data()) ).show(); tr.addClass('shown'); } } ); } ); JS Fiddle Link However I would really like to get one of the details columns to be a hyperlink. So to be specific how would I make the student's math column be a hyperlink so that when the user clicks on math they are navigated to the math.html link e.g "http://math.com". Just to be clear I believe $.each(v, function(a, b){ tbody_row.append($("<td></td>",{"text":b})); }); Is the portion that is creating the row, what I'd like is to have elemnt X of that row to be a hyperlink while all the other elements can be text. I don't really understand javascript so I think that {"text":b} is adding the elements as text to the row. But I don't know how to specify element X of the object v to be a URL, while keeping the rest of the elements of v, as text A: Change: var tbody_row = $("<tr></tr>").append($("<td></td>",{"text": k})); to var tbody_row = $("<tr></tr>").append($("<td></td>",{"html": '<a href="' + k + '.html">' + k + '</a>'})); to construct links to math.html when subject is math. See updated jsFiddle for code and demonstration.
{ "language": "en", "url": "https://stackoverflow.com/questions/33737000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java URL check for 404 HTTP response code I read from a URL type in Java and get the output line by line. But if the page didn't exist, it throws a 404 error code. How can I add a check if the response code is 200 (and not 404), get the line? And if it is 404, print something. url = new URL("http://my.address.com/getfile/12345.txt"); Scanner s = new Scanner(url.openStream()); while (s.hasNextLine()) { s.nextLine(); break; } A: try { URL url = new URL("https://www.google.com/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) {// status 200 Scanner s = new Scanner(url.openStream()); while (s.hasNextLine()) { s.nextLine(); break; } }else if(code == HttpURLConnection.HTTP_NOT_FOUND){//status 404 // TODO: url not found }else{ // TODO: other reponse status } } catch (IOException ex) { Logger.getLogger(Week8.class.getName()).log(Level.SEVERE, null, ex); } This is sample code for your scenario. I used google site for URL.
{ "language": "en", "url": "https://stackoverflow.com/questions/63442660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does 1..self mean in this ruby code? I can't seem to figure out what the 1..self means in this code..more specifically I can't figure out what self returns in this scope? ( I know what 1...10 means for example class Fixnum def palindrome_below i (1...self).select{|f| f.to_s(i) == f.to_s(i).reverse} end end Thanks for the help. A: The palindrome_below definition is an instance method on Fixnum. An instance method is a function that can be called on an instance of a class (in contrast to a class method, which is called on the class itself). Given this code, any instance of Fixnum will have access to palindrome_below method whereinself refers to the Fixnum instance itself (and i refers to the argument being passed to the method call). 14.palindrome_below(5) #=> [1, 2, 3, 4, 6, 12] # `self` refers to the Fixnum `14` Consequently, the output below is identical to the example above: (1...14).select{|f| f.to_s(5) == f.to_s(5).reverse} #=> [1, 2, 3, 4, 6, 12] A: x...y creates a Range with the interval (x, y]. In your context, self is referring to an instance of Fixnum. Any integer that can be represented in one native machine word is an instance of Fixnum. Here is a simple example: class Fixnum def double self * 2 end end # self is `2` 2.double # => 4 # self is `8` 8.double # => 16
{ "language": "en", "url": "https://stackoverflow.com/questions/27197987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find and filter both not working I am trying to find a span with a particular class, which includes a variable to assign it a width attribute in jQuery. I think I can use find() because it is a child element of a td that I am using to find it. I've tried both find() and filter() and it isn't returning anything. Help! $(document).ready(function() { //these two variables come from lists var person = "Rick"; var var1 = 2; var element = $('td').filter(function() { var Text = $(this).contents()[0].textContent.trim(); return parseInt(Text, 10) == var1; }); add_html = element.append('</br><span class="calendar_element ' + person + '"></span>'); $(window).on('resize', function() { //calculate needed width of span (var for simplicity) var length = 3; var cell_width = element.width(); var width = function() { return length * cell_width; } //why is this not working??? var resize_span = element.find('.calendar_element ' + person); $('span.calendar_element ' + person).css('width', width); }).resize(); }); div.class1 { position: relative; } table { border: 1px solid navy; width: 70%; text-align: center; } table th { text-align: center; width: 100px; height: 20px; } table td { width: 100px; height: 100px; vertical-align: top; text-align: right; border: 1px solid #c6c6ec; } span.calendar_element { background-color: purple; height: 14px; display: inline-block; padding: 2px; z-index: 1; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div class="class1"> <table> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> </tr> <tr> <td>7</td> <td>8</td> <td>9</td> <td>10</td> <td>11</td> <td>12</td> </tr> </tbody> </table> </div> A: Your code has two issues. Firstly, you're defining width as a function, so passing it as a value to the css() setter won't have the effect you expect. Secondly, your selector is not quite right. You need a . prefix on the class selector, and no space between the values as both classes are on the same element. Try this version, with some additional logic amendments: $(document).ready(function() { var person = "Rick"; var var1 = 2; var $element = $('td').filter(function() { return parseInt($(this).text().trim(), 10) == var1; }).append('<br /><span class="calendar_element ' + person + '"></span>'); $(window).on('resize', function() { var length = 3; var width = $element.width() * length; $element.find('.calendar_element.' + person).css('width', width); }).resize(); }); div.class1 { position: relative; } table { border: 1px solid navy; width: 70%; text-align: center; } table th { text-align: center; width: 100px; height: 20px; } table td { width: 100px; height: 100px; vertical-align: top; text-align: right; border: 1px solid #c6c6ec; } span.calendar_element { background-color: purple; height: 14px; display: inline-block; padding: 2px; z-index: 1; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div class="class1"> <table> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> </tr> <tr> <td>7</td> <td>8</td> <td>9</td> <td>10</td> <td>11</td> <td>12</td> </tr> </tbody> </table> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/42629832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How print array if he created in function? Arrays created in function test(). Then I would like print their on page test.php. My code down: conf.php function test(){ $str= array( 'items' => array( 0 => array( 'title' => 'Title', 'category' => 'Category name', ), 1 => array( 'title' => 'Title', 'category' => 'Category name', ), ), 'details' => array( 'firstname' => 'firstname', 'lastname' => 'lastname', ), 'Id' => $Id, 'OrderId' => 'fsdfsfdsrew' ); $json = json_encode($str); $base64 = base64_encode($json); $sig = signMessage($base64, $secretPhrase); } test.php require_once("conf.php"); test(); print_r($str); print_r($json); print_r($base64); print_r($sig); Tell me please why code not worked? Tell me please why weren't printed $str, $json, $base64, and $sig? How do it? Preferably without global parameters. A: You can't without returning them as the function return value. In PHP, variables declared in a function (the arrays you're trying to print_r in this case) are only available within the scope of that function unless you declare them global with the global keyword. Here's the details on variable scope in PHP: http://php.net/manual/en/language.variables.scope.php You could construct a larger array to contain these arrays and return them from the test() function: function test(){ //function code here.... ////... $results = array('str'=> $str, 'json'=> $json, 'base64'=>$base64, 'sig' => signMessage($base64, $secretPhrase) ) ; return $results; } Then call it like this: $results = test(); print_r($results['str']); print_r($results['sjson']); print_r($results['base64']); print_r($results['sig']); A: Many ways to do that: first, you have to return the value if you want use on other class. on your test you can do: $something = new Conf(); $someelse = $something->test(); echo $someelse;
{ "language": "en", "url": "https://stackoverflow.com/questions/14382680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: '\n' not detected by VTTCue for video subtitles in Javascript I'm trying to play a video with subtitles. I'm extracting duration and the subtitles string from a subtitles.txt file. The subtitles are extracted and player properly but the next line = '\n' is not being detected by 'code'. So please help me. The Output I want: Golden dreams and great heartache The Output I get: Golden dreams\nand great heartache My subtitles.txt File: 211 --> 223 "Golden dreams\nand great heartache" My Code: <html> <head> <meta charset="utf-8"/> <title></title> </head> <body> <video video-player src="video.mp4"></video> <script> var video_player = document.querySelectorAll('[video-player]')[0]; track_english = video_player.addTextTrack("captions", undefined, "en"); track_english.mode = "showing"; subtitles_xhr(function(buffer) { var file = buffer; file = file.split('\n'); for (var x = 0; x < file.length; x+=2) { track_english.addCue(new VTTCue(file[x].split(" --> ")[0], file[x].split(" --> ")[1], file[x+1])); } }); function subtitles_xhr (cb) { var xhr = new XMLHttpRequest; xhr.open('GET', "subtitles.txt"); xhr.onload = function () { cb(xhr.response); }; xhr.send(); } </script> </body> </html> A: Your problem is that the \n characters displayed when your read your text file are actually \\n characters. These characters won't get identified by the VTTCue parser as being new lines, so you need to replace these characters in the third argument of the VTTCue constructor to actual new lines, \n. // make the file available in StackSnippet const txt_uri = URL.createObjectURL(new Blob([String.raw`1 --> 13 "Golden dreams\nand great heartache"`], {type: 'text/plain'})); var video_player = document.querySelectorAll('[video-player]')[0]; track_english = video_player.addTextTrack("captions", undefined, "en"); track_english.mode = "showing"; subtitles_xhr(function(buffer) { var file = buffer; file = file.split('\n'); for (var x = 0; x < file.length; x += 2) { let startTime = file[x].split(" --> ")[0], endTime = file[x].split(" --> ")[1], content = file[x + 1] .replace(/\\n/g, '\n'); // here replace all occurrences of '\\n' with '\n' track_english.addCue( new VTTCue(startTime, endTime, content) ); } }); function subtitles_xhr(cb) { var xhr = new XMLHttpRequest; xhr.open('GET', txt_uri); xhr.onload = function() { cb(xhr.response); }; xhr.send(); } video{max-height:100vh} <video video-player src="https://upload.wikimedia.org/wikipedia/commons/transcoded/a/a4/BBH_gravitational_lensing_of_gw150914.webm/BBH_gravitational_lensing_of_gw150914.webm.480p.webm" autoplay controls></video>
{ "language": "en", "url": "https://stackoverflow.com/questions/50939541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Touchable info (i) button on top of Scroll View Is there better (framework built in) way to add small "touchable" round info button (i) on top of scroll view? Theoretically I think there should be container view for button(UIControl or UIImageView with png?) and scroll view. A: Simply make your information button float above the scroll view by adding it to the scroll view's superview, then ordering the views such that the information button resides on top of the scroll view. You'll retain scrolling capability, while still catching button touches.
{ "language": "en", "url": "https://stackoverflow.com/questions/3291809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle - How to tell between null and not null string? In an anonymous block I have an input string that is empty/null and want to check that against a non-null string. Example: DECLARE v_notnull varchar2(50):='this string is never null'; v_input varchar2(50):=''; BEGIN IF trim(v_input) != trim(v_notnull) THEN dbms_output.put_line('the strings do NOT match'); ELSE dbms_output.put_line('the strings DO match'); END IF; END; The issue here is that when I run this block, the output is always 'the strings DO match' even though I am inputting the empty string '' (aka null) into v_input which is not the same as the string 'this string is never null'. How can I make sure oracle covers the empty string case? When v_input is empty I want the output to be 'the strings do NOT match'. A: The documentation has a section on null handling. An empty string is treated the same as null, and you cannot compare nulls (of any type) with equality - as the table in the documentation shows, the result of comparing anything with null is unknown - neither true nor false. You have to use is [not] null to compare anything with null. In this case you could spell it out explicitly, by seeing is one variable is null and the other isn't, and vice versa, and only compare the actual values if that tells you neither are null: DECLARE v_notnull varchar2(30):='this string is never null'; v_input varchar2(30):=''; BEGIN IF (trim(v_input) is null and trim(v_notnull) is not null) or (trim(v_input) is not null and trim(v_notnull) is null) or trim(v_input) != trim(v_notnull) THEN dbms_output.put_line('the strings do NOT match'); ELSE dbms_output.put_line('the strings DO match'); END IF; END; / the strings do NOT match PL/SQL procedure successfully completed. I've added the missing varchar2 sizes; presumably you based this on a procedure that took arguments without running what you were posting stand-alone... A: '' is NULL in oracle. So, any comparison with null will always result in false. Demo: SQL> DECLARE 2 v_notnull varchar2(1000):='this string is never null'; 3 v_input varchar2(1000):=''; 4 BEGIN 5 IF v_input is null THEN 6 dbms_output.put_line('v_input is null'); -- should print because v_input is actually null 7 END IF; 8 9 IF trim(v_input) = trim(v_notnull) THEN -- always false because of null 10 dbms_output.put_line('the strings do NOT match'); 11 ELSE 12 dbms_output.put_line('the strings DO match'); -- so should print this 13 END IF; 14 END; 15 / v_input is null -- verified the strings DO match -- verified PL/SQL procedure successfully completed. SQL> A: Often you only care whether the values match, in which case null values make no difference: declare v_notnull varchar2(50) := 'this string is never null'; v_input varchar2(50) := ''; begin if trim(v_input) = trim(v_notnull) then dbms_output.put_line('the strings DO match'); else dbms_output.put_line('the strings do NOT match'); end if; end; In some cases you can simplify a comparison of nullable values using a coalesce() or nvl() expression: if nvl(v_yesno,'N') <> 'Y' then ... You might be able to use a dummy comparison value (although of course there is a risk that it will match an actual value, depending on the situation): if nvl(somevalue, chr(0)) <> nvl(othervalue, chr(0)) then ... By the way, you can distinguish between null and '' by copying the value to a char variable, as a '' will trigger its normally unhelpful blank-padding behaviour. I can't really think of a situation where this would be useful, but just for fun: declare v1 varchar2(1) := null; v2 varchar2(1) := ''; c char(1); begin c := v1; if v1 is null and c is not null then dbms_output.put_line('v1 = '''''); elsif c is null then dbms_output.put_line('v1 is null'); end if; c := v2; if v2 is null and c is not null then dbms_output.put_line('v2 = '''''); elsif c is null then dbms_output.put_line('v2 is null'); end if; end; Output: v1 is null v2 = ''
{ "language": "en", "url": "https://stackoverflow.com/questions/42031125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: PrimeFaces Poll I try to make a site where I place a clock. Not a default primefaces clock because I need the actual time not just to show it. I use Netbeans8.0, Java8.0, Primefaces5.0, and I'm building a Mobile site. So I tried the p:poll but it not works for me. @ViewScoped @ManagedBean(name = "navigationTo") public class NavigationTo implements Serializable{ private int number; public int getNumber() { return number; } public void increment() { number++; } } <h:body> <pm:page id="index"> <pm:header title="xyz"></pm:header> <pm:content> <h:form> <p:growl id="growl" showDetail="true"/> <h:outputText id="txt_count" value="#{navigationTo.number}" /> <p:poll interval="3" listener="#{navigationTo.increment}" update="txt_count" /> <p:graphicImage value="xyz.png" style="width: 30%; I use this default primefaces example but only shows the 0 and it's not incrementing... Anyone any idea? !!!EDIT: Primefaces Mobile (here: pm) not support polling. So it only work with the basic primefaces. A: well, I look your situation, I did a example about it, It work for me! I have created a Bean similar to your bean. @ViewScoped @ManagedBean(name="clockBean") public class clockBean implements Serializable{ private int number; public void increment(){ number++; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } } Besides I created a simple web page <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui" xmlns:pe="http://primefaces.org/ui/extensions"> <ui:composition template="/layout/template.xhtml"> <ui:define name="body"> <h:form id="form"> <p:poll interval="1" listener="#{clockBean.increment}" update=":form" /> <p:outputLabel value="#{clockBean.number}" /> </h:form> </ui:define> </ui:composition> </html> It has worked for me, I hope it can help you!. I think that your problem is that you need use id for the different components in your web page for exaMple the component form, it should has a id. A: Adding <h:outputScript library="primefaces" name="primefaces.js" /> inside h:body solved for me. I'm using PrimeFaces 5.1.20 A: For me, adding this line to <h:body> helped: <h:outputScript library="primefaces/poll" name="poll.js" /> A: Have you debugged the actual navigationTo.increment method, and checked that the poll actually goes inside? It seems that you are missing attributes inside the poll, if you want to trigger the back end method, and start the actual poll as soon as you load the page, add this: process="@this" autoStart="true"
{ "language": "en", "url": "https://stackoverflow.com/questions/24187556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to deal with locks (JPA)? According to the Java Persistent/Locking wikibooks*, the best way to deal with locks is to report the Optimistic Lock Error/Exception to the user. The problem is that it's not scalable. Suppose that I have many users who are likely to cause a lock with the same action. The user does not care about the lock error message. In a nutshell : * *The best way is to disable all locks ? *The best way is to report to the user the error lock message ? But the user must retry his action until it will work ! *The best way is to retry the transaction until there's no lock ? * Handling optimistic lock exceptions Unfortunately programmers can frequently be too clever for their own good. The first issue that comes up when using optimistic locking is what to do when an OptimisticLockException occurs. The typical response of the friendly neighborhood super programmer, is to automatically handle the exception. They will just create a new transaction, refresh the object to reset its version, and merge the data back into the object and re-commit it. Presto problem solved, or is it? This actually defeats the whole point of locking in the first place. If this is what you desire, you may as well use no locking. Unfortunately, the OptimisticLockException should rarely be automatically handled, and you really need to bother the user about the issue. You should report the conflict to the user, and either say "your sorry but an edit conflict occurred and they are going to have to redo their work", or in the best case, refresh the object and present the user with the current data and the data that they submitted and help them merge the two if appropriate. Some automated merge tools will compare the two conflicting versions of the data and if none of the individual fields conflict, then the data will just be automatically merged without the user's aid. This is what most software version control systems do. Unfortunately the user is typically better able to decide when something is a conflict than the program, just because two versions of the .java file did not change the same line of code does not mean there was no conflict, the first user could have deleted a method that the other user added a method to reference, and several other possible issues that cause the typically nightly build to break every so often. A: The user will care about the message, because he wanted to do some modification, and the modifications have not been made. He will thus refresh the page to see the new state of the data, and will redo his modifications, or decide they should not be made anymore given the new state. Is it a problem if two users modify an entity concurrently, and if the last modification wins, whatever the modification is? If it is a problem, then use optimistic locking, and inform your user when there is a problem. There's no way around it. If it's not a problem, then don't use optimistic locking. The last modification, if it doesn't break constraints in your database, will always win. But having concurrent users modifying the same data will always lead to exceptions (for example, because some user might delete an entity before some other user submits a modification to the same entity). Retrying is not an option: * *either it will fail again, because it's just not possible to do the modifications *or it will succeed, but will defeat the point of having optimistic locking in the first place. Your problem could be explained with a car analogy. Suppose you choose to buy a car with a speed limiter, in order to make sure you don't break the speed limit. And now you ask: but I don't care about the speed limits. Shouldn't I always disable the speed limiter? You can, but then don't be surprised if you get caught by the police.
{ "language": "en", "url": "https://stackoverflow.com/questions/7202409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: not getting the proper page through jsoup I am trying to get this page with jsoup: http://poalimparents.bankhapoalim.co.il/ But all I get is this: <html> <head> <meta charset="utf-8"> </head> <body> <script>window.rbzns = {fiftyeightkb: 43200000, days_in_week : 1};</script> <script src="//d1a702rd0dylue.cloudfront.net/js/sugarman/v7/flat.js"></script> <script>rbzns.challdomain="poalimparents.bankhapoalim.co.il"; rbzns.ctrbg="FBJbOCP+Rehoy7Oy/WdwW78giok75ZJ41qiRAeMY6ngbkLDEoRQiaRnij/E1vDpJr8bXfF2RriK5XaIq/Hp55vlAaMCPBIVryBF/YYXoti09rQmZeDa16289c+L2T8eFOCCIjmmtSn7gp75lWrKDHxJgS7Te/RxMGL/93TjdGxpofgMceO/Z2y/d7oCYNO/HKn4ZciE4aqCU8AU6rtyVjH0HxWz47/pps9uqcV0VnR/up4gHLztME+GHfJzjZ80Vy/14g5wvCKRtZU7P6I3zgQ==";rbzns.rbzreqid="bnhp-rbzr0131343537323737333137e0b31050bf436236"; winsocks(true);</script> </body> </html> I'm not trying to get the script tag inside the page. Why am I not getting all the other tags? How can I get this kind of pages? Thanks ahead. A: Try adding some headers that your browser would send, too. Also a cookie might be required - you could fetch one with a "normal" browser. Example (curl): curl "http://poalimparents.bankhapoalim.co.il/" -H "Host: poalimparents.bankhapoalim.co.il" -H "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" -H "Accept-Language: de,en-US;q=0.7,en;q=0.3" --compressed -H "DNT: 1" -H "Cookie: rbzreqid=bnhp-rbzr0231343537323737353630894b901088a07d30; rbzid=YnVIYjc0K2RmTDFXZFdiZy95UTNrOUJ0NEp0MzgzbW9oNlhHcFdVMU1mR25oT1NGQXowdGdZbjR3WktuQ2ZBZ0ljUTVCbHFDK213bGZXRk1DekJMMnhQMVFZVG4zcHpNT1lEWTRpM3FVeiswbkxtaFVCR25CU0taQ2pnNU1IQ1Z5WDc2ZWgxa2ZxR25vR1JadFpTVThidWs0d0s5QUF2YUVRSG1QcUpsS1ltRGpYNzhPR0lpRDNkak1VRmVxdm5nY0RpM1dEUnYrWU1rR2R1c3pWY2JGZHd6ODlOdkxHUkxuOW03N0VzWC9oOD1AQEAwQEBALTc0MDc0MDczNDA-" -H "Connection: keep-alive" -H "If-Modified-Since: Mon, 22 Feb 2016 11:40:18 GMT" -H "If-None-Match: W/""af3920fb581df1e4de68d46a4694689a""" -H "Cache-Control: max-age=0"
{ "language": "en", "url": "https://stackoverflow.com/questions/35828371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there an easy way to copy a variable in the heap into shared memory I have a couple of structs with pointers to one another allocated on the heap. I'm converting a multi-threaded program to a multi-process program so I have to make those structs on the heap into shared memory. So far, I've run into nothing but problems on top of problems. MY TA suggested I use memcpy, but I'm not sure that's going to work. Is there any way to convert a set of structs on the heap into shared memory? Structs I'm using: struct SharedData { int da; int isopen; int refcount; // reference count: number of threads using this object unsigned int front; // subscript of front of queue unsigned int count; // number of chars in queue unsigned int bufsize; pthread_cond_t buffer_full; pthread_cond_t buffer_empty; pthread_mutex_t mtex; fifo_t* queue; sem_t empty_count; sem_t full_count; sem_t use_queue; // mutual exclusion }; struct OverSharedData{ struct SharedData ** rep; int rop; }; I malloc'd OverSharedData , the SharedData structs, and the fifo_t queue, along with multiple char pointers later on. Do they all have to be declared as shared memory? A: In the way malloc() request memory from heap, there are system calls (for e.g. shmget()) to request/create shared memory segment. If your request is successful, you can copy whatever you like over there. (Yes, you can use memcpy.) But remember to be careful about pointers, a pointer valid for one process, kept in its shared memory, is not necessarily valid for another process using that shared memory segment. The shared memory is accessible to all processes for reading and/or writing. If multiple processes are reading/writing to a shared memory segment, then, needless to say, some synchronization techniques (for e.g. semaphore) need to be applied. Please read up on shared memory. An excellent source is "The Linux Programming Interface" by Michael Kerrisk. Reference: * *http://man7.org/linux/man-pages/man7/shm_overview.7.html *http://man7.org/linux/man-pages/man2/shmget.2.html *http://www.amazon.com/The-Linux-Programming-Interface-Handbook/dp/1593272200
{ "language": "en", "url": "https://stackoverflow.com/questions/23145802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS padding not applying to parent div I really don't understand CSS :( Why is the following padding not pushing out the size of the parent div? HTML <div class="lead-table"> <div class="row table-head-1"> <div class="col-md-9"> <span><strong>My Leads</strong></span> </div> </div> </div> CSS .lead-table .table-head-1 { background-color: #053449; text-transform: uppercase; color: #ffffff; font-size: 12px; } .lead-table .table-head-1 span { padding: 20px 18px; } http://www.bootply.com/gsT2mwsA8h# Any help appreciated for this CSS noob. Thanks A: span is not a block element. padding will not work for inline elements. But margin will work. * *either you can use margin: 20px 18px; or *add display:block; or display:inline-block; to the span. padding will take effect once you make it a block element. A: Unlike div, p 1 which are Block Level elements which can take up padding or margin on all sides,span2 cannot as it's an Inline element which takes up padding or margin horizontally only. From the specification : Use div instead of span...below code will work .lead-table .table-head-1 { background-color: #053449; text-transform: uppercase; color: #ffffff; font-size: 12px; } .lead-table .table-head-1 .col-txt{ padding: 20px 18px; } <div class="lead-table"> <div class="row table-head-1"> <div class="col-md-9"> <div class='col-txt'><strong>My Leads</strong></div> </div> </div> </div> A: Just replace that both css with following, it may help you :- .lead-table .table-head-1 { background-color: #053449; text-transform: uppercase; color: #ffffff; font-size: 12px; padding: 20px 18px; } A: Your html needs to be wrapped in a "container" class division tag with bootstrap. HTML: <div class="container"> <div class="lead-table"> <div class="row table-head-1"> <div class="col-md-9"> <span><strong>My Leads</strong></span> </div> </div> </div> </div> Also, your CSS can be reduced for what you have currently as shown below. CSS: /* CSS used here will be applied after bootstrap.css */ .lead-table{ background-color: #053449; text-transform: uppercase; color: #ffffff; font-size: 12px; } .table-head-1{ padding: 20px 18px; } A: By default a span is an inline element. You cannot add padding top or bottom to it unless you add display:block. .lead-table .table-head-1 span { padding: 20px 18px; display:block; } Working code example: http://www.bootply.com/kSh1hNCkTb#
{ "language": "en", "url": "https://stackoverflow.com/questions/33795521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to configure cascade delete where there are cycles and multiple cascade paths I'm having a bit of trouble getting my head around this relationship, and how to possibly setup cascade delete settings for it. * *There is a table of employees, where each employee has any number of handles, attachments and jobs *There is a table of handles, where each handle belongs to an employee and may be used in a tool *There is a table of attachments, where each attachment belongs to an employee and may be used in a tool *There is a table of tools, where each tool is made up of one attachment, one handle and is used on any number of jobs *There is a table of jobs, where each job belongs to an employee, and may or may not have a tool used on it Note: it's possible for handles and attachments to exist without being used to make a tool In short: an employee can mix-and-match handles and attachments to make tools, and then use a tool on a job they are assigned. This diagram shows how the database is wired together (feel free to suggest a better design) DB Diagram This is how the models are setup, the Job model has a nullable reference to the tools FK (ToolId) so a job can exist without a tool. public class Employee { public int EmployeeId { get; set; } public string Name { get; set; } public List<Handle> Handles { get; set; } public List<Attachment> Attachments { get; set; } public List<Job> Jobs { get; set; } } public class Handle { public int HandleId { get; set; } public string Material { get; set; } public double ExpectedLife { get; set; } public double LifetimeMaintenance { get; set; } public int EmployeeId { get; set; } public Employee Employee { get; set; } public List<Tool> Tools { get; set; } } public class Attachment { public int AttachmentId { get; set; } public string Material { get; set; } public string Type { get; set; } public double ExpectedLife { get; set; } public double LifetimeMaintenance { get; set; } public int EmployeeId { get; set; } public Employee Employee { get; set; } public List<Tool> Tools { get; set; } } public class Tool { public int ToolId { get; set; } public string OperationSpeed { get; set; } public int HandleId { get; set; } public Handle Handle { get; set; } public int AttachmentId { get; set; } public Attachment Attachment { get; set; } public List<Job> Jobs { get; set; } } public class Job { public int JobId { get; set; } public string Name { get; set; } public double EffortRequired { get; set; } public int EmployeeID { get; set; } public Employee Employee { get; set; } public int? ToolId { get; set; } public Tool Tool { get; set; } } This is how the DB context has been created. There is a cascade delete setting to set the tool FK in Jobs (ToolId) to null when a tool is deleted (so the job wont get deleted when its tool is deleted). public class ToolsDbContext : DbContext { public ToolsDbContext(DbContextOptions<ToolsDbContext> options) : base(options) { } public DbSet<Employee> employees { get; set; } public DbSet<Handle> handles { get; set; } public DbSet<Attachment> attachments { get; set; } public DbSet<Tool> tools { get; set; } public DbSet<Job> jobs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Tool>() .HasMany(j => j.Jobs) .WithOne(t => t.Tool) .OnDelete(DeleteBehavior.SetNull); } } Creating the migration works, but then updating the database fails with the following error: Introducing FOREIGN KEY constraint 'FK_tools_handles_HandleId' on table 'tools' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors. I'm not too sure how to understand this error. Thinking it through: * *If a handle is deleted, it will delete all tools it's used in, which in turn will set ToolId in related Jobs to null *If an attachment is deleted, it will delete all tools it's used in, which in turn will set ToolId in related Jobs to null *If a tool is deleted it will set ToolId in related Jobs to null *If a job is deleted, there will be no cascade effect Therefore I think the problem must be with deleting an employee, but I can't see why (yet?)... * *If an employee is deleted everything should be deleted; it should delete all related jobs, handles and attachments. Then those deleted handles or attachments should in turn delete the tools associated with them (it shouldn't matter what came first). So there is cascade paths deleting an employee, but I would expect this would all work based on the model setup as-is... So do I need to configure more cascade delete requirements in the dbcontext? If so, I'm not sure how it should be configured... Note: without the employees model in the database, everything seems to work A: SQL server doesn't allow to have multiple cascade paths to the same table in the database. In your case there are two of them for Tools: * *Employee -> Handle -> Tool *Employee -> Attachment -> Tool All ways to fix the issue consist in setting DeleteBehavior.Restrict for one relationship or the other, for example: * *Setting DeleteBehavior.Restrict for Entity -> Handle relationship and handling this cascade path by a trigger (otherwise "restrict" won't allow to delete a record having references to it) *Setting DeleteBehavior.Restrict for Entity -> Handle relationship and handling this cascade path in application code (update/delete all related entities explicitly before deleting the main one) *Setting "restrict" behavior for both Entity relationships etc... A: You said: There is a table of employees, where each employee has any number of handles, attachments and jobs But your diagram establishes a direct link between an employee and a handle, one handle has many employees, and an employee has only one handle Your statement is in conflict with your diagram I think this modelling is wrong, from the database perspective. I think a job should have an employee. (If a job has multiple employees you'll need another table jobemployees that maps one job id to multiple employees.) A job has a tool, a tool has a handle and an attachment. I fail to see why deleting an employee should delete their jobs (if I fired someone the house he built while working for me still exists) but you can clean this up without using cascading constraints Ultimately you can see in the diagram the cycle you've created. If deleting something at a 1 end deletes everything at the * end then deleting anything in your diagram starts a chain that takes a split path that comes back together. Removing the employee entity does indeed break this up Ultimately an employee should not directly have a job, a handle or an attachment
{ "language": "en", "url": "https://stackoverflow.com/questions/56999585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python recursion - how to exit early I've been playing with BST (binary search tree) and I'm wondering how to do an early exit. Following is the code I've written to find kth smallest. It recursively calls the child node's find_smallest_at_k, stack is just a list passed into the function to add all the elements in inorder. Currently this solution walks all the nodes inorder and then I have to select the kth item from "stack" outside this function. def find_smallest_at_k(self, k, stack, i): if self is None: return i if (self.left is not None): i = self.left.find_smallest_at_k(k, stack, i) print(stack, i) stack.insert(i, self.data) i += 1 if i == k: print(stack[k - 1]) print "Returning" if (self.right is not None): i = self.right.find_smallest_at_k(k, stack, i) return i It's called like this, our_stack = [] self.root.find_smallest_at_k(k, our_stack, 0) return our_stack[k-1] I'm not sure if it's possible to exit early from that function. If my k is say 1, I don't really have to walk all the nodes then find the first element. It also doesn't feel right to pass list from outside function - feels like passing pointers to a function in C. Could anyone suggest better alternatives than what I've done so far? A: Passing list as arguments: Passing the list as argument can be good practice, if you make your function tail-recursive. Otherwise it's pointless. With BST where there are two potential recursive function calls to be done, it's a bit of a tall ask. Else you can just return the list. I don't see the necessity of variable i. Anyway if you absolutely need to return multiples values, you can always use tuples like this return i, stack and this i, stack = root.find_smallest_at_k(k). Fast-forwarding: For the fast-forwarding, note the right nodes of a BST parent node are always bigger than the parent. Thus if you descend the tree always on the right children, you'll end up with a growing sequence of values. Thus the first k values of that sequence are necessarily the smallest, so it's pointless to go right k times or more in a sequence. Even in the middle of you descend you go left at times, it's pointless to go more than k times on the right. The BST properties ensures that if you go right, ALL subsequent numbers below in the hierarchy will be greater than the parent. Thus going right k times or more is useless. Code: Here is a pseudo-python code quickly made. It's not tested. def findKSmallest( self, k, rightSteps=0 ): if rightSteps >= k: #We went right more than k times return [] leftSmallest = self.left.findKSmallest( k, rightSteps ) if self.left != None else [] rightSmallest = self.right.findKSmallest( k, rightSteps + 1 ) if self.right != None else [] mySmallest = sorted( leftSmallest + [self.data] + rightSmallest ) return mySmallest[:k] EDIT The other version, following my comment. def findKSmallest( self, k ): if k == 0: return [] leftSmallest = self.left.findKSmallest( k ) if self.left != None else [] rightSmallest = self.right.findKSmallest( k - 1 ) if self.right != None else [] mySmallest = sorted( leftSmallest + [self.data] + rightSmallest ) return mySmallest[:k] Note that if k==1, this is indeed the search of the smallest element. Any move to the right, will immediately returns [], which contributes to nothing. A: As said Lærne, you have to care about turning your function into a tail-recursive one; then you may be interested by using a continuation-passing style. Thus your function could be able to call either itself or the "escape" function. I wrote a module called tco for optimizing tail-calls; see https://github.com/baruchel/tco Hope it can help. A: Here is another approach: it doesn't exit recursion early, instead it prevents additional function calls if not needed, which is essentially what you're trying to achieve. class Node: def __init__(self, v): self.v = v self.left = None self.right = None def find_smallest_at_k(root, k): res = [None] count = [k] def helper(root): if root is None: return helper(root.left) count[0] -= 1 if count[0] == 0: print("found it!") res[0] = root return if count[0] > 0: print("visiting right") find(root.right) helper(root) return res[0].v A: If you want to exit as soon as earlier possible, then use exit(0). This will make your task easy!
{ "language": "en", "url": "https://stackoverflow.com/questions/32861587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Css calling class into other style I don't understand why this doesn't work .mix{ -moz-border-radius: 5px 5px; border-radius: 5px 5px / 5px 5px; -moz-box-shadow: 2px 2px 2px #888; -webkit-box-shadow: 2px 2px 2px #888; box-shadow: 2px 2px 2px #888; } #adm_content_login, .mix{ top:100px; position:relative; width:450px; height:200px; margin:auto; background-color:#ccc; text-align:center; border:5px solid #111; } When I try to call a class into another class with adm_content_login, .mix , because there is no need if I use this code each time I have the same content I have in the .mix. I don't understand what's wrong with this code. The CSS works if I put it into adm_content_login, but if I try using this method it doesn't work. A: Hi if you are trying to use .mix class with #adm_content_login you can make both of them either a class or id. for instance, if both of them are class you can you it like this <div class="adm_content_login mix"></div> notice that there is a space between two classes. If that's not what you are trying to achieve then you can achieve something like that using LESS(CSS FRAMEWORK) A: you are using class but you define id used to this way as like this <div id="adm_content_login" class="mix"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/15352091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript/AJAX/send to server text and file with JSON I'm developing a small software that allow to insert of my client's store products, description text and product photos, then i need to send with $.ajax() either text and files with 1 call. I have no problem sending text or file separately, with 2 call, but can i do it with 1? A: var formData = new FormData(); formData.append("file-identifier", $('#file-identifier').get(0).files[0]); formData.append("variable", $.session.get("variable")); $.ajax({ url : "path/to/file.file", type : "POST", processData: false, contentType: false, data : formData, dataType: "json", success : function(data){ //handle on success }, error : function(jqXHR, textStatus, errorThrown){ console.log(arguments); } }); This is a sample from a script I used recently to upload a jpeg and a variable taking content from a session variable. Appending these to a FormData object allows you to transfer both file and variable in one request.
{ "language": "en", "url": "https://stackoverflow.com/questions/23599559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to find selected fields from sample data in nested array in mongodb I have sample collection of data [ { data: [ { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular" }, { "id": "1002", "type": "Chocolate" }, { "id": "1003", "type": "Blueberry" }, { "id": "1004", "type": "Devil's Food" } ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5005", "type": "Sugar" }, { "id": "5007", "type": "Powdered Sugar" }, { "id": "5006", "type": "Chocolate with Sprinkles" }, { "id": "5003", "type": "Chocolate" }, { "id": "5004", "type": "Maple" } ] }, { "id": "0002", "type": "donut", "name": "Raised", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular" } ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5005", "type": "Sugar" }, { "id": "5003", "type": "Chocolate" }, { "id": "5004", "type": "Maple" } ] }, { "id": "0003", "type": "donut", "name": "Old Fashioned", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular" }, { "id": "1002", "type": "Chocolate" } ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5003", "type": "Chocolate" }, { "id": "5004", "type": "Maple" } ] } ] } ] and I need data only in this formate of a specific id. [ { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55 } ] A: aggregate db.collection.aggregate({ "$unwind": "$data" }, { "$match": { "data.id": "0001" } }, { "$project": { "_id": "$data.id", "type": "$data.type", "name": "$data.name", "ppu": "$data.ppu" } }) mongoplayground
{ "language": "en", "url": "https://stackoverflow.com/questions/69551786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AzureDevOps ServiceTags Availability for NSG Is service tag for Azure DevOps in roadmap? if yes, do we have an ETA on the availability? or Do we have any other tags which covers Azure DevOps IP range? As of now, we have Azure DevOps Agent IP ranges available online through weekly XML but we dont have a tag for Azure DevOps as of now to be used with NSGs. https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/hosted?view=azure-devops&tabs=yaml#agent-ip-ranges A: It appears from this issue that Azure is not implementing a service tag, but instead thinking of creating a product where you can spin up semi-managed build agents inside your own subscription. Details can be found on the design in github A: Azure DevOps Service Tag have been released Now that a service tag has been set up for Azure DevOps Services, customers can easily allow access by adding the tag name AzureDevOps to their NSGs or firewalls programmatically using Powershell and CLI. The portal will be supported at a later date. Customers may also use the service tag for on-prem firewall via a JSON file download. Azure Service Tags are supported for inbound connection only from Azure DevOps to customers’ on-prem. Outbound connection from customers’ networks to Azure DevOps is not supported. Customers are still required to allow the Azure Front Door (AFD) IPs provided in the doc for outbound connections. The inbound connection applies to the following scenarios documented here. Note: Service Tag AzureDevOps is available from the portal now. However this will not cover IP Ranges of MS Hosted agents
{ "language": "en", "url": "https://stackoverflow.com/questions/55587639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to refactor the code of a class composed of one public method and multiple private method that only do check There is a code I'm working on that I find kind of annoying. Indeed, the class is composed of one public method and many private methods to check stuff and or to output some logs. There are 3 types of private method in the code. The firsts private method only do some check on the input data and raise if something is inconsistent. (3 methods) The seconds do the only produce some log reports. (2 methods) And the thirds prepare and save the data (2 methods) (The purpose of this class), those are composed of many other external library that I have to mock. Then each of the private method are called in the public method of the class that we will call execute(). Every test runs on the execute method that include the whole logic of the code behind private functions. To test the code, I mock many call of external methods inside the method that save and look at the args that are called when I run the execute method in my test, because of this every test I write are 75% function mocking calls. It's annoying. I would like to split it but each I tried I look at it and find it useless because it's more like I just extract the private method in another. Here is pseudo code of the class. It's in python but it is irrelevant : class MyDigustingClass(): def _first_check(self, args...): pass def _second_check(self, args...): pass def _third_check(self, args...): pass def _log_method_1(self, args...): pass def _log_method_2(self, args...): pass def _prepare_data(self, args...): pass def _save_data(self, args...): pass def execute(self, args...): # Call check methods # Call prepare_data # Call save_data # Call logs method As I said, I struggle to find a good idea of refactoring because I can't do better than a flat pass. What would you suggest.
{ "language": "en", "url": "https://stackoverflow.com/questions/59141337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: open protected excel file with com, but the running excel does not support addins I need to open the encrypted excel file from code, and the end user can also edit or save the opened file. Then I found a way to handle it by using com: https://learn.microsoft.com/zh-cn/previous-versions/office/troubleshoot/office-developer/automate-excel-from-c However, The opened excel application does not support excel addins. for example: the excel setting like excel setting 1 excel setting 2 when open excel.exe normally,it's like: normally open, correct but when use com to open excel.exe by the code, it's like: open from code, incorrect the addins disappear. Also, if you reconfig addins option, addins appear again. So I think there may have no initialization when excel.exe was started. Is there any way to start open encrypted excel file by excel.exe from code, and all excel function are fine? Here is the code with vbs(the link below is c code): Set oExcel = CreateObject("Excel.Application") Set oWorkbook = oExcel.Workbooks.Open("C:\Users\melon\Desktop\excel\excel tests\chat&sample exam.xlsm", 0, 0, 5, "76350e01-a0bd-44c6-9e4d-0df382c2d789") oExcel.Visible = true A: Programs started with COM are started by COM with the slash /a parameter. This means Automation is starting the program so it should load clean. /a Starts Word and prevents add-ins and global templates (including the Normal template) from being loaded automatically. The /a switch also locks the setting files. https://support.microsoft.com/en-us/office/command-line-switches-for-microsoft-office-products-079164cd-4ef5-4178-b235-441737deb3a6
{ "language": "en", "url": "https://stackoverflow.com/questions/73076052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Elastic search structure AND/EXISTS Im new to Elasticsearch and this is driving me crazy. The docs are pretty unhelpful and so about 6 hours in I come to the amazing SO community. I have a query which is implemented all over a large and 95% finished website, so I cannot rewrite much at this point. I need add a check to make sure that the userID is not null. In SQL this would take seconds, but I have a pretty large query which is giving me either crazy unhelpful error messages or not working. I have tried restructuring, moving the "exists" into an existing "and" where it doesnt work at all. This is what I have: GET _search { "from": 0, "size": 30, "query": { "filtered": { "query": { "match_all": {} }, "filter": { "and": [ { "bool": { "must": [ { "exists" : { "field" : "userID" } } ] } },{ "term": { "property.rental": false } }, { "term": { "property.status": 100 } }, { "term": { "property.showOnHomepage": true } } ] } } }, "sort": { "_script": { "script": "Math.random()", "type": "number", "params": {}, "order": "asc" } }, "aggregations": { "min_price": { "min": { "field": "basePrice" } }, "max_price": { "max": { "field": "basePrice" } }, "avg_price": { "avg": { "field": "basePrice" } } }, "filter": { "range": { "property.price": { "lte": 1000000000 } } } } This gives the following results: { "took": 7, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 0, "max_score": null, "hits": [] }, "aggregations": { "min_price": { "value": null }, "max_price": { "value": null }, "avg_price": { "value": null } } } I simply don't understand where to place the "exists" : { "field" : "userID" } inorder for it to filter out just the properties with null for a userID. Any help would be amazing.
{ "language": "en", "url": "https://stackoverflow.com/questions/24563680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Splitting a Clojure namespace over multiple files Is it possible to split a Clojure namespace over multiple source files when doing ahead-of-time compilation with :gen-class? How do (:main true) and (defn- ...) come into play? A: Overview Certainly you can, in fact clojure.core namespace itself is split up this way and provides a good model which you can follow by looking in src/clj/clojure: core.clj core_deftype.clj core_print.clj core_proxy.clj ..etc.. All these files participate to build up the single clojure.core namespace. Primary File One of these is the primary file, named to match the namespace name so that it will be found when someone mentions it in a :use or :require. In this case the main file is clojure/core.clj, and it starts with an ns form. This is where you should put all your namespace configuration, regardless of which of your other files may need them. This normally includes :gen-class as well, so something like: (ns my.lib.of.excellence (:use [clojure.java.io :as io :only [reader]]) (:gen-class :main true)) Then at appropriate places in your primary file (most commonly all at the end) use load to bring in your helper files. In clojure.core it looks like this: (load "core_proxy") (load "core_print") (load "genclass") (load "core_deftype") (load "core/protocols") (load "gvec") Note that you don't need the current directory as a prefix, nor do you need the .clj suffix. Helper files Each of the helper files should start by declaring which namespace they're helping, but should do so using the in-ns function. So for the example namespace above, the helper files would all start with: (in-ns 'my.lib.of.excellence) That's all it takes. gen-class Because all these files are building a single namespace, each function you define can be in any of the primary or helper files. This of course means you can define your gen-class functions in any file you'd like: (defn -main [& args] ...) Note that Clojure's normal order-of-definition rules still apply for all functions, so you need to make sure that whatever file defines a function is loaded before you try to use that function. Private Vars You also asked about the (defn- foo ...) form which defines a namespace-private function. Functions defined like this as well as other :private vars are visible from within the namespace where they're defined, so the primary and all helper files will have access to private vars defined in any of the files loaded so far.
{ "language": "en", "url": "https://stackoverflow.com/questions/4690758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "97" }
Q: How to access Entity Framework DbContext entities in Server-Side Blazor Components I'm new to .NET Core and Blazor, with mostly WebForms and MVC experience. All the Blazor documentation and tutorials I've found use a separate API project and access data through HttpClient and Json serialization/deserialization. I see why this would be necessary for client-side Blazor using WebAssembly, but for Server-Side Blazor using SignalR what's the best way to access the database directly from the components' .razor files using an Entity Framework DbContext? For example, in an MVC controller you can just do something like: private ApplicationDbContext context = new ApplicationDbContext(); and then query the data by doing something like: var things = context.Things.Where(t => t.ThingAttributes == something); Is there an approach that is this clean and efficient when working with components in server-side Blazor? Sorry for the broad nature of this question, feel free to point me to blogs, docs, or tutorials I should have already read. Thanks! A: What you call a controller should be turned into a service class, that retrieves data from the database, and pass it to the calling methods. You should add this service to the DI container in the Startup class. To use this service in your components you should inject it like this: @inject DataService myDataService I think that the Blazor templates come with sample how to define such a service and use it in your components. Here's a link to a sample by the Blazor team how to create a service and how to use it in your components. The service doesn't use Entity Framework, but this is something really minor I'm sure you'll cope with.
{ "language": "en", "url": "https://stackoverflow.com/questions/59805446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to pad strings inside curly braces with odd number of character with a single space? We have many \foo{something}. As the string inside the curly braces contains odd number of character, we want to add a space after the string. The result will be \foo{something }. We only want odd number of characters only. For example, in \foo{string} the string inside the curly braces has even number of character, then we do not add a space. What I have tried: * *a dot means a character, two dots means two characters *asterisk means repeat 0 or more times *Then, [..]*. means 1, 3, 5 ... characters. *Then, \foo{[..]*.} will be my matching sequence. *Then, :%s/\foo{[..]*.}/\foo{[..]*. }/g will add the space we want. But we failed. A: This cmd should do: :%s/\\foo{\zs[^}]\+\ze}/\=substitute(submatch(0), '$', len(submatch(0))%2?' ':'','g')/ A: :%s/\\\w\+{\([^}]\{2}\)*[^}]\zs\ze}/ /g Explanation: Find pairs of characters (\([^}]\{2}\)*) followed by another character ([^}]) in between a macro \\\w\+{...}. Then do a substitution adding an additional space. Glory of details: * *\\\w\+{...} find macros of the pattern \foo{...} *Look for character that does not match an ending curly brace, [^}] *Look for pairs of non-}'s, \([^}]\{2}\)* *Find an odd length string by finding pairs and then finding one more, \([^}]\{2}\)*[^}] *Use \zs and \ze to set where the start and end of the match *Use a space in the replacement portion of the substitution to add additional space and thereby making the string even in length Fore more help see: :h :s :h :range :h /\[] :h /\( :h /\zs :h /\w :h /star :h /\+ A: This should work :%s/\v[(\{(\w{2})*) ]@<!}/ }/g break down: %s " run substitute on every line \v " very magic mode [(\{(\w{2})*) ] " matches every `{` followed by an equal number of word characters and space, since you don't want to add a space again everytime you run it. @<!} " negative lookahead, matches all } not following the pattern before Update To solve the precise problem as you can read in the comments, the following command helps. g/^\\foo/s/\v(\{([^}]{2})*)@<!}/ }/g Changes: g/^\\foo/... " only run it on lines starting with \foo [^}] " it does now match all characters between { and } not only word characters. Pitfalls: won't work correct with multiple braces on the line ( \foo{"hello{}"} and \foo{string} {here it would also match} f.e. will fail). if one of these is a problem. just tell me
{ "language": "en", "url": "https://stackoverflow.com/questions/48439096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Catching errors at the end of a chain of promises I am using a factory to query data from Parse.com, this occurs many times in my ionic app and would like to apply a little more DRY to my code. To call data I am using: ParseFactory.provider('Clients', query).getAll().success(function(data) { $localStorage.Clients = data.results; }).error(function(response) { errorFactory.checkError(response); }); And often run many of these back to back to get data from different classes on the loading of a page. Is it possible to use one error block at the end of all of these? like this: ParseFactory.provider('Favourites', query).getAll().success(function(data) { $localStorage.Favourites = data.results; }) ParseFactory.provider('Somethings/', query).getAll().success(function(data) { $localStorage.Programmes = data.results; }) ParseFactory.provider('UserItems', query).getAll().success(function(data) { $localStorage.UserExercises = data.results; }) ParseFactory.provider('Customers', query).getAll().success(function(data) { $localStorage.Clients = data.results; }).error(function(response) { errorFactory.checkError(response); }); A: You could create helper method: function query(resource, query) { function querySucceeded(data) { $localStorage[resource] = data.results; } function queryFailed() {} ParseFactory.provider(resource, query) .getAll() .success(querySucceeded) .error(queryFailed); } and, then just call: query('Favourites', query); query('Customers', query); and so on. Alternatively, you could factor queryFailed out, as such: function query(resource, query) { function querySucceeded(data) { $localStorage[resource] = data.results; } return ParseFactory.provider(resource, query) .getAll() .success(querySucceeded); } function queryFailed() { } $q.all([ query('Favourites', query1), query('UserItems', query2)]) .error(queryFailed); A: $q.all takes an array (or object) of promises, and returns a single one. The returned promise is resolved when all the original promises are resolved. It's rejected as soon as one of the original promises is rejected. So, what you can simply do is something like var request = function(path) { return ParseFactory.provider(path, query).getAll(); }; var promises = { favourites: request('Favourites'), programmes: request('Somethings/'), exercises: request('UserItems'), customers: request('Customers') }; $q.all(promises).then(function(results) { $localStorage.Favourites = results.favourites.data.results; // ... }).catch(function() { // ... });
{ "language": "en", "url": "https://stackoverflow.com/questions/32368782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Discord Bot will not login to server I will start this off by saying I'm a bit new to discord bot making. I'm just trying to get the bot online at this point and I keep getting the error: TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client. at Client._validateOptions (C:\Users\levan\Desktop\Discordbot\node_modules\←[4mdiscord.js←[24m\src\client\Client.js:544:13) at new Client (C:\Users\levan\Desktop\Discordbot\node_modules\←[4mdiscord.js←[24m\src\client\Client.js:73:10) at Object. (C:\Users\levan\Desktop\Discordbot\main.js:3:16) ←[90m at Module._compile (node:internal/modules/cjs/loader:1101:14)←[39m ←[90m at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)←[39m ←[90m at Module.load (node:internal/modules/cjs/loader:981:32)←[39m `←[90m at Function.Module._load (node:internal/modules/cjs/loader:822:12)←[39`m ←[90m at Function.executeUserEntryPoint [as runMain] ``(node:internal/modules/run_main:79:12)←[39m ←[90m at node:internal/main/run_main_module:17:47←[39m { [←[32mSymbol(code)←[39m]: ←[32m'CLIENT_MISSING_INTENTS'←[39m } thus far this is what I have const Discord = require('discord.js'); const client = new Discord.Client(); client.once('ready', () => { console.log('Tec Control Bot is online!'); }); client.login('redacted sign in key'); A: So, you are using discord.js v13 which is a lot different from the previous version which is v12. In v13, it is compulsory to add intents. You can read this for more information: here A: new Discord version V13 requires you to set the intents your bot will use. First, you can go to https://ziad87.net/intents/ where you can choose the intents you want and gives you a number, you should use that number like this: const intents = new Discord.Intents(INTENTS NUMBER); const client = new Discord.Client({ intents }); For example, if you want all the intents, you will have: const intents = new Discord.Intents(32767); const client = new Discord.Client({ intents });
{ "language": "en", "url": "https://stackoverflow.com/questions/68853636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Re-read environment variables from VBScript I'm running a VBScript from a MSI installer (created using WiX toolset). This script checks using the PATH environment variable whether another software is installed or not. The installer also offers a retry button which runs the script again. Now the problem is this: If the PATH environment variable is changed while my installer is running, my script will not detect that change. My script only uses the new value of the PATH environmental variable after a re-start of the installer. So the question is this: How can I force the installer process to update its copy of the environment variables using VBScript? Edit: It looks like this article explains how to solve the problem with PowerScript. But I need a solution for VBScript. A: With WScript.CreateObject("WScript.Shell") .Environment("PROCESS")("PATH") = .ExpandEnvironmentStrings(Replace( _ .Environment("USER")("PATH") & ";" & .Environment("SYSTEM")("PATH"), ";;", ";" _ )) End With This will overwrite the in memory current process PATH environment variable with the information retrieved from registry for the user and system environment variables. note: Previous code only updates the environment copy of the [c|w]script process that executes the code. It does not update the installer's copy of the environment (you can not update another process environment). A: Alternately, from jscript (still the cscript interpreter, but the jscript language) // Re-read PATH vars in case they've changed var shell = new ActiveXObject("WScript.shell"); var newPath = (shell.Environment("USER")("PATH") + ";" + shell.Environment("SYSTEM")("PATH")).replace(/;;/g, ";"); // Expand any %STRINGS% inside path and set to the new running process shell.Environment("PROCESS")("PATH") = shell.ExpandEnvironmentStrings(newPath); shell.Exec('myprocess.exe'); // throws exception if not found
{ "language": "en", "url": "https://stackoverflow.com/questions/44391553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Determine number of row spans given a start index and a length I have a matrix start index of my data and the number of elements of my data and I need to find the number of rows that the data span. e.g. the matrix 0 5 ------------------- | | | | |x |x | ------------------- |x |x |x |x |x |x | ------------------- | | | | | | | ------------------- | | | | | | | ------------------- My data is marked with x. I know the start index 4, the length of the data 8. And I need to determine the number of rows this data spans, 2 in this case. (just doing length/6 is off by one in many cases, surely there have to be a simple formula for this..) A: If you only know offset (i.e. index of the starting column), size (i.e. how many data), cols (i.e. maximum number of colums), and you want to calculate how many rows your data will span, you can do int get_spanned_rows(int offset, int size, int cols) { int spanned_rows = (offset + size) / cols if ( ( (offset + size ) % cols) != 0 ) spanned_rows++ return spanned_rows } where % is the modulus (or reminder) operator A: int calc_rows(int start,int length){ int rows = 0; int x= 0; if (start != 0){ x = 6%start; rows+=1; } if ((start+length) % 6 != 0){ x +=(start+length) % 6; rows+=1; } rows+= (length - x)/6; return rows; } calculates number of rows by dividing by 6 but after subtracting partially filled rows count A: In case you only want the number of rows you can calculate num_rows = (offset + size + cols - 1) / cols which in this case is num_rows = (4 + 8 + 6 - 1) / 6 = 17 / 6 = 2
{ "language": "en", "url": "https://stackoverflow.com/questions/5859784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fortify- spring-boot-starter-actuator deserialization vulnerability with latest spring boot version I am facing Dynamic Code Evaluation: Unsafe Deserialization in fortify scan with latest spring boot version 2.2.4 Release. can you anyone help to resolve this issue?
{ "language": "en", "url": "https://stackoverflow.com/questions/60494640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: javascript syntax reader is wrong? i have this code , don't get me wrong it all work fine var w = "window" , gg = "gg" , pr = "prototype" , al = "alert" , pi = "parseInt" , st = String , ts = "toString"; st[pr][gg] = function(){return window[this[ts]()];}; w = w[gg](); w[al](w[pi]("0")); the problem starts when i replace this piece of code w = w[gg](); w[al](w[pi]("0")); with this one w[gg]()[al](w[pi]("0")); now it's not working. i don't get it , it suppose to get the same result , what is wrong here? A: There are two places that w is used: w[al](w[pi]("0")); ^ ^ So you need to substitute in w[gg]() twice: w[gg]()[al](w[gg]()[pi]("0")); ^^^^^^^ ^^^^^^^ Note also that this transformation might still not equivalent, for example if w[gg]() has side-effects or is non-deterministic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7800420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql rollBack error from different database try{ $SQL=$user_db->prepare("INSERT INTO user (..."); $SQL->execute(); $id=$user->lastInsertId('user');//Need this id for next query //connect to 2nd db //$SQL2=$message_db->prepare("UPDATE...."); }catch{...} I have 2 queries from 2 different db is any way to roll back the error & stop process if there is any error? because its from 2 different db so I couldn't use transaction. ps.1st db is innodb, but my 2nd db is mysqlISAM (not support transaction)
{ "language": "en", "url": "https://stackoverflow.com/questions/19225847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic Route Matching -- how to bind an object key that contains a space? I am trying to use Vue Router dynamic route matching and have an object key of NAS ID with a space. How would I bind that to the router path? { path: '/:NAS ID', component: DataDetail } The above path value gives me an error in console: Expected "NAS" to be defined A: Route matching is powered by https://github.com/pillarjs/path-to-regexp . You can use their documentation to look for a similar case. My first guess would be to try escaping the space: path: '/:NAS\ ID'
{ "language": "en", "url": "https://stackoverflow.com/questions/51486522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript: on click change button text color Hey I have the below javascript code with accompanying HTML. I am trying to get each button when clicked to change the text color to blue and then when the next button is clicked it changes text of the previously clicked button back to green. basically only the most recently clicked button has blue text. I have tried this code but with this it changes all button text to blue on the first button click. Any help is appreciated. Javascript, HTML, and CSS below. function swapIphoneImage( tmpIPhoneImage ) { var el = document.getElementById('my-link'); var el1 = document.getElementById('my-link1'); var el2 = document.getElementById('my-link2'); var el3 = document.getElementById('my-link3'); var el4 = document.getElementById('my-link4'); var iphoneImage = document.getElementById('iphoneImage'); iphoneImage.src = tmpIPhoneImage; el.className = 'clicked-class'; el1.className = 'clicked-class1'; el2.className = 'clicked-class2'; el3.className = 'clicked-class3'; el4.className = 'clicked-class4'; } html <ul class="features"> <li><a id="my-link" href="javascript:swapIphoneImage('wscalendarws.png');" title="">HaPPPs Calendar</a></li> <li><a id="my-link1" href="javascript:swapIphoneImage('wsweekendws.png');" title="">Weekend Events</a></li> <li><a id="my-link2" href="javascript:swapIphoneImage('wsfollowingws.png');" title="">Places & People</a></li> <li><a id="my-link3" href="javascript:swapIphoneImage('wstemplateviewws.png');" title="">Customize Events</a></li> <li><a id="my-link4" href="javascript:swapIphoneImage('wscheckinws.png');" title="">Interaction</a></li> </ul> css a#my-link.clicked-class { color: #71a1ff !important; } a#my-link1.clicked-class1 { color: #71a1ff !important; } a#my-link2.clicked-class2 { color: #71a1ff !important; } a#my-link3.clicked-class3 { color: #71a1ff !important; } a#my-link4.clicked-class4 { color: #71a1ff !important; } Where am I failing? A: Try using JavaScript to change the classes then you only need one class to determine which one is clicked. Here is an example: JS: $("UL.features LI A").click(function(){ $("UL.features LI A").removeClass('clicked'); $(this).addClass('clicked'); }); CSS: A.clicked { color:#71a1ff !important; } Here it is in jsfiddle: http://jsfiddle.net/57PBm/ EDIT: This solution uses JQuery which will I would definitely suggest using if you are not already A: Rewrite JS code to: function swapIphoneImage( elThis, tmpIPhoneImage ) { var el = document.getElementByClassName('clicked-class'); var iphoneImage = document.getElementById('iphoneImage'); iphoneImage.src = tmpIPhoneImage; el.className = ''; elThis.className = 'clicked-class'; } and each button to: <li><a id="my-link" href="javascript:swapIphoneImage(this, 'wscalendarws.png');" title="">HaPPPs Calendar</a></li> You don't need to set up 5 CSS classes for the same thing. A: You are changing every element to a clicked class. Just pass in a number to the function that identifies which button to color blue, then color that one blue and all the others green via JS.
{ "language": "en", "url": "https://stackoverflow.com/questions/14845217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mongo C# Driver - How to apply ToLower() to a DistinctAsyc I am retrieving a list of strings from MongoDB using DistinctAsync. The problem is that the results are distinct except that I get some values all in uppercase and some are in lower case which count as distinct of course. How could I apply a .ToLower() to this query? public async Task<List<string>> GetAllAuthorsUserNames() { var filter = Builders<Episode>.Filter.Where(x => x.CreatedBy != null); var cursor = await GetCollection().DistinctAsync(o => o.CreatedBy, filter); return cursor.ToList(); } I have tried this but it doesn't work: var cursor = await GetCollection().DistinctAsync(o => o.CreatedBy.ToLower(), filter); A: There are various approaches you can take to yield the result you want. Some are: * *Store the authors's names in lowercase only (or at least in a consistent manner such that you do not have to transform their names to yield distinct ones among them in the first place) and in that case a distinct query alone is enough to get you the desired result. *After you fetch the distinct authors's names from the current data, map their names to their respective lowercase version in-memory and then apply another distinct function on it to get all authors's names in lowercase and distinct form. That will look like: var filter = ... var cursor = await GetCollection().DistinctAsync(v => v.CreatedBy, filter); var list = await cursor.ToListAsync(); var names = list.Select(v => v.ToLower()).Distinct().ToList(); *Use aggregation. Basically, you can project all authors's names to their respective lowercase form (see: toLower) and then group all the projected lowercase names to a set (see: addToSet). That set will be your result which you can extract from the aggregated result. My opinion is that you should consider altering your data so as to not add unnecessary computational complexity which takes up valuable resources. If that is not possible, but the names themselves are relatively few, you can use the second approach. Use the third approach with the understanding that it is not the ideal and it will add to more processing on the part of your DBMS.
{ "language": "en", "url": "https://stackoverflow.com/questions/55495999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add previous load count using the the present count and the timestamp column I have a table with the following columns id, timestamp, current load count, previous load count and it has many rows. I have values for all the first three columns, but for the "previous load count", I need to get the count of the date one day before the count of the current load count. See the below image (table example) to view the sample table For example: previous load count of id:4 is the count same as the current load count of id:5. Is there anyway to write a SQL statement to update the previous load count? A: Can you try this? SELECT [id] ,[timestamp] ,[current load count] ,LAG([current load count]) OVER (ORDER BY [timestamp] ASC, [id]) AS [previous load count] FROM [table] The LAG function can be used to access data from a previous row in the same result set without the use of a self-join. It is available after SQL Server 2012. In the example I added ordering by id, too - in case you have records with same date, but you can remove it if you like. A: If you need exactly one day before, consider a join: select t.*, tprev.load_count as prev_load_count from t left join t tprev on tprev.timestamp = dateadd(day, -1, t.timestamp); (Note: If the timestamp has a time component, you will need to convert to a date.) lag() gives you the data from the previous row. If you know you have no gaps, then these are equivalent. However, if there are gaps, then this returns NULL on the days after the gap. That appears to be what you are asking for. You can incorporate either this or lag() into an update: update t set prev_load_count = tprev.load_count from t join t tprev on tprev.timestamp = dateadd(day, -1, t.timestamp);
{ "language": "en", "url": "https://stackoverflow.com/questions/60612027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Qt. Is connection name valuable to connect to the MySQL server? Is connection name valuable to connect to the MySQL server? QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "conectionName"); A: No it is not, If you don't provide then a default name will be given but you can use that name to get that connection some where else. QSqlDatabase db = QSqlDatabase::database("connectionName"); Here's what documentation says. If connectionName is not specified, the new connection becomes the default connection for the application, and subsequent calls to database() without the connection name argument will return the default connection. If a connectionName is provided here, use database(connectionName) to retrieve the connection. So if you don't provide any name, then whenever the below will return you that connection. QSqlDatabase db = QSqlDatabase::database();
{ "language": "en", "url": "https://stackoverflow.com/questions/24639506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can we check whether empty partitions are present in Athena using lambda function code or query I am trying to fetch whether partition is added or not to Athena table using lambda function code. But when I use Select * from "table $partitions" where batch date ='yyyymmdd' It is showing error because in lambda function " is not taking. But with out " my code is not working. Can someone suggest anything on this
{ "language": "en", "url": "https://stackoverflow.com/questions/72092025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cyclomatic Complexity - Delphi API I am searching for a Cyclomatic Complexity Api in Delphi (2010). I need to create a program that will analize a source code and report the Cyclomatic Complexity of all methods in all classes (just like SourceMonitor does). I cant use other softwares, I really need to build one. Does anyone knows an API for delphi 2010 that does that? A: You'll need a language parser from which you can generate a control flow graph. Then you need to calculate the CC using this formula. I know of no library that will do this for you. You may be able to use the free pascal source to generate the control flow graph (its a common technique used in compilers to eliminate unreachable code). Unfortunately, Delphi hasn't shipped with a complete formal definition(bnf grammar) of the language in its documentation since Delphi 6 I believe. (even then it wasn't completely accurate) So all third party parsers are shooting in the dark.
{ "language": "en", "url": "https://stackoverflow.com/questions/4474044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need to redirect to 403 if / is not supplied by included conf I should say that i'm very new to Nginx so i'm sorry if this is a stupid question. In my Nginx configuration I use includes to determine wether or not I export a webpage. If export the web page I do I want the http://hostname/ to redirect to http://hostname/ui/. If not I would like to return 403 error code. The code in my included ui.conf contains this location block: location = / { return 302 " /ui"; } I want to define default behaviour when this is not included but when I add a location / in my regular nginx.conf I get an error saying I can't define the same location twice. what should I do? A: So what ended up working is using location = / { } in my ui.conf file and location / { } In my main conf file.
{ "language": "en", "url": "https://stackoverflow.com/questions/62281461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PF 11.0.0: which mojarra versions are supported? PF 11.0.0: which mojarra versions are supported? It is not specified in pom.xml. The showcase used to show the mojarra version, but not now. A: Based on documentation PrimeFaces 11 has dependency JSF with ver. 2.0, 2.1, 2.2, 2.3, 3.0, 4.0. Where JSF can be Apache MyFaces or Eclipse (former Oracle) Mojarra.
{ "language": "en", "url": "https://stackoverflow.com/questions/73241084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Add multiple users to multiple groups from one import csv I have a csv with 2 columns, one column is AD group names and one is user account names. I am trying to read the csv and import the users into their corresponding group. Here is what i have to so far. It's saying both arguments(identity,member) are null, which makes no sense since the headers are correctly specified. import-module activedirectory $list = import-csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" Foreach($user in $list){ add-adgroupmember -identity $_.Group -member $_.Accountname } Heres whats in the csv file Group Accountname group1 user1 group1 user2 group1 user3 group2 user4 group2 user5 group3 user6 group3 user7 group3 user8 group4 user9 group5 user10 EDIT Command and error Here is my script, error i receive and csv. Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups.csv" | ForEach { get-aduser $_.Accountname | add-adgroupmember $_.Group} A: Change this: add-adgroupmember -identity $_.Group -member $_.Accountname To this: add-adgroupmember -identity $user.Group -member (Get-ADUser $user.Accountname) A: @EBGreen has answered what's wrong with your code. Just coming up with an alternative here. Instead of running the command once per member, you can try to add all members of a group at the same time. The Member parameter supports an array, so try this: Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" | Group-Object Group | % { #Foreach Group, get ADUser object for users and add members $users = $_.Group | % { Get-ADUser $_.Accountname } Add-ADGroupMember -Identity $_.Name -Member $users } EDIT I've sucessfully tested this on 2012 DC with following content in test.csv (values represent existing group name and existing samaccountname/username): Group,Accountname "Mytestgroup","kim_akers" "Mytestgroup","user1" EDIT2 It shouldn't have any problems with deeper level OUs. I tested with an OU that was 7 levels deep and it had no problem. If you have all the user inside one OU (or find the closest OU that contains all the sub-OUs), see if this script helps. Remember to replace DN for "base OU" in -Searchbase parameter. Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" | Group-Object Group | % { #Foreach Group, get ADUser object for users and add members $users = $_.Group | % { Get-ADUser -Searchbase "OU=mybaseou,OU=test,OU=users,OU=contoso,DC=Contoso,DC=com" -Filter { samaccountname -eq $_.Accountname } } Add-ADGroupMember -Identity $_.Name -Member $users }
{ "language": "en", "url": "https://stackoverflow.com/questions/16651580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can't dissasemble function in Linux kdb I have kdb launched in my crashed Linux. And for some reason there is no id instruction in list of instructions (? command). So I can't disassemble any code. But here is some cheat-sheet, where we can see the id command in common list. So how could I disassemble any known function in Linux kernel with kdb?
{ "language": "en", "url": "https://stackoverflow.com/questions/63473925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a string variable in sql Postgresql Can someone help-me set up an SQL command that retrieves only the value of the first occurrence of "cost" in a string like the example below. See below two results returned from a table where I store sql query execution plan. I use Postgres. The word cost always comes at the beginning, but it does not always come in the same position, so you can not simply do substring (...). I think you should find the initial and final position every time, to be able to extract only the cost value. If anyone can help me, the expected result for the example below is: select (.... ) ----------------- cost=399301 (only this) ----------------------SAMPLE STRING SOURCE ------------------ Sort (cost=399301.55..399301.57 rows=6 width=36) Sort Key: l_returnflag, l_linestatus -> HashAggregate (cost=399301.21..399301.48 rows=6 width=36) -> Seq Scan on h_lineitem (cost=0.00..250095.98 rows=5968209 width=36) Filter: (l_shipdate <= (to_date('1998/12/01'::text, 'YYYY/MM/DD'::text) - '10 days'::interval day)) -------------------- SECOND SAMPLE -------------------------------- Aggregate (cost=7922058.70..7922058.71 rows=1 width=16)" -> Hash Join (cost=1899763.92..7922058.69 rows=1 width=16)" Hash Cond: (h_lineitem.l_partkey = h_part.p_partkey)" Join Filter: (((h_part.p_brand = 'Brand#13'::bpchar) AND (h_part.p_container = ANY ('{"SM CASE","SM BOX","SM PACK","SM PKG"}'::bpchar[])) AND (h_lineitem.l_quantity >= 4::double precision) AND (h_lineitem.l_quantity <= 14::double precision) AND (h_ (...)" -> Seq Scan on h_lineitem (cost=0.00..235156.84 rows=211094 width=32)" Filter: ((l_shipmode = ANY ('{AIR,"AIR REG"}'::bpchar[])) AND (l_shipinstruct = 'DELIVER IN PERSON'::bpchar))" -> Hash (cost=1183158.46..1183158.46 rows=35278997 width=33) -> Seq Scan on h_part (cost=0.00..1183158.46 rows=35278997 width=33) Filter: (p_size >= 1)" Best Regards A: Assuming the plans are stored in a table named plan_table in a column named execution_plan you can use the following: select replace(substring(execution_plan from '\(cost=[0-9]+'), '(cost=', '') from plan_table; The substring(...) returns the first occurrence of (cost= and the replace is then used to remove that prefix. A: I get successful and the solution, the obcjetive was get the value 27726324.41, the Expression Regular final developted is: select substring('Aggregate (cost=27726324.40..27726324.41 Rows' from '[.]Y*([0-9]+.?[0-9]{2})') RESULT 27726324.41 Thanks a_horse_with_no_name and anothers that help-me.
{ "language": "en", "url": "https://stackoverflow.com/questions/41653300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: maven assembly dir with a jar dependency from project I am trying to use maven to assemble a directory for a install package. The install package requires several things: configuration files, dependency libraries and an executable jar of my class files. I am having trouble figuring out how to add the executable jar. Here is what I have so far: <project> <modelVersion>4.0.0</modelVersion> <groupId>com.myproject</groupId> <artifactId>myproject</artifactId> <version>8.1.1</version> <name>my project</name> <packaging>pom</packaging> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.2-beta-2</version> <configuration> <descriptor>${basedir}/src/main/assembly/client.xml</descriptor> </configuration> <executions> <execution> <id>create-client</id> <configuration> <descriptor>${basedir}/src/main/assembly/client.xml</descriptor> </configuration> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencies> . . . </dependencies> </project> Then my assembly descriptor looks like this: <assembly> <id>client</id> <formats> <format>dir</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <fileSets> <fileSet> <directory>${basedir}/src/main/reports</directory> <outputDirectory>/reports</outputDirectory> </fileSet> <fileSet> <directory>${basedir}/src/main/resources/audio</directory> <outputDirectory>/audio</outputDirectory> </fileSet> <fileSet> <directory>${basedir}/src/main/client</directory> <outputDirectory>/</outputDirectory> </fileSet> </fileSets> <dependencySets> <dependencySet> <scope>runtime</scope> <useProjectArtifact>false</useProjectArtifact> <outputDirectory>lib</outputDirectory> <unpack>false</unpack> </dependencySet> </dependencySets> </assembly> If i call mvn assembly:assembly I get a directory with all the libraries and configuration files. Works great. But now I want to add an executable jar of all my compiled code. I can create this jar alone by adding this to my pom and calling mvn jar:jar <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <configuration> <finalName>run</finalName> <archive> <manifest> <mainClass>com.myproject.main.StartProcess</mainClass> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> </manifest> </archive> </configuration> </plugin> The question is, how can I get that jar into my assembly automatically? I have tried a couple things but I have no idea where to start. Can I somehow call the jar execution from my assembly? Any help appreciated. A: I think you should turn your useProjectArtifact to true (this is the default value). It determines whether the artifact produced during the current project's build should be included in this dependency set.
{ "language": "en", "url": "https://stackoverflow.com/questions/9526978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why Index object is not shared across different pandas objects that are reindexed with it? As per pandas docs, Index objects can be shared between different series and dataframes. So let's say I have the following: df = pd.DataFrame(np.random.randn(5, 2), index=list("abcde"), columns=["x", "y"]) s = pd.Series(np.random.randn(5), index=list("abcde")) It's also clearly stated that passing an Index object directly to reindex() is preferable to passing an array-like object, since it avoids duplicating data. So I'm assuming that: rs = s.reindex(df.index) would use the same Index object for s as for df. However: rs.index is df.index is False, and I cannot understand why. Am I missing or misunderstanding something, or I'm reading an outdated section in docs?
{ "language": "en", "url": "https://stackoverflow.com/questions/68637322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create large amount of user accounts in OS X Lion Server's Server App/Server Admin/Workgroup Manager I'm trying to managing iOS devices by OS X Lion Server on Mac Mini. Now I need to create more than 100 user accounts in Server App. If there's any way to do this without creating each account one by one? Writing script? http://manuals.info.apple.com/en_US/UserMgmt_v10.6.pdf According to this document, the exported file of accounts is a XML file. But I find no where to create or edit this file in a efficient way. A: If you are using Open Directory (which you probably should with that amount of users) one option is to use dscl which is probably a little easier to automate. There's a thread at Apple Discussions describing how to add users to a group. A: Workgroup Manager (part of the Server Admin Tools package) can import tab-delimited text files with a little work. When you do the import, you'll need to tell it the file's format -- what the record and field delimiters are (generally newline and tab), then what data each field contains. See this video for an example of the process. If you need to set attributes that aren't in the file, you can either select all of the imported accounts and set the attribute for all of them at once (the video shows doing this for the home directory location), or (if you think of it before doing the import) create a template account with the relevant settings, save it as a preset (there's a pop-up menu at the bottom of WGM's window), then select that preset in the import dialog box. A: Try using Passenger http://macinmind.com/?area=app&app=passenger&pg=info If you have more than 20 users you might want to buy it for $60 or do what I do and group them by 20 users and run it 5 times.
{ "language": "en", "url": "https://stackoverflow.com/questions/10649984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to delete published branch without creating pull request on github console Is there any way to delete the published branch without creating a pull request and merging it into the default branch on the GitHub console. One way I know is to create a pull request and then close it, then I am able to delete that branch. Edit :- I could not find exisiting question on SO with below conditions - * *How to delete branch without raising pull request. *How to do it on GitHub website. Thanks. A: Just found a solution for this. Click on the branches tab shown below - Delete your published banch from the list -
{ "language": "en", "url": "https://stackoverflow.com/questions/63986489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: cant able to print first 20 even and odd numbers in assemble language I am using procedures for printing even and odd numbers but it is not working what is wrong with my code? since I am new to assembly language This is my main funtion: .data S BYTE ? .code main proc call ven MOV AH,4ch INT 21h main endp this is my procedure: ven proc MOV S,0 \\ S is a variable L1: JE ter MOV AX,S MOV bl,2 DIV bl CMP AH,0 JE EVE JNE ODD EVE: MOV AH,2 MOV DL,AL INT 21h jmp L1 ODD: MOV AH,2 MOV DL,AL INT 21h jmp L1 ter: RET ven ENDP END MAIN is there is something with my ven procedure aur I am linking it with main with a wrong manner. A: there are some little errors in you code, I fixed them and pointed them with arrows (◄■■■) : .stack 100h ;◄■■■ PROCEDURES REQUIERE STACK. .data S dw ? ;◄■■■ DW, NOT BYTE, BECAUSE AX IS TYPE DW. .code main proc call ven ;call outdec MOV AH,4ch INT 21h main endp ven proc MOV S,0 L1: INC S ;◄■■■ S+1 CMP S,20 ;◄■■■ IF S > 20... JA ter ;◄■■■ ...JUMP TO TER. MOV AX,S MOV bl,2 DIV bl CMP AH,0 JE EVE JNE ODD EVE: MOV AH,2 MOV DL,AL ;◄■■■ HERE YOU PRINT "AL", BUT THE NUMBER INT 21h ;◄■■■ TO PRINT IS "S". USE "CALL OUTDEC". jmp L1 ODD: MOV AH,2 MOV DL,AL ;◄■■■ HERE YOU PRINT "AL", BUT THE NUMBER INT 21h ;◄■■■ TO PRINT IS "S". USE "CALL OUTDEC". jmp L1 ter: RET ven ENDP END MAIN
{ "language": "en", "url": "https://stackoverflow.com/questions/39980368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android google maps API 2 got JSONException:org.json.JSONException: Index 0 out of range [0..0) at org.json.JSONArray.get(JSONArray.java:263) I am drawing route between 18 locations to draw the google map v2.When i start fetching routes it draws route but some times it is not drawing route and it gives JSONException :org.json.JSONException: Index 0 out of range [0..0) at org.json.JSONArray.get(JSONArray.java:263) and also it gives "error_message" : "You have exceeded your daily request quota for this API." "routes" : [] "status" : "OVER_QUERY_LIMIT" public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public String getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } json = sb.toString(); is.close(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } Log.d("JSON_RUTA", json); return json; } } private String makeURL(double sourcelat, double sourcelog, double destlat, double destlog, String mode) { StringBuilder urlString = new StringBuilder(); if (mode == null) mode = "driving"; urlString.append("http://maps.googleapis.com/maps/api/directions/json"); urlString.append("?origin=");// from urlString.append(Double.toString(sourcelat)); urlString.append(","); urlString.append(Double.toString(sourcelog)); urlString.append("&destination=");// to urlString.append(Double.toString(destlat)); urlString.append(","); urlString.append(Double.toString(destlog)); urlString.append("&sensor=false&mode=" + mode + "&units=metric"); return urlString.toString(); } private List<LatLng> decodePoly(String encoded) { List<LatLng> poly = new ArrayList<LatLng>(); int index = 0, len = encoded.length(); int lat = 0, lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5))); poly.add(p); } return poly; } try { // Tranform the string into a json object final JSONObject json = new JSONObject(result); JSONArray routeArray = json.getJSONArray("routes"); JSONObject routes = routeArray.getJSONObject(0); JSONObject overviewPolylines = routes.getJSONObject("overview_polyline"); encodedString = overviewPolylines.getString("points"); List<LatLng> list = decodePoly(encodedString); } catch (JSONException e) { e.printStackTrace(); } for (int z = 0; z < list.size() - 1; z++) { LatLng src = list.get(z); LatLng dest = list.get(z + 1); Polyline line = mMap.addPolyline(new PolylineOptions() .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude)).width(4) .color(Color.BLUE).geodesic(true)); line.isVisible(); } Can any one suggest me what ll be the solutions for this? Thanks in advance. A: I faced the same problem before, and it was not because of Json. It was because of sending too much requests to google in a period. So I just slow down the frequency of sending post to Google, and never seen this message again. A: what @ohyes means is that you send multiple (too much) requests to google using your API key in too short of a time (for example, over 100 in a minute - just an example). for that you are receiving the OVER_QUERY_LIMIT and the empty JSON array while you should consider changing the time between the requests, you should also verify that the array received in fact has any elements try { // Tranform the string into a json object final JSONObject json = new JSONObject(result); JSONArray routeArray = json.getJSONArray("routes"); if(routeArray.size() > 0) { JSONObject routes = routeArray.getJSONObject(0); JSONObject overviewPolylines = routes.getJSONObject("overview_polyline"); encodedString = overviewPolylines.getString("points"); List<LatLng> list = decodePoly(encodedString); } } catch (JSONException e) { e.printStackTrace(); } That would solve the exception being thrown, but it won't solve the fact that you are getting no result, probably because of the too much requests EDIT: The OVER_QUERY_LIMIT thing happens (probably) because of too fast calls to getJSONFromUrl() function. Please add the code that makes these calls so we could try and be more helpful on that. Probably 500 ms delay is not enough (I'm assuming you're doing this on a background thread and not Sleeping the UI thread as this is a bad habbit). try increasing the delay to something very high, such as a minute (60000 ms) and see if this helps. If it does, lower that number to the lowest one that works. And add the code please.
{ "language": "en", "url": "https://stackoverflow.com/questions/20700478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: WPF UI to Screenshots I have a WPF application which has a toolbox with items same as Visual Studio. These items can be dragged on to the gird and configured. Each item has its own configuration i.e., different textboxes, dropdowns etc. Similar to Visio user will connects items if required (two or more). We call this as a Playlist (collections of items with different configurations). I have a requirement to present the configuration of a playlist in a report. The customer will be using this playlist report to recreate the playlist. All configurations are saved in XML. I am able to deserialise the XML and show it in the report but ideally the customer would like screenshots of each item in the report or some other format. How can i achieve it? Sorry if it is a very wide question. Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/47017637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unknown register name "r0" in asm I'm in the process of converting an iOS 32-bit app to a 64-bit binary. I was able to build and test the app fine on the simulator and device however when I build for distribution to the App Store I get an error: Unknown register name "r0" in asm The debugger points to this line: VFP_VECTOR_LENGTH_ZERO : "=r" (result), "=r" (m2) : "r" (m1), "0" (result), "1" (m2) : "r0", "cc", "memory", VFP_CLOBBER_S0_S31 ); I saw a similar post here however i'm unsure what the solution is. Any assistance would be much appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/43370619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to copy multiple element values from XML value into a table? I have following script, and I want to fill AddOnFeatureEnum values in #rewardscusts table : DECLARE @AddOnFeatures AS VARCHAR(1500) DECLARE @AddOnFeaturesXML AS XML SET @AddOnFeatures = '<p1:Addons xmlns:p1="http://www.alarm.com/WebServices"><p1:AddOnFeatureEnum>WeatherToPanel</p1:AddOnFeatureEnum><p1:AddOnFeatureEnum>EnterpriseNotices</p1:AddOnFeatureEnum></p1:Addons>' SET @AddOnFeaturesXML = CAST(@AddOnFeatures AS XML) SELECT @AddOnFeaturesXML CREATE TABLE #rewardscusts (AddOnFeature VARCHAR(100) primary key) -- I want to fill AddOnFeatureEnum values in #rewardscusts table please DROP TABLE #rewardscusts A: This is one possible way by shredding the XML on p1:AddOnFeatureEnum elements (reference nodes() method for this part), then use value() method on the shredded elements to extract the varchar(100) values : ;WITH XMLNAMESPACES('http://www.alarm.com/WebServices' as p1) INSERT INTO #rewardscusts SELECT enum.value('.','varchar(100)') FROM @AddOnFeaturesXML.nodes('/p1:Addons/p1:AddOnFeatureEnum') as T(enum) This is full working demo codes : DECLARE @AddOnFeatures AS VARCHAR(1500) DECLARE @AddOnFeaturesXML AS XML SET @AddOnFeatures = '<p1:Addons xmlns:p1="http://www.alarm.com/WebServices"><p1:AddOnFeatureEnum>WeatherToPanel</p1:AddOnFeatureEnum><p1:AddOnFeatureEnum>EnterpriseNotices</p1:AddOnFeatureEnum></p1:Addons>' SET @AddOnFeaturesXML = CAST(@AddOnFeatures AS XML) DECLARE @rewardscusts TABLE(AddOnFeature VARCHAR(100) primary key) ;WITH XMLNAMESPACES('http://www.alarm.com/WebServices' as p1) INSERT INTO @rewardscusts SELECT x.value('.','varchar(100)') FROM @AddOnFeaturesXML.nodes('/p1:Addons/p1:AddOnFeatureEnum') as T(x) SELECT * FROM @rewardscusts output : | AddOnFeature | |-------------------| | EnterpriseNotices | | WeatherToPanel |
{ "language": "en", "url": "https://stackoverflow.com/questions/31953265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: List emailAddress how to replace value in a particular string I have the following method /// <summary> /// Replaces SemiColons with commas because SMTP client does not accept semi colons /// </summary> /// <param name="emailAddresses"></param> public static List<string> ReplaceSemiColon(List<string> emailAddresses) // Note only one string in the list... { foreach (string email in emailAddresses) { email.Replace(";", ","); } //emailAddresses.Select(x => x.Replace(";", ",")); // Not working either return emailAddresses; } However the email string is not replacing the ";" with the ",". What am I missing? A: I think you should try setting it back to itself email = email.Replace(";", ","); A: String.Replace method returns new string. It doesn't change existing one. Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String. As Habib mentioned, using foreach with the current list gets a foreach iteration variable error. It is a read-only iteration. Create a new list and then add replaced values to it instead. Also you can use for loop for modifying existing list which keyboardP explained on his answer. List<string> newemailAddresses = new List<string>(); foreach (string email in emailAddresses) { newemailAddresses.Add(email.Replace(";", ",")); } return newemailAddresses; Be aware since strings are immutable types, you can't change them. Even if you think you change them, you actually create new strings object. A: As others have already mentioned that strings are immutable (string.Replace would return a new string, it will not modify the existing one) and you can't modify the list inside a foreach loop. You can either use a for loop to modify an existing list or use LINQ to create a new list and assign it back to existing one. Like: emailAddresses = emailAddresses.Select(r => r.Replace(";", ",")).ToList(); Remember to include using System.Linq; A: Strings are immutable so another string is returned. Try for(int i = 0; i < emailAddress.Count; i++) { emailAddress[i] = emailAddress[i].Replace(";", ","); } A foreach loop would not compile here because you're trying to change the iteration variable. You'd run into this issue. A: You should use somthing like: var tmpList = new List(); add each modified email address to the tmplist and when you are done, return the TmpList. In .NET strings are inmutable, that's why your code doesnt work.
{ "language": "en", "url": "https://stackoverflow.com/questions/19053047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how can i avoid asking username and password for facebook in my UIWebView? in my app i need a facebook like button. when user will click that button it ll like a facebook group. i used a UIWebView and used iframe in that. now i have a local html document which is loaded when user click on the webView. but when i click on the webView it asks for facebook user name and password. i also have a publish button which uses facebook api. once its loged in it doesn't ask username and password again. but webView asks always. how can i get auto login in webView? A: This may help you http://forum.developers.facebook.net/viewtopic.php?id=37430
{ "language": "en", "url": "https://stackoverflow.com/questions/5169503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails / Dalli: expire fragment from another namespace I have two apps connecting to memcached servers on different namespaces, for example's sake we'll call them "admin" and "users". Every now and then I want to expire some fragments in the "users" namespace from the admin application. Note: I am not caching/expiring actions as per the other several questions/answers I found here. I want to expire keys such as "abcde". I cache all sorts of things, AR results, JSON, and so on. Already tried things like: Rails.cache.delete("abcd") Rails.cache.delete("users/abcd") Rails.cache.delete("/users/abcd") Digests are off. How do I do this? A: If your rails cache is configured with a namespace, that namespace will be prepended to the cache key automatically. So, when you Rails.cache.write("FOO", "BAR") the key will actually be $NAMESPACE:FOO. Keys are just strings and can't be navigated like a file system or anything fancy (AFAIK). I think your best option is instantiate a separate instance of a dalli client for your alternative namespace to delete the key.
{ "language": "en", "url": "https://stackoverflow.com/questions/47291489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get aggs count/buctuks from Flux I'm trying the Elasticsearch aggregations in spring webflux. I what to know how to get the buckets values (inside buckets count) from Flux<AggregationContainer<?>> in Java API and total records in elasticsearch. Request: order/_search { "size": 0, "aggs": { "status": { "terms": { "field":"order_status" , "size": 100}}}} Response: { "took" : 1, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { ..... }, "aggregations" : { "status" : { "buckets" : [ { "key" : "CREATED", "doc_count" : 34 }, ..... { "key" : "CANCELLED", "doc_count" : 2 }, { "key" : "COMPLETED", "doc_count" : 1 } ] } } } Java imp: @Autowired private ReactiveElasticsearchOperations operations; Flux<AggregationContainer<?>> result = operations.aggregate(searchQuery, Count.class, "indexs");
{ "language": "en", "url": "https://stackoverflow.com/questions/74213060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing data from one screen to another screen in iPhone using phone gap I have just started to look into the phone gap.I have created one basic form which taking the data of the employee.I have table view in another screen .I want to pass the employee details to the second screen .I was googling for this purpose.I have found that there are some ways to do this like: 1.Server side post back 2. Client side URL examination 3.What's in a window.name = local cross-page session 4.HTML5 local storage 5. Cookies But will my phone gap application be 100% native by using these ways? Is there any alternate way or tutorial to pass the data between the screens? A: What you actually mean by "a screen"? If you're talking about a pop-up dialog box or page by jQuery Mobile you can probably serialize the form with jQuery and assign it to a JavaSCript variable. But if you're changing your "screen" by changing UIView to a different url you can use either: * *File API to store serialized form in a file and load it on the 2nd "screen" *Storage API to ... actually do the same I'd go for number one, as it's easier to implement than using SQL and writing loads of additional code. Search for: * *jQuery.serialize() *PhoneGap File API
{ "language": "en", "url": "https://stackoverflow.com/questions/12419324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to validate forms when a user changes the name of an input element in firebug? I realize it's impossible to prevent someone from changing the names of input elements in firebug. How should I approach this problem? A user changes the name of the input element "firstname" to "month" and visa versa. <form action="example.php" method="post" enctype="multipart/form-data"> <table border='2'> <tr> <td> First name: <input type="text" name="firstname" /><br /> </td> </tr> <tr> <td> Last name: <input type="text" name="lastname" /><br /> </td> </tr> <tr> <td>Birth Month: <select name="month"> <option value="01">January</option> <option value="02">February</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <br /> </td> </tr> <tr> <td><input type="submit" name="Submit" value="Sign Up!" /></td> </tr> </table> </form> My best idea so far is: <?php $month= $_POST['month']; if($month!= 01 || $month!= 02 ... $month!= 12) echo 'wrong month'; ?> However this won't be clean for the year of birth... Facebook does a great job of preventing this when you sign up but I wasn't able to figure out what they did. A non-javascript solution would be much appreciated. EDIT: Lawrence, what do you recommend for a location form? A: Going through each month in a condition is unneeded, php has functions for that. <?php $firstname= (string)$_POST['firstname']; $lastname = (string)$_POST['lastname']; $month = $_POST['month']; if(in_array($month,range(01,12))===true){ $cont = TRUE; }else{ $cont = FALSE; } //If set, not empty, not swapped for month & greater or equals to 6 chars if(isset($firstname) && $firstname!="" && strlen($firstname) >=6 && in_array($month,range(01,12))===false){ $cont = TRUE; } //If set, not empty, not swapped for month & greater or equals to 6 chars if(isset($lastname) && $lastname!="" && strlen($lastname) >=6 && in_array($month,range(01,12))===false){ $cont = TRUE; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/6718351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows OpenFileDialog with more than one file type I want to open a Windows OpenFileDialog with two possible selections: foo*bar.xml *.xml The file name wildcard is specified with the FileName property but it applies to every file selection specified with the Filter property. With the Filter property, users can select more than one set of file types, but is there a way to specify different file names in one dialog? Paul A: The file name wildcard is specified with the FileName property That doesn't work, only the Filter property can be used to filter files. Furthermore, a wildcard like foo*bar.xml does do what you hope it does, anything past the * is ignored. A wildcard doesn't behave like a regular expression at all. This goes way, way back to early operating systems that didn't have the horsepower to implement regex. Definitely at CP/M, probably as far back as RSX. Options are very limited, you can specify multiple wildcards by separating them with a ; semicolon. Like "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*". But that's as far as you can push it.
{ "language": "en", "url": "https://stackoverflow.com/questions/11727236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WSO2 Enterprise Integrator (6.5) - how to Store and retrieve Registry data using dynamic registry path I have a sequence to utilise an API which issues time-constrained bearer tokens from an authorization endpoint based on client ID and Secret. The Bearer Token remains valid for 1 hour and so I'm storing the bearer token and its expiry time in the registry whenever I renew the token and on subsequent calls will use the stored token rather than request a new one - unless it's expired. This is all working as expected - however - it is feasible that this Sequence could be called from processes that have different client IDs - so for scalability I would like to modify the process so the Token and expiry are held under a registry branch for each client_id. I'm unable to find a way to dynamically create the registry entries to incorporate the client_id in the registry path. I can Read from a dynamic path successfully as follows: <property expression="get-property('registry', fn:concat('conf:/resource/MyApplication/',$ctx:client_id,'/TokenExpiry'))" name="RegBearerExpiryStr" scope="default" type="STRING"/> but I cannot work out how to successfully Write a registry entry in a similar fashion. I have tried the following with no success - I can see from the wire logs that everything in the key name is being interpreted literally : <property expression="json-eval($.access_token)" name="fn:concat('conf:/resource/MyApplication/',$ctx:client_id,'/TokenExpiry'))" scope="registry" type="STRING"/> and <property expression="json-eval($.access_token)" name="conf:/resource/MyApplication/{$ctx:client_id}/TokenExpiry" scope="registry" type="STRING"/> I'm running EI 6.4 and 6.5 Any brilliant ideas - there must surely be a way to create a dynamic path for writing as well as reading ? A: I personally use jsonObject XML and use OM type for storing complex types as WSO2 has better xml type support. <property expression="//jsonObject" name="token" scope="default" type="OM"/> <property name="conf:/storage/SampleToken.xml" scope="registry" expression="$ctx:token" type="OM"/> But, there is one "pitfall", as WSO2 are cacheing the registry entries for default 15seconds. So you will read old values for some time. If that is a problem i use workaround. I use script mediator for better handling that, and with checking if that resource exist or not. I tested it on EI 6.5 <script language="js"><![CDATA[ var regUrl = mc.getProperty('regUrl'); var registry = mc.getConfiguration().getRegistry(); if(registry.isResourceExists(regUrl) == false) { registry.newResource(regUrl, false); } registry.updateResource(regUrl,mc.getProperty('token')); var regEntry = registry.getRegistryEntry(regUrl); regEntry.setCachableDuration(0); registry.updateRegistryEntry(regEntry);]]> </script> I also made some blog post, may be also useful:: Reading, modifying and writing data in WSO2 Enterprise Integrator registry on an example
{ "language": "en", "url": "https://stackoverflow.com/questions/74705511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: excel how to use index and match to match the data Morning, My fault, let me converted to English. My concern is that I do not know how to connect table_1's category with the table_2's column and then found the correct color A: You need to use either the VLOOKUP or HLOOKUP feature when structuring your results table. For instance in cell C3 (color for head/set1) you would type =HLOOKUP(a2,e2:h5,2,FALSE). It will look horizontally in the first row for whatever is in cell A2 (HEAD) and return the value from the 2nd row (RED). Of flip it around to use HLOOKUP. https://support.office.com/en-us/article/hlookup-function-a3034eec-b719-4ba3-bb65-e1ad662ed95f A: Please try this formula, to be entered in row 3 where columns A and B are "category" and "Sets" respectively. =VLOOKUP(B3,E1:H4,MATCH(A3,E1:H1,0),FALSE) E1:H4 represents your entire table2 incl captions. You can exclude the caption row - probably better. E1:H4 is the first row of that same range. There is presumed to be only one caption row which is needed, and must be 1 only. If you prefer a neater solution take the data column captions only and adjust the result. Then your formula might look like this. =VLOOKUP(B2,E2:H4,MATCH(A2,F1:H1,0)+1,FALSE)
{ "language": "en", "url": "https://stackoverflow.com/questions/60859655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Squarespace Code Block Alignment Issues We have custom coded animate flipping cards on our website. There is an issue with the alignment and sizing of them. The issue only occurs when there are multiple cards on the page (they are made using code blocks). You can see the issue on the link below. Any help would be appreciated! LINK TO SITE JSFIDDLE (ONLY 1 CARD...ISSUE DOESN'T SHOW UP) HTML: <div class="flip-container" ontouchstart="this.classList.toggle('focus');"> <div class="flipper"> <div class="front-brian"> </div> <div class="back"> <div class="centerize"> <div class="socicon-style"> <a href="imdb.com"> <span class="socicon-imdb"> </span> </a> </div> <div class="back-title">Brian Perry</div> <div class="role">CEO</div> </div> </div> </div> CSS: .back { -webkit-transform: rotateY(180deg); -moz-transform: rotateY(180deg); -o-transform: rotateY(180deg); transform: rotateY(180deg); background: #bd2d2c; } .flip-container { -webkit-perspective: 1000; -moz-perspective: 1000; -o-perspective: 1000; perspective: 1000; } .flip-container:hover .flipper, .flip-container.hover .flipper { -webkit-transform: rotateY(180deg); -moz-transform: rotateY(180deg); -o-transform: rotateY(180deg); transform: rotateY(180deg); } .flip-container, .front-brian, .front-tony, .front-blaine, .front-alex, .front-eric, .front-sue, .front-tamara, .front-kenyon, .front-dom, .front-lt, .front-lindsey, .front-chris, .front-ethan, .back { width:6000px; min-height:100%; max-width:100%; max-height: 10000px; height:0; padding-bottom: 70%; } .flipper { -webkit-transition: 0.6s; -webkit-transform-style: preserve-3d; -moz-transition: 0.6s; -moz-transform-style: preserve-3d; -o-transition: 0.6s; -o-transform-style: preserve-3d; transition: 0.6s; transform-style: preserve-3d; position: relative; } .front-brian, .front-tony, .front-blaine, .front-alex, .front-eric, .front-sue, .front-tamara, .front-kenyon, .front-dom, .front-lt, .front-lindsey, .front-chris, .front-ethan, .back { -webkit-backface-visibility: hidden; -moz-backface-visibility: hidden; -o-backface-visibility: hidden; backface-visibility: hidden; position: absolute; top: 0; left: 100; } .front-brian{ background: url(http://static1.squarespace.com/static/573e762945bf219b6da541d1/t/57a5d191e3df28ea3c3f9bfb/1470484886737/Brian+Headshots-29.jpg); background-size: cover; background-repeat: no-repeat; background-position: 50% 50%; } .back-title { color: #fff; font-size: 2em; position: absolute; top: 14%; left: 0%; right: 0%; text-align: center; } .role { color: #fff; font-size: 1.5em; position: absolute; top: 30%; left: 0%; right: 0%; text-align: center; } A: This appears to be occurring because you have nested blocks. That is, each code-block ( .code-block ) is nested within the previous one, so each image is slightly more padded than the one before. See the attached image. Nested Squarespace Code Blocks - Dev. Tools Screenshot I'm not sure how this problem was created. Did you copy and paste code containing sqs-block code-block sqs-block-code elements? It appears that you did, at least at first glance. To fix this, you're going to need to remove all of the Squarespace-specific divs that wrap each of your flip-container divs. Within the code block, all you should have is a series of flip-container divs, one after another. Like this: <div class="flip-container" ontouchstart="this.classList.toggle('focus');">etc</div> <div class="flip-container" ontouchstart="this.classList.toggle('focus');">etc</div> <div class="flip-container" ontouchstart="this.classList.toggle('focus');">etc</div> <div class="flip-container" ontouchstart="this.classList.toggle('focus');">etc</div>
{ "language": "en", "url": "https://stackoverflow.com/questions/38824728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP code is rendered as text I'm using Ubuntu 16.04 and I want to run php files. I installed Php 7 on it using: sudo mkdir -p /var/www/html sudo chown -R $USER:$USER /var/www/html sudo apt install php sudo apt install apache2 I created a php file (e.g. test.php) in /var/www/html. I can access it in the browser (e.g. http://localhost/test.php). Instead of executing the <?php ... ?> code, it is displayed as plain text: I tried to turn short_open_tag to On. So I edited the /etc/php/7.0/fpm/php.ini and enabled it. Then I ran sudo service php7.0-fpm restart. This didn't make any change in the browser. The php code is still displayed as plain text. How can I fix this? A: You didn't install apache properly, doing an apt-get on apache2 does not install everything. what @newman stated is correct you can follow that guide, or here is a digitalocean link that is usuable for production server (since you would do this on a droplet). Note this is full stack LAMP, which I would assume you would get to eventually when you want to dab with mysql https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-14-04
{ "language": "en", "url": "https://stackoverflow.com/questions/36777886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How convert a Photoshop made logo into CSS properly? I am trying to convert a logo made into Photoshop in CSS. As i am no master of both, i've tried but greatly failed by using the Photoshop build in "copy css" function. I've tried to redo the CSS via my limited knowledge, but failed miserably. .Group_5 { position: absolute; left: 0px; top: 0px; width: 1920px; height: 1080px; z-index: 47; } .Group_4 { position: absolute; left: -2px; top: -2px; width: 1924px; height: 1084px; z-index: 46; } .Ellipse_3 { border-width: 6.25px; border-color: rgb(0, 0, 0); border-style: solid; border-radius: 50%; position: absolute; left: 1119px; top: 486px; width: 168.5px; height: 174.5px; z-index: 45; } .Ellipse_2 { border-width: 6.25px; border-color: rgb(0, 0, 0); border-style: solid; border-radius: 50%; position: absolute; left: 1122px; top: 505px; width: 139.5px; height: 139.5px; z-index: 44; } .Ellipse_1_copy { border-width: 6.25px; border-color: rgb(0, 0, 0); border-style: solid; border-radius: 50%; position: absolute; left: 1109px; top: 512px; width: 139.5px; height: 139.5px; z-index: 43; } .Ellipse_1 { border-width: 6.25px; border-color: rgb(0, 0, 0); border-style: solid; border-radius: 50%; position: absolute; left: 1091px; top: 492px; width: 176.5px; height: 176.5px; z-index: 42; } .Shape_26 { background-color: rgb(1, 1, 1); position: absolute; left: 1358px; top: 409px; width: 10px; height: 7px; z-index: 41; } .Shape_25 { background-color: rgb(1, 1, 1); position: absolute; left: 1347px; top: 409px; width: 18px; height: 17px; z-index: 40; } .Shape_24 { background-color: rgb(1, 1, 1); position: absolute; left: 1394px; top: 409px; width: 11px; height: 7px; z-index: 39; } .Shape_23 { background-color: rgb(1, 1, 1); position: absolute; left: 1385px; top: 408px; width: 21px; height: 20px; z-index: 38; } .Shape_22 { background-color: rgb(1, 1, 1); position: absolute; left: 1386px; top: 430px; width: 20px; height: 20px; z-index: 37; } .Group_2 { position: absolute; left: 2px; top: 2px; width: 1920px; height: 1080px; z-index: 36; } .Shape_16_copy_2 { background-color: rgb(1, 1, 1); position: absolute; left: 1395px; top: 410px; width: 8px; height: 26px; z-index: 35; } .Shape_16_copy { background-color: rgb(1, 1, 1); position: absolute; left: 1384px; top: 419px; width: 8px; height: 25px; z-index: 34; } .Shape_16 { background-color: rgb(1, 1, 1); position: absolute; left: 1346px; top: 419px; width: 8px; height: 25px; z-index: 33; } .Shape_15 { background-color: rgb(1, 1, 1); position: absolute; left: 1346px; top: 439px; width: 46px; height: 8px; z-index: 32; } .Shape_19 { border-width: 4.167px; border-color: rgb(0, 0, 0); border-style: solid; position: absolute; left: 1357px; top: 407px; width: 37.666px; height: 0; z-index: 31; } .Shape_21_copy { background-color: rgb(1, 1, 1); position: absolute; left: 1344px; top: 407px; width: 19px; height: 18px; z-index: 30; } .Shape_21 { background-color: rgb(1, 1, 1); position: absolute; left: 1383px; top: 407px; width: 20px; height: 18px; z-index: 29; } .Shape_20 { background-color: rgb(1, 1, 1); position: absolute; left: 1395px; top: 409px; width: 8px; height: 7px; z-index: 28; } .Shape_18 { background-color: rgb(1, 1, 1); position: absolute; left: 1346px; top: 417px; width: 46px; height: 8px; z-index: 27; } .Shape_17_copy { background-color: rgb(1, 1, 1); position: absolute; left: 1381px; top: 408px; width: 20px; height: 19px; z-index: 26; } .Shape_17 { background-color: rgb(1, 1, 1); position: absolute; left: 1384px; top: 428px; width: 19px; height: 19px; z-index: 25; } .Group_1 { position: absolute; left: 2px; top: 2px; width: 1920px; height: 1080px; z-index: 23; } .Rectangle_1 { border-width: 4.167px; border-color: rgb(0, 0, 0); border-style: solid; position: absolute; left: 1325px; top: 472px; width: 48.666px; height: 19.666px; z-index: 22; } .Shape_10 { background-color: rgb(1, 1, 1); position: absolute; left: 1132px; top: 656px; width: 11px; height: 8px; z-index: 21; } .Shape_9 { background-color: rgb(1, 1, 1); position: absolute; left: 1394px; top: 423px; width: 41px; height: 242px; z-index: 20; } .Shape_8 { background-color: rgb(1, 1, 1); position: absolute; left: 1132px; top: 451px; width: 271px; height: 213px; z-index: 19; } .Shape_11 { background-color: rgb(1, 1, 1); position: absolute; left: 1132px; top: 450px; width: 17px; height: 8px; z-index: 18; } .Shape_7 { background-color: rgb(1, 1, 1); position: absolute; left: 1132px; top: 416px; width: 64px; height: 41px; z-index: 17; } .Shape_14 { background-color: rgb(1, 1, 1); position: absolute; left: 1427px; top: 417px; width: 8px; height: 215px; z-index: 16; } .Shape_13 { background-color: rgb(1, 1, 1); position: absolute; left: 1393px; top: 415px; width: 44px; height: 44px; z-index: 15; } .Shape_12 { background-color: rgb(1, 1, 1); position: absolute; left: 1144px; top: 416px; width: 302px; height: 42px; z-index: 14; } .Group_3 { position: absolute; left: 0px; top: 0px; width: 1920px; height: 1080px; z-index: 11; } .Shape_3 { background-color: rgb(1, 1, 1); position: absolute; left: 577px; top: 684px; width: 710px; height: 12px; z-index: 10; } .Shape_2 { background-color: rgb(1, 1, 1); position: absolute; left: 571px; top: 301px; width: 137px; height: 403px; z-index: 9; } .I { font-size: 283.333px; font-family: "Kozuka Gothic Pr6N"; color: rgb(0, 0, 0); line-height: 1.2; text-align: center; -moz-transform: matrix( 1,0,0,0.76592618857706,0,0); -webkit-transform: matrix( 1,0,0,0.76592618857706,0,0); -ms-transform: matrix( 1,0,0,0.76592618857706,0,0); position: absolute; left: 1043.001px; top: 406px; z-index: 7; } .C_copy_2 { font-size: 283.333px; font-family: "Kozuka Gothic Pro"; color: rgb(0, 0, 0); line-height: 1.2; text-align: center; -moz-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0); -webkit-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0); -ms-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0); position: absolute; left: 869.507px; top: 406.5px; z-index: 6; } .C { font-size: 283.333px; font-family: "Kozuka Gothic Pro"; color: rgb(0, 0, 0); line-height: 1.2; text-align: center; -moz-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0); -webkit-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0); -ms-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0); position: absolute; left: 711.507px; top: 406.5px; z-index: 5; } .Shape_4 { background-color: rgb(1, 1, 1); position: absolute; left: 685px; top: 289px; width: 98px; height: 212px; z-index: 4; } .Shape_1 { background-color: rgb(1, 1, 1); position: absolute; left: 693px; top: 309px; width: 89px; height: 191px; z-index: 3; } I might be just missplacing something, or the given CSS result is not working properly, as anything i do and/or try results into a blank page. I am not exactly sure how i could get this logo converted, as mentioned above i am no master in both. The logo is made of circiles/lines and the 2"C" texts. Some of the layers have masks on them for transparency (where they overlap) It's not the best made, as it was supposed to have the same thickness overall, but i would like a way to get into CSS form.
{ "language": "en", "url": "https://stackoverflow.com/questions/55521260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass a different argument conditionally I want to be able to change an argument to a function when a condition is met. Currently I am doing this which works, but I am repeating the first argument, is there a way to just change the second argument? credential = './credentials.json' if os.path.exists(credential): account = authenticate(client_config=secrets, credentials=credential) else: account = authenticate(client_config=secrets, serialize=credential) A: An elegant way is to use kwargs: credential = './credentials.json' key = "credentials" if os.path.exists(credentials) else "serialize" auth_kwargs = {"client_config": secrets, key: credential} account = authenticate(**auth_kwargs) A: I think your way is fine too, but you can do this credential = './credentials.json' params = {'serialize': credential} if os.path.exists(credentials): params['credentials'] = params.pop('serialize') account = authenticate(client_config=secrets, **params) A: You can pass an (unpacked) dictionary to a function: credential = './credentials.json' arguments = {'client_config': secrets, 'serialize': credential} # default if os.path.exists(credentials): arguments.pop('serialize') arguments['credentials'] = credential account = authenticate(**arguments) A: There is functools.partial for this: from functools import partial credential = './credentials.json' auth = partial(authenticate, client_config=secrets) if os.path.exists(credential): account = auth(credentials=credential) else: account = auth(serialize=credential)
{ "language": "en", "url": "https://stackoverflow.com/questions/66968563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pickle multiple machine learning model I have multilayer model consist of two models, kmeans and random forest classifier; that work inside single function. My question is how to pickle both and keep them work in sequence??? Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/72623676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I generate numbers in series using IntegerField in Django I have created a model where Integer field is among the field in my model, when each post is added I want to have number that will be generated in series in each post. Can I achieve by just using Integer field, Please help!!! models.py class Documents(models.Model): docs_name = models.CharField(max_length=200,verbose_name="Jina la Nyaraka") item_type = models.CharField(default="", max_length=100,verbose_name="Aina ya nyaraka" ) police_station = models.CharField(max_length=255, verbose_name="Kituo cha polisi") phone_no = models.CharField(verbose_name="Namba yako ya simu", max_length=10, blank=False, validators=[int_list_validator(sep=''),MinLengthValidator(10),]) date = models.DateTimeField(default=timezone.now,verbose_name="Date") Description = models.TextField(blank=True, null=True,verbose_name="Maelezo zaidi") pay_no = models.IntegerField(default=0,verbose_name="Namba ya malipo") publish = models.BooleanField(default=False) image = models.ImageField(upload_to="Documents",blank=False, verbose_name="Picha ya nyaraka") """docstring for Documents""" def __str__(self): return self.docs_name views.py @login_required def PostNew(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('loststuffapp:IndexView') else: form = PostForm() return render(request, 'loststuffapp/form.html', {'form': form}) A: well as far i can get it, you need to make some kind of sequence for your IntegerField. while it's not and id field, you can emmulate it by taking max value of that field among all objects: max_val = YourModelClass.objects.all().aggregate(Max('that_field_in_question')) # then just make new object, and assign max+1 to 'that_field_in_question' new_obj = YourModelClass('that_field_in_question'=max_val + 1) new_obj.save()
{ "language": "en", "url": "https://stackoverflow.com/questions/57506490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using UIRefreshControl in UIViewController with UITableView I wonder how i can use UIRefreshController for a UITableView inside a UIViewController. I want to implement pull-to-refresh functionality to TableView but i don't have a TableViewController. Is there a way to do this in xcode 6 (swift) A: Of course you can do this. Initiate a RefreshControl and simply put it as subview of your tableview. You don't necessarily need a UITableViewController for this. EDIT: Try something like this: let control = UIRefreshControl() control.addTarget(self, action: "action", forControlEvents: .ValueChanged) tableView.addSubview(control) A: Here's the Objective-C version that worked for me in case anyone needs it. I added it to viewDidLoad: UIRefreshControl *refresh = [[UIRefreshControl alloc] init]; [refresh addTarget: self action: @selector(didPullToRefresh:) forControlEvents: UIControlEventValueChanged]; [self.tableView addSubview: refresh]; Not a fan of UITableViewController...
{ "language": "en", "url": "https://stackoverflow.com/questions/28915689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Flutter paint(): is this legit? Rendering Renderobject in different context I try to render the child of a listitem (somewhere up) to a different place (widget) in the tree; In the approach below, BlendMask is the "target" widget that checks for and paints "source" widgets that got themself an GlobalKey which is stored in blendKeys. This works somewhat. And I'm not quite sure if I might fight the framework, or just missing some points... The problems are two: * *The minor one: This approach doesn't play nice with the debugger. It compiles and runs fine but every hot-reload (on save f.e.) throws an "can't findRenderObject() of inactive element". Maybe I miss some debug flag? *the real problem, that brought me here questioning the idea en gros: As mentioned, the Source-Widget is somewhere in the subtree of the child of a Scrollable (from a ListView.build f.e.): How can I update the Òffset for the srcChild.paint() when the list is scrolled? - without accessing the lists scrolController?! I tried listening via WidgetsBindingObservers didChangeMetrics on the state of the Source widget, but as feared no update on scroll. Maybe a strategically set RepaintBounderyis all it needs? *hope* :D Anyway, every tip much appreciated. Btw the is an extend of this question which itself extends this... class BlendMask extends SingleChildRenderObjectWidget { [...] @override RenderObject createRenderObject(context) { return RenderBlendMask(); } } class RenderBlendMask extends RenderProxyBox { [...] @override void paint(PaintingContext context, offset) { <-- the target where we want to render a widget [...] from somewhere else in the tree! for (GlobalKey key in blendKeys) { if (key.currentContext != null) { RenderObject? srcChild <-- the source we want to render in this sibling widget! = key.currentContext!.findRenderObject(); if (srcChild != null) { Matrix4 mOffset = srcChild.getTransformTo(null); context.pushTransform(true, offset, mOffset, (context, offset) { srcChild.paint(context, offset); }); } } } } } //RenderBlendMask
{ "language": "en", "url": "https://stackoverflow.com/questions/70637401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difficulty screen scraping http://www.momondo.com using nokogiri I have some difficulty to extract the total price (css selector = '.total') from the flight result. http://www.momondo.com/multicity/?Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false I get the error "undefined method `text' for nil:NilClass nokogiri ". My code desc "Fetch product prices" task :fetch_details => :environment do require 'nokogiri' require 'open-uri' include ERB::Util OneWayFlight.find_all_by_money(nil).each do |flight| url = "http://www.momondo.com/multicity/Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false" doc = Nokogiri::HTML(open(url)) price = doc.at_css(".total").text[/[0-9\.]+/] flight.update_attribute(:price, price) end end A: The content you're attempting to scrape appears to be populated by JS after the page loads. To see for yourself, inspect the content of div#flight_results of the document you're currently parsing: url = 'http://www.momondo.com/multicity/?Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false' doc = Nokogiri::HTML(open(url)) doc.at_css('div#flight_results').to_html #=> '<div id="flight_results"></div>' Though it is outside of the scope of this question, you can generally reconstruct the JS requests used to populate the content you're after.
{ "language": "en", "url": "https://stackoverflow.com/questions/13551779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ Function pointers vs Switch * *What is faster: Function pointers or switch? The switch statement would have around 30 cases, consisting of enumarated unsigned ints from 0 to 30. I could do the following: class myType { FunctionEnum func; string argv[123]; int someOtherValue; }; // In another file: myType current; // Iterate through a vector containing lots of myTypes // ... for ( i=0; i < myVecSize; i ++ ) switch ( current.func ) { case 1: //... break; // ........ case 30: // blah break; } And go trough the switch with func every time. The good thing about switch would also be that my code is more organized than with 30 functions. Or I could do that (not so sure with that): class myType { myReturnType (*func)(int all, int of, int my, int args ); string argv[123]; int someOtherValue; }; I'd have 30 different functions then, at the beginning a pointer to one of them is assigned to myType. * *What is probably faster: Switch statement or function pointer? Calls per second: Around 10 million. I can't just test it out - that would require me to rewrite the whole thing. Currently using switch. I'm building an interpreter which I want to be faster than Python & Ruby - every clock cycle matters! A: I think the difference is negligible in most cases - your case might be an exception. Why don't you put together a simple prototype app to explicitly measure the performance of each solution? My guess is that it would not take more than an hour of work... However, think about clarity and maintainability of the code as well. IMHO it is obvious that the function pointer solution wins hands down in this respect. Update: Note also that even if one solution is, let's say, twice as fast as the other as it is, it still may not necessarily justify rewriting your code. You should profile your app first of all to determine how much of the execution time is actually spent in those switches. If it is 50% of total time, there is a reason to optimize it. If it is a couple of percents only, optimizing it would be a waste of effort. A: Péter Török has the right idea about trying both and timing them. You may not like it, but unfortunately this is the reality of the situation. The "premature optimization" chant happens for a reason. I'm always in favour of using performance best-practices right from the start as long as it doesn't sacrifice clarity. But in this kind of case it's not a clear win for either of the options you mentioned. In most cases, this kind of minor change will have no measurable effect. There will be a few major bottlenecks that completely govern the speed of the whole system. On modern computers a few instructions here and there will be basically invisible because the system is blocked by memory cache misses or by pipeline stalls and those can be hard to predict. For instance in your case, a single extra cache miss would likely decide which method would be slower. The real-world solution is to evaluate the performance of the whole system with a profiler. That will show you where your "hot spots" are in the code. The usual next step is to make algorithmic changes to reduce the need for that many calls into the hot code either through better algorithms or through caching. Only if a very tiny section of code is lighting up the profiler is it worth getting down to small micro-optimizations like this. At that point, you have to try different things and test the effect on speed. Without measuring the effect of the changes, you're just as likely to make it worse, even for an expert. All that being said, I would guess that function calls in your case might be very slightly faster if they have very few parameters, especially if the body of each case would be large. If the switch statement doesn't use a jump table, that likely be slower. But it would probably vary a lot by compiler and machine architecture, so I wouldn't spend much time on it unless you have hard evidence later on that it is a bottleneck to your system. Programming is as much about re factoring as it is about writing fresh code. A: Switch statements are typically implemented with a jump table. I think the assembly can go down to a single instruction, which would make it pretty fast. The only way to be sure is to try it both ways. If you can't modify your existing code, why not just make a test app and try it there? A: Writing interpreters is fun, isn't it? I can guess that the function pointer might be quicker, but when you're optimizing, guesses won't take you very far. If you really want to suck every cycle out of that beast, it's going to take multiple passes, and guesses aren't going to tell you what to fix. Here's an example of what I mean.
{ "language": "en", "url": "https://stackoverflow.com/questions/2662442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How to give strokes a specific width based on base64 i'm trying to build a stroked line, based on a svg file, cause of the color and the corner shapes that it has. Each stroke is 15px wide and has a gap between each line from also 15px. The problem is that when i try to include it via background-image it always makes the line longer than it actually should be. .stroke-dotted { background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTVweCIgaGVpZ2h0PSI0cHgiIHZpZXdCb3g9IjAgMCAxNSA0IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPGcgaWQ9IldlYnNpdGUiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJEZXNrdG9wIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTQyLjAwMDAwMCwgLTE5NDAuMDAwMDAwKSIgc3Ryb2tlPSIjMTZDREM3IiBzdHJva2Utd2lkdGg9IjMiPgogICAgICAgICAgICA8ZyBpZD0iU2VydmljZSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMC4wMDAwMDAsIDE0ODguMDAwMDAwKSI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iV2ViZGVzaWduIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg2MC4wMDAwMDAsIDQzOC4wMDAwMDApIj4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNODIsMTYgTDk3LDE2IiBpZD0ibGluZSI+PC9wYXRoPgogICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=); width: 100%; background-repeat: repeat-x; } <div class="stroke-dotted"></div> Thats how it should look like: And that's how it looks now: Is there a way to give the lines a specific width of 15px and also an gap of 15px? I also tried to fix it with the background-size attribute, but it didn't worked out. A: First things first: don't encode your SVG as a base64, it is much longer than the original code and its unnecessary as you can just add the code to the url. You might need to URL encode it for IE11 and earlier, but otherwise all browsers support it. Now, to control your sizing in SVG tags, ommit the viewBox and simply give it a width and height of 100% and express all other values in percentage. Now you can control the size of the line by defining its pixel size, even though the points are defined in percentage: div { position: absolute; width: 100%; height: 100%; left: 0%; top: 0%; background: url('data:image/svg+xml;charset=utf8,<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">\ <line x1="0%" y1="50%" x2="100%" y2="50%" stroke="cyan" stroke-width="1px" stroke-dasharray="15px 15px" />\ </svg>') no-repeat 50% 50% / cover; } body { /* A reference grid */ background: url('data:image/svg+xml;charset=utf8,<svg width="15px" height="15px" xmlns="http://www.w3.org/2000/svg">\ <rect x="0" y="0" width="100%" height="100%" stroke="#222" stroke-width="1px" fill="black" />\ </svg>'); } <div></div> Once your SVG is correctly set up, it is as simple as defining the stroke-dasharray property with the pixel values: <line x1="0%" y1="50%" x2="100%" y2="50%" stroke="black" stroke-width="1px" stroke-dasharray="15px 15px" /> Now you can use CSS to change your box, or even SVG to change the offsets within the SVG background.
{ "language": "en", "url": "https://stackoverflow.com/questions/58413152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Notice: Undefined index errors I have been creating some code in PHP and the logs of my server keep showing the following errors. The code are handlers for a game that I have been creating. I have tried to fix them by researching and applying the ''fixes'' but it didn't go well. Undefined index: a#jt in /usr/share/nginx/Sweater/Sweater/GameHandler.php on line 160 Undefined index: a#jt in /usr/share/nginx/Sweater/Sweater/GameHandler.php on line 161 Undefined index: a#jt in /usr/share/nginx/Sweater/Sweater/GameHandler.php on line 167 Undefined index: a#lt in /usr/share/nginx/Sweater/Sweater/GameHandler.php on line 227 Trying to get property of non-object in /usr/share/nginx/Sweater/Sweater/GameHandler.php on line 302 This is the code for them: function handleJoinTable(Array $arrData, Client $objClient) { $intPlayer = $arrData[4]; $tableId = $arrData[2]; $strUsername = $this->objDatabase->getUsername($intPlayer); $seatId = count($this->tablePopulationById[$tableId]) - 1; // Line 160 if($this->gamesByTableId[$tableId] === null) { // Line 161 $findFourGame = new FindFour(); $this->gamesByTableId[$tableId] = $findFourGame; } $this->tablePopulationById[$tableId][$strUsername]; // Line 167 $seatId += 1; $objClient->sendXt('jt', $objClient->getIntRoom(), $tableId, $seatId); $objClient->sendXt('ut', $objClient->getIntRoom(), $tableId, $seatId); $this->playersByTableId[$tableId][] = $intPlayer; $this->tableId = $tableId; } function handleLeaveTable(Array $arrData, Client $objClient) { $intPlayer = $arrData[2]; $tableId = $arrData[3]; $strUsername = $this->arrClientsByID[$intPlayer]; // Line 227 unset($objClient->arrPlayer[$intPlayer]); $objClient->sendXt('lt', $objClient->getIntRoom(), $strUsername); } function handleGetGame(Array $arrData, Client $objClient) { $intPlayer = $arrData[3]; if($objClient->getExtRoom() == 802) { $puckData = $this->rinkPuck; $objClient->sendXt('gz', $objClient->getIntRoom(), $puckData); } elseif($intPlayer->tableId !== null) { // Line 302 $tableId = $intPlayer->tableId; $playerUsernames = array_keys($this->tablePopulationById[$tableId]); @list($firstPlayer, $secondPlayer) = $playerUsernames; $boardString = $this->gamesByTableId[$tableId]->convertToString(); $objClient->sendXt('gz', -1, $firstPlayer, $secondPlayer, $boardString); } } What's going on here? A: $this->tablePopulationById[$tableId] tablePopulationById is an array that DOES NOT contain a key of index $tableId. $arrData[3]; DOES NOT contain an object of whatever class you were expecting! In both cases, var_dump them to see what you DO have! var_dump($this->tablePopulationById); var_dump($arrData);
{ "language": "en", "url": "https://stackoverflow.com/questions/45865056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript: Testing form submit with sinon spy and chai Hi im trying to test a form submit using sinon spy and chai, however I am not sure if I am doing the right thing. Whenever i run the test, seconds comes back as undefined. Not sure why this is happening. I'm new to sinon, chai. Here is the code This is the test file: describe('CountdownForm', () => { it('should exist', () => { expect(CountdownForm).to.exist; }); it('should call onSetCountdown if valid seconds entered', () => { const spy = sinon.spy(); const countDownForm = shallow(<CountdownForm onSetCountdown={spy}/>) countDownForm.refs.seconds.value = '109'; countDownForm.find('form').simulate('submit', { preventDefault(){} }) expect(spy.called).to.be.true; }); }); This is the jsx file: class CountdownForm extends Component { onSubmit = (e) => { e.preventDefault(); const stringSeconds = this.refs.seconds.value; if (stringSeconds.match(/^[0-9]*$/)) { this.refs.seconds.value = ''; this.props.onSetCountdown(parseInt(stringSeconds, 10)); } } render() { return ( <div> <form ref="form" onSubmit={this.onSubmit} className='countdown-form'> <input type="text" ref="seconds" placeholder="Enter time in seconds"/> <button className="button expanded">Start</button> </form> </div> ); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/41753740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ssh reverse port forwarding from local to remote2 by using remote1 I need port forwarding and also reverse port forwarding betwwen my localhost and remote2 pc using remote1 pc. My local pc can not connect directly remote2. Design looks like: local ----------------> remote1 -----------------> remote2 5037 ---(ssh -L 5037:remote2:7385 user@remote1)---> 7385 //working 27183 <-----------( I can not achieve )------------ 27183 //need I used ssh -L 5037:remote2:7385 -R remote2:27183:localhost:27183 user@remote1 But it forwards my local 27183 port to remote1's 27183 port. How to use ssh tunnelling to forward my local 27183 port to remote2's 27183 port?
{ "language": "en", "url": "https://stackoverflow.com/questions/74387629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET removing DropDownList item inside repeater? I don't know if I am allowed to post such a specific issue here. The scenario is that I have a Product that has a many to many relationship with Category. Means one product may belong to multiple categories and a category may have multiple products. Now on the form I have provide a dropdown along with a button that says add another category and when I click on that button another dropdown should appear below that first dropdown. and the selected item of the previous dropdown must be remove from the dropdown items. Below is my code of the dropdown's repeater and the two buttons mentioned. protected void btnAddAnotherCategory_Click(object sender, EventArgs e) { List<int> selectedIndices = new List<int>(); foreach (RepeaterItem item in rptCategories.Items) { if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) { DropDownList ddlCategory = (DropDownList)item.FindControl("ddlCategory"); int selectedIndex = ddlCategory.SelectedIndex; selectedIndices.Add(selectedIndex); } } ViewState["objSelectedIndices"] = selectedIndices; rptCategories_DataSource("add", false); } protected void btnRemoveCategory_Click(object sender, EventArgs e) { List<int> selectedIndices = new List<int>(); foreach (RepeaterItem item in rptCategories.Items) { if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) { DropDownList ddlCategory = (DropDownList)item.FindControl("ddlCategory"); int selectedIndex = ddlCategory.SelectedIndex; selectedIndices.Add(selectedIndex); } } ViewState["objSelectedIndices"] = selectedIndices; rptCategories_DataSource("remove", false); } protected void rptCategories_DataSource(string editCommand, bool pageLoad) { switch (editCommand) { case "add": if (ViewState["categoriesCount"] == null) { List<Category> count = new List<Category>(); count.Add(new Category()); ViewState["categoriesCount"] = count; } if (!pageLoad) { List<Category> count = (List<Category>)ViewState["categoriesCount"]; count.Add(new Category()); ViewState["categoriesCount"] = count; } List<Category> objCategories = (List<Category>)ViewState["categoriesCount"]; objCategories = objCategories.Where(x => x.StatusID != 3).ToList(); rptCategories.DataSource = objCategories; rptCategories.DataBind(); break; case "remove": if (((List<Category>)ViewState["categoriesCount"]).Count > 1) { List<Category> count = (List<Category>)ViewState["categoriesCount"]; count.Remove(count.Last()); count = count.Where(x => x.StatusID != 3).ToList(); ViewState["categoriesCount"] = count; rptCategories.DataSource = count; rptCategories.DataBind(); } break; } } protected void rptCategories_ItemDataBound(object sender, RepeaterItemEventArgs e) { Category objCategory = (Category)e.Item.DataItem; DropDownList ddlCategory = (DropDownList)e.Item.FindControl("ddlCategory"); ddlCategory.DataSource = new CategoryBLL().GetAllCategoriesWithStatus(); ddlCategory.DataTextField = "Name"; ddlCategory.DataValueField = "ID"; ddlCategory.DataBind(); if (objCategory.CategoryID != null) ddlCategory.SelectedValue = objCategory.CategoryID.ToString(); if (ViewState["objSelectedIndices"] != null) { List<int> objSelectedIndices = (List<int>)ViewState["objSelectedIndices"]; if (objSelectedIndices.Count > e.Item.ItemIndex) ddlCategory.SelectedIndex = objSelectedIndices.ElementAt(e.Item.ItemIndex); } if (e.Item.ItemIndex < ((List<Category>)rptCategories.DataSource).Count - 1) { ddlCategory.Enabled = false; } btnAddAnotherCategory.Visible = true; btnRemoveCategory.Visible = true; if (rptCategories.Items.Count < 1) { btnRemoveCategory.Visible = false; } if (rptCategories.Items.Count >= new CategoryBLL().GetAllCategoriesWithStatus().Count - 1) { btnAddAnotherCategory.Visible = false; } } The StatusID mentioned in the code is to determine the deleted products as I am not ACTUALLY deleting the Product rather only setting its StatusID Now the problem is that my code works fine with the above statements but as you can see it does not remove the selected items from the dropdown. The dropdown's are required to be populated from a single table everytime. The tricky part is removing the selecteditems in the previous repeateritems dropdownlist. Any solution would be welcomed.
{ "language": "en", "url": "https://stackoverflow.com/questions/16001134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calling a variable into main function - Jython I'm an newbie playing around with JES and I'm testing how to call a variable in from another function to the main function. I'm using return which from what I understand should return variable num but it's still erroring :( Any guidance would be most appreciated. def update(): a = sqrt(10) b = 239 getTotal(a,b) print num def getTotal(a,b): num = a*b return num A: Need somewhere for that value to return to. Try this: def update(): a = sqrt(10) b = 239 c = getTotal(a,b) print c def getTotal(a,b): num = a*b return num
{ "language": "en", "url": "https://stackoverflow.com/questions/21348247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ValueError invalid literal for int() with base 2: '' in Python I'm trying to get a string, jJ, as input and then converting each character to it's 6 bit binary form using the mapping given in a and concatenating them and returning it in mapFirst(string). That is, jJ becomes 100011001001. In binaryToLetter(string) I'm taking the returned value and separating it into parts of 8 bits and converting it back to it's character form and concatenated. 100011001001 becomes 00001000 and 11001001, which are then converted and joined to give (backspace)É. In my code, I'm getting the error : Exception has occurred: ValueError invalid literal for int() with base 2: '' File "C:\Users\Sembian\Desktop\exc files new\Ex_Files_Learning_Python\Exercise Files\task_cs\task1.py", line 11, in <genexpr> return ''.join( str( int( (binNew[newLen:newLen-i]),2 ) ).replace('0b','').zfill(8) for i in range(0, newLen, n) ) The code I used is : from textwrap import wrap a = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'] def mapFirst(string): return ''.join(str(bin(ord(chr(a.index(c))))).replace('0b','').zfill(6) for c in string) def binaryToLetter(binNew): newLen = len(str(binNew)) n=8 return ''.join( str( int( (binNew[newLen:newLen-i]),2 ) ).replace('0b','').zfill(8) for i in range(0, newLen, n) ) def main(): k = 'jJ' print("the first binary value is: ",mapFirst(k)) print("the final decoded value is: ", binaryToLetter(mapFirst(k))) if __name__ == "__main__": main() A: I managed to get something kinda working. For the first part: def mapFirst(string): return ''.join(bin(a.index(c))[2:].zfill(6) for c in string) I have removed a bunch of unnecessary clutter: * *ord(chr(x)) == x (assuming x:int < 256), because ord is an inverse of chr. *str(bin(x)) == bin(x), because bin already returns a string. *bin(x).replace('0b', '') == bin(x)[2:], because bin will always return a string starting with 0b, so you can use string (list) slicing. For the second part: def binaryToLetter(binNew): return ''.join(reversed([chr(int(binNew[max(0, i - 8):i], 2)) for i in range(len(binNew), 0, -8)])) To break it down a little: * *I am using range(len(binNew), -1, -8) to generate decreasing a sequence from len(binNew) to 0 (inclusive) in steps of -8. *I am then using the list slicing again to get the 8-bit long chunks from binNew, making sure that I don't overshoot the last one (that what the max() is for). *I am turning these 8 char strings to a number with int(..., 2) and turning that number to chr. *Because I am "chopping" away the 8 long substrings starting from the back, I need to reverse the order. But reversed doesn't accept generators, so I change the original generator into a list.
{ "language": "en", "url": "https://stackoverflow.com/questions/56118521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call parent function in child button Suppose I have a component called ButtonComponent which will be used in various places in the application, so I make is as generic as possible, like so: button.component.ts import { Component, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core'; import { FormGroup } from '@angular/forms'; @Component({ selector: 'app-button', templateUrl: './button.component.html', styleUrls: ['./button.component.scss'], encapsulation: ViewEncapsulation.None }) export class ButtonComponent{ @Input() group: FormGroup; @Input() type: string; @Input() description: string; @Input() class: string; @Input() callFunction: Function; } button.component.html <div [formGroup]="group"> <button type="{{ type }}" class="{{ class }}" (click)="callFunction()">{{ description }}</button> </div> Now my button is completely customizable (in theory). I am now going to import it to a login component which has a function called login(). I want my button instance to run this specific function when I click it: login.component.ts //imports /** * This component is rendered at the start of application, it provides the UI * & functionality for the login page. */ @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) /** * This class is used to build a login form along with initialization of validators * as well as authenticate the user, and reroute upon success */ export class LoginComponent implements OnInit, AfterContentInit{ @ViewChild('login', { read: ViewContainerRef }) login_button; /** * This property initializes the formGroup element. */ userForm: FormGroup; /** * The constructor initializes Router, FormBuilder, OauthService, LoggerService, ToastrService * & TranslatePipe in the component. */ constructor(//initializations ) { } /** * This is the hook called on the initialization of the component, it initializes * the form. */ ngOnInit() { this.buildForm(); } /** * This method initialized the the formGroup element. Its properties and the validators. * * @method buildForm * @return */ buildForm() { // validations }); } /** * This method returns the values of the form controls. * * @return */ get form() { return this.userForm.controls; } /** * This method is triggered on success, it reroutes the user to main page. * * @return */ onSuccess() { let result = this.translate.transform("pages[login_page][responses][success]"); this.logger.info(result); this.toastr.success(result); this.router.navigate(['main']); } /** * This method is triggered when user clicks log-in, it calls the aunthenication method * from oauth service. * * @return */ login() { this.oauth.authenticateUser(this.form.username.value, this.form.password.value, this.onSuccess.bind(this)); } ngAfterContentInit() { //here I build my login button instance after init this.buildLoginButton(); } /** * This function builds the login button, imports the ButtonComponent * */ buildLoginButton(){ let data = { type: "button", class: "btn btn-primary px-4", description: this.translate.transform("pages[login_page][login_form][buttons][login]"), function: "login", group: this.userForm } const inputFactory = this.resolver.resolveComponentFactory(ButtonComponent); const loginButton = this.login_button.createComponent(inputFactory); loginButton.instance.group = data.group; loginButton.instance.type = data.type; loginButton.instance.class = data.class; loginButton.instance.description = data.description; loginButton.instance.callFunction = function(){ //I call parent function using a static method LoginComponent.executeMethod(data.function); } } static executeMethod(someMethod){ //for my login button this should return this.login() eval("this."+someMethod+"()"); } } To make the button instance visible I add the reference into my login template like this: <div #login></div> Now my button is visible, great! But now when i click the button: ERROR TypeError: this.login is not a function at eval (eval at push../src/app/views/login/login.component.ts.LoginComponent.executeMethod (login.component.ts:225), :1:6) at Function.push../src/app/views/login/login.component.ts.LoginComponent.executeMethod (login.component.ts:225) at ButtonComponent.loginButton.instance.callFunction (login.component.ts:179) at Object.eval [as handleEvent] (ButtonComponent.html:2) at handleEvent (core.js:10251) at callWithDebugContext (core.js:11344) at Object.debugHandleEvent [as handleEvent] (core.js:11047) at dispatchEvent (core.js:7710) at core.js:8154 at HTMLButtonElement. (platform-browser.js:988) How do I make my button run the function in the parent component instead of looking for the function within itself? I don't want to change a lot in the ButtonComponent that would make it less generic as I have to make other buttons as well that would probably run other functions. There was a solution that stated using EventEmitter for this, but I am unsure how this would work given how I am importing the button into the login component, both the ts and the html Edit the complete login.component.html: <div class="app-body"> <main class="main d-flex align-items-center"> <div class="container center"> <div class="row"> <div class="col-md-8 mx-auto"> <div class="card-group"> <div class="card p-4"> <div class="card-body"> <form [formGroup]="userForm" (submit)="login()"> <h1>{{ 'pages[login_page][login_form][labels][login]' | translate }}</h1> <p class="text-muted">{{ 'pages[login_page][login_form][labels][sign_in]' | translate }}</p> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text"><i class="icon-user"></i></span> </div> <div #username> </div> </div> <div class="input-group mb-4"> <div class="input-group-prepend"> <span class="input-group-text"><i class="icon-lock"></i></span> </div> <div #password> </div> </div> <div class="row"> <div class="col-6"> <div #login></div> <!-- <button type="button" class="btn btn-primary px-4" (click)="login()">{{ 'pages[login_page][login_form][buttons][login]' | translate }}</button> --> </div> <div class="col-6 text-right"> <div #forgot></div> <!-- <button type="button" class="btn btn-link px-0">{{ 'pages[login_page][login_form][urls][forgot_password]' | translate }}</button>--> </div> </div> </form> </div> </div> <div class="card text-white bg-primary py-5 d-md-down-none" style="width:44%"> <div class="card-body text-center"> <div> <h2>{{ 'pages[login_page][sign_up_panel][labels][sign_up]' | translate }}</h2> <p>{{ 'pages[login_page][sign_up_panel][labels][new_account]' | translate }}</p> <div #signUp></div> <!-- <button type="button" class="btn btn-primary active mt-3">{{ 'pages[login_page][sign_up_panel][buttons][register]' | translate }}</button> --> </div> </div> </div> </div> </div> </div> </div> </main> </div> A: Add this code in button.component.ts @Output() clickFunctionCalled = new EventEmitter<any>(); callFunction() { this.clickFunctionCalled.emit(); } No change in button.template.html Add this code where you use app-button component in html <app-button (clickFunctionCalled)="callCustomClickFunction($event)"></app-button> Add this in login.component.ts callCustomClickFunction() { console.log("custom click called in login"); this.login(); } Basically, emit the click event from the child component. Catch the event in the parent component and call the desired function of the parent component. You can also directly call the parent component's function like this <app-button (clickFunctionCalled)="login($event)"></app-button> As you are using dynamic component creator for creating the button component, you need to do something like this, for binding output event loginButton.instance.clickFunctionCalled.subscribe(data => { console.log(data); });
{ "language": "en", "url": "https://stackoverflow.com/questions/54879354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: unable to compile play 2.8.15 using sbt 1.7.1 Due to log4j vulnerability, using sbt 1.7.1 version with play 2.8.15,but unable to compile the play code and getting errors. Steps taken: * *Downloaded sbt code 1.7.1 from https://www.scala-sbt.org/download.html *Installed the new Play binary eg PlayDev-2.8.15 *Removed .sbt .cache .ivy2 from /home directory *Ran sbt_stage.sh and see below error . [PlayDev-2.8.15]$ ./sbt_stage.sh /apps/Play/PlayDev-2.8.15/build.sbt:2: error: not found: value PlayJava .enablePlugins(PlayJava,LauncherJarPlugin) ^ /apps/Play/PlayDev-2.8.15/build.sbt:2: error: not found: value LauncherJarPlugin .enablePlugins(PlayJava,LauncherJarPlugin) ^ /apps/Play/PlayDev-2.8.15/build.sbt:3: error: not found: value PlayFilters .disablePlugins(PlayFilters) ^ /apps/Play/PlayDev-2.8.15/build.sbt:9: error: not found: value guice guice, ^ /apps/Play/PlayDev-2.8.15/build.sbt:10: error: not found: value ws ws, ^ /apps/Play/PlayDev-2.8.15/build.sbt:11: error: not found: value ehcache ehcache, ^ /apps/Play/PlayDev-2.8.15/build.sbt:12: error: not found: value javaJpa javaJpa, ^ /apps/Play/PlayDev-2.8.15/build.sbt:14: error: not found: value javaWs javaWs % "test", ^ /apps/Play/PlayDev-2.8.15/build.sbt:24: error: not found: value routesGenerator routesGenerator := InjectedRoutesGenerator, ^ /apps/Play/PlayDev-2.8.15/build.sbt:24: error: not found: value InjectedRoutesGenerator routesGenerator := InjectedRoutesGenerator, ^ /apps/Play/PlayDev-2.8.15/build.sbt:25: error: not found: value PlayKeys PlayKeys.externalizeResources := false, ^ /apps/Play/PlayDev-2.8.15/build.sbt:39: error: not found: value PlayKeys PlayKeys.externalizeResourcesExcludes += baseDirectory.value / ^ sbt.compiler.EvalException: Type error in expression [warn] Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore? (default: r) sbt script version: _to_be_replaced [info] welcome to sbt 1.7.1 (Oracle Corporation Java 1.8.0_232) [info] loading project definition from /apps/Play/PlayDev-2.8.15/project
{ "language": "en", "url": "https://stackoverflow.com/questions/74351669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: opencv MSER.detectRegions() vs findContours(): what's the difference? I am building a generic text parsing algorithm for images. I was running: MSER.detectRegions() vs findContours(...cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) on a binary image. The results where the same. I know MSER can be done on gray-scale but I wanted to go safer. I need to select one of them and the findContours() takes less then half the run time MSER does. Am I missing something? What would you pick? A: As already pointed out, it does not make sense to compute MSER on a binary image. MSER basically thresholds an image (grayscale) multiple times using increasing (decreasing) thresholds and what you get is a so called component tree like this here. The connected components which change their size/shape at least over the different binarizations are the so-calles Maximally Stable Extremal Regions (e.g. the K in the schematic graphic). This is of course a very simplified explanation. Please ask Google for more details, you'll find enough. As you can see, thresholding an already thresholded image does not make sense. So pass the grayscale image to the MSER algorithm instead. MSER is a common basis for state-of-the-art text detection approaches (see here and here).
{ "language": "en", "url": "https://stackoverflow.com/questions/39490063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Test return value from jest mocked event callback I have the following component in Button.tsx: // Button.tsx import * as React from 'react'; import { Button as ReactstrapButton } from 'reactstrap'; interface IHandlerParams<onClickArgsType> { onClickParams?: onClickArgsType } export interface IButtonProps<onClickArgsType = {}> { color?: string, onClick?: (event: React.MouseEvent<any>, args?: onClickArgsType) => any, handlersParams?: IHandlerParams<onClickArgsType> } interface IHandlers { onClick: React.MouseEventHandler<any> } export class Button<onClickArgsType> extends React.Component<IButtonProps<onClickArgsType>> { private handlers: IHandlers; constructor(props: IButtonProps<onClickArgsType>) { super(props); this.handlers = { onClick: (MouseEvent:React.MouseEvent<any>) => { if (this.props.onClick) {this.props.onClick( MouseEvent, this.props.handlersParams ? this.props.handlersParams.onClickParams : undefined) }} } } render() { return ( <ReactstrapButton color={this.props.color} onClick={this.handlers.onClick}> {this.props.children} </ReactstrapButton> ) } } NOTE: I am using that weird "handlers" object to manage the event's callback, so that I do not have an arrow function directly in the ReactstrapButton properties, avoiding creating a new object each time and thus preventing the component from being re-rendered. And a corresponding test file in Button.unit.test.tsx: // Button.unit.test.tsx import { mount, shallow } from "enzyme"; import * as React from "react"; import { Button, IButtonProps } from "./Button"; interface IOnClickParamsTest { a: number, b: number } describe('App component', () => { it('renders without crashing', () => { shallow( <Button /> ); }); it('test the onClick method', () => { const onClick = jest.fn((event: React.MouseEvent<IButtonProps<IOnClickParamsTest>>, params: IOnClickParamsTest) => params.a + params.b); const onClickParams: IOnClickParamsTest = { a: 4, b: 5 }; const buttonComponent = mount( <Button<IOnClickParamsTest> onClick={onClick} handlersParams={{ onClickParams }} /> ); buttonComponent.simulate("click"); expect(onClick).toBeCalled(); expect(onClick.mock.calls[0][1]).toBe(onClickParams);// The second argument of the first call to the function was onClickParams // expect(onClick.mock.results[0].value).toBe(9);// The return value of the first call to the function was 9 }); }); The test passes as expected, but fails in the last commented line with following error: TypeError: Cannot read property '0' of undefined The error is referencing to the onClick.mock.results property. I have debugged the onClick.mock property and results, of course, is not there. Nevertheless, as per this docs in Jest, there should exist a results property in there. By the way, I am using : "react": "^16.4.0", "react-dom": "^16.4.0", "enzyme": "^3.3.0", "enzyme-adapter-react-16": "^1.1.1", "jest": "^23.1.0", "jest-enzyme": "^6.0.2", "ts-jest": "^22.4.6" Any thoughts? Thank you so much in advance! A: The return value is available in Jest v23. Apps bootstrapped using create-react-app with react-scripts-ts as of today (Aug 1, 2018) are using Jest v22. create-react-app will be updated to use Jest v23 in the near future. In the meantime, testing the return value is possible using Sinon fakes. In this case the updated test looks like this: // Button.unit.test.tsx import { mount, shallow } from "enzyme"; import * as React from "react"; import * as sinon from 'sinon'; import { Button, IButtonProps } from "./Button"; interface IOnClickParamsTest { a: number, b: number } describe('App component', () => { it('renders without crashing', () => { shallow( <Button /> ); }); it('test the onClick method', () => { const onClick = sinon.fake((event: React.MouseEvent<IButtonProps<IOnClickParamsTest>>, params: IOnClickParamsTest) => params.a + params.b); const onClickParams: IOnClickParamsTest = { a: 4, b: 5 }; const buttonComponent = mount( <Button<IOnClickParamsTest> onClick={onClick} handlersParams={{ onClickParams }} /> ); buttonComponent.simulate("click"); expect(onClick.calledOnce).toBe(true); expect(onClick.firstCall.args[1]).toBe(onClickParams); expect(onClick.returnValues[0]).toBe(9); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/51625074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Comparison of 2 string variables in shell script Consider there is a variable line and variable word: line = 1234 abc xyz 5678 word = 1234 The value of these variables are read from 2 different files. I want to print the line if it contains the word. How do I do this using shell script? I tried all the suggested solutions given in previous questions. For example, the following code always passed even if the word was not in the line. if [ "$line"==*"$word"*]; then echo $line fi A: No need for an if statement; just use grep: echo $line | grep "\b$word\b" A: You can use if [[ "$line" == *"$word"* ]] Also you need to use the following to assign variables line="1234 abc xyz 5678" word="1234" Working example -- http://ideone.com/drLidd A: Watch the white spaces! When you set a variable to a value, don't put white spaces around the equal sign. Also use quotes when your value has spaced in it: line="1234 abc xyz 5678" # Must have quotation marks word=1234 # Quotation marks are optional When you use comparisons, you must leave white space around the brackets and the comparison sign: if [[ $line == *$word* ]]; then echo $line fi Note that double square brackets. If you are doing pattern matching, you must use the double square brackets and not the single square brackets. The double square brackets mean you're doing a pattern match operation when you use == or =. If you use single square brackets: if [ "$line" = *"$word"* ] You're doing equality. Note that double square brackets don't need quotation marks while single brackets it is required in most situations. A: echo $line | grep "$word" would be the typical way to do this in a script, of course it does cost a new process A: You can use the bash match operator =~: [[ "$line" =~ "$word" ]] && echo "$line" Don't forget quotes, as stated in previous answers (especially the one of @Bill). A: The reason that if [ "$line"==*"$word"* ] does not work as you expect is perhaps a bit obscure. Assuming that no files exist that cause the glob to expand, then you are merely testing that the string 1234 abc xyz 5678==*1234* is non empty. Clearly, that is not an empty string, so the condition is always true. You need to put whitespace around your == operator, but that will not work because you are now testing if the string 1234 abc xyz 5678 is the same as the string to which the glob *1234* expands, so it will be true only if a file named 1234 abc xyz 5678 exists in the current working directory of the process executing the shell script. There are shell extensions that allow this sort of comparison, but grep works well, or you can use a case statement: case "$line" in *$word*) echo $line;; esac A: An alternative solution would be using loop: for w in $line do if [ "$w" == "$word" ]; then echo $line break fi done A: Code Snippet: $a='text' $b='text' if [ $a -eq $b ] then msg='equal' fi
{ "language": "en", "url": "https://stackoverflow.com/questions/18346824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript Errors when loading Bootstrap Modal a second and third time that contains a form with drop downs I'm a complete beginner...please excuse the mess. Only been learning for about a month. The structure is like this. I have a nav.html template I've created for a top level menu across the site. It contains a drop down for creating New entries...and in this case a 'New Job' Job has two special parts. * *I've used Django-autocomplete-light for finding/creating new customers in the one form. This leverages select2 and some other javascript wizards *A google places autocomplete for finding site addresses Everything worked fine as just opening in a fresh page. Then I decided I wanted to put the New Job form in to a modal instead. I'm an idiot. I'm using non-modified bootstrap css and the js for it as well...but pulled them down to be local copies in my static folder. Same goes for jquery and popper. Got it to actually work/pop up fine but then these happened in the background. Grabs from the google chrome console. These are the errors I see when just opening and closing without entering any data. I started learning about the javascript event loop and it hurt my brain...but does this all have something to do with that? This kind of feels like things are loading...and then not unloading if I'm making any sense. Every example out there is based on using a button...and I've gone with a drop down selection but I don't feel like that should make any difference. Please help. Screenshot of the first run error Screenshot of the second run error Screenshot of the third run error Here's the code for all the bits n pieces. If I'm missing something, let me know. NAV.HTML (contains the dropdown to trigger the modal....towards the bottom called "create-job") {% load static %} <!DOCTYPE html> <head> <link rel="stylesheet" href="{% static '/css/bootstrap/bootstrap.css'%}"> <title>Easy Insulation</title> </head> <body> <script src="{% static '/js/jquery.js'%}"></script> <script src="{% static '/js/jqueryUI/jquery-ui.js'%}"></script> <script src="{% static '/js/popper.js'%}"></script> <script src="{% static '/js/bootstrap/bootstrap.bundle.js'%}"></script> <script src="{% static '/js/bootstrap/jquery.bootstrap.modal.forms.js' %}"></script> <script type="text/javascript"> $(document).ready(function () { $(".create-job").modalForm({ formURL: "{% url 'create_job' %}" }); }); </script> <div class="modal fade" role="dialog" id="modal" data-backdrop="false"> <div class="modal-dialog" role="document"> <div class="modal-content"> </div> </div> </div> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#"> <img src="{% static '/images/LogowithText.png'%}" width="110" height="40" alt="Easy Insulation" loading="lazy"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'home' %}">Dashboard<span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="#">Planning<span class="sr-only">(current)</span></a> </li> <li class="nav-item dropdown active"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Jobs </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{% url 'pipes' %}">Pipelines</a> <a class="dropdown-item" href="{% url 'job_list' %}">List</a> </div> </li> <li class="nav-item dropdown active"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Contacts </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Businesses</a> <a class="dropdown-item" href="#">Contacts</a> </div> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'prod_list' %}">Services<span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="../admin">Admin<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Meh</a> </li> </ul> </div> <div class="btn-group"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> New </button> <div class="dropdown-menu"> <a class="dropdown-item submit-btn create-job" data-toggle="modal" data-target="#myModal" type="button">Job</a> <a class="dropdown-item" href="#">Activity</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Contact</a> <a class="dropdown-item" href="#">Organisation</a> </div> </div> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> {% block content %} You need to build some content here tups {% endblock %} {% block extra_content %} More space for stuff {% endblock %} </body> </html> And this is the code for the Modal that pops up NEWJOB.HTML {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static '/css/bootstrap/bootstrap.css'%}"> <link rel="stylesheet" href="{% static '/css/modal.css'%}"> </head> <body> {% block content %} <script src="{% static '/js/googlepac.js'%}"></script> <script src="https://maps.googleapis.com/maps/api/js?key=IVEREMOVEDTHEKEYFORSHARINGPURPOSES&libraries=places&callback=initAutocomplete" async defer></script> <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Create New Job</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} invalid{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field }} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} </div> <div class="modal-footer"> <button id="disposeBtn" type="button" class="btn btn-primary" data-dismiss="modal">Close</button> <button type="button" class="submit-btn btn btn-primary">Create</button> </div> </form> {% endblock %} {% block extra_content %} {{form.media}} {% endblock %} </body> </html> This is the googlepac.js file var autocomplete; function initAutocomplete() { autocomplete = new google.maps.places.Autocomplete( document.getElementById('id_site_address'), {types: ['address']}); autocomplete.setFields(['address_component']); } the query.bootstrap.modal.forms.js from some super smart bro on the internet. /* django-bootstrap-modal-forms version : 1.5.0 Copyright (c) 2019 Uros Trstenjak https://github.com/trco/django-bootstrap-modal-forms */ (function ($) { // Open modal & load the form at formURL to the modalContent element var newForm = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn) { $(modalID).find(modalContent).load(formURL, function () { $(modalID).modal("show"); $(modalForm).attr("action", formURL); // Add click listener to the submitBtn addListeners(modalID, modalContent, modalForm, formURL, errorClass, submitBtn); }); }; // Submit form callback function var submitForm = function(modalForm) { $(modalForm).submit(); }; var addListeners = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn) { // submitBtn click listener $(submitBtn).on("click", function (event) { isFormValid(modalID, modalContent, modalForm, formURL, errorClass, submitBtn, submitForm); }); // modal close listener $(modalID).on('hidden.bs.modal', function (event) { $(modalForm).remove(); }); }; // Check if form.is_valid() & either show errors or submit it var isFormValid = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn, callback) { $.ajax({ type: $(modalForm).attr("method"), url: $(modalForm).attr("action"), // Serialize form data data: $(modalForm).serialize(), beforeSend: function() { $(submitBtn).prop("disabled", true); }, success: function (response) { if ($(response).find(errorClass).length > 0) { // Form is not valid, update it with errors $(modalID).find(modalContent).html(response); $(modalForm).attr("action", formURL); // Reinstantiate listeners addListeners(modalID, modalContent, modalForm, formURL, errorClass, submitBtn); } else { // Form is valid, submit it callback(modalForm); } } }); }; $.fn.modalForm = function (options) { // Default settings var defaults = { modalID: "#modal", modalContent: ".modal-content", modalForm: ".modal-content form", formURL: null, errorClass: ".invalid", submitBtn: ".submit-btn" }; // Extend default settings with provided options var settings = $.extend(defaults, options); return this.each(function () { // Add click listener to the element with attached modalForm $(this).click(function (event) { // Instantiate new modalForm in modal newForm(settings.modalID, settings.modalContent, settings.modalForm, settings.formURL, settings.errorClass, settings.submitBtn); }); }); }; }(jQuery));
{ "language": "en", "url": "https://stackoverflow.com/questions/62111063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'Termination due to memory pressure" in UIWebView I have started receiving app termination due to memory pressures very recently (mostly with iOS 7). The app used to work very well on iOS 6. The app is mostly uses a UIWebView to display a webpage. However for a few webpages it creates ever increasing Dirty memory with most of it due to Image IO and Performance tool data (see attached instruments screenshots). I am completely clueless as to where to dig next. Could someone guide me what should I do here onwards? In the second screenshot I see a sudden bump in the memory allocations. Is there a way to spot the process/part of the code which caused it? EDIT One can reproduce these results in a simple demo kept at www.github.com/nikhiljjoshi/iosCrash (just change the site to www.nzz.ch). Thanks in advance, Nikhil
{ "language": "en", "url": "https://stackoverflow.com/questions/20455246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Windows Phone 8.1 xbox music Is it any way to control Xbox Music on Windows Phone 8.1 or Windows Phone 8.0 from another application. I want to create an application with different style controls which start local music in background, getting some information from xbox music and so on. Is native Windows Phone 8.1 xbox music provide any API? Thanks! A: Have you tried with the official API? Getting started with the API is on MSDN. A: the Xbox Music API I could not find it working for windows Phone 8.1 but there are packages for Windows Phone 8 and windows 8.1
{ "language": "en", "url": "https://stackoverflow.com/questions/23835564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }