text
stringlengths
15
59.8k
meta
dict
Q: AWS Delete items by non-primary key I have a problem, and i don't really know how to ask it I've tables like this user table ----------------------------------- UID (primary key) | name (another key) ----------------------------------- a1c8d3 | Hugo f9e2d7 | Thomas s2c9d4 | Damien metadata table ----------------------------------- MID (primary key) | UID (another key) ----------------------------------- c3d9d3 | a1c8d3 d8f1e6 | a1c8d3 d3j5c2 | f9e2d7 I have a function to get all UID of my user table, they're store in an array When i delete users of this array, i want to delete items on my metadata table which has same UID than my deleted users Is it possible to delete items of my metadata table without using the primary key (here, MID) ? Or did i need to set UID's of my metadata table to a global secondary index ? If yes, how can i do it ? Thank you in advance Best regards A: No. DeleteItem() requires a primary key for the table (docs) You'd need to query the metadata table, and delete the rows with the matching UID. If you don't already have it, I'd recommend a global secondary index with hash key = UID sort key = MID Then a Query(GSI, hash = UID) would using your example data return two rows. You'd then call DeleteItem(Table, HashKey = MID) for each returned row. Or better yet, collect both deletes and send once as a BatchWriteItem()
{ "language": "en", "url": "https://stackoverflow.com/questions/58325663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Simple scrollX element with scroll snap, Changing page numbers I'm trying to create simple element with scroll snapping. I've created a demo in Codepen. I would like to scroll to an other image and after scroll, when other image is visible, change page number and the color of bottom circles. I've tried to put onscroll"function()" in div .container and calculate somehow winW & scrollX ratios, but this approach is buggy and messy. How should I make it, please? Thanks a lot. * { margin: 0; padding: 0; box-sizing: border-box; font-family: sans-serif; } .container { display: flex; overflow: auto; flex: none; width: 100vw; height: 100vw; flex-flow: row nowrap; scroll-snap-type: x mandatory; -ms-overflow-style: none; scrollbar-width: none; } .container::-webkit-scrollbar { display: none; } .pagination { position: absolute; top: 16px; right: 16px; background: #777; color: #fff; line-height: 40px; width: 50px; font-size: 12px; border-radius: 20px; text-align: center; } .image { width: 100vw; height: 100vw; scroll-snap-align: center; flex: none; } #image-1 { background: url("https://i.ibb.co/fMp05Jf/tamanna-rumee-ov-U2t-Rgfj-H8-unsplash.jpg"); background-size: cover; beckground-position: center; } #image-2 { background: url("https://i.ibb.co/Fx3Vm0S/pranav-madhu-KHD8vyputcg-unsplash.jpg"); background-size: cover; beckground-position: center; } #image-3 { background: url("https://i.ibb.co/4Fznzvs/tijana-drndarski-cj-Es-Ho-Pk-ZOQ-unsplash.jpg"); background-size: cover; beckground-position: center; } #image-4 { background: url("https://i.ibb.co/bPWXGfR/kristaps-ungurs-trs-Gn-MDb-T2-E-unsplash.jpg"); background-size: cover; beckground-position: center; } #image-5 { background: url("https://i.ibb.co/5jyBdGK/joanna-kosinska-pj-Pe-CRkl83-M-unsplash.jpg"); background-size: cover; beckground-position: center; } .pills { padding: 8px; display: flex; justify-content: center; } .circle { margin: 8px; height: 10px; width: 10px; border-radius: 5px; background: #ccc; } #circle-1 { background: #777; } <div class="container x mandatory-scroll-snapping""> <div class="pagination">1 / 5</div> <div class="image" id="image-1"></div> <div class="image" id="image-2"></div> <div class="image" id="image-3"></div> <div class="image" id="image-4"></div> <div class="image" id="image-5"></div> </div> <div class="pills"> <div class="circle" id="circle-1"></div> <div class="circle" id="circle-2"></div> <div class="circle" id="circle-3"></div> <div class="circle" id="circle-4"></div> <div class="circle" id="circle-5"></div> </div> A: You could simply add anchor tags with the ID name of the slide to automatically scroll to them: pills (with anchor tag) <div class="pills"> <a href="#image-3"> <div class="circle" id="circle-1"></div> </a> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/66800217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Props is not defined using render props I want to build an app that uses render.props. I created the component where all my logic is stored: import React, {useState} from 'react'; function Test(){ let [click, setClick] = useState(0); function funClick(){ setClick(click++) } return( <div> {props.render(click, setClick)} </div> ) } export default Test; The issue is that i've got an error Line 10: 'props' is not defined no-undef. What means this error and how to solve it? A: You need props as an argument for your component. import React, {useState} from 'react'; function Test(props) { let [click, setClick] = useState(0); function funClick(){ setClick(click++) } return( <div> {props.render(click, setClick)} </div> ) } export default Test;
{ "language": "en", "url": "https://stackoverflow.com/questions/58894368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: call the same name functions in jquery? i have 2 file js in my asp website named 1-jquery.datepick.js 2-jquery.hijridatepick.js these file have the same name functions but second one apear popup hijricalender i call it by <script type="text/javascript"> $(function () { $('[id$=TextBox1]').datepick({ dateFormat: 'dd/mm/yyyy' }); }); </script> for textbox2 i wanna 2 use datepick function from first file how icall it cause i refrenced the first file as $('[id$=TextBox2]').datepick({ dateFormat: 'dd/mm/yyyy' }); but this call again the function of second file ??? A: The second file is overwriting the first. You must change the name of one of the functions to avoid the collision. You'll find something like this in the files: jQuery.fn.datepick = function() { // etc. }; This is where the jQuery plugin method is created. Just change datepick in one or both files to something different and unique. A: As noted in FishBasketGordo's answer, the second function to load will overwrite the first, and changing the name of one will fix this, however there is a deeper problem that needs to be addressed. The reason this happens is that the functions are being added to the global namespace. In javascript the file that the code comes from is irrelevant. One way to avoid avoid polluting the global namespace is to wrap functions inside an object, so in your case you might have: /* 1-jquery.datepick.js */ datepick = new Object; datepick.datepick = function() { /* function definition here */ alert('first file function'); }; /* 2-jquery.hijridatepick.js */ hijridatepick = new Object; hijridatepick.datepick = function() { /* function definition here */ alert('second file function'); }; These functions can then be accessed using: datepick.datepick(); /* alerts 'first file function' */ hijridatepick.datepick(); /* alerts 'second file function' */
{ "language": "en", "url": "https://stackoverflow.com/questions/9944233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: barplot with 2 columns I would like to create barplot horizontal with the following dataframe studentData = { 0 : { 'stylevel' : 'bachelor', 'q' : 'agree', 'Type' : 'Nascent' }, 1 : { 'stylevel' : 'bachelor', 'q' : 'very', 'Type' : 'Nascent' }, 2 : { 'stylevel' : 'master', 'q' : 'very', 'Type' : 'Active' }, 3 : { 'stylevel' : 'master', 'q' : 'agree', 'Type' : 'Active' }, 4 : { 'stylevel' : 'master', 'q' : 'agree', 'Type' : 'Student' }, } dfObj = pd.DataFrame(studentData) dfObj = dfObj.T I'm using the following code to plot the graph dfObj['q'].value_counts().plot(kind='barh') Could you tell me how I could create the same graph using the Type column in the original dataframe to split the q data in 3 subgroups (i.e. Student, Active and nascent)? A: You have three options. using pandas: dfObj.groupby('Type')['q'].value_counts().plot(kind='barh') using pandas stacked bars: dfObj.groupby('Type')['q'].value_counts().unstack(level=0).plot.barh(stacked=True) using seaborn.catplot: import seaborn as sns df2 = dfObj.groupby('Type')['q'].value_counts().rename('count').reset_index() sns.catplot(data=df2, x='q', hue='Type', y='count', kind='bar')
{ "language": "en", "url": "https://stackoverflow.com/questions/68892938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use implicit wait and explicit wait together? In my framework we are using singleton driver and we are mainly using explicit wait. As documentation suggests we shouldn't use both together but at some points because of synchronization issues I need to use implicit wait. In that case I found a workaround, I add implicit wait to my driver, then at the end of this test I just create brand new driver. But I would like to know if there is any other way to do that ? A: As per the documentation: Warning: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example, setting an implicit wait of 10 seconds and an explicit wait of 15 seconds could cause a timeout to occur after 20 seconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/71403950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I limit the input number range with angular I would like to limit the input number that can go up to the current year, the user cannot enter a year higher than the current one. How can I do it? My code: <ion-content > <form> <ion-list> <ion-item> <ion-label>Stagione</ion-label> <ion-input [(ngModel)]="season.Description"></ion-input> </ion-item> <ion-item> <ion-label>Year</ion-label> <ion-input [(ngModel)]="season.Year" type="number"></ion-input> </ion-item> <ion-item> <ion-label>Primavera/Estate</ion-label> <ion-checkbox [(ngModel)]="season.IsSpringSummer"></ion-checkbox> </ion-item> <ion-item> <ion-label>Default</ion-label> <ion-checkbox [(ngModel)]="season.IsDefault"></ion-checkbox> </ion-item> <ion-item> <ion-label>Nascosto</ion-label> <ion-checkbox [(ngModel)]="season.IsHidden"></ion-checkbox> </ion-item> </ion-list> </ion-content> <ion-footer> <ion-toolbar color="footer"> <ion-buttons right> <button ion-button clear color="dark" (click)="save()">Save&nbsp; </button> </ion-buttons> </ion-toolbar> </ion-footer> A: You can make use of the min and max properties. Bind the max property to the current year like so: <ion-input [(ngModel)]="season.Year" type="number" [max]="{{(new Date()).getFullYear()}}"></ion-input>. The logic for getting the full year could be moved to the typescript file and could be stored in a variable like currentYear. In the template we can then bind to max like so: [max]="currentYear". A: You can do it simply by HTML only: <input type="number" oninput="if(value > (new Date()).getFullYear()) alert('Year exceeds current year')"> If you really want to do it by Angular only you have to create custom Validator which you can find in the link given below: Min / Max Validator in Angular 2 Final If you are using Angular 6 then you can use min and max validators which you can find in the link given below: https://angular.io/api/forms/Validators#min A: I suggest you simply to do a check in function save(). It can be like this: if((new Date()).getFullYear() < this.season.Year) { //display an error message, maybe using alert or toast }
{ "language": "en", "url": "https://stackoverflow.com/questions/51362612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Alpha animation works, then does not work My app is about users picking three buttons: Sad, Happy and Confuse. If they click the Sad button, the image changes into a sad emoji. If they click the Happy button, happy emoji is displayed. Simple. But, when I run my app, and I click any of the buttons, the alpha animation works. If I then click another button, the alpha animation does not work anymore. The alpha animation only works once. The alpha animation is only for the images. Here's my Java code: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Happy_Btn = findViewById(R.id.Happy_Btn); Sad_Btn = findViewById(R.id.Sad_Btn); Confuse_Btn = findViewById(R.id.Confuse_Btn); Feeling_txtView = findViewById(R.id.Feeling_txtView); Face_Img = findViewById(R.id.Face_Img); Animation animation = new AlphaAnimation(0f, 1.0f); animation.setDuration(2000); Feeling_txtView.setText("You are feeling happy!"); Happy_Btn.setEnabled(false); Sad_Btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Sad_Btn.setEnabled(false); Happy_Btn.setEnabled(true); Confuse_Btn.setEnabled(true); Feeling_txtView.setText("You are feeling sad..."); Face_Img.setAnimation(animation); Face_Img.setImageResource(R.drawable.sad); } }); Happy_Btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Sad_Btn.setEnabled(true); Happy_Btn.setEnabled(false); Confuse_Btn.setEnabled(true); Feeling_txtView.setText("You are feeling happy!"); Face_Img.setAnimation(animation); Face_Img.setImageResource(R.drawable.happyface); } }); Confuse_Btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Sad_Btn.setEnabled(true); Happy_Btn.setEnabled(true); Confuse_Btn.setEnabled(false); Feeling_txtView.setText("You are feeling confused?"); Face_Img.setAnimation(animation); Face_Img.setImageResource(R.drawable.confuse); } }); } (EDIT) I made few changes to my code and then when I run it, my issue is solved! But I'm not sure if this is the right way to do it. What I did was I first cut these two lines: Animation animation = new AlphaAnimation(0f, 1.0f); animation.setDuration(2000); and then paste them into each buttons (Sad, Happy and Confuse) My app works the way I wanted it to be. A: you should renew AlphaAnimation you do it is the right
{ "language": "en", "url": "https://stackoverflow.com/questions/67431176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cancel sharepoint workflow when cancel sharepoint workflow by web browser or programatically by code SPWorkflowManager.CancelWorkflow() All task in my workflow task list was deleted, where i can turn off this, i need this task to reporting. A: This is the way SharePoint works, canceling a workflow deletes all related tasks, but the workflow history is kept. Do not rely on tasks as a proof that something did or did not happen.
{ "language": "en", "url": "https://stackoverflow.com/questions/9500458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How "==" works for objects? public static void main(String [] a) { String s = new String("Hai"); String s1=s; String s2="Hai"; String s3="Hai"; System.out.println(s.hashCode()); System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); System.out.println(s3.hashCode()); System.out.println(s==s2); System.out.println(s2==s3); } From the above code can anyone explain what is going behind when JVM encounters this line (s==s2) ? A: It compares references - i.e. are both variables referring to the exact same object (rather than just equal ones). * *s and s2 refer to different objects, so the expression evaluates to false. *s and s1 refer to the same objects (as each other) because of the assignment. *s2 and s3 refer to the same objects (as each other) because of string interning. If that doesn't help much, please ask for more details on a particular bit. Objects and references can be confusing to start with. Note that only string literals are interned by default... so even though s and s2 refer to equal strings, they're still two separate objects. Similarly if you write: String x = new String("foo"); String y = new String("foo"); then x == y will evaluate to false. You can force interning, which in this case would actually return the interned literal: String x = new String("foo"); String y = new String("foo"); String z = "foo"; // Expressions and their values: x == y: false x == z: false x.intern() == y.intern(): true x.intern() == z: true EDIT: A comment suggested that new String(String) is basically pointless. This isn't the case, in fact. A String refers to a char[], with an offset and a length. If you take a substring, it will create a new String referring to the same char[], just with a different offset and length. If you need to keep a small substring of a long string for a long time, but the long string itself isn't needed, then it's useful to use the new String(String) constructor to create a copy of just the piece you need, allowing the larger char[] to be garbage collected. An example of this is reading a dictionary file - lots of short words, one per line. If you use BufferedReader.readLine(), the allocated char array will be at least 80 chars (in the standard JDK, anyway). That means that even a short word like "and" takes a char array of 160 bytes + overheads... you can run out of space pretty quickly that way. Using new String(reader.readLine()) can save the day. A: == compars objects not the content of an object. s and s2 are different objects. If you want to compare the content use s.equals(s2). A: I suppose you know that when you test equality between variables using '==', you are in fact testing if the references in memory are the same. This is different from the equals() method that combines an algorithm and attributes to return a result stating that two Objects are considered as being the same. In this case, if the result is true, it normally means that both references are pointing to the same Object. This leaves me wondering why s2==s3 returns true and whether String instances (which are immutable) are pooled for reuse somewhere. A: Think of it like this. Identical twins look the same but they are made up differently. If you want to know if they "look" the same use the compare. If you want to know they are a clone of each other use the "==" :) A: == compares the memory (reference) location of the Objects. You should use .equals() to compare the contents of the object. You can use == for ints and doubles because they are primitive data types A: It should be an obvious false. JVM does a thing like using the strings that exist in the Memory . Hence s2,s3 point to the same String that has been instantiated once. If you do something like s5="Hai" even that will be equal to s3. However new creates a new Object. Irrespective if the String is already exisitng or not. Hence s doesnot equal to s3,s4. Now if you do s6= new String("Hai"), even that will not be equal to s2,s3 or s. A: The literals s2 and s3 will point to the same string in memory as they are present at compile time. s is created at runtime and will point to a different instance of "Hai" in memory. If you want s to point to the same instance of "Hai" as s2 and s3 you can ask Java to do that for you by calling intern. So s.intern == s2 will be true. Good article here. A: You are using some '==' overload for String class...
{ "language": "en", "url": "https://stackoverflow.com/questions/1887626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Trouble with UPDATE query I'm having problems trying to use the UPDATE query in SQL server. this is my query: UPDATE THEATER SET SeatsAvailable = SeatsAvailable - 1 FROM THEATER INNER JOIN CINEMA_SESSION ON CINEMA_SESSION.tid = THEATER.tid WHERE THEATER.tid = 2 AND CINEMA_SESSION.sid = 2 -tid is the pk for THEATER -sid is the pk for CINEMA_SESSION When I use a SELECT statement to search for the SeatsAvailable in CINEMA_SESSION.sid = 3, which also has .tid=2, it also comes with the updated value for the CINEMA_SESSION.sid = 2. The statement that I'm using is this simple Select statement: SELECT THEATER.SeatsAvailable as SeatsAvailable FROM THEATER INNER JOIN CINEMA_SESSION ON CINEMA_SESSION.tid = THEATER.tid WHERE CINEMA_SESSION.sid = 3 AND THEATER.tid = 2 Here I want to specify the THEATER.tid which is the same in the UPDATE query but in a different CINEMA_SESSION.sid in which the SeatsAvailable should have remained the same. A: The update statement is decrementing the value of SeatsAvailable on the Theatre table for tid=2 (the AND CINEMA_SESSION.sid = 2 is immaterial - you are updating the row on the THEATER table). Since tid is the primary key for theatre, there is only one record with that value, and that record is updated. Your select for session sid=3 joins to theatre by the tid column, and it's matching the row where tid=2, which is why you're seeing the new value - it is matching the record that you just updated. This may make more sense if you just look at the contents of the THEATER table (without any joins). If you are trying to indicate that a seat has been booked for a particular session, then I would suggest you need to be updating a field on a different table. I'll leave that to you to work out. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/49959034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get the variable list from each data frame in a list I have a list of df, and I would like to rename the df as df1, df2, df3. and then create a summary like below to capture the variables in each df. What should I do? I tried to use map to setNames for the data frames in lst, but I must do it in the wrong way. my current codes set variable names to df1, df2, def3. lst<- map( lst ~ setNames(.x, str_c("df", seq_along(lst)))) sample data: lst<-list(structure(list(ID = c("Tom", "Jerry", "Mary"), Score = c(85, 85, 96), Test = c("Y", "N", "Y")), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame")), structure(list(ID = c("Tom", "Jerry", "Mary", "Jerry"), Score = c(75, 65, 88, 98), try = c("Y", NA, "N", NA)), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame")), structure(list(ID = c("Tom", "Jerry", "Tom"), Score = c(97, 65, 96), weight = c("A", NA, "C")), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"))) A: We get the column names with names/colnames by looping, paste to a single string with toString, convert to a data.frame column and bind the elements (_dfr). library(purrr) library(dplyr) library(stringr) setNames(lst, str_c("df", seq_along(lst))) %>% map_dfr(~ tibble(Var = toString(names(.x))), .id = 'Data') -output # A tibble: 3 × 2 Data Var <chr> <chr> 1 df1 ID, Score, Test 2 df2 ID, Score, try 3 df3 ID, Score, weight
{ "language": "en", "url": "https://stackoverflow.com/questions/73666322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check for uniformity of a multidimensional list Following my other question I was surprised to know that Numpy is pretty loose on the definition of array_like objects. Basically np.array(1) is a valid numpy ndarray of shape () and dimension of 0! also np.array([[1,2],[3]]) is a valid ndarray of shape (2,) and dimension of 1. Basically np.array digs as many dimensions as possible till it reaches nonuniformity or zero-dimensional values. This implementation might be pretty fast, but is not necessarily safe. In fact it is very error prone. if somebody forgets one element of an input list, the function returns no error, leading to other most probably more confusing errors down the code. I was thinking if it is possible to write a checkArr function to check the homogeneity and uniformity of the multidimensional list, with the least possible overhead. Scavenging over a couple of other SO post I ended up with this recursive solution: def checkArr(A): assert isinstance(A, (list,tuple,range)), "input must be iterable (list, tuple, range)" assert all(isinstance(a, type(A[0])) for a in A[1:]), "elements of the input must of a the same type, input must be homogeneous" if isinstance(A[0], (list,tuple,range)): assert all(len(a)==len(A[0]) for a in A[1:]), "elements of the input must of a the same size, input must be uniform" [checkArr(a) for a in A] now my question is if this is the fastest solution or more performant/Pythonic implementations are possible? A: Specifying dtype argument when creating an array avoids the unintentional creation of object arrays from jagged matrices, without writing any additional code. np.array([[1, 2], [3, 4]], dtype=int) # okay np.array([[1, 2], [3]], dtype=int) # ValueError np.array([[1, "b"]], dtype=int) # ValueError (Regarding the last one, np.array([1, "b"]) would silently convert "1" to a string if the data type was not set.) A: There's Python saying that it's easier to ask forgiveness than permission. So there might be less overhead if you just call np.array and then check for object dtype. One other thing that you need to watch out for is when it throws an error. For example: In [273]: np.array((np.zeros((2,3)), np.ones((2,4)))) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-273-70f6273e3371> in <module>() ----> 1 np.array((np.zeros((2,3)), np.ones((2,4)))) ValueError: could not broadcast input array from shape (2,3) into shape (2) If the non-uniformity is in the first dimension, it produces an object dtype array, e.g. np.array((np.zeros((2,3)), np.ones((1,4)))). But when it's at a deeper level it appears to allocate the result array, and then has problems copying one or more of the component arrays to it. This is a tricky case to diagnose. Or consider: In [277]: np.array([[1,2,3],[4,5,'6']]) Out[277]: array([['1', '2', '3'], ['4', '5', '6']], dtype='<U21') The last element in the nested list forces the string dtype. And if that last element is some other PYthon object, we may be a object dtype: In [279]: np.array([[1,2,3],[4,5,{}]]) Out[279]: array([[1, 2, 3], [4, 5, {}]], dtype=object) But if the object is a list, we get a variant on the broadcasting error: In [280]: np.array([[1,2,3],[4,5,['6']]]) ValueError: setting an array element with a sequence But if you do want to check first, np.stack might a good model. With axis=0 it behaves much like np.array if given arrays or lists.
{ "language": "en", "url": "https://stackoverflow.com/questions/53146270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PostgreSQL: "index row requires 1460216 bytes, maximum size is 8191" I'm new to PostgreSQL and I'm trying to populate a table with the content of a list of dictionaries built in Python, which looks like: diclist = [{'accession':'value', 'species':'value', 'seq':'value', 'length': 'value'}, {'accession':'value', 'species':'value', 'seq':'value', 'length': 'value'}, ...] 'seq' values are strings with sometimes > 300.000 characters... However, my data include genetic sequences which are pretty long so when I try to load these data into the table, PostgreSQL claims the following: index row requires 1460216 bytes, maximum size is 8191 Is there a way to increase the row index maximum size?? Or is there a way to compress the space required by my data? I know BioPython and BioSQL are made to handle genetic sequences, but they don't exactly match what I need... This is the function I've built for the moment (diclist is the list of dictionaries): def insert_biosequence(diclist): try: params = config() conn = psycopg2.connect(**params) cur = conn.cursor() cur.executemany("""INSERT INTO biosequence(accession, species, seq, length) VALUES (%(accession)s, %(species)s, %(seq)s, %(length)s)""", diclist) conn.commit() cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() My CREATE TABLE command is the following: CREATE TABLE biosequence ( accession TEXT, species TEXT, seq TEXT PRIMARY KEY, length INTEGER ); I'm not using any INDEX commands, I think it's done by default by PostgreSQL... should I? A: Given that your data is structured, you probably want to create a schema that better suits your structure and then load it in that format rather than just raw source data, or at the very least load the raw data and then transform it into your structure format for easier searching. Otherwise, you might be able to use full text search with GIN index or a GIN index with the pg_trgm operators.
{ "language": "en", "url": "https://stackoverflow.com/questions/50962803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to play a specific tone using python3? I'm working on a python3 project (in PyCharm, using Windows 10) and I'm trying to play a series of tones and save them all to a mp3 file. I can get it to play a series of notes with winsound: import winsound while True: winsound.Beep(1000, 1000) But I can't save it. All help appreciated! A: If you want to save output to a file, rather than just play it, probably the most ideal way of doing this is to generate midi files. There are a few packages that can help you create midi files in a similar way. This example uses the package called mido from mido import Message, MidiFile, MidiTrack mid = MidiFile() track = MidiTrack() mid.tracks.append(track) track.append(Message('note_on', note=64, velocity=64, time=32)) mid.save('new_song.mid') You can convert midi files to MP3s easily if needed (many programs or even online tools can do this) although, midi files are generally well-supported in most applications. See also Although perhaps dated, you can also check the PythonInMusic wiki for references to more MIDI and other audio libraries. Alternatively, you can use a separate program to record your audio output when running your python script using winsound.
{ "language": "en", "url": "https://stackoverflow.com/questions/64838270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can setting MinHeight of a WPF control be a workaround for failing VirtualizingStackPanel.ExtendViewport? And if it is, what control would be the best bet? DataGrid that has the virtualization or something else? This happens very very rarely so trial and error is not an option. Portion of my xaml and converter used is in the end. This happens sometimes (maybe 1/1000?) when DataGrid's itemssource (ICollectionView) is refreshed. 2017-10-06 09:00:35: myapp.exe Error: 0 : Unhandled exception. System.ArgumentException: Height must be non-negative. at System.Windows.Rect.set_Height(Double value) at System.Windows.Controls.VirtualizingStackPanel.ExtendViewport(IHierarchicalVirtualizationAndScrollInfo virtualizationInfoProvider, Boolean isHorizontal, Rect viewport, VirtualizationCacheLength cacheLength, VirtualizationCacheLengthUnit cacheUnit, Size stackPixelSizeInCacheBeforeViewport, Size stackLogicalSizeInCacheBeforeViewport, Size stackPixelSizeInCacheAfterViewport, Size stackLogicalSizeInCacheAfterViewport, Size stackPixelSize, Size stackLogicalSize, Int32& itemsInExtendedViewportCount) at System.Windows.Controls.VirtualizingStackPanel.IsExtendedViewportFull() at System.Windows.Controls.VirtualizingStackPanel.ShouldItemsChangeAffectLayoutCore(Boolean areItemChangesLocal, ItemsChangedEventArgs args) at System.Windows.Controls.VirtualizingPanel.OnItemsChangedInternal(Object sender, ItemsChangedEventArgs args) at System.Windows.Controls.Panel.OnItemsChanged(Object sender, ItemsChangedEventArgs args) at System.Windows.Controls.ItemContainerGenerator.OnItemAdded(Object item, Int32 index) at System.Windows.Controls.ItemContainerGenerator.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args) at System.Windows.WeakEventManager.ListenerList`1.DeliverEvent(Object sender, EventArgs e, Type managerType) at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args) at System.Collections.ObjectModel.ReadOnlyObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item) at MS.Internal.Data.CollectionViewGroupInternal.Insert(Object item, Object seed, IComparer comparer) at MS.Internal.Data.CollectionViewGroupRoot.AddToSubgroup(Object item, LiveShapingItem lsi, CollectionViewGroupInternal group, Int32 level, Object name, Boolean loading) at MS.Internal.Data.CollectionViewGroupRoot.AddToSubgroups(Object item, LiveShapingItem lsi, CollectionViewGroupInternal group, Int32 level, Boolean loading) at System.Windows.Data.ListCollectionView.AddItemToGroups(Object item, LiveShapingItem lsi) at System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs args, Int32 adjustedOldIndex, Int32 adjustedNewIndex) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item) at MS.Internal.Data.EnumerableCollectionView.LoadSnapshotCore(IEnumerable source) at MS.Internal.Data.EnumerableCollectionView.LoadSnapshot(IEnumerable source) at System.Windows.Data.CollectionView.RefreshInternal() XAML: <Grid Margin="5"> <Grid.RowDefinitions> <RowDefinition Name="SelectedObjectsRowDefinition"> <RowDefinition.Height> <MultiBinding Converter="{StaticResource GridRowHeightConverter}"> <Binding ElementName="SelectedObjectsExpander" Path="IsExpanded" /> <Binding Path="IsSelectedObjectsVisible" /> <Binding ElementName="SelectedObjectsGrid" Path="Items.Count" /> </MultiBinding> </RowDefinition.Height> </RowDefinition> <RowDefinition Name="SelectedSwitchesRowDefinition"> <RowDefinition.Height> <MultiBinding Converter="{StaticResource GridRowHeightConverter}"> <Binding ElementName="SelectedSwitchesExpander" Path="IsExpanded" /> <Binding Path="IsSelectedSwitchesVisible" /> <Binding ElementName="SelectedSwitchesGrid" Path="Items.Count" /> </MultiBinding> </RowDefinition.Height> </RowDefinition> <RowDefinition Name="SelectionsRowDefinition"> <RowDefinition.Height> <MultiBinding Converter="{StaticResource GridRowHeightConverter}"> <Binding ElementName="SelectionsExpander" Path="IsExpanded" /> <Binding Path="IsSelectionSetsVisible" /> <Binding ElementName="SelectionSetsGrid" Path="Items.Count" /> </MultiBinding> </RowDefinition.Height> </RowDefinition> </Grid.RowDefinitions> <Expander Grid.Row="0" Header="{DynamicResource XpStrSelectedObjects}" x:Name="SelectedObjectsExpander" AutomationProperties.AutomationId="SelectedObjectsExp" IsExpanded="{Binding IsSelectedObjectsExpanded}" Visibility="{Binding IsSelectedObjectsVisible, Converter={StaticResource BoolToVisibilityConverter}}"> <Grid Margin="15,0,0,0"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid Background="White" Visibility="{Binding ShowSelectedObjectsInfoPanel, Converter={StaticResource BoolToVisibilityConverter}}" Margin="0,0,4,0"> <StackPanel Margin="0,0,4,0"> <TextBlock Text="{Binding SelectedObjectsInfoPanelText}" FontStyle="Italic" HorizontalAlignment="Center" VerticalAlignment="Center" /> <Button HorizontalAlignment="Center" Content="{StaticResource NisStrShowAnyway}" Visibility="{Binding IsFetchObjectsAnywayVisible, Converter={StaticResource BoolToVisibilityConverter}}" Command="{ui:CommandHandler FetchObjectsAnyway}" AutomationProperties.AutomationId="ShowAnywayBtn"/> </StackPanel> </Grid> <DataGrid Name="SelectedObjectsGrid" AutomationProperties.AutomationId="SelectedObjectsDgd" Visibility="{Binding ShowSelectedObjectsInfoPanel, Converter={StaticResource BoolNegationToVisibilityConverter}}" ItemsSource="{Binding SelectedObjectItems}" SelectionMode="Extended" CanUserAddRows="False" AutoGenerateColumns="False" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.IsVirtualizingWhenGrouping="True" VirtualizingPanel.VirtualizationMode="Standard" VerticalAlignment="Top" IsReadOnly="True" Grid.Row="0" Margin="0,0,4,0"> Convert-method of IMultivalueConverter used in XAML above: public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { try { bool isExpanded = (bool)values[0]; bool isVisible = (bool)values[1]; int itemsCount = (int)values[2]; if (!isVisible || !isExpanded || itemsCount == 0) return System.Windows.GridLength.Auto; else return new System.Windows.GridLength(1, System.Windows.GridUnitType.Star); } catch (Exception) { return new System.Windows.GridLength(1, System.Windows.GridUnitType.Star); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/46646592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Trying to use AJAX for the first time - modified code from W3Schools does not work I was editing the default code from W3Schools, and it doesn't work now. Can someone point out my error and why it will not update the text? <html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } function switchText() {loadXMLDoc() xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="switchText()">Change Content</button> </body> </html> A: Your var = xmlhttp; is outside of switchText scope and so it's undefined and throws an error. Try this <html> <head> <script type="text/javascript"> var xmlhttp; function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } function switchText() {loadXMLDoc(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="switchText()">Change Content</button> </body> </html> A: I think the issue you have is that you have not validated your code, even down to whether you have matching curly braces or not (hint, you do not!) moving the open and send commands back into the first function and removing the extra curly brace shoudl work. the below should work : <html> <head> <script type="text/javascript"> var xmlhttp; function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } function switchText() { loadXMLDoc(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="switchText()">Change Content</button> </body> </html> hope that helps Olly A: I think the problem is with the following line in ajax_object.html file: if (xmlhttp.readyState==4 && xmlhttp.status==200) If you run the file with the above line and look at the 'Show Page Source', it will be apparent that the 'Request & Response' header has its -- Status and Code --- set to nothing So, delete the line and you will get: <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!--script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script--> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html> If you run this code it will output the ajax_info.txt file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7983063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I assign the "active" value to a tab on the first tab in a php while loop? I'm using a while loop to populate tabs with PHP. If I assign active while it's in the loop then they are all active. This much I understand. If I only want the first item / tab to have the class="tab-pane fade p-2 -->active<--" where should the script be changed? while($row = $result->fetch_assoc() ) { $id = $row['id']; $in = $row['initial']; $name = $row['name']; echo "<div class=\"tab-pane fade p-2 active\" id=\"$in\" role=\"tabpanel\" aria-labelledby=\"$in-tab\">"; // make tabs A: Track an indicator that you've already rendered the "first" tab. Something as simple as: $firstTab = true; Then within the loop, set it to true after rendering the "first" tab, conditionally including the active class: $firstTab = true; while($row = $result->fetch_assoc() ) { $id = $row['id']; $in = $row['initial']; $name = $row['name']; echo "<div class=\"tab-pane fade p-2 " . ($firstTab ? "active" : "") . "\" id=\"$in\" role=\"tabpanel\" aria-labelledby=\"$in-tab\">"; $firstTab = false; } A: First: write HTML as HTML, not using strings. You'll need to use a index, like: <?php $i = 0; while($row = $result->fetch_assoc() ) { $id = $row['id']; $in = $row['initial']; $name = $row['name']; ?> <div class="tab-pane fade p-2 <?= $i === 0 ? 'active' : '' ?>" id="<?= $in ?>" role="tabpanel" aria-labelledby="<?= $in-tab ?>"> ... </div> <?php $i++; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/73907965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Updating an Activity from an AsyncTask So I'm an iOS developer learning android, and I'm having a difficult time understanding some things. Right now I have a datamanager class. In that class it has an AsyncTask to update the data. OnPreExecute I pop an activity to show it is updating. I understand I could use extras to pass initial information to the UpdateActivity. My problem is I'm not sure how to send new information in OnProgressUpdate. Here is my code widdled down: private class myTask extends AsyncTask<Integer,String,Void>{ @Override protected void onCancelled() { super.onCancelled(); isUpdating = false; } @Override protected Void doInBackground(Integer... params) { //My BG Code } @Override protected void onPostExecute(Void result) { // TODO Remove updating view super.onPostExecute(result); } @Override protected void onPreExecute() { super.onPreExecute(); Intent myIntent = new Intent(mContext,UpdateActivity.class); mContext.startActivity(myIntent); } } A: AsyncTask is designed to work best when nested in an Activity class. What makes AsyncTask 'special' is that it isn't just a worker thread - instead it combines a worker thread which processes the code in doInBackground(...) with methods which run on the Activity's UI thread - onProgressUpdate(...) and onPostExecute(...) being the most commonly used. By periodically calling updateProgress(...) from doInBackground(...), the onProgressUpdate(...) method is called allowing it to manipulate the Activity's UI elements (progress bar, text to show name of file being downloaded, etc etc). In short, rather than firing your 'update' Activity from an AsyncTask, your update Activity itself should have a nested AsyncTask which it uses to process the update and publish progress to the UI. A: You have two options: 1) Pass an instance of activity to your AsyncTask constructor in order to invoke some method on it: new MyTask(this).execute(); So, you can do: public MyTask (Activity activity) { this.activity = activity; } public void onPostExecute(...) { activity.someMethod(); } 2) Pass a Handler instance and send message from onPostExecute() to the activity.
{ "language": "en", "url": "https://stackoverflow.com/questions/6215313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Cordova no standby smartphone I have developed a corded app for a radio station where you can listen to broadcasts. now after some time the smartphones go dark (go to standby) and after a while the audio is also interrupted. How can I avoid this? A: You can avoid this by using the insomnia plugin
{ "language": "en", "url": "https://stackoverflow.com/questions/69480083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google indexing cfc's and giving 500 error So I'm working on a ColdFusion site and this morning we found out that Google is crawling our site and following cfc and getting a 500 error. We are using the cfc with ajax calls so they should not be crawled. How can we fix this? A: The only reason I can think of that Google would index your cfc's would be that it is finding links to them in your pages. Remember, the Google bot can also find the links in your JavaScript code. You should be able to create/modify your robots.txt file to tell the search engines to exclude the directory(ies) that contain your cfc's from their indexes. Sample robots.txt entry: User-Agent: * Disallow: /cfc-directory/ The Google bot (but not all search engines) can even support some pattern matching (reference). So you could tell the Google bot not to index any files ending with .cfc by doing this: User-agent: Googlebot Disallow: /*.cfc$ A quick search turned up this similar question. In it @nosilleg mentions that the javascript code generated by ColdFusion's cfajaxproxy includes links to cfc's (in particular to /baseCFC/Statement.cfc. So if you are using that in any of your pages it will also contain links to cfc's.
{ "language": "en", "url": "https://stackoverflow.com/questions/18200034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't this simple VBA code work in Excel? I'm quite new to programming with VBA (or any language, let's be honest). I'm trying to do a project for work, adding short sections at a time to see if the code still works, and trying out new code in a separate Sub. I've come across an error that I can't get around. The results don't change when they're the only line in a separate Sub. The following code works: ActiveWorkbook.Sheets("Template").Copy After:=ActiveWorkbook.Sheets("Student info") Whereas the following code, when run, breaks with a 424 run-time error (object required). I've tried selecting instead of naming, still no luck. It does successfully copy the worksheet to the correct place, despite the error, but is called 'Template (2)'. ActiveWorkbook.Sheets("Template").Copy(After:=ActiveWorkbook.Sheets("Student info")).name = "newname" This is very confusing because the code below does work. Is it just that trying to name something after using 'add' does work, but after 'copy', it doesn't? ActiveWorkbook.Sheets.Add(After:=ActiveWorkbook.Sheets("Student info")).name = Student_name Thanks in advance for any help. A: The reference (to the created copy) as return value (of a function) would be useful, but as Worksheet.Copy is a method of one worksheet (in opposite to Worksheets.Add what is a method of the worksheets-collection), they didn't created it. But as you know where you created it (before or after the worksheet you specified in arguments, if you did), you can get its reference by that position (before or after). In a function returning the reference: Public Enum WorkdheetInsertPosition InsertAfter InsertBefore End Enum Public Function CopyAndRenameWorksheet(ByRef sourceWs As Worksheet, ByRef targetPosWs As Worksheet, ByVal insertPos As WorkdheetInsertPosition, ByVal NewName As String) As Worksheet 'If isWsNameInUse(NewName) then 'Function isWsNameInUse needs to be created to check name! 'Debug.Print NewName & " alredy in use" 'Exit Function 'End If With sourceWs Dim n As Long Select Case insertPos Case InsertAfter .Copy After:=targetPosWs n = 1 Case InsertBefore .Copy Before:=targetPosWs n = -1 Case Else 'should not happen unless enum is extended End Select End With Dim NewWorksheet As Worksheet Set NewWorksheet = targetPosWs.Parent.Worksheets(targetPosWs.Index + n) 'Worksheet.Parent returns the Workbook reference to targetPosWs NewWorksheet.Name = NewName ' if name already in use an error occurs, should be tested before Set CopyWorksheetAndRename = NewWorksheet End Function usage (insert after): Private Sub testCopyWorkSheet() Debug.Print CopyAndRenameWorksheet(ActiveWorkbook.Sheets("Template"), ActiveWorkbook.Sheets("Student info"), InsertAfter, Student_name).Name End Sub to insert the copy before the target worksheet, change third argument to InsertBefore (enumeration of options). New Worksheet.Name needs to be unique or you'll get an error (as long you not implemented the isWsNameInUse function to check that). Also note that there is a difference between .Sheets and .Worksheets You can get the links to the documentation by moving the cursor (with mouse left-click) in the code over the object/method you want more infos on and then press F1
{ "language": "en", "url": "https://stackoverflow.com/questions/63968869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP preg_replace: remove style=“..” from all tags except img It is the reverse of : PHP preg_replace: remove style=".." from img tags Im trying to find an expression for preg_replace, that deletes all inline css styles except for images. For example, I have this text: <img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" style="myCustom" attribut='value' style='myCustom'> <span attribut="value" style="myCustom" attribut='value' style='myCustom'> style= </span> And I need to make it look like: <img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" "myCustom" attribut='value' 'myCustom'> <span attribut="value" "myCustom" attribut='value' 'myCustom'> style= </span> or like this: <img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" attribut='value'> <span attribut="value" attribut='value'> style= </span> It might looks like this preg_replace('/(\<img[^>]+)(style\=\"[^\"]+\")([^>]+)(>)/', '${1}${3}${4}', $article->text) A: The regex issue can be answered with a simple negative assertion: preg_replace('/(<(?!img)\w+[^>]+)(style="[^"]+")([^>]*)(>)/', '${1}${3}${4}', $article->text) And a simpler approach might be using querypath (rather than fiddly DOMDocument): FORACH htmlqp($html)->find("*")->not("img") EACH $el->removeAttr("style"); A: This does as you've asked $string = '<img attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\' /> <input attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\'> <span attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\'> style= </span>'; preg_match_all('/\<img.+?\/>/', $string, $images); foreach ($images[0] as $i => $image) { $string = str_replace($image,'--image'.$i.'--', $string); } $string = preg_replace(array('/style=[\'\"].+?[\'\"]/','/style=/'), '', $string); foreach ($images[0] as $i => $image) { $string = str_replace('--image'.$i.'--',$image, $string); } OUTPUTS <img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" attribut='value' > <span attribut="value" attribut='value' > </span> A: A very simple regular expression to get rid of them, without going too much into it would be preg_replace( '/style="(.*)"/', 'REPLACEMENT' ) Very simple, effective enough though
{ "language": "en", "url": "https://stackoverflow.com/questions/8344293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I debug my code for the A star algorithm? I have been trying to program different A star algorithms I found online and though they make sense, every implementation I have programmed failed. This is my Free Pascal code: function getHeuristic(currentXY, targetXY: array of word): word; begin getHeuristic:=abs(currentXY[0]-targetXY[0])+abs(currentXY[1]-targetXY[1]); end; function getPath(startingNodeXY, targetNodeXY: array of word; grid: wordArray3; out pathToControlledCharPtr: word; worldObjIndex: word): wordArray2; var openList, closedList: array of array of word; { x/y/g/h/parent x/parent y, total } qXYGH: array[0..5] of word; { x/y/g/h/parent x/parent y } gridXCnt, gridYCnt: longInt; maxF, q, openListCnt, closedListCnt, parentClosedListCnt, getPathCnt, adjSquNewGScore: word; openListIndexCnt, closedListIndexCnt, qIndexCnt, successorIndexCnt: byte; getMaxF, successorOnClosedList, successorOnOpenList, pathFound: boolean; begin { Add the starting square (or node) to the open list. } setLength(openList, 6, length(openList)+1); openList[0, 0]:=startingNodeXY[0]; openList[1, 0]:=startingNodeXY[1]; setLength(closedList, 6, 0); { Repeat the following: } { D) Stop when you: } { Fail to find the target square, and the open list is empty. In this case, there is no path. } pathFound:=false; { writeLn('h1'); } while length(openList[0])>0 do begin { A) Look for the lowest F cost square on the open list. We refer to this as the current square. } maxF:=0; q:=0; getMaxF:=true; for openListCnt:=0 to length(openList[0])-1 do begin //writeLn(formatVal('open list xy {} {}, cnt {}, list max index {}', [openList[0, openListCnt], openList[1, openListCnt], openListCnt, length(openList[0])-1])); { readLnPromptX; } if (getMaxF=true) or (maxF>openList[2, openListCnt]+openList[3, openListCnt]) then begin getMaxF:=false; maxF:=openList[2, openListCnt]+openList[3, openListCnt]; q:=openListCnt; end; end; for qIndexCnt:=0 to length(qXYGH)-1 do qXYGH[qIndexCnt]:=openList[qIndexCnt, q]; { B). Switch it to the closed list. } setLength(closedList, length(closedList), length(closedList[0])+1); for closedListIndexCnt:=0 to length(closedList)-1 do closedList[closedListIndexCnt, length(closedList[0])-1]:=qXYGH[closedListIndexCnt]; { Remove current square from open list } if q<length(openList[0])-1 then begin for openListCnt:=q to length(openList[0])-2 do begin for openListIndexCnt:=0 to length(openList)-1 do openList[openListIndexCnt, openListCnt]:=openList[openListIndexCnt, openListCnt+1]; end; end; setLength(openList, length(openList), length(openList[0])-1); //writeLn(formatVal('q[x] {}, q[y] {}, startingNodeXY x {}, startingNodeXY y {}, targetNodeXY x {}, targetNodeXY y {}', [qXYGH[0], qXYGH[1], startingNodeXY[0], startingNodeXY[1], targetNodeXY[0], targetNodeXY[1]])); { readLnPromptX; } { D) Stop when you: } { Add the target square to the closed list, in which case the path has been found, or } if (qXYGH[0]=targetNodeXY[0]) and (qXYGH[1]=targetNodeXY[1]) then begin pathFound:=true; break; end; { C) For each of the 8 squares adjacent to this current square … } for gridXCnt:=qXYGH[0]-1 to qXYGH[0]+1 do begin for gridYCnt:=qXYGH[1]-1 to qXYGH[1]+1 do begin { Adjacent square cannot be the current square } if (gridXCnt<>qXYGH[0]) or (gridYCnt<>qXYGH[1]) then begin //writeLn(formatVal('gridXCnt {} gridYCnt {} qXYGH[0] {} qXYGH[1] {}', [gridXCnt, gridYCnt, qXYGH[0], qXYGH[1]])); { readLnPromptX; } { Check if successor is on closed list } successorOnClosedList:=false; if length(closedList[0])>0 then begin for closedListCnt:=0 to length(closedList[0])-1 do begin if (closedList[0, closedListCnt]=gridXCnt) and (closedList[1, closedListCnt]=gridYCnt) then begin successorOnClosedList:=true; break; end; end; end; { If it is not walkable or if it is on the closed list, ignore it. Otherwise do the following. } if (gridXCnt>=0) and (gridXCnt<=length(grid[3])-1) and (gridYCnt>=0) and (gridYCnt<=length(grid[3, 0])-1) and (grid[3, gridXCnt, gridYCnt]=0) and (successorOnClosedList=false) then begin { If it isn’t on the open list, add it to the open list. Make the current square the parent of this square. Record the F, G, and H costs of the square. } successorOnOpenList:=false; if length(openList[0])>0 then begin for openListCnt:=0 to length(openList[0])-1 do begin if (openList[0, openListCnt]=gridXCnt) and (openList[1, openListCnt]=gridYCnt) then begin successorOnOpenList:=true; break; end; end; end; if successorOnOpenList=false then begin setLength(openList, length(openList), length(openList[0])+1); openList[0, length(openList[0])-1]:=gridXCnt; openList[1, length(openList[0])-1]:=gridYCnt; openList[4, length(openList[0])-1]:=qXYGH[0]; openList[5, length(openList[0])-1]:=qXYGH[1]; if (openList[0, length(openList[0])-1]=qXYGH[0]) or (openList[1, length(openList[0])-1]=qXYGH[1]) then begin openList[2, length(openList[0])-1]:=openList[2, length(openList[0])-1]+10; end else begin openList[2, length(openList[0])-1]:=openList[2, length(openList[0])-1]+14; end; openList[3, length(openList[0])-1]:=getHeuristic([openList[0, length(openList[0])-1], openList[1, length(openList[0])-1]], [targetNodeXY[0], targetNodeXY[1]]); end else begin { If it is on the open list already, check to see if this path to that square is better, using G cost as the measure (check to see if the G score for the adjacent square is lower if we use the current square to get there (adjacent square new G score = current square G score + 10 (if adjacent squre is vertical or horizontal to current square) or +14 (if it is diagonal); if result is lower than adjacent square current G score then this path is better). A lower G cost means that this is a better path. If so, change the parent of the square to the current square, and recalculate the G and F scores of the square. If you are keeping your open list sorted by F score, you may need to resort the list to account for the change. } adjSquNewGScore:=openList[2, openListCnt]; if (openList[0, openListCnt]=qXYGH[0]) or (openList[1, openListCnt]=qXYGH[1]) then begin adjSquNewGScore:=adjSquNewGScore+10; end else begin adjSquNewGScore:=adjSquNewGScore+14; end; if adjSquNewGScore<openList[2, openListCnt] then begin openList[4, openListCnt]:=qXYGH[0]; openList[5, openListCnt]:=qXYGH[1]; openList[2, openListCnt]:=adjSquNewGScore; end; end; end; end; end; end; end; { writeLn('h2'); } { writeLn(pathFound); } { readLnHalt; } if pathFound=true then begin { Save the path. Working backwards from the target square, go from each square to its parent square until you reach the starting square. That is your path. } closedListCnt:=length(closedList[0])-1; setLength(getPath, 2, 0); { While starting node has not been added to path } while (length(getPath[0])=0) or (getPath[0, length(getPath[0])-1]<>startingNodeXY[0]) or (getPath[1, length(getPath[0])-1]<>startingNodeXY[1]) do begin { Add node from closed list to path } setLength(getPath, 2, length(getPath[0])+1); getPath[0, length(getPath[0])-1]:=closedList[0, closedListCnt]; getPath[1, length(getPath[0])-1]:=closedList[1, closedListCnt]; { Find next node on closed list with coord matching parent coord of current closed list node } for parentClosedListCnt:=length(closedList[0])-1 downto 0 do if (closedList[0, parentClosedListCnt]=closedList[4, closedListCnt]) and (closedList[1, parentClosedListCnt]=closedList[5, closedListCnt]) then break; closedListCnt:=parentClosedListCnt; { if (closedList[0, closedListCnt]=0) and (closedList[1, closedListCnt]=0) then break; } end; pathToControlledCharPtr:=length(getPath[0])-1; end; end; The steps I'm following are: * *Add the starting square (or node) to the open list. *Repeat the following: A) Look for the lowest F cost square on the open list. We refer to this as the current square. B). Switch it to the closed list. C) For each of the 8 squares adjacent to this current square … * *If it is not walkable or if it is on the closed list, ignore it. Otherwise do the following. *If it isn’t on the open list, add it to the open list. Make the current square the parent of this square. Record the F, G, and H costs of the square. *If it is on the open list already, check to see if this path to that square is better, using G cost as the measure. A lower G cost means that this is a better path. If so, change the parent of the square to the current square, and recalculate the G and F scores of the square. If you are keeping your open list sorted by F score, you may need to resort the list to account for the change. D) Stop when you: * *Add the target square to the closed list, in which case the path has been found, or *Fail to find the target square, and the open list is empty. In this case, there is no path. *Save the path. Working backwards from the target square, go from each square to its parent square until you reach the starting square. That is your path. A: Solved it! This is the working code: function getHeuristic(currentXY, targetXY: array of word): word; begin getHeuristic:=abs(currentXY[0]-targetXY[0])+abs(currentXY[1]-targetXY[1]); end; function getPath(startingNodeXY, targetNodeXY: array of word; grid: wordArray3; out pathToControlledCharPtr: word; worldObjIndex: word): wordArray2; var openList, closedList: array of array of word; { x/y/g/h/parent x/parent y, total } qXYGH: array[0..5] of word; { x/y/g/h/parent x/parent y } gridXCnt, gridYCnt: longInt; maxF, q, openListCnt, closedListCnt, parentClosedListCnt, getPathCnt, adjSquNewGScore: word; openListIndexCnt, closedListIndexCnt, qIndexCnt, successorIndexCnt: byte; getMaxF, successorOnClosedList, successorOnOpenList, pathFound: boolean; begin { Add the starting square (or node) to the open list. } setLength(openList, 6, length(openList)+1); openList[0, 0]:=startingNodeXY[0]; openList[1, 0]:=startingNodeXY[1]; setLength(closedList, 6, 0); { Repeat the following: } { D) Stop when you: } { Fail to find the target square, and the open list is empty. In this case, there is no path. } pathFound:=false; { writeLn('h1'); } while length(openList[0])>0 do begin { A) Look for the lowest F cost square on the open list. We refer to this as the current square. } maxF:=0; q:=0; getMaxF:=true; for openListCnt:=0 to length(openList[0])-1 do begin //writeLn(formatVal('open list xy {} {}, cnt {}, list max index {}', [openList[0, openListCnt], openList[1, openListCnt], openListCnt, length(openList[0])-1])); { readLnPromptX; } if (getMaxF=true) or (maxF>openList[2, openListCnt]+openList[3, openListCnt]) then begin getMaxF:=false; maxF:=openList[2, openListCnt]+openList[3, openListCnt]; q:=openListCnt; end; end; for qIndexCnt:=0 to length(qXYGH)-1 do qXYGH[qIndexCnt]:=openList[qIndexCnt, q]; { B). Switch it to the closed list. } setLength(closedList, length(closedList), length(closedList[0])+1); for closedListIndexCnt:=0 to length(closedList)-1 do closedList[closedListIndexCnt, length(closedList[0])-1]:=qXYGH[closedListIndexCnt]; { Remove current square from open list } if q<length(openList[0])-1 then begin for openListCnt:=q to length(openList[0])-2 do begin for openListIndexCnt:=0 to length(openList)-1 do openList[openListIndexCnt, openListCnt]:=openList[openListIndexCnt, openListCnt+1]; end; end; setLength(openList, length(openList), length(openList[0])-1); //writeLn(formatVal('q[x] {}, q[y] {}, startingNodeXY x {}, startingNodeXY y {}, targetNodeXY x {}, targetNodeXY y {}', [qXYGH[0], qXYGH[1], startingNodeXY[0], startingNodeXY[1], targetNodeXY[0], targetNodeXY[1]])); { readLnPromptX; } { D) Stop when you: } { Add the target square to the closed list, in which case the path has been found, or } if (qXYGH[0]=targetNodeXY[0]) and (qXYGH[1]=targetNodeXY[1]) then begin pathFound:=true; break; end; { C) For each of the 8 squares adjacent to this current square … } for gridXCnt:=qXYGH[0]-1 to qXYGH[0]+1 do begin for gridYCnt:=qXYGH[1]-1 to qXYGH[1]+1 do begin { Adjacent square cannot be the current square } if (gridXCnt<>qXYGH[0]) or (gridYCnt<>qXYGH[1]) then begin //writeLn(formatVal('gridXCnt {} gridYCnt {} qXYGH[0] {} qXYGH[1] {}', [gridXCnt, gridYCnt, qXYGH[0], qXYGH[1]])); { readLnPromptX; } { Check if successor is on closed list } successorOnClosedList:=false; if length(closedList[0])>0 then begin for closedListCnt:=0 to length(closedList[0])-1 do begin if (closedList[0, closedListCnt]=gridXCnt) and (closedList[1, closedListCnt]=gridYCnt) then begin successorOnClosedList:=true; break; end; end; end; { If it is not walkable or if it is on the closed list, ignore it. Otherwise do the following. } if (gridXCnt>=0) and (gridXCnt<=length(grid[3])-1) and (gridYCnt>=0) and (gridYCnt<=length(grid[3, 0])-1) and (grid[3, gridXCnt, gridYCnt]=0) and (successorOnClosedList=false) then begin { If it isn’t on the open list, add it to the open list. Make the current square the parent of this square. Record the F, G, and H costs of the square. } successorOnOpenList:=false; if length(openList[0])>0 then begin for openListCnt:=0 to length(openList[0])-1 do begin if (openList[0, openListCnt]=gridXCnt) and (openList[1, openListCnt]=gridYCnt) then begin successorOnOpenList:=true; break; end; end; end; if successorOnOpenList=false then begin setLength(openList, length(openList), length(openList[0])+1); openList[0, length(openList[0])-1]:=gridXCnt; openList[1, length(openList[0])-1]:=gridYCnt; openList[4, length(openList[0])-1]:=qXYGH[0]; openList[5, length(openList[0])-1]:=qXYGH[1]; if (openList[0, length(openList[0])-1]=qXYGH[0]) or (openList[1, length(openList[0])-1]=qXYGH[1]) then begin openList[2, length(openList[0])-1]:=openList[2, length(openList[0])-1]+10; end else begin openList[2, length(openList[0])-1]:=openList[2, length(openList[0])-1]+14; end; openList[3, length(openList[0])-1]:=getHeuristic([openList[0, length(openList[0])-1], openList[1, length(openList[0])-1]], [targetNodeXY[0], targetNodeXY[1]]); end else begin { If it is on the open list already, check to see if this path to that square is better, using G cost as the measure (check to see if the G score for the adjacent square is lower if we use the current square to get there (adjacent square new G score = current square G score + 10 (if adjacent squre is vertical or horizontal to current square) or +14 (if it is diagonal); if result is lower than adjacent square current G score then this path is better). A lower G cost means that this is a better path. If so, change the parent of the square to the current square, and recalculate the G and F scores of the square. If you are keeping your open list sorted by F score, you may need to resort the list to account for the change. } adjSquNewGScore:=openList[2, openListCnt]; if (openList[0, openListCnt]=qXYGH[0]) or (openList[1, openListCnt]=qXYGH[1]) then begin adjSquNewGScore:=adjSquNewGScore+10; end else begin adjSquNewGScore:=adjSquNewGScore+14; end; if adjSquNewGScore<openList[2, openListCnt] then begin openList[4, openListCnt]:=qXYGH[0]; openList[5, openListCnt]:=qXYGH[1]; openList[2, openListCnt]:=adjSquNewGScore; end; end; end; end; end; end; end; { writeLn('h2'); } { writeLn(pathFound); } { readLnHalt; } if pathFound=true then begin { Save the path. Working backwards from the target square, go from each square to its parent square until you reach the starting square. That is your path. } closedListCnt:=length(closedList[0])-1; setLength(getPath, 2, 0); { While starting node has not been added to path } while (length(getPath[0])=0) or (getPath[0, length(getPath[0])-1]<>startingNodeXY[0]) or (getPath[1, length(getPath[0])-1]<>startingNodeXY[1]) do begin { Add node from closed list to path } setLength(getPath, 2, length(getPath[0])+1); getPath[0, length(getPath[0])-1]:=closedList[0, closedListCnt]; getPath[1, length(getPath[0])-1]:=closedList[1, closedListCnt]; //writeLn(formatVal('path found {} {}, start {} {}, target {} {}', [getPath[0, length(getPath[0])-1], getPath[1, length(getPath[0])-1], startingNodeXY[0], startingNodeXY[1], targetNodeXY[0], targetNodeXY[1]])); { readLnPromptX; } { Find next node on closed list with coord matching parent coord of current closed list node } for parentClosedListCnt:=length(closedList[0])-1 downto 0 do if (closedList[0, parentClosedListCnt]=closedList[4, closedListCnt]) and (closedList[1, parentClosedListCnt]=closedList[5, closedListCnt]) then break; closedListCnt:=parentClosedListCnt; { if (closedList[0, closedListCnt]=0) and (closedList[1, closedListCnt]=0) then break; } end; pathToControlledCharPtr:=length(getPath[0])-1; end; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/59805545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windowless WPF Application I am hoping someone can point me in the right direction here. I am trying to turn my analog clock application into a windowless clock. I have searched google but I think my issue is I do not know the correct term for what I am trying to do. My analog clock application is a circle that contains the clock hands. This is contained in a window like most other applications. I would like to remove the window and have only the clock show above the background. I would be able to bring up the close button maybe on mouse over. Or perhaps I could make the whole window transparent except for the clock and on mouse over I would be able to see the window and close it. Anyone have any experience on this? Maybe some tips or a tutorial somewhere? Thank you, A: You can build your Window, and set the Background="Transparent" like so: <Window ... AllowsTransparency="True" WindowStyle="None" Background="Transparent" > This gives you a window with a transparent background and no border.
{ "language": "en", "url": "https://stackoverflow.com/questions/15620096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What is the CSS (font-family, size) for a blockquote in Bootstrap I would think this was easy to find somewhere, but I haven't been able to. I don't want to use the blockquote class, but create a custom named one. Basically I want the same font and size, but not the border of the blockquote and a custom name. Could anybody give me the Bootstrap CSS for blockquote? A: Check out the source code and look for the blockquote tag. blockquote { padding: 10px 20px; margin: 0 0 20px; font-size: 17.5px; border-left: 5px solid #eee; } There's lots more. CTRL + F will help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/35375630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Using Object Assign to clear state This is my state: export default new Vuex.Store({ state: { items: [ ], user: { isAuthenticated: false, info: { createdAt: '', email: '', firstName: '', id: '', lastName: '', }, token: { accessToken: '', expiresIn: '', refreshToken: '', tokenType: '', }, }, }, actions, mutations, getters, plugins: [createPersistedState({ key: 'persistedState', paths: ['user'], })], strict: process.env.NODE_ENV !== 'production', }); I keep separately the default state of user - so I don't have to manually reset every property when necessary. export const defaultUser = { isAuthenticated: false, info: { createdAt: '', email: '', firstName: '', id: '', lastName: '', }, token: { accessToken: '', expiresIn: '', refreshToken: '', tokenType: '', }, }; So, when a logout action is triggered: export const logout = ({ commit, dispatch }) => { commit(types.LOGOUT_USER); dispatch('changeStatus', 'You need to login or register.'); }; [types.LOGOUT_USER](state) { Object.assign(state.user, defaultUser); }, but magically sometimes the entire user object seems to not have been replaced... (or the defaultState object is filled with the last values?) A: In addition to the other answers: Essentially this question is an indirect duplicate of Changes to object made with Object.assign mutates source object. Object.assign is safe to use for a max of 2 levels of nesting. For example Object.assign(myObj.firstProp, myDefaultObj.firstProp); Taken from the MDN documentation: Warning for Deep Clone For deep cloning, we need to use other alternatives because Object.assign() copies property values. If the source value is a reference to an object, it only copies that reference value.
{ "language": "en", "url": "https://stackoverflow.com/questions/46621053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to show "Copy" menu for a table cell? I would add the option to copy the selected cell in a table like in the contacts app. I have tried to follow this question about Objective-C and impliment those methods in Swift: override func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { return (action == #selector(NSObject.copy(_:))) } However, that is an old question, and I can't get the menu to show up using Swift code. Could someone explain how the shouldShowMenuForRowAtIndexPath method is used and how to allow for a user to copy a cell. A: You refer to an Objective-C example, but you have not done what it says to do! Your second method is the wrong method. You want to say this: override func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return action == #selector(copy(_:)) } You will also need a third override: override func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { // ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/36241465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to find the github fork of a project with the most recent commit? Is there a way (other than try them all..) to find which fork for an (abandoned) GitHub project has the most recent commit? The default list of forks returned by GitHub is by fork date I believe...
{ "language": "en", "url": "https://stackoverflow.com/questions/71941953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: align elements in center and to the left I need to align my list items like in the picture(in the bottom that dropdown). As you can see they are centered but alson aligned in a line vertically. How can I achive this? Here is my code: <div class="footer"> <div class="outer"> <div class="container"> <ul id="insurances"> <li><a href="conditions-form.html"><img src="img/estate-insurance.png">Ubezpieczenia nieruchomości</a></li> <li><a href="conditions-form.html"><img src="img/tourist-insurance.png">Ubezpieczenia turystycznego</a></li> <li><a href="conditions-form.html"><img src="img/health-insurance.png">Ubezpieczenia zdrowotnego</a></li> <li><a href="conditions-form.html"><img src="img/car-insurance.png">Ubezpieczenia samochodu</a></li> <li><a href="conditions-form.html"><img src="img/assistance-insurance.png">Ubezpieczenia assistance</a></li> <li><a href="conditions-form.html"><img src="img/NNW-insurance.png">Ubezpieczenia NNW</a></li> <li><a href="conditions-form.html"><img src="img/law-insurance.png">Ochrony prawnej</a></li> </ul> <p>Szukam</p> <a class="insurance-type"> <span>Ubezpieczenia nieruchomości</span> </a> <div clas="clear"></div> </div> </div> And Css .footer .outer .container ul { position: absolute; border:none; padding: 0; margin: 0; bottom:110px; left:0; right:0; display:none; } .footer .outer .container ul li a img { height: 25px; margin-right: 20px; } .footer .outer .container ul li { padding:0; margin:0; list-style: none; } .footer .outer .container ul li a { color: #fff; text-decoration: none; font-size:21px; font-family: 'Lato', sans-serif; font-weight: 300; text-align: left; margin: 0 auto; display:block; height: 70px; line-height: 70px; } Would be thankful for any proposals A: Mocked something quickly, possibly this is what you are looking for http://jsfiddle.net/kasperoo/eHLBu/1/ <div class="container"> <ul id="insurances"> <li><p><a href="conditions-form.html"><img src="img/estate-insurance.png">Ubezpieczenia nieruchomości</a></p></li> <li><p><a href="conditions-form.html"><img src="img/estate-insurance.png">Ubezpieczenia nieruchomości</a></p></li> <li><p><a href="conditions-form.html"><img src="img/estate-insurance.png">Ubezpieczenia nieruchomości</a></p></li> </ul> .container { position: relative; } #insurances { list-style-type: none; width: auto; } #insurances li p { margin: 0; width: 200px; margin: 0 auto; } #insurances li:nth-child(even) { background: green; } #insurances li:nth-child(odd) { background: grey; }
{ "language": "en", "url": "https://stackoverflow.com/questions/24323076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass Glue annotations for multiple inputs in AWS for multiple input source Glue diagram is generated as per the annotations passed to it and edges are created as per @input frame value passed, I want to generate diagram where it should take multiple inputs as there should be multiple edges coming to vertex for each source but in all the example it's given for single input source only , I tried comma separated value but in that diagram it is not getting generated at all. If anyone can share a link to blog or video where annotation is explained in more detail that will also be very helpful, ## @type: DataSink ## @args: [connection_type = "s3", connection_options = {"path": "s3://example-data-destination/taxi-data"}, format = "json", transformation_ctx = "datasink2"] ## @return: datasink2 ## @inputs: [frame = applymapping1] A: I was able to find the answer , just for future reference if someone else get's stuck in this situation ## @inputs: [frame1 = applymapping1,frame2 = applymapping2,frame3 = applymapping3,frame4 = applymapping4 ]
{ "language": "en", "url": "https://stackoverflow.com/questions/68974779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to specifically provides multiple query of the attributes using PHP mysql I have a table named student with its attributes and data: table student ---------------- student_id | student_name | year | exam | level | mark | gred 1111 Alicia 2017 First 6 90 A 1111 Alicia 2016 Final 5 80 A 1111 Alicia 2016 Mid 5 87 A 1111 Alicia 2016 First 5 70 B 1111 Alicia 2015 Final 4 40 D 1111 Alicia 2015 Mid 4 60 C 1111 Alicia 2015 First 4 70 B 2222 Kelvin 2017 First 6 86 A 2222 Kelvin 2016 Final 5 80 A 2222 Kelvin 2016 Mid 5 80 A 2222 Kelvin 2016 First 5 70 B 2222 Kelvin 2015 Final 4 38 D 2222 Kelvin 2015 Mid 4 65 C 2222 Kelvin 2015 First 4 75 B I need to display the marks of each student based on their exam and level in a table. No | Student's Name |First-Term Exam L4 |Mid-Term Exam L4 | Final Exam L4 |First-Term Exam L5 |Mid-Term Exam L5 | Final Exam L5 |First-Term Exam L6 | | Mark | Grade | Mark | Grade | Mark | Grade | Mark | Grade | Mark | Grade | Mark | Grade | Mark | Grade | 1 Alicia 70 B 60 C 40 D 70 B 87 A 80 A 90 A 2 Kelvin 75 B 65 C 38 D 70 B 80 A 80 A 86 A I need to output the table like this, but I can't figure it out on how to query them.
{ "language": "en", "url": "https://stackoverflow.com/questions/47476195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insufficient space allocated to copy array contents I am building up some code to request multiple information from a database in order to have a time table in my front end incl. multiple DB requests. The problem is that with one particular request where . am using swiftKuery and DispatchGroups i receive ooccasionally but not always an error message in my XCode. This can not be reconstructed by different request but just sometimes happens. here is a snippet of my code. var profWorkDaysBreak = [time_workbreaks]() let groupServiceWorkDayBreaks = DispatchGroup() ... ///WorkdaysBreakENTER AsyncCall //UnreliableCode ? profWorkDays.forEach {workDay in groupServiceWorkDayBreaks.enter() time_workbreaks.getAll(weekDayId: workDay.id) { results, error in if let error = error { print(error) } if let results = results { profWorkDaysBreak.append(contentsOf: results) // The error happens here ! } groupServiceWorkDayBreaks.leave() } } ... groupServiceWorkDayBreaks.wait() The results and profWorkDaysBreak variables are the same just sometimes i receive the message: Fatal error: Insufficient space allocated to copy array contents This leads to a stop of the execution. I assume, that maybe the loop might sometimes finish an earlier execution in the DispatchGroup ??? but this is the only think i have as an idea.... A: Most likely this is caused by some race conditions due to the fact that you modify the array from multiple threads. And if two threads happen to try and alter the array at the same time, you get into problems. Make sure you serialize the access to the array, this should solve the problem. You can use a semaphore for that: var profWorkDaysBreak = [time_workbreaks]() let groupServiceWorkDayBreaks = DispatchGroup() let semaphore = DispatchSemaphore(value: 0) ... profWorkDays.forEach { workDay in groupServiceWorkDayBreaks.enter() time_workbreaks.getAll(weekDayId: workDay.id) { results, error in if let error = error { print(error) } if let results = results { // acquire the lock, perform the non-thread safe operation, release the lock semaphore.wait() profWorkDaysBreak.append(contentsOf: results) // The error happens here ! semaphore.signal() } groupServiceWorkDayBreaks.leave() } } ... groupServiceWorkDayBreaks.wait() The semaphore here acts like a mutex, allowing at most one thread to operate on the array. Also I would like to emphasise the fact that the lock should be hold for the least amount of time possible, so that the other threads don't have to wait for too much. A: Here is the only way i got my code running reliable so far.. i skipped contents of completely and just went to a forEach Loop var profWorkDaysBreak = [time_workbreaks]() let groupServiceWorkDayBreaks = DispatchGroup() ... ///WorkdaysBreakENTER AsyncCall //UnreliableCode ? profWorkDays.forEach {workDay in groupServiceWorkDayBreaks.enter() time_workbreaks.getAll(weekDayId: workDay.id) { results, error in if let error = error { print(error) } if let results = results { results.forEach {profWorkDayBreak in profWorkDaysBreak.append(profWorkDayBreak) } /* //Alternative causes error ! profWorkDaysBreak.append(contentsOf: results) */ } groupServiceWorkDayBreaks.leave() } } ... groupServiceWorkDayBreaks.wait()
{ "language": "en", "url": "https://stackoverflow.com/questions/58143558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it bad to always run nginx-debug? I'm reading the debugging section of NGINX and it says to turn on debugging, you have to compile or start nginx a certain way and then change a config option. I don't understand why this is a two step process and I'm inferring that it means, "you don't want to run nginx in debug mode for long, even if you're not logging debug messages because it's bad". Since the config option (error_log) already sets the logging level, couldn't I just always compile/run in debug mode and change the config when I want to see the debug level logs? What are the downsides to this? Will nginx run slower if I compile/start it in debug mode even if I'm not logging debug messages? A: First off, to run nginx in debug you need to run the nginx-debug binary, not the normal nginx, as described in the nginx docs. If you don't do that, it won't mater if you set the error_log to debug, as it won't work. If you want to find out WHY it is a 2 step process, I can't tell you why exactly the decision was made to do so. Debug spits out a lot of logs, fd info and so much more, so yes it can slow down your system for example as it has to write all that logs. On a dev server, that is fine, on a production server with hundreds or thousands of requests, you can see how the disk I/O generated by that log can cause the server to slow down and other services to get stuck waiting on some free disk I/O. Also, disk space can run out quickly too. Also, what would be the reason to run always in debug mode ? Is there anything special you are looking for in those logs ? I guess i'm trying to figure out why would you want it. And it's maybe worth mentioning that if you do want to run debug in production, at least use the debug_connection directive and log only certain IPs.
{ "language": "en", "url": "https://stackoverflow.com/questions/41150509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change title css and area radius size in ImageMap of MS Chart How to change title element css of area element of imagemap which is there in MS Chart. For i.e. <map id="ctl00_ContentPlaceHolder1_chtActivityImageMap" name="ctl00_ContentPlaceHolder1_chtActivityImageMap"> <area alt="" title="30-07-2013 : 600" coords="618,180,623,185" shape="rect" style="cursor:pointer"> <area alt="" title="29-07-2013 : 400" coords="609,207,614,212" shape="rect" style="cursor:pointer"> <area alt="" title="30-05-2013 : 1400" coords="80,70,85,75" shape="rect" style="cursor:pointer"> </map> Here, it is the code of MS chart area. I want to change css of title element. And I also want to increase radius of area element when anyone hover on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/20605969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django 'context' for function-based and class-based views Help me understand how to use Django's context--Is the issue related to the use of context in function-based vs class-based views: I have created two views (index and post_list) and respective templates (following the Assessment portion of the Mozilla Django Tutorial). The code for index works, but identical code for post_list doesn't. Why is that? view #1 def index(request): post_list = Post.objects.all() num_posts = Post.objects.all().count() num_comments = Comment.objects.all().count() num_authors = Author.objects.count() num_commenters = Commenter.objects.count() context = { 'num_posts': num_posts, 'num_comments': num_comments, 'num_authors': num_authors, 'num_commenters': num_commenters, 'post_list' : post_list, } return render(request, 'index.html', context=context) template #1 --Works: {% block content %} <h1>Index:</h1> This blog has a total of {{num_posts}} posts by {{ num_authors}} authors. {% endblock %} view #2 class PostListView(generic.ListView): model = Post post_list = Post.objects.all() num_posts = Post.objects.all().count() num_authors = Author.objects.count() template_name = 'blog/post_list.html' context = { 'num_posts': num_posts, #'num_authors': num_authors, # Removed b/c it doesn't work 'post_list' : post_list, } def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['num_authors'] = Author.objects.count() # But this works! return context #edited, this line was left out in the original post template#2 - not totally working: {% block content %} <h1>All Posts:</h1> This blog has a total of {{num_posts}} posts by {{ num_authors}} authors. {% endblock %} A: Your definition of the get_context_data method does not update all the variables you expect to be using within your template. For instance, the context class variable is not the same thing as the context variable you are returning inside the get_context_data method. Therefore, the only variable to which you have access in the template is num_authors. To make sure you have all the needed variables within your template, you need to edit get_context_data to update the context with the dictionary defined at the class level: class PostListView(generic.ListView): model = Post post_list = Post.objects.all() num_posts = Post.objects.all().count() num_authors = Author.objects.count() template_name = 'blog/post_list.html' context_vars = { 'num_posts': num_posts, 'num_authors': num_authors, 'post_list' : post_list, } def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context.update(PostListView.context_vars) return context Two main updates are made to your original code snippet: the class variable context is changed to context_vars to avoid conflicts and confusion; and the context variable within the get_context_data method is updated with the contents of context_vars. This will make sure that everything defined at the class level (i.e. PostListView.context_vars) makes it to your template.
{ "language": "en", "url": "https://stackoverflow.com/questions/68351443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Two fingers on trackpad with Qt app I'm currently trying to make our Qt application react as it should when using the "two fingers" feature of the trackpad on Mac. As of now, when working in a QGraphicsScene, if the user use "two fingers" the view is zoomed which is not what I want. I want the scene to scroll in the right direction. I looked at the GestureType and tried to grab the gestures and use custom event with them. That part works fine. However, it seems that when using the "two fingers", all I'm catching is a pinch gesture instead of what should be a pan gesture (I think). From what i found here http://qt-project.org/doc/note_revisions/214/358/view , it should work with the two touch points, but it doesn't seems to. So is there any way to detect the "two fingers" from the trackpad ? I'm currently working with QT 4.8.2 on Mac OS X Mavericks. Any help would be greatly appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/26673898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Calabash: How to set up test data I am in the process of implementing GUI tests using Calabash. In The Cucumber Book it is emphasized that scenarios should setup test data itself, locally, preferably using libraries such as factory_girl. This question is about the performance, cleanness and manageability of testing Android and iOS applications using Calabash. The benefit of tools such as factory_girl is that tests should tend to be less brittle and that the test data can be created/inserted without using the GUI, which speeds up the tests considerably (which makes them worth more to the developers). Also, each scenario should be independent from all other scenarios, such that it does not require scenario A to be run before B if B is to work correctly. This allows developers to run only a single scenario. This seems reasonable for programs that is running locally, where for example the web-service database can be accessed directly, such that test data can be inserted. However, how does a tester insert data in programs that run on another device (emulator, simulator, real phone). Specifically, how does one manage test data probably when running against an iOS and Android target? I am tempted to use a Set of Fixture Data as described in The Cucumber Book, however, they explicitly says to avoid this. I ask because the app I am creating has a lot of setup before the user can enter the main app view. The user needs to: * *Sign up, which consists of multiple steps: A. Press "Sign up" B. Accept terms C. Link to 3rd party service (multiple steps) D. Enter user details (name, ...) E. Press the "Sign up" button F. Confirming email by pressing link in sent email *Log in with the newly created user *Synchronize data with the server As you can see, if each scenario has to work from a clean state, then just getting to the correct view in the application can be a real time consumer. Those steps has to be executed for nearly all scenarios. I would like to be able to start with the required state and start at the correct view. How is this achieved for iOS and Android using Calabash? A: We were able to create our own test data by using the 'Rest-Client’ gem (to call endpoints) and Cucumber hooks (used to determine when to generate test data). See below example of how we created new accounts/customers by using the Rest-Client gem, cucumber hooks, a data manager class and a factory module. Here's a link with a bit more info on how it works. AccountDataManager.rb require 'rest-client' require_relative '../factory/account' class AccountDataManager include Account def create current_time = Time.now.to_i username = 'test_acc_' + current_time.to_s password = 'password1' url = 'http://yourURLhere.com/account/new' request_body = manufacture_account(username, password) response = RestClient.post url, request_body.to_json, {:content_type => 'application/json', :accept => 'application/json'} if response.code != 200 fail(msg ="POST failed. Response status code was: '#{response.code}'") end response_body = JSON.parse(response clientId = response_body['Account']['ClientId'] # return a hash of account details account_details = { username: username password: password, clientId: clientId } end end Account.rb The below factory manufactures the request's body. module Account def manufacture_account(username, password) payload = { address:{ :Address1 => '2 Main St', :Address2 => '', :Suburb => 'Sydney', :CountryCode => 8 }, personal:{ :Title => 'Mr', :Firstname => 'John', :Surname => 'Doe', :UserName => "#{username}", :Password => "#{password}", :Mobile => '0123456789', :Email => "#{username}@yopmail.com", :DOB => '1990-12-31 00:00:00' } } end end Hook.rb You should add your hook.rb file to a shared directory and then add a reference to it into your env.rb file (we added our hook file to the "/features/support" directory). require_relative '../data_manager/data_manager_account' Before() do $first_time_setup ||= false unless $first_time_setup $first_time_setup = true # call the data managers needed to create test data before # any of your calabash scenarios start end end Before('@login') do # declare global variable that can be accessed by step_definition files $account_details = AccountDataManager.new.create end at_exit do # call the data managers to clean up test data end Login_steps.rb The final piece of the jigsaw is to get your calabash scenarios to consume the test data your've just generated. To solve this problem we declared a global variable ($account_details) in our hook.rb file and referenced it in our step_definition file. Given(/^I log in with newly created customer$/) do @current_page = @current_page.touch_login_button unless @current_page.is_a?(LoginPage) raise "Expected Login page, but found #{@current_page}" end # use global variable declared in hook.rb @current_page = @current_page.login($account_details) unless @current_page.is_a?(HomePage) raise "Expected Home page, but found #{@current_page}" end end A: I haven't gotten into using any fixture data libraries myself, however I've had luck just using simple models, like the following for a User. class User @validUser = "[email protected]" @validPass = "123" @invalidUser = "[email protected]" @invalidPass = "foobar" def initialize(username, password) @username = username @password = password end def username @username end def password @password end def self.getValidUser return new(@validUser, @validPass) end def self.getInvalidUser return new(@invalidUser, @invalidPass) end end Let's say I have the following feature: Scenario: Successful login When I enter valid credentials into the login form Then I should see a logout button Then when I need a valid user, it's as easy as: When(/^I enter valid credentials into the login form$/) do user = User.getValidUser enterCredentials(user) end And you can obviously replicate this model structure for anything than needs to hold a simple amount of information. Again, I can't speak for any fixture libraries as I haven't utilized those. However, to your other question regarding the non-dependence of Scenario A on Scenario B - this is true, but this does not mean you can't string together step definitions to achieve your goals. Let's say the test above was simply used to validate that I can successfully log in to the application with a valid user - all is well, the user is logged in, and everyone's happy. But what happens when I need to test the profile page of a user? Well I obviously need to login, but I don't need that to be explicitly stated in my feature file, I can create a step definition that chains together other step definitions: Scenario: Validate behavior of user profile page Given I'm on my profile page Then I should see a selfie Given(/^I'm on my profile page$/) do step "I enter valid credentials into the login form" navigateToProfilePage() end This is a quick example, but hopefully you're seeing that you can indeed chain together step definitions without having scenarios themselves being depending on one another. Such a bad style of cucumber would be such that you log in to the application with Scenario "Login Successful" but then NEVER log the user out, and simply proceed with Scenario "Validate behavior of profile" which just navigates to the profile page without first logging back in. I hope I wasn't too far off from your original request! * *https://github.com/cucumber/cucumber/wiki/Calling-Steps-from-Step-Definitions A: You can write a Backdoor to clean up your data before running tests: public class MainActivity extends Activity { public void setUp() { // Here you can clean and setup the data needed by your tests } }
{ "language": "en", "url": "https://stackoverflow.com/questions/24915532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ace Editor Handle Marker Events I'm trying to take some actions when sitting on top of a marker in Ace Editor based on keydown operations. However, it looks like I'm unable to trap events on markers using simple jquery hookups. I declare my markers like this: var marker =session.addMarker(range, "misspelled", "typo", true); end then try to hook up events like this: $(document).on('keydown',".misspelled", function (e) { //if (e.keyCode == 93) alert('show popup here'); }); No matter what I do I can't get events to fire on the marker elements. I set up a jsbin example here: http://jsbin.com/xowaledobi/5/edit?html,output and used a click to make it easier to play with. When clicking on the marker - nothing happens. Looking at the DOM I can see the marker and my custom style: And based on selecting that node it looks like it is accessible via the UI, but still I can't seem to fire any events on it. Neither click or keydown cause anything to happen. So - what's the best way to capture key events in a Ace Editor marker? ps In another part of the application I use a right click pop up handler and there I am using rather expensive code that maps the marker id and location to the current mouse position. It works ok for mouse ops, but is too way too slow to do for keyboard operations. A: you can't use jquery to work with dom elements inside the editor, you need to use editor api like this: <!DOCTYPE html> <html lang="en"> <head> <title>ACE in Action</title> <style type="text/css" media="screen"> #e1 { position: absolute; top: 0; right: 0; bottom: 50%; left: 0; } .misspelled { border-bottom: 1px dashed red; position: absolute; } </style> </head> <body> tfa <div id="e1">&lt;xml> function foo(items) { var x = "All this is syntax highlighted"; return x; } &lt;/xml></div> <pre id="e2"> second editor </pre> <script src="http://ajaxorg.github.io/ace-builds/src/ace.js"></script> <script> var Range = ace.require("ace/range").Range var editor = ace.edit("e1"); editor.session.setMode("ace/mode/javascript"); editor.session.addMarker(new Range(1,0,1,20),"misspelled","fullLine",true); editor.on("click", function(e) { if (e.getDocumentPosition().row == 1) alert('clicked'); }); </script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/44010601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Symfony2 cache warm up issue I have an issue when I execute capifony command: cap deploy. When the error happens I get this output: * 2013-10-03 18:32:39 executing `symfony:cache:warmup' --> Warming up cache * executing "sudo -p 'sudo password: ' sh -c 'cd myapp && php app/console cache:warmup --env=prod --no-debug'" servers: ["127.0.0.1"] [127.0.0.1] executing command *** [err :: 127.0.0.1] No entry for terminal type "unknown"; *** [err :: 127.0.0.1] using dumb terminal settings. *** [err :: 127.0.0.1] PHP Warning: require_once(myapp/app/bootstrap.php.cache): failed to open stream: No such file or directory in myapp/app/console on line 12 *** [err :: 127.0.0.1] PHP Fatal error: require_once(): Failed opening required 'myapp/app/bootstrap.php.cache' (include_path='.:/usr/share/php:/usr/share/pear') in myapp/app/console on line 12 command finished in 567ms *** [deploy:update_code] rolling back * executing "rm -rf myapp; true" servers: ["127.0.0.1"] [127.0.0.1] executing command command finished in 182ms I have to indicate that my deploy.rb looks like this: set :application, "PT" set :domain, "MY IP" set :deploy_to, "/var/www/#{application}.es" set :app_path, "app" set :repository, "https://github.com/trepafi/repo.git" set :scm, :git # Server set :ssh_options, {:forward_agent => true} set :user, "root" set :domain, "#{domain}" set :model_manager, "doctrine" role :web, domain role :app, domain, :primary => true set :keep_releases, 3 set :deploy_via, :rsync_with_remote_cache logger.level = Logger::MAX_LEVEL # S2.4 set :use_composer, true set :vendors_mode, "install" set :shared_files, ["app/config/parameters.ini"] set :shared_children, [app_path + "/cache", app_path + "/logs", web_path + "/uploads", "vendor"] set :update_vendors, true I guess that it's an error clearing the S2 cache, How should I give permission to the corresponding folders? Does anyone know how to fix it? A: Finally I got the solution, it was because the new S2 version. The shared files was renamed from parameters.ini to parameters.yml set :shared_files, ["app/config/parameters.yml"]
{ "language": "en", "url": "https://stackoverflow.com/questions/19164781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can collections.filter be wrong? I try to filter a collection according to a predicate: private void filterExpiredOffers() { mOffersList = Lists.newArrayList(Collections2.filter( mOffersList, new Predicate<Offer>() { @Override public boolean apply(Offer offer) { return mUnlockExpirationCalculator .isUnlockValid(offer); } })); } and: public boolean isUnlockValid(Offer offer) { return ((offer.unlockExpirationDate == null) || (System .currentTimeMillis() < offer.unlockExpirationDate.getTime())); } I see an offer has gotten a "false" as a result but yet, I see it in the arrayList later on. Am I doing the filter wrong? A: You really shouldn't do things like this: public boolean isUnlockValid(Offer offer) { return ((offer.unlockExpirationDate == null) || (System .currentTimeMillis() < offer.unlockExpirationDate.getTime())); } Create a class instance instead, which captures System.currentTimeMillis() and uses it. This way your filter will stay stable over time. Consider something like this class UnlockValidPredicate implements Predicate<Offer> { public UnlockValidPredicate() { this(System.currentTimeMillis()); } public UnlockValidPredicate(long millis) { this.millis = millis; } @Overrride public boolean apply(Offer offer) { return offer.unlockExpirationDate == null || millis < offer.unlockExpirationDate.getTime(); } private final long millis; } Also consider getting rid of nulls. Setting unlockExpirationDate to new Date(Long.MAX_VALUE) is good enough for "never expire", isn't it? That's not it. The current time was Sep 7th. The unlockExpirationDate was Aug 30th. It's not a matter of days between the filtering and the debugging i did. what else can it be? Get rid of Date, it's stupid mutable class. Most probably, you changed it somehow. Things like MyClass(Date date) { this.date = date; } and Date getDate() { return date; } are a recipe for disaster. The best solution is to use an immutable class (available in Java 8 or JodaTime). The second best is to use long millis. The last is to clone the Date everywhere. A: What seems most likely is that the predicate was true when you did the filtering, and then the predicate became false later -- which seems perfectly possible when you're using System.currentTimeMillis().
{ "language": "en", "url": "https://stackoverflow.com/questions/25705266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook invite friend with tracking I am about to create a Facebook iFrame page which will consist of content that I want browsers to share. The page will feature a Facebook friend chooser, most probably the following javascript http://labs.thesedays.com/blog/2011/06/20/the-missing-facebook-interface-component-for-friend-selection/ What I'd like to know is if there is a way to track who shared the link and with how many people? A: You should read the documentation on the Requests Dialog. When you use the Facebook Javascript SDK to call the dialog, you will recieve a callback as soon as the dialog has closed. This callback will contain details about the users actions within the dialog. Taken from the documentation : FB.ui({method: 'apprequests', message: 'My Great Request' }, function requestCallback(response) { // Handle callback here }); In the callback's response argument there is details about the request_id and who the request was sent to : Object request: "REQUEST_ID" to: Array[2] 0: "FB_ID1" 1: "FB_ID2" 2: "FB_ID3" ... Unless there is a specific and valid reason not to use facebook's dialogs, I recommend staying with the features facebook has given us. As soon as you start using 3rd party plugins to "mimic" facebook behavior, you are dependent on those developers to update their code when facebook makes changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/8895871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is a HTTP Get request of size 269KB allowed? I am debugging a test case. I use Python's OptionParser (from optparse) to do some testing and one of the options is a HTTP request. The input in this specific case for the http request was 269KB in size. So my python program fails with "Argument list too long" (I verified that there was no other arguments passed, just the request and one more argument as expected by the option parser. When I throw away some of the request and reduce its size, things work fine. So I have a strong reason to believe the size of the request is causing my problems here.) Is it possible for a HTTP request to be that big ? If so how do I fix the OptionParser to handle this input? A: Is it possible for a HTTP request to be that big ? Yes it's possible but it's not recommended and you could have compatibility issues depending on your web server configuration. If you need to pass large amounts of data you shouldn't use GET. If so how do I fix the OptionParser to handle this input? It appears that OptionParser has set its own limit well above what is considered a practical implementation. I think the only way to 'fix' this is to get the Python source code and modify it to meet your requirements. Alternatively write your own parser. UPDATE: I possibly mis-interpreted the question and the comment from Padraic below may well be correct. If you have hit an OS limit for command line argument size then it is not an OptionParser issue but something much more fundamental to your system design that means you may have to rethink your solution. This also possibly explains why you are attempting to use GET in your application (so you can pass it on the command line?) A: A GET request, unlike a POST request, contains all its information in the url itself. This means you have an URL of 269KB, which is extremely long. Although there is no theoretical limit on the size allowed, many servers don't allow urls of over a couple of KB long and should return a 414 response code in that case. A safe limit is 2KB, although most modern software will allow a bit more than that. But still, for 269KB, use POST (or PUT if that is semantically more correct), which can contain larger chunks of data as the content of a request rather than the url. A: Typical limit is 8KB, but it can vary (like, be even less).
{ "language": "en", "url": "https://stackoverflow.com/questions/31630636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Adding link to an element in Javascript? (Current method risks "bad javascript?") Right now I have some element <span class="CLASSNAME" id="FOO">Barack Obama</span> Referenced by document.getElementById('FOO') And I want to make it so the text "Barack Obama" is turned into a blue link where the text is the same, but it links to (for example) www.google.com I've seen this method, but innerHTML is apparently BAD especially since the link I'll be using is a value returned from an ajax call ("potential for bad js"?). document.getElementById('FOO').innerHTML = desiredText.link(desiredLink); What is the best way to go about this without a huge perfomance hit or potentially "bad js"? Will also be adding mouseover features to said element later on, so if this is worth consideration I figured I'd mention it. No jQuery. A: var el=document.getElementById('FOO'); el.innerHTML="<a href='whitehouse.gov'>"+el.textContent+"</a>"; Simply wrap it into a link. Note that html injection is possible. And do not care about performance, were talking about milliseconds... If you want to prevent html injectin, you may build it up manually: var el=document.getElementById('FOO'); var a=document.createElement("a"); a.href="whitehouse.hov"; a.textContent=el.textContent; el.innerHTML=""; el.appendChild(a); A: You have two possibilities: Add an <a> element as a child of the <span> element Replace the text node ("Barack Obama") with an <a> element: function addAnchor (wrapper, target) { var a = document.createElement('a'); a.href = target; a.textContent = wrapper.textContent; wrapper.replaceChild(a, wrapper.firstChild); } addAnchor(document.getElementById('foo'), 'http://www.google.com'); <span id="foo">Barack Obama</span> This will result in the following DOM structure: <span id="foo"> <a href="http://www.google.com">Barack Obama</a> </span> Replace the <span> element with an <a> element Replace the entire <span> element with an <a> element: function addAnchor (wrapper, target) { var a = document.createElement('a'); a.href = target; a.textContent = wrapper.textContent; wrapper.parentNode.replaceChild(a, wrapper); } addAnchor(document.getElementById('foo'), 'http://www.google.com'); <span id="foo">Barack Obama</span> This will result in the following DOM structure: <a href="http://www.google.com">Barack Obama</a> Use methods like createElement, appendChild and replaceChild to add element instead of innerHTML. A: var changeIntoLink = function(element, href) { // Create a link wrapper var link = document.createElement('a'); link.href = href; // Move all nodes from original element to a link while (element.childNodes.length) { var node = element.childNodes[0]; link.appendChild(node); } // Insert link into element element.appendChild(link); }; var potus = document.getElementById('potus'); changeIntoLink(potus, 'http://google.com/'); <span id="potus">Barack Obama</span>
{ "language": "en", "url": "https://stackoverflow.com/questions/45127820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get object instances in template using ModelMultipleChoiceField/CheckboxSelectMultiple in Django With this code I managed to the get the object's pk and name (return value of the __str__ method), however I need access to the object instance itself (I need some of its methods/fields in the template). How can I do that? {% for value, name in form.stuffs.field.choices %} {{ value }} + {{ name }} {% endfor %}
{ "language": "en", "url": "https://stackoverflow.com/questions/32854320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does my Azure Build break when I add a WPF 4.72 app to my solution? Environment: Web API .Net Core 3.1 WPF 4.72 Wix 3.1.2 Visual Studio 2019 Pro ed. The following is my build script for my Wix installer and my Web API project only: trigger: - master pool: 'TakeKidsToPool' variables: solution: '**/*.sln' buildPlatform: 'Any CPU' buildConfiguration: 'Release' steps: - task: NuGetToolInstaller@0 - task: NuGetCommand@2 inputs: restoreSolution: '$(solution)' - task: DotNetCoreCLI@2 displayName: Publish API inputs: command: publish publishWebProjects: false arguments: /p:PublishProfile=FolderProfile -c $(buildConfiguration) zipAfterPublish: false modifyOutputPath: false - task: MSBuild@1 displayName: Create API msi inputs: solution: SetupProject1/*.wixproj msbuildArchitecture: x64 configuration: $(buildConfiguration) When I add a WPF project to the solution and not even change the build script it fails on the publish part which has nothing to do with the WPF project. I don't understand. Determining projects to restore... Restored C:\agent2\_work\10\s\WebApplication1\WebApplication1.csproj (in 891 ms). C:\Program Files\dotnet\sdk\3.1.402\Microsoft.Common.CurrentVersion.targets(1177,5): error MSB3644: The reference assemblies for .NETFramework,Version=v4.7.2 were not found. To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application. You can download .NET Framework Developer Packs at https://aka.ms/msbuild/developerpacks [C:\agent2\_work\10\s\WpfApp1\WpfApp1.csproj] WebApplication1 -> C:\agent2\_work\10\s\WebApplication1\bin\Release\netcoreapp3.1\win-x64\WebApplication1.dll WebApplication1 -> C:\agent2\_work\10\s\WebApplication1\bin\Release\netcoreapp3.1\win-x64\publish\ ##[error]Error: The process 'C:\Program Files\dotnet\dotnet.exe' failed with exit code 1 ##[error]Dotnet command failed with non-zero exit code on the following projects : ##[section]Finishing: Publish API Here's the publish profile that is a parameter in the build script: <?xml version="1.0" encoding="utf-8"?> <!-- https://go.microsoft.com/fwlink/?LinkID=208121. --> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <DeleteExistingFiles>False</DeleteExistingFiles> <ExcludeApp_Data>False</ExcludeApp_Data> <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish> <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration> <LastUsedPlatform>Any CPU</LastUsedPlatform> <PublishProvider>FileSystem</PublishProvider> <PublishUrl>bin\Release\netcoreapp3.1\publish\</PublishUrl> <WebPublishMethod>FileSystem</WebPublishMethod> <SiteUrlToLaunchAfterPublish /> <TargetFramework>netcoreapp3.1</TargetFramework> <RuntimeIdentifier>win-x64</RuntimeIdentifier> <PublishSingleFile>True</PublishSingleFile> <ProjectGuid>5c246494-0b84-4e8b-943b-e13381b8fb83</ProjectGuid> <SelfContained>true</SelfContained> </PropertyGroup> </Project> A: If we use self-hosted agent, we need to configure the environment on the local machine. According to the error message, It seems that your agent machine do not have the .NETFramework 4.7.2, we should Install the .NET Framework 4.7.2 and restart the agent. A: It looks like I had to add some specificity to publish command with the projects argument. I put the Web API project path here and the build now works. I guess it was trying to publish both the Web API and WPF projects. Anymore insights?
{ "language": "en", "url": "https://stackoverflow.com/questions/63876828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails route is not being found My Rails route isn't working, I get this error on load: undefined method `accept_roomidex_requests_path' for #<#<Class:0x00000103394050>:0x000001033ac920> Here are my (relevant) file contents: config.rb get '/roomidex_requests/:id/accept' => 'roomidex_requests#accept', :as => :accept_roomidex_requests_path roomidex_requests_controller.rb def accept # code to do stuff end some_view.rb <%= link_to "Accept", accept_roomidex_requests_path(:id), :method => :post, :remote => true %> A: Try (without _path suffix in as option): get '/roomidex_requests/:id/accept' => 'roomidex_requests#accept', :as => :accept_roomidex_requests And probably you should change http verb to post.
{ "language": "en", "url": "https://stackoverflow.com/questions/22441737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Invalid argument during changing ownership I want to change ownership of file. I made this command as root: chown test:test make_import.py I recieved this error: chown: changing ownership of ‘make_import.py’: Invalid argument I couldn't find clear solution in web. Thanks for any hint. A: Most likely this file is on a remote/mounted filesystem. Can you check that with either "df" or "mount" command? If it is remote filesystem then possibly the mount options disallow changing the file.
{ "language": "en", "url": "https://stackoverflow.com/questions/44431899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LOAD CSV hangs / does nothing while consuming 10 GB of RAM and 100% CPU I have the following query to import a huge CSV dataset: USING PERIODIC COMMIT LOAD CSV WITH HEADERS FROM "file:///data_ssd/world/test.csv" AS line WITH line WHERE line.lang IS NOT NULL MATCH (i:Item {id: line.id}) MERGE (s:String {value: line.name, lang: line.lang}) CREATE (i)-[:name]->(s) The CSV contains ~53m items. All :Items are already created (about ~15m; hence the MATCH); I'm only missing the :Strings and relations. neo4j consumes about 10 GB of memory and the query runs for like 1 hour now, but there's still even not a single :String or relationship inserted into the database. neo4j runs at 100% CPU. This is a different behavior than my first query I ran where I inserted all the :Items (I saw the node counter increasing fast over time). Is there anything wrong with my LOAD CSV command? Update: Indexes are created on :Item(id), :String(value) and :String(lang). A: My first thought: are you sure you have any lines with a lang property? [EDITED] Also, try decreasing the batch size for each periodic commit. The default is 1000 lines. For example: USING PERIODIC COMMIT 500 to specify a batch size of 500. Also, I see a probable logic error, but it should not be the cause of your main issue ("nothing" happening). The logic error is this: even if the MERGE clause found an existing (s:String) node, the CREATE clause will always go ahead and create (yet another) [:name] relationship between i and s (even if one or more already existed). You probably meant something like this, instead: USING PERIODIC COMMIT LOAD CSV WITH HEADERS FROM "file:///data_ssd/world/test.csv" AS line WITH line WHERE line.lang IS NOT NULL MERGE (i:Item {id: line.id})-[:name]->(s:String {value: line.name, lang: line.lang})
{ "language": "en", "url": "https://stackoverflow.com/questions/26368459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Express - Error Handling Doesn't Work with Async Function So this is the POST request for /products, when a form is submitted, this function will be invoked. I use a try-catch to catch the error if the form is submitted wrongly. This is my Schema. const productSchema = new mongoose.Schema({ name: { type: String, required: true }, price: { type: Number, required: true, min: 0 }, category: { type: String, lowercase: true, enum: ['fruit', 'vegetable', 'dairy'] } }); The error is with the newProduct.save() line, so if I submit a form that goes against the Schema, like not having a name, I will get an error instead of getting redirected to the page. app.post('/products', (req, res, next) => { try { const newProduct = new Product(req.body); newProduct.save(); res.redirect(`/products/${newProduct._id}`); } catch (e) { next(e); } }); This is my error handler. app.use((err, req, res, next) => { const { status = 500, message = 'Something went wrong!' } = err; res.status(status).send(message); }); A: The save method is asynchronous and returns a promise. In your case, newProduct.save() returns a promise which is not being fulfilled and no error is actually thrown: app.post('/products', async (req, res, next) => { try { const newProduct = new Product(req.body); await newProduct.save(); res.redirect(`/products/${newProduct._id}`); } catch (e) { next(e); } }); A: The best solution would be validate req.body with a validator and save newProduct after it is validated. It'd be better to return the newProduct after it is saved rather than redirecting to certain endpoint. If it is not validated you can throw your custom error. I recommend using JOI which is very easy to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/75153803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to arrange 0,1,-1 digits at 6 positions (python)? I want to place three numbers [0,1,-1] at 6 positions. It should give 3^6 = 729 combinations. The code should return something like: (0,0,0,0,0,0) (0,0,0,0,0,1) (0,0,0,0,0,-1) (0,0,0,0,1,1) (0,0,0,0,1,-1) . . (-1,-1,-1,-1,-1,0) (-1,-1,-1,-1,-1,-1) I tried using "itertools.permutations", but am confused about how to incorporate 0,1,-1 into it. A: Check out itertools.product(*iterables, repeat=1) here. Use like: > product([-1, 0, 1], repeat=6) [...] (1, 1, 1, 0, -1, -1), (1, 1, 1, 0, -1, 0), (1, 1, 1, 0, -1, 1), (1, 1, 1, 0, 0, -1), (1, 1, 1, 0, 0, 0), (1, 1, 1, 0, 0, 1), (1, 1, 1, 0, 1, -1), (1, 1, 1, 0, 1, 0), (1, 1, 1, 0, 1, 1), (1, 1, 1, 1, -1, -1), (1, 1, 1, 1, -1, 0), (1, 1, 1, 1, -1, 1), (1, 1, 1, 1, 0, -1), (1, 1, 1, 1, 0, 0), (1, 1, 1, 1, 0, 1), (1, 1, 1, 1, 1, -1), (1, 1, 1, 1, 1, 0), (1, 1, 1, 1, 1, 1)] Gets you len(list(product([-1, 0, 1], repeat=6))) = 729 A: Use itertools.product import iertools assert(sum(1 for _ in itertools.product([-1, 0, 1], repeat=6)) == 3**6) If you know itertools.permutations I think no more explanation is required.
{ "language": "en", "url": "https://stackoverflow.com/questions/66600919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to suppress scroll-into-view behavior in Flutter? I have a CustomScrollView with a SliverAppBar that hides on scroll. On the app bar is a search button that, when pressed, puts a TextField into the app bar. When the field gets focus, it causes the scroll view to scroll all the way to the top, and the app bar gets stuck up in the "unsafe" area: The Scaffold docs mention that when the keyboard is shown the scaffold's insets change and the scaffold is rebuilt, causing the "focused widget will be scrolled into view if it's within a scrollable container". This seems like the behavior I don't want. I looked but couldn't understand the mechanism or how to suppress it. Is doing so possible? The source code for the view in the image is here. Also I note that this problem didn't happen in my previous implementation with non-sliver, standard widgets. I suspect this is because the app bar was not in a scrollable view, whereas SliverAppBar is inside the CustomScrollView so that it can interact with the main body. A: Edit: This issue was fixed by this PR which appears to have first landed in Flutter 1.22.0. It took some sleuthing, but I eventually found the mechanism for this behavior. TextField wraps EditableText. When the latter gains focus, it will invoke _showCaretOnScreen, which includes a call to renderEditable.showOnScreen. This bubbles up and eventually causes the scrolling behavior. We can force _showCaretOnScreen to return early here if we supply to the TextField a hacked ScrollController that always returns false from hasClients: class _HackScrollController extends ScrollController { // Causes early return from EditableText._showCaretOnScreen, preventing focus // gain from making the CustomScrollView jump to the top. @override bool get hasClients => false; } The behavior does not seem intentional, so I reported it as bug #60422. Caveats This workaround may not be very stable. I don't know what adverse effects the hasClients override might have. The docs for TextField say that the scrollController is used "when vertically scrolling the input". In this use case we don't want vertical scrolling anyway, so the workaround might not cause any problems. In my brief testing it didn't seem to cause problems with horizontal (overflow) scrolling. A: Just like the documentation mentions try and use resizeToAvoidBottomInset parameter to false (defaults to true) in the scaffold widget https://api.flutter.dev/flutter/material/Scaffold/resizeToAvoidBottomInset.html Also I would recommend creating ValueListenableBuilder after the scaffold (as the first widget in the body) to avoid rebuilding the whole scaffold and just the body widget
{ "language": "en", "url": "https://stackoverflow.com/questions/62576622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to work with data returned after form submit I have an AMP form that calls a web service on submit, and after that, I have a JSON as result. The JSON contains data and in order to see them, I am using amp-mustache template in submit-success div. And all is working fine. I see all the data I need. But I am unable to access that data from outside the submit-success div. Since I need to set some controls on my form that are out of submit-success div, I need to access the JSON result outside thesubmit-success div. Can anybody share how can I do this? A: One way of doing it would be by saving your JSON response to a state. You can do this by using the on attribute of the form to set the state on the event submit-success as follows: <form id="form123" action-xhr="/formHandle" method="POST" on="submit-success:AMP.setState({ msg : event.response.message })" > Now you can use this state to implement your control logic anywhere in your page by using it with an amp-bind expression. For example, <p class="" [text]=" 'Response is :' + msg"> If you just want to perform common actions like hide, show, toggling accordion, scroll, opening a ligthbox etc., you can do this by using the corresponding AMP action inside the on attribute against the submit-success event, without having to use amp-bind.
{ "language": "en", "url": "https://stackoverflow.com/questions/53284201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get wordpress data feeds in xml format I am developing wordpress site for newspaper. I want to send news feeds to mobile. I want to send these news feeds in xml format only. Currently, I am getting feeds in html format. How to get wordpress feeds in xml format? A: There is a built in feed in Wordpress that you can use. I would recommend you to read up on https://codex.wordpress.org/WordPress_Feeds and try the examples to see if you can make it work. A: Wordpress creates an RSS feed in XML by default; this might appear to you as HTML when you view the RSS in a browser. View the page source to see the XML structure. Get the feed programmatically (the DOM structure might be different in your instance): $xml = simplexml_load_file('http://wordpress.example.com/feed/'); foreach ($xml->channel->item as $item) { print $item->title; print PHP_EOL; }
{ "language": "en", "url": "https://stackoverflow.com/questions/37742802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making special combinations (C++) I need some help with a C++ problem. User enters how many numbers he want to enter, then all the numbers and a special value. Program must find and write all the combinations of numbers whose sum equals to the special value. Example: Input 12 1 5 7 3 10 8 9 2 4 6 11 13 15 Output: 4 11 2 13 9 6 9 2 4 3 2 4 6 3 8 4 3 10 2 7 2 6 7 8 5 4 6 5 8 2 5 10 5 7 3 1 8 6 1 8 2 4 1 10 4 1 3 11 1 3 9 2 1 7 3 4 1 5 9 1 5 3 6 1 5 3 2 4 1 5 7 2 Code Here's the code that writes all the combinations that consist of 2 elements: #include <iostream> using namespace std; int main(int argc, const char * argv[]) { int size; cout << "Enter size: "; cin >> size; int *numbers = new int[size]; cout << "Enter numbers: "; for (int i = 0; i < size; i++) cin >> numbers[i]; int target; cout << "Enter target: "; cin >> target; int sum = 0; for (int i = 0; i < size-1; i++) { for (int j = i+1; j < size; j++) { sum = numbers[i]; sum += numbers[j]; if (sum == target) cout << numbers[i] << " " << numbers[j] << "\n"; } } return 0; } If I replace that for loop with this one, the program will write all the combinations that consist of 3 elements: for (int i = 0; i < size-2; i++) { for (int j = i+1; j < size-1; j++) { for (int k = j+1; k < size; k++) { sum = numbers[i] + numbers[j]; sum += numbers[k]; if (sum == target) cout << numbers[i] << " " << numbers[j] << " " << numbers[k] << "\n"; } } } Here's my question: how to make a program that writes ALL the possible combinations? A: * *Take the first number from your list (e.g., 1). *Remove this number from your list, as well as deduct it from your "destination" total. *Now you have a new list and a new destination total. Repeat. *If your total exceeds your destination, skip the current number (i.e., retain the number within the list, don't update the destination) and move to the next. *If none of the remaining items in the list let you reach your destination, pop the last number you added to your destination total, and update it with the next number in the list. *If you reach your destination total, you have a subset of numbers from your original list (with a size that is anything between 1 and the number of elements in the list) that add up to your intended total.
{ "language": "en", "url": "https://stackoverflow.com/questions/13417570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pulling Data Out of A ComboBox I have a ComboBox that is being populated by a table, but when I have my ComboBox populated I have it concatenated with some formatting. Do strValue = "Loc: " & .Fields(0).Value & " Weight : " & .Fields(1).Value cbAlloys.AddItem strValue rsDB1.MoveNext Loop Until rsDB1.EOF So now that it's like this I need to take just the weight value and output it without anything but the weight number. I tried this: siBinWeightDescription.Value = cbBinAndWeight.Value siBinWeightDescription.Value = InStr(6, cbBinAndWeight.Value) But, later realized that Instr only outputs the count. How would I go about getting the weight value I need from the ComboBox? A: To answer the multicolumn comobobox part of the question: Use an array for AddItem (put it in a loop if you want) Dim Arr(0 To 1) As String Arr(0) = "Col 1" Arr(1) = "Col 2" cmb.AddItem Arr and to retrieve data for the selected item: cmb.List(cmb.ListIndex, 1) you can also set up an enumeration for your column numbers like this: Enum ColList Loc=0 Weight=1 End Enum then to retrieve data it would look like this (much more readable code) cmb.List(cmb.ListIndex, ColList.Weight) also, you dont have to use the word Fields... you can address your recordset like this: rsDB1!Weight A: split string into an array (zero based) debug.print split("Loc: abc Weight : 1234"," ")(4) ' the second argument is the separator character debug.print split("Loc: abc Weight : 1234")(4) ' space is the default separator both print 1234
{ "language": "en", "url": "https://stackoverflow.com/questions/45380212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Temporarily untrack files from git I have a base install of ExpressionEngine (a CMS) which I clone for new projects. The base install has hundreds of core files that will never change, unless I install an update of expressionengine. Tracking all these files makes git very slow. So, I want to untrack all of them for during my development, and only track them when I install an update. What would be the best way to do this? I have tried using .gitignore, but this isn't meant to ignore files that are already being tracked. Should I use exclude or assume-unchanged, or something else? A: If your project use an external library, you may want to use git submodule to include it in your repository, then go in that directory to git checkout the tag (or branch, or sha1) you want to use. git init newproject cd newproject git submodule add https://url-or-path/to/base/ee-repository target_dir cd target_dir git checkout sometag cd - git add target_dir git commit
{ "language": "en", "url": "https://stackoverflow.com/questions/33437257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angular 4 TypeError: Cannot read property 'IndustrySegments' of undefined I'm fairly new to Angular 4 and am having a problem with this error coming up in Chrome: ERROR TypeError: Cannot read property 'IndustrySegments' of undefined at Object.eval [as updateDirectives] (IndustrialComponent.html:15) at Object.debugUpdateDirectives [as updateDirectives] ( I'm trying to populate a dropdown. The dropdown does populate though it does have a blank entry at the top that I don't want. I wonder if that is due to the error I'm getting. Here's my component HTML code: <select formControlName="drpIndustrySegments"> <option value="-">Industry Segment</option> <option *ngFor="let industrySegment of industrialDropdown.IndustrySegments" value="{{ industrySegment }}">{{ industrySegment }}</option> </select> The contents of the dropdown is coming from a JSON file called industrial-dropdown.json: { "IndustrySegments": [ "Amusement and Theme Parks", "Construction Equipment", "Conveyor Equipment", "Hot Mix Asphalt", "Industrial & Commercial Facilities", "Locomotive & Rail Car", "Portable & Modular Buildings", "Portable and Modular Buildings", "Propane Gas", "Ready Mix Concrete", "Right of Way Equipment", "Short Line Rail Road", "Ski Resorts" ] } Here's my industrial.component.ts code: import { Component, OnInit } from '@angular/core'; import { FormControl, FormArray, FormBuilder, FormGroup } from '@angular/forms'; import { Router, ActivatedRoute } from '@angular/router'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/min'; import { IndustrialService } from '../../services/industrial.service'; import { IndustrialDropdown } from '../../shared/industrial-dropdown'; @Component({ selector: 'industrial', templateUrl: './industrial.component.html' }) export class IndustrialComponent implements OnInit { heroForm: FormGroup; industrialDropdown: IndustrialDropdown; constructor( private fb: FormBuilder, private industrialService: IndustrialService, private router: Router) { this.createForm(); } ngOnInit() { this.getIndustrialDropdowns(); } getIndustrialDropdowns(): void { this.industrialService.getIndustrialDropdown().then(industrialDropdown => this.industrialDropdown = industrialDropdown); } createForm() { this.heroForm = this.fb.group({ drpIndustrySegments: '', drpItemsPainted: '', drpEnvironments: '', drpSurfaces: '', drpVOCs: '' }); } onSubmit() { this.router.navigate(['/industrial-search', this.heroForm.value.drpIndustrySegments, this.heroForm.value.drpItemsPainted, this.heroForm.value.drpEnvironments, this.heroForm.value.drpSurfaces, this.heroForm.value.drpVOCs ]); } } Does anyone know what I'm doing wrong here? I appreciate any suggestions. A: try this using the ? operator: <option *ngFor="let industrySegment of industrialDropdown?.IndustrySegments" value="{{ industrySegment }}">{{ industrySegment }}</option> industrialDropdown is not present when template is rendered
{ "language": "en", "url": "https://stackoverflow.com/questions/45946726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it bad practice to have a function that doesn't return if it throws an exception? I have some computational functions for configurations for software that will drive a hardware setup. In some cases, the user may input invalid configuration values. I handle this by throwing an exception if invalid values are used, or simply returning my calculated value if the configuration works: def calc_exhale_dur(breath_rate, inh_dur, breath_hold_dur): """Calculate exhalation duration. Args: breath_rate (float): animal breath rate (br/min) inh_dur (float): animal inhalation duration (ms) breath_hold_duration (float): animal breath hold duration (ms) """ single_breath_dur = calc_breath_dur(breath_rate) exhale_dur = single_breath_dur - (inh_dur + breath_hold_dur) if (inh_dur + breath_hold_dur + exhale_dur) > single_breath_dur: raise error.ConfigurationError elif exhale_dur <= 0: raise error.ConfigurationError else: return exhale_dur Is it considered bad practice to do it this way? Do I always need to have some valid return value if there is a return value to begin with? I'm trying to learn how best to write Pythonic code while still satisfying the needs of my computational methods. A: The purpose of raising an exception is to provide an alternate exit point in the event where a valid return value can't be found. You are using exceptions exactly as they are intended. However, I would probably check if exhale_dir is non-positive first, which would save you from performing a calculation with an invalid value. if exhale_dur <= 0: raise error.ConfigurationError elif (inh_dur + breath_hold_dur + exhale_dur) > single_breath_dur): raise error.ConfigurationError # You can also omit the else, since the only way to reach this point # is to *not* have raised an exception. This is a matter of style, though. return exhale_dur A: No. Exceptions are either handled in a piece of code, or thrown, and leave it to the caller to decide what to do with them. If you return something, you have to choose the first option. You chose the second. Makes perfect sense. That's the whole idea of throwing an exception
{ "language": "en", "url": "https://stackoverflow.com/questions/52117366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use function recursively in javascript? I have one form where on keyup function I am showing amount in words below that input. It's working as expected with my function. Now O have another input with 2 radio buttons. Onchange this radio buttons also I have to work my function of ShowAmountInWords. I am stuck here. Suppose, I have 2 radio buttons with FD and RD. Limit for FD is 10 digits and Limit for RD is 11 digits. $(document).ready(function() { $('#amount').on('keyup', function() { var amountInWrods = $('#amount').val(); var words = changeToWord(amountInWrods); //calling that function to show amount in words $('#words').val(words); }); }); function changeToWord(amount) { //code to convert number to word return amountInWrods; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type='text' name='amount' id='amount'> <label id='words'>To show Amount in words</label> <input type="radio" id="FD" name="tyoeofdeposit" value="FD"> <input type="radio" id="RD" name="tyoeofdeposit" value="RD"> I am adding my code for radio button validation inside above function. function changeToWord(amount) { $('input[type=radio][name=typeofDeposit]').change(function() { if (this.value == 'FD') { if (amount > 10) { return 'input less amount'; } } else if (this.value == 'RD') { if (amount > 11) { return 'input less amount'; } } }); //code to convert number to word return amountInWrods; } User will input amount and it will go to onkeyup event and from here it will go to function changetowords in that it will check for deposit type If user input 10 digits with FD then it will show amount in words If user input 11 digits with FD then it will return error msg. same for RD. But problem is when FD is selected and user will add 11 digits so it returns errormsg but now, user want to change deposit type to RD so in this case that errormsg should be gone and Amountinwords should return proper response.I am stuck here.I tried with recursion function but it shows me error of max size exceeded.
{ "language": "en", "url": "https://stackoverflow.com/questions/62348639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Red5 application debug i'm trying to deploy my red5 app to the webapps folder. But! I've got some errors in my output. Exception in thread "Launcher:/myApp" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'web.context' defined in ServletContext resource [/WEB-INF/red5-web.xml]: Unsatisfied dependency expressed through bean property 'clientRegistry': : Cannot find class [org.red5.core.Application] for bean with name 'web.handler' defined in ServletContext resource [/WEB-INF/red5-web.xml]; nested exception is java.lang.ClassNotFoundException: org.red5.core.Application; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.red5.core.Application] for bean with name 'web.handler' defined in ServletContext resource [/WEB-INF/red5-web.xml]; nested exception is java.lang.ClassNotFoundException: org.red5.core.Application at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1147) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1040) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416) at org.red5.server.tomcat.TomcatLoader$1.run(TomcatLoader.java:594) Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.red5.core.Application] for bean with name 'web.handler' defined in ServletContext resource [/WEB-INF/red5-web.xml]; nested exception is java.lang.ClassNotFoundException: org.red5.core.Application at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1208) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:568) [INFO] [Launcher:/myApp] org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1af1915: defining beans [placeholderConfig,web.context,web.scope,web.handler]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@46136 at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:302) at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:185) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:805) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:762) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:680) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1132) ... 11 more Caused by: java.lang.ClassNotFoundException: org.red5.core.Application at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1484) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1329) at org.springframework.util.ClassUtils.forName(ClassUtils.java:258) at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408) at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1229) at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1200) ... 19 more After all of that i've got my app folder in webapps, but there is no .class file in the classes folder of my project. So, i can't use server-side app in my client app. What's wrong? App was built by default. Here is my red5-web.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- Defines a properties file for dereferencing variables --> <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="/WEB-INF/red5-web.properties" /> </bean> <!-- Defines the web context --> <bean id="web.context" class="org.red5.server.Context" autowire="byType" /> <!-- Defines the web scopes --> <bean id="web.scope" class="org.red5.server.WebScope" init-method="register"> <property name="server" ref="red5.server" /> <property name="parent" ref="global.scope" /> <property name="context" ref="web.context" /> <property name="handler" ref="web.handler" /> <property name="contextPath" value="${webapp.contextPath}" /> <property name="virtualHosts" value="${webapp.virtualHosts}" /> </bean> <!-- Defines the web handler which acts as an applications endpoint --> <bean id="web.handler" class="org.red5.core.Application" singleton="true" /> </beans> And my Application class package org.red5.core; /* * RED5 Open Source Flash Server - http://www.osflash.org/red5 * * Copyright (c) 2006-2008 by respective authors (see below). All rights reserved. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 2.1 of the License, or (at your option) any later * version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import org.red5.server.adapter.ApplicationAdapter; import org.red5.server.api.IConnection; import org.red5.server.api.IScope; import org.red5.server.api.service.ServiceUtils; /** * Sample application that uses the client manager. * * @author The Red5 Project ([email protected]) */ public class Application extends ApplicationAdapter { /** {@inheritDoc} */ @Override public boolean connect(IConnection conn, IScope scope, Object[] params) { return true; } /** {@inheritDoc} */ @Override public void disconnect(IConnection conn, IScope scope) { super.disconnect(conn, scope); } } I did all of that with Red5 plugin in Eclipse. So... i have no idea what could be wrong.. A: I had the exact same problem. Sounds like you're trying to follow the tutorial videos only using the new Red5_1.0, Like I was. After many days, beers, and bruises from banging my head against my desk, I discovered that if you change your class to "org.red5.server.scope.WebScope" in your red5-web.xml file it should work correctly (bean id="web.scope"). Also, you may need to change your org.red5.core source imports from "import org.red5.server.api.IScope;" to "import org.red5.server.api.scope.IScope;". Apparently there has been some class refactoring in the newer versions of Red5 A: I was getting a similar error, although when I checked my class was already set to "org.red5.server.scope.WebScope" as mentioned in Ninth Realm Matt's answer. I later found that I was missing the lib directory under webaps/chat/WEB-INF/. This may be useful if anyone else has a similar problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/11839084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Javascript to jquery a document.get with children What is the equivalent of this to jquery and how can I shorten it using children (both in jquery and javascript as I'm really curious why mine didn't work)? I tried children actually but didn't get a result I wanted. document.getElementById('ShowRow').getElementsByClassName('value')[0].getElementsByTagName('a')[0].innerHTML Thanks in advance A: Something like this: $('#ShowRow').find('.value:first a:first').html() A: You can do: $('#ShowRow').find('.value:first a:first').html()
{ "language": "en", "url": "https://stackoverflow.com/questions/16723152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to open page in new tab from GridView? I want to open page in new tab while clicking on the gridview link button. But I want to open new page based on alert type. For example, from the given below grid I clicked link button of Alert1 then it should open alert1.aspx page, if it is Alert2 then alert2.aspx. etc Help me to find a proper solution. Thank you. GridView: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowHeader="False"> <Columns> <asp:TemplateField HeaderText="Alert Type" SortExpression="Alert_Type"> <EditItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Eval("Alert_Type") %>'> </asp:Label> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("Alert_Type") %>'> </asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Created_Time" HeaderText="Created Time" ReadOnly="True" SortExpression="Created_Time" /> <asp:TemplateField > <ItemTemplate> <asp:LinkButton ID="lnk" runat="server" Text="Click" OnClick="lnk_Click"> </asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> C#: protected void lnk_Click(object sender, EventArgs e) { Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_newtab');", true); } A: Here's the solution that you looking for: protected void lnk_Click(object sender, EventArgs e) { LinkButton lnk = sender as LinkButton; Label Label1 = lnk.NamingContainer.FindControl("Label1") as Label; if (Label1.Text == "Alert1") { Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true); } else if (Label1.Text == "Alert2") { Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert2.aspx','_blank');", true); } } Also, Give unique names to controls inside GridView. A: Replace '_newtab' to '_blank' Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true); A: You need to set target attribute to _blank Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true); The second argument in window.open is to specify whether you want to open page in new tab or in existing tab. So you need to set it to _blank to open page in new tab A: set CommandName to alert type and access it in click event <asp:LinkButton ID="lnk" runat="server" Text="Click" OnClick="lnk_Click" CommandArgument='<%# Bind("Alert_Type") %>'> </asp:LinkButton> Click event protected void lnk_Click(object sender, EventArgs e) { string alerttype=e.CommandArgument.ToString(); Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open("+alerttype+"'.aspx','_newtab');", true); }
{ "language": "en", "url": "https://stackoverflow.com/questions/30236288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Replace image with different image/button - javascript within a function, I'm trying to replace a image/button with another image/button. <img src="images/14.gif" id="ImageButton1" onClick="showLoad()"> <img src="images/getld.png" id="ImageButton2" alt="Get Last Digits" style="display:none;" onClick="showLock()" /> <script type="text/javascript" language="javascript"> function swapButton(){ document.getElementById('ImageButton1').src = document.getElementById('ImageButton2').src; } </script> But I have the problem that there is two of the same button, (button 2) when it is replaced! (one at the top of the page, and one where it is meant to be). I was wondering if there is a way of getting rid of the extra button at the top, or creating the button element within the javascript function? Thanks for any help. A: You can remove an element in javascript using var el = document.getElementById('id'); var remElement = (el.parentNode).removeChild(el); A: I'd suggest something akin to the following: function swapImageSrc(elem, nextElemId) { if (!elem) { return false; } if (!nextElemId || !document.getElementById(nextElemId)) { var id = elem.id.replace(/\d+/, ''), nextNum = parseInt(elem.id.match(/\d+/), 10) + 1, next = document.getElementById(id + nextNum).src; } else { var next = document.getElementById(nextElemId).src; } elem.src = next; } var images = document.getElementsByTagName('img'); for (var i = 0, len = images.length; i < len; i++) { images[i].onclick = function() { swapImageSrc(this,imgButton2); }; }​ JS Fiddle demo. Edited to add that, while it is possible to switch the src attribute of an image it seems needless, since both images are present in the DOM. The alternative approach is to simply hide the clicked image and show the next: function swapImageSrc(elem, nextElemId) { if (!elem) { return false; } if (!nextElemId || !document.getElementById(nextElemId)) { var id = elem.id.replace(/\d+/, ''), nextNum = parseInt(elem.id.match(/\d+/), 10) + 1, next = document.getElementById(id + nextNum); } else { var next = document.getElementById(nextElemId); } if (!next){ return false; } elem.style.display = 'none'; next.style.display = 'inline-block'; } var images = document.getElementsByTagName('img'); for (var i = 0, len = images.length; i < len; i++) { images[i].onclick = function() { swapImageSrc(this,imgButton2); }; }​ JS Fiddle demo. Edited to offer an alternate approach, which moves the next element to the same location as the clicked image element: function swapImageSrc(elem, nextElemId) { if (!elem) { return false; } if (!nextElemId || !document.getElementById(nextElemId)) { var id = elem.id.replace(/\d+/, ''), nextNum = parseInt(elem.id.match(/\d+/), 10) + 1, next = document.getElementById(id + nextNum); } else { var next = document.getElementById(nextElemId); } if (!next){ return false; } elem.parentNode.insertBefore(next,elem.nextSibling); elem.style.display = 'none'; next.style.display = 'inline-block'; } var images = document.getElementsByTagName('img'); for (var i = 0, len = images.length; i < len; i++) { images[i].onclick = function() { swapImageSrc(this,imgButton2); }; }​ JS Fiddle demo. A: You can hide the first button, not only change the image source. The code below shows one way of doing that. <img src="images/14.gif" id="ImageButton1" onClick="swapButtons(false)" style="visibility: visible;" /> <img src="images/getld.png" id="ImageButton2" alt="Get Last Digits" style="visibility: hidden;" onClick="swapButtons(true)" /> <script type="text/javascript" language="javascript"> function swapButtons(show1) { document.getElementById('ImageButton1').style.visibility = show1 ? 'visible' : 'hidden'; document.getElementById('ImageButton2').style.visibility = show1 ? 'hidden' : 'visible'; } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/10463359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Global instance method I created a an instance method in my MainMenu init. -(NSString*) iPhoneiPadConversionString: (NSString*) fileNameHold : (char) fileType { ....My Code. } All I want to do is reuse this method in my other classes.... fileName = [self iPhoneiPadCOnversionString: @"background.png": 'B']; But I can't seem to figure out what the right stuff to do is... I have been trolling the board and can't quite put all the information together. Any Help would be greatly appreciated. A: What you want is a called a "category". With categories you can extend NSString (and add your method). http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html
{ "language": "en", "url": "https://stackoverflow.com/questions/11978275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: creating separate rules for horizontal and vertical alignment in css The plunkr link is https://plnkr.co/edit/mv3lL1vwu2LxoeFZw0TX I want to position a div at the center of a page (vertically and horizontally). The div has a button which should be at the center of the div. I found a solution in Vertically center in viewport using CSS but it doesn't work for me. Also, I want to create two separate rules, one for vertical alignment and one for horizontal alignment and use them together (or separately) so that I can pick which element should be aligned in which way. I do not want to use Flex, Bootstrap etc. as I am trying to understand CSS concepts. the horizontal alignment rule is straightforward. .center-horizontally-common-styles { display: block; margin: auto auto; } The vertical alignment rule is (modified from the SO link) .centre-vertical-common-styles { position: fixed; right: 50%; top: 50%; transform: translateY(-50%); transform: translateX(50%); } .debug-border-common-styles { border: 3px solid black; height:40px; width:200px; } HTML <div class="debug-border-common-styles centre-vertical-common-styles center-horizontally-common-styles"> <button type="button"> Click Me! </button> </div> My understanding is that right: 50%; top: 50%; will use the browser's window (viewport?) as the reference and move the div's top edge and right edge to the location which is 50% mark of the browser's respective edge's location. TranslateY and TranslateX should now move the div upwards (-50%) and towards left(50%) respectively to align the button's center to the middle of the page thus centering the button. The issues I am facing are: 1) The translateY doesn't seem to work. If I change the height of the div to say 200px. the div starts growing downwards (i.e. its top edge seem to be fixed!) It doesn't happen if the width is changed to say 200px. .debug-border-common-styles { border: 3px solid black; height:200px; width:200px; } 2) The button inside the div is not at the center of the div. I created the following css rule for the button but translateY doesn't seem to work on this one as well. .centre-button-vertical-common-styles { position: absolute; /*use absolute so that the origin is no the parent div*/ right: 50%; top: 50%; transform: translateY(-50%); transform: translateX(50%); } 3) Ideally, I would like to create two separate rules, say .center-vertical and .center-horizontal and combine them to use the desired effect. But If I do something like follows, it doesn't work. Is it possible to create two separate rules? .center-horizontally-common-styles { display: block; margin: auto auto; } Not use right here because horizontal rule should place the item in middle .centre-button-vertical-common-styles { position: absolute; top: 50%; transform: translateY(-50%); } A: Bro, you need few arrows of style. Do like this:) .centre-vertical-common-styles { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); } .debug-border-common-styles { border: 3px solid black; height:40px; width:200px; display:flex; align-items:center; justify-content:center; }
{ "language": "en", "url": "https://stackoverflow.com/questions/48162413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Perl Vs Python variable Scoping - gotchas to be aware of While investigating scoping in Perl and Python, I came across a silent scoping related behavior of Perl that can cause bugs very difficult to trace. Specifically for programmers who are new to the language and not fully aware of all it's nuances. I have provided example code for both Perl and Python to illustrate how scoping works in both the languages In Python if we run the code: x = 30 def g(): s1 = x print "Inside g(): Value of x is %d" % s1 def t(var): x = var print "Inside t(): Value of x is %d" % x def tt(): s1 = x print "Inside t()-tt(): Value of x is %d" % x tt() g() t(200) The resulting output is: Inside t(): Value of x is 200 Inside t()-tt(): Value of x is 200 Inside g(): Value of x is 30 This is the usual lexical scoping behavior. Python treats an assignment in a block by default as the definition and assignment to a new variable, not to the global variable that may exist in the enclosing scope. To override this behavior, the keyword global needs to be used explicitly to modify the global variable x instead. The scope of the variable x in the function g() is determined by the place in the program where it is defined, not where the function g() gets called. As a result of lexical scoping behavior in Python when the function g() is called within the function t() where another lexically scoped variable x is also defined and set to the value of 200, g() still displays the old value 30, as that is the value of the variable x in scope where g() was defined. The function tt() displays a value of 200 for the variable x that is in the the lexical scope of tt(). Python has only lexical scoping and that is the default behavior. By contrast Perl provides the flexibility of using lexical scoping as well as dynamic scoping. Which can be a boon in some cases, but can also lead to hard to find bugs if the programmer is not careful and understands how scoping works in Perl. To illustrate this subtle behavior, if we execute the following Perl code: use strict; our $x = 30; sub g { my $s = $x; print "Inside g\(\)\: Value of x is ${s}\n"; } sub t { $x = shift; print "Inside t\(\)\: Value of x is ${x}\n"; sub tt { my $p = $x; print "Inside t\(\)-tt\(\)\: Value of x is ${p}\n"; } tt($x); g(); } sub h { local $x = 2000; print "Inside h\(\)\: Value of x is ${x}\n"; sub hh { my $p = $x; print "Inside h\(\)-hh\(\)\: Value of x is ${p}\n"; } hh($x); g(); } sub r { my $x = shift; print "Inside r\(\)\: Value of x is ${x}\n"; sub rr { my $p = $x; print "Inside r\(\)-rr\(\)\: Value of x is ${p}\n"; } rr($x); g(); } g(); t(500); g(); h(700); g(); r(900); g(); the resulting output is: Inside g(): Value of x is 30 Inside t(): Value of x is 500 Inside t()-tt(): Value of x is 500 Inside g(): Value of x is 500 Inside g(): Value of x is 500 Inside h(): Value of x is 2000 Inside h()-hh(): Value of x is 2000 Inside g(): Value of x is 2000 Inside g(): Value of x is 500 Inside r(): Value of x is 900 Inside r()-rr(): Value of x is 900 Inside g(): Value of x is 500 Inside g(): Value of x is 500 The line our $x defines/declares a global variable $x visible throughout the Package/code body. The first call to t() the global variable $x is modified and this change is visible globally. Perl as opposed to Python by default just assigns a value to a variable, whereas Python by default defines a new variable and assigns a value to it within a scope. That is why we have the different results in the Python and the Perl code above. That is why even the call to g() within t() prints the value 500. The call to g() immediately after the call to t() also prints 500 and proves that the call to t() indeed modified the global variable $x in the global scope. $x within function t() is lexically scoped, but not displaying the expected behavior as the assignment at line 8 makes a global change to the variable $x in the global scope. This results in the call to g() within t() displaying 500 instead of 30. In the call to the function h() where g() is called (line 25), the function g() prints 2000, similar to the output from function t(). However when the function h() returns and we again call g() immediately after it, we find that $x has not changed at all. That is the change to $x within h() did not change $x in it's global scope but only within the scope of h(). The change to $x is somehow temporarily confined to within the current scope where the local keyword is used. This is dynamic scoping in practice in Perl. The call to g() returns the value of the variable $x in the current execution scope of g() instead of the value of $x where g() is defined within the code a.k.a lexical scope. Finally in the call to function r() at line 28, the keyword my forces the creation of a new lexically scoped local variable, identical to the behavior within function t() in the Python code snippet. This is in stark contrast to what happened within h() or t() where no new variable was ever created. Within function r() we observe that the call to g() actually prints the value of $x as 500, the value $x has in the lexical scope where g() has been defined and not the value in the current execution scope of g() (as opposed to dynamic scope result in h()). The Perl function r() is the closest match in terms of scoping behavior to the original Python function t(). By default Perl modifies the global variable $x instead of creating a new lexically scoped $x variable as in Python, and this can be some times a source of confusion and errors to a Perl newbie. For statically typed languages, this is not an issue as variables need to be declared explicitly and the chances of any confusion of whether an existing variable is being assigned to or a new variable is being defined and assigned to does not arise. In dynamically typed languages, that do not require explicit declaration and where the programmer is unaware of the consequences of not using scoping syntaxes appropriately (as in use of my in Perl), it can often lead to unintended consequences if one is not careful. The programmer might think that a new variable is being declared at line 8, but actually the global variable $x is being modified. This is exactly the way Perl intends it to be used, but can lead to interesting effects if the programmer is not careful and not fully aware of what it means. This kind of error could get difficult to catch and debug in a large program of several hundreds or thousands of lines of code. The thing to remember is that without a my prefix, Perl treats assignments to variables as just assignments not a definition + assignment. Perl treats assignment in a block by default as assignment to the global variable of the same name and requires explicit override by using my to define + assign to a lexically scoped local variable. Python has opposite default behavior and treats all assignments in a block by default as defining and assigning to a local lexically scoped variable. The use of the global key word needs to be explicitly used to override this default behavior. I feel Python's default behavior is safer and maybe kinder to novice and intermediate level programmers than Perl's default scoping behavior. Please add any other subtle scoping related issues to be aware of for both Perl and Python that you may be aware of. A: The line $x = shift in your second Perl example just overwrites a global, lexically-scoped variable, same as if you would add global x to your Python code. This has nothing to do with dynamic scoping, and there are many other languages with the same behaviour as Perl - I'd consider Python the odd man out here for requiring to explicitly import a variable name visible at lexical scope. The real problem with the Perl code is not lexical scoping, but lack of declared parameters. With declared parameters, it would be impossible to forget the my, and the problem would go away as well. I find Python's approach to scoping (as of Python 2) far more problematic: it's inconsistent (explicit imports for globals to get a read-write binding, whereas lexicals in nested functions are bound automatically, but read-only) and makes closures secon-class citizens.
{ "language": "en", "url": "https://stackoverflow.com/questions/6868846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: kernel gets stuck if I train/test split by 55% and 45% I am trying to train a neural net on a dataset. Everything works. There is no issue with the code if I specifiy 70% or 50% percent of the data as training and the rest as testing. But as I specify 55% and 45% for training and testing, the kernel gets stuck and gives the following error: Error in plot.nn(nnet, rep = "best"): weights were not calculated Traceback: 1. plot(nnet, rep = "best") 2. plot(nnet, rep = "best") 3. plot.nn(nnet, rep = "best") 4. stop("weights were not calculated") Here is the code that I have written so far: library(neuralnet) Main <- read.table("miRNAs200TypesofCancerData.txt", header = TRUE,stringsAsFactors = T ) # reading the dataset for(i in 1:ncol(Main)){ Main[is.na(Main[,i]), i] <- mean(Main[,i], na.rm = TRUE) } set.seed(123) # in the following line, if you replace p=0.55 by p=0.5, no problem is reported and everything works smoothly indexes = createDataPartition(Main$Type, p=0.55, list = F) # Creating test and train sets. train = Main[indexes, ] test = Main[-indexes, ] xtest = test[, -1] ytest = test[, 1] nnet = neuralnet(Type~., train, hidden = 5, linear.output = FALSE) # Plotting plot(nnet, rep = "best") # Predictions ypred = neuralnet::compute(nnet, xtest) yhat = ypred$net.result yhat=data.frame("yhat"=ifelse(max.col(yhat[ ,1:4])==1, "Mesenchymal", ifelse(max.col(yhat[ ,1:4])==2, "Proneural", ifelse(max.col(yhat[ ,1:4])==3, "Classical","Neural")))) # Confusion matrix cm = confusionMatrix(as.factor(yhat$yhat),as.factor(ytest)) print(cm) Here is a link to the: Dataset A: By adding just act.fct = "tanh" parameter in the model, everything runs smoothly. Here is the working version: library(neuralnet) Main <- read.table("miRNAs200TypesofCancerData.txt", header = TRUE,stringsAsFactors = T ) # reading the dataset for(i in 1:ncol(Main)){ Main[is.na(Main[,i]), i] <- mean(Main[,i], na.rm = TRUE) } set.seed(123) # in the following line, if you replace p=0.55 by p=0.5, no problem is reported and everything works smoothly indexes = createDataPartition(Main$Type, p=0.55, list = F) # Creating test and train sets. train = Main[indexes, ] test = Main[-indexes, ] xtest = test[, -1] ytest = test[, 1] nnet = neuralnet(Type~., train, hidden = 5, act.fct="tanh", linear.output = FALSE) # Plotting plot(nnet, rep = "best") # Predictions ypred = neuralnet::compute(nnet, xtest) yhat = ypred$net.result yhat=data.frame("yhat"=ifelse(max.col(yhat[ ,1:4])==1, "Mesenchymal", ifelse(max.col(yhat[ ,1:4])==2, "Proneural", ifelse(max.col(yhat[ ,1:4])==3, "Classical","Neural")))) # Confusion matrix cm = confusionMatrix(as.factor(yhat$yhat),as.factor(ytest)) print(cm)
{ "language": "en", "url": "https://stackoverflow.com/questions/65353146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: yolov4-tiny on Colab. ConverterError: Variable constant folding is failed I'm trying to convert the tensorflow weights to tensorflow lite. First of all, I converted.tflite from generating TensorFlow SavedModel. I do this in Google colab. Can I execute this code? %cd /content/tensorflow-yolov4-tflite !python convert_tflite.py --weights ./checkpoints/yolov4-tiny-pretflite-416 --output ./checkpoints/yolov4-tiny-416.tflite then the result `tensorflow.lite.python.convert_phase.ConverterError`: Variable constant folding is failed. Please consider using enabling `experimental_enable_resource_variables` flag in the TFLite converter object. For example, converter.experimental_enable_resource_variables = True btw, this my file convert_tflite.py import tensorflow as tf from absl import app, flags, logging from absl.flags import FLAGS import numpy as np import cv2 from core.yolov4 import YOLOv4, YOLOv3, YOLOv3_tiny, decode import core.utils as utils import os from core.config import cfg flags.DEFINE_string('weights', './checkpoints/yolov4-416', 'path to weights file') flags.DEFINE_string('output', './checkpoints/yolov4-416-fp32.tflite', 'path to output') flags.DEFINE_integer('input_size', 416, 'path to output') flags.DEFINE_string('quantize_mode', 'float32', 'quantize mode (int8, float16, float32)') flags.DEFINE_string('dataset', "/Volumes/Elements/data/coco_dataset/coco/5k.txt", 'path to dataset') def representative_data_gen(): fimage = open(FLAGS.dataset).read().split() for input_value in range(10): if os.path.exists(fimage[input_value]): original_image=cv2.imread(fimage[input_value]) original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB) image_data = utils.image_preprocess(np.copy(original_image), [FLAGS.input_size, FLAGS.input_size]) img_in = image_data[np.newaxis, ...].astype(np.float32) print("calibration image {}".format(fimage[input_value])) yield [img_in] else: continue def save_tflite(): converter = tf.lite.TFLiteConverter.from_saved_model(FLAGS.weights) if FLAGS.quantize_mode == 'float16': converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_types = [tf.compat.v1.lite.constants.FLOAT16] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] converter.allow_custom_ops = True elif FLAGS.quantize_mode == 'int8': converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8] converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] converter.allow_custom_ops = True converter.representative_dataset = representative_data_gen tflite_model = converter.convert() open(FLAGS.output, 'wb').write(tflite_model) logging.info("model saved to: {}".format(FLAGS.output)) def demo(): interpreter = tf.lite.Interpreter(model_path=FLAGS.output) interpreter.allocate_tensors() logging.info('tflite model loaded') input_details = interpreter.get_input_details() print(input_details) output_details = interpreter.get_output_details() print(output_details) input_shape = input_details[0]['shape'] input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32) interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() output_data = [interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details))] print(output_data) def main(_argv): save_tflite() demo() if __name__ == '__main__': try: app.run(main) except SystemExit: pass I save this file in folder tensorflow-yolov4 tflite. Can someone know how to solve this problem? I need you guys. Thank you A: Add two lines before tflite_model = converter.convert() in save_tflite() function like this converter.experimental_enable_resource_variables = True converter.experimental_new_converter = True tflite_model = converter.convert()
{ "language": "en", "url": "https://stackoverflow.com/questions/73088684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: onbackpressed make my app close without confirmation I'm new android developer, my app closes when I press back from any page in menu. I added this code with dialog but it is not working @Override public void onBackPressed() { super.onBackPressed(); FragmentManager fm = getSupportFragmentManager(); int count = fm.getBackStackEntryCount(); if(count == 0) { // Do you want to close app? } } A: Have you tried putting the super call in an else block so it is only called if the key is not KEYCODE_BACK ? /* Prevent app from being killed on back */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Back? if (keyCode == KeyEvent.KEYCODE_BACK) { // Back moveTaskToBack(true); return true; } else { // Return return super.onKeyDown(keyCode, event); } } That should work for now! Feel free to comment if you have any problems. A: try this: @Override public void onBackPressed() { FragmentManager fm = getSupportFragmentManager(); int count = fm.getBackStackEntryCount(); if(count == 0) { // Do you want to close app? showDialog(); } } public void showDialog() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Do you want to close the app"); alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { finish(); //or super.onBackPressed(); } }); alert.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); } A: Override activity's onBackPressed with the following in case you have for instance made changes in some values and forgot to update those afterwards, but in stead pressed the back button : @Override public void onBackPressed() { if( <condition>) { AlertDialog.Builder ad = new AlertDialog.Builder( this); ad.setTitle("Changes were made. Do you want to exit without update?"); ad.setPositiveButton( "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { backPress(); } } ); ad.setNegativeButton( "Update the changes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { <Update the changes>; Toast.makeText(getApplicationContext(), "Changes were updated", Toast.LENGTH_SHORT).show(); backPress(); } } ); ad.setCancelable( false); ad.show(); } else { backPress(); } } private void backPress() { super.onBackPressed(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/31776351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cacti graph not showing properly Hoping to reach all of you Cacti experts right there. I have tried posting the same issue on the Cacti forums website, but after nearly a week had no answer. Hoping to have more luck here. I'm pretty new to Cacti, and in the past days I've worked my way through to installation, configuration, etc. I am now at a stage where I need to hook up the system I need to monitor (called Diffusion) into cacti. Diffusion is a java-based push engine, and my aim is to graph specific MBeans the server exposes. I have created Perl scripts that give me the info I need in a correct fashion, and built a graph template to display data from 4 data sources pertaining a threadpool. As of now the values are fixed, hence the outcome is always 0, 3, 8 and 10 (4 data sources, dumping on 4 rrds). For some reason, though the only line I can see is the one returning 0, and the graph is sized between 0 and 1, wehreas I'd expect to see the other lines as well and the graph being sized between 0 and some value above 10. Just to make it clear, logs (DEBUG level) do not show any warning, data gathering seems to work well, and I have no "complain" from cacti when creating sources, templates, etc. Any help would be appreciated. Thanks. A: After a few attempts with changing a variety of parameters, I managed to solve the issue by simply changing the graph type to GAUGE. Seems to wrk pretty well now.
{ "language": "en", "url": "https://stackoverflow.com/questions/16024637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jupiternote book on iPad / makrdown cells / how to drag a picture? I use JUNO connect to run cocalc on my iPad. How can I get a picture in my picture file on the iPad into a markdown cell? Thanks a lot for any help!
{ "language": "en", "url": "https://stackoverflow.com/questions/74504652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In an IntelliJ Kotlin project, when I try to run a java class, I get a "Could not find or load main class" error I try to run the class from the green arrow in IntelliJ and I get the "Could not find or load main class" error. If I try to run the class from the terminal by running javac <filename.java> java <filename> it works. I tried to do "rebuild project" and to make a new project and it did not change anything. Here is a photo of my project: Here is a photo of my Run-Edit configurations A: Your java code needs to be placed in src/main/java directory instead of src/main/kotlin. Kotlin compiler doesn't compile Java files in Kotlin source roots, Java compiler doesn't compile Java files in Kotlin source roots, therefore .class files are not created by any of the compilers and you get this error. The solution is to move *.java files into src/main/java directory. Create this directory manually if it doesn't exist.
{ "language": "en", "url": "https://stackoverflow.com/questions/70992145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call a setter method in the Data Assignments I/O in a jbpm task? I have a process in jBPM. The process has a Human Task. Also there are Data Objects: SrcData, CalcInter. In the Human Task's Assignment Data I/O panel I need to read properties from the objects in Data Inputs section, and write a calculated variable in the property of CalcInter object in Data Outputs section (see picture). Screenshot of Assignment Data I/O panel Objects' properties reading in Data Inputs works as intended. As suggested here: How to call a getter method in the Data Assignments I/O in a jbpm task? But writing Object property in Data Outputs in such way doesn't work. I've tried: #{CalcInter.setAxx(axx)} #{CalcInter.setAxx((int)axx)} #{CalcInter.setAxx(#{axx})} How to solve this? (And why is it so complicated?) A: I've found that the issue can be solved by using MVEL notation instead of pure Java. If in Data Outputs as a Target we use following expression: #{CalcInter.axx} The jBPM engine correctly updates the object property. (How to use a Java style in the case and if it is possible — I still don't know.)
{ "language": "en", "url": "https://stackoverflow.com/questions/70269532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what is the significance of " #!flask/bin/python " in flask? why this line #!flask/bin/python is added on the top of this code? from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello, World!" if __name__ == '__main__': app.run(debug=True) I got following error when I removed it from: can't read /var/mail/flask ./app.py: line 3: syntax error near unexpected token `(' ./app.py: line 3: `app = Flask(__name__)' A: #! is a shebang. On UNIX/UNIX like operating systems it basically tells your shell which executable (python in your case) to execute the script with. Without it, the shell is executing the script directly and since it does not understand Python code, it raises an error.
{ "language": "en", "url": "https://stackoverflow.com/questions/30954599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Adding rows to tables of datasets? I created a data set within VS2012 and created some tables for it. But i am unable to fill the tables using C#. This runs without errors: Database1DataSet.LocationRow newLocationRow; newLocationRow = database1DataSet.Location.NewLocationRow(); newLocationRow.LocationID = 1; newLocationRow.LocationName = "Test"; newLocationRow.LocationInfo = "Test"; database1DataSet.Location.Rows.Add(newLocationRow); //<- i get an error here ONLY if i use a row with a incorrect foreign key. this.tableAdapterManager.UpdateAll(database1DataSet); When i insert a simple row into a table like this i cannot find it in the database explorer, it still shows a single row with NULL. Am i doing something wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/23430113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Array.length seemingly not working; console.log shows otherwise I want to eventually write contactList to the page but even though console.log is showing that contactList is properly receiving contacts being pushed from localStorage, its length remains at 1! And when I do try to iterate over contactList to write to the page, it doesn't work as expected and I see undefined where values should be. var contactList = []; window.onload = init; function init(){ var data = window.localStorage.getItem("contacts"); if(data){ myData = JSON.parse(data); console.log("This is local storage:\n"); console.log(myData); console.log("This is contact list before I push local storage:\n"); console.log(contactList); contactList.push(myData); console.log("This is contact list after I push local storage:\n"); console.log(contactList); var j = contactList.length; console.log("This is the length of contact list:\n"); console.log(contactList.length); } } Here's an example of my console window: This is local storage: form.js (line 12) [[[Object { firstname="hi", lastname="hi", number="hi"}], Object { firstname="hi", lastname="hi", number="hi"}], Object{ firstname="hi", lastname="hi", number="hi"}] form.js (line 13) This is contact list before I push local storage: form.js (line 14) [] form.js (line 15) This is contact list after I push local storage: form.js (line 17) [[[[Object { firstname="hi", lastname="hi", number="hi"}], Object { firstname="hi", lastname="hi", number="hi"}], Object { firstname="hi", > lastname="hi", number="hi"}]] form.js (line 18) This is the length of contact list: form.js (line 20) 1 A: That is the expected outcome with push. It looks like you want to use concat. push will append whatever the argument is to a new element at the end of the array. If you add a string it will add the string. If you add an array it will add an array...as the last element. It will not flatten the resultant array. On the other hand concat will concat the two arrays and return a new array. The original array will be unchanged though. A: var a = [1] console.log(a.length) // 0 var b = [2] var c = a.push(b) console.log(c) // [1, [2]] console.log(c.length) // 2 Try using concat(): var a = [1] console.log(a.length) // 1 var b = [2] var c = a.concat(b) console.log(c) // [1, 2] <<< Desired behaviour console.log(c.length) // 2
{ "language": "en", "url": "https://stackoverflow.com/questions/29551468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: [MySQL]Insert a value depending on a condition I'm studying MySQL so I'm a bit new to all this stuff, but the last time I asked you guys, you proved to be really helpful, so perhaps you can help me again because I haven't been able to find the answer on my own. Ok, so the thing is, I need to add a new column to an already existing table, and it should be like: ALTER TABLE `medicos` ADD COLUMN `tipo_medico` VARCHAR(20) NOT NULL DEFAULT 'indiferente' AFTER `sueldo`; Now I'm supposed to run an INSERT instruction to add the data there. After adding that column, the table looks like this: These values equal to: Medic_number, Surnames, Speciality, Day of birth, University, Wage and Medic_type (the new column I've added). The data I add on all the columns except the last one doesn't really matter, but the last column must be filled following the next conditions: -By default, it'll be "indiferente" (that's working). -If a medic has studied in an university ending in -a (i.e. Valencia), it'll say "Excellent". -If a medic is 40 years old or older, it'll say "Expert". Now, I know how to do these conditions ("... university like = '%a'", etc), but I don't know how to add that into the INSERT instruction. This is what I've gotten so far: insert into medicos values ('A021', 'Apellidos :D', 'Loquesealogia', '1970-03-14', 'Valencia', '3500'); That adds everything but the last column, which is the one where I'm lost. What can I do to tell the INSERT instruction to, depending on which of the previously named conditions are true, add one value or another? I hope I've been clear enough, I'm not a native English speaker so I'm sorry if that wasn't good enough. Also I've tried to format the codes this time, I hope that'll work. Thanks. A: This seems to be a case when we need to apply a logic on column values before a record is inserted. I would suggest creating a BEFORE INSERT trigger on this table, which will be automatically executed by MySql before each record is inserted. We can write the logic to determine the value of last column depending upon values supplied for the other columns. Have a look at this link for trigger example. If the requirement here is to do a one time bulk insert then, we can drop this trigger once insertion is complete. A: I would advise you to do it either with BEFORE INSERT trigger as Darshan Mehta recommends, or do your logic in the programming side, or with a stored procedure. Still it is doable at query time, so to answer your question specifically, try something like this: INSERT INTO medicos (num_colegiado, apellidos, especialidad, fecha_nac, universidad, sueldo, tipo_medico) SELECT 'A021', 'Apellidos :D', 'Loquesealogia', '1970-03-14', 'Valencia', '3500', IF('Loquesealogia' like '%a','Excellent',IF(DATE_ADD('1970-03-14', interval 40 YEAR)>NOW(),'Expert','indiferente'))
{ "language": "en", "url": "https://stackoverflow.com/questions/35760064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Caling procedure in conversion.asm from main .asm I have two asm files, one is conversion.asm and one is main.asm, I am using conversion.asm in main.asm. I am using floating point stack but I am not getting the right output. main.asm Include conversion.asm .386 .stack 4096 ExitProcess PROTO, dwExitCode:DWORD .data Cel DD 25 Faren DD ? .code main PROC push dword ptr Cel fld dword ptr [esp] call C2F fstp dword ptr [Faren] mov ebx, [Faren] INVOKE ExitProcess, ebx main ENDP END main conversion.asm .model flat, stdcall ExitProcess PROTO, dwExitCode:DWORD .stack 4096 .data Cfirst DD 2 Csecond DD 1 common DD 32 C2F PROC push dword ptr Cfirst fld dword ptr [esp] add esp,4 fmulp sub esp,4 push dword ptr Csecond fld dword ptr [esp] add esp,4 fdivp sub esp,4 push dword ptr common fld dword ptr [esp] add esp,4 faddp sub esp,4 RET C2F ENDP Please help me out A: fmul, fdiv, fadd edit data in floating stack directly, so instead of pulling from stack to register, do operation directly in floating stack. Correct usage of floating point stack in conversion.asm: .DATA five DWORD 5.0 nine DWORD 9.0 ttw DWORD 32.0 .CODE C2F proc fmul nine fdiv five fadd ttw ret C2F ENDP For reading float and writing float I used Irvine library, which uses floating point stack: Include Irvine32.inc Include conversion.asm .data Celprompt BYTE "Enter a value in C:",0 Cel DWORD 0 Resprompt BYTE "In Farenheit that value is - " Faren DD ? .code main PROC mov edx, OFFSET Celprompt call WriteString call Crlf call ReadFloat call C2F call Crlf mov edx, OFFSET Resprompt call WriteString call WriteFloat main ENDP END main
{ "language": "en", "url": "https://stackoverflow.com/questions/74668770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy tables form schema in another schema in Oracle I want to write a procedure or a cursor. Input data -- NAME OWNER. We know name (OWNER) AND from table ALL_OBJECTS Take the name of the table. Tables > 30. How to write correctly ? CREATE OR REPLACE PROCEDURE USER_NAME ( v_USER VARCHAR2 ) AS v_sysdate VARCHAR2(10) := to_char(SYSDATE ,'MMDDYYYY'); v_table_name VARCHAR2(50); BEGIN SELECT TABLE_NAME INTO v_table_name FROM ALL_OBJECTS F -- Table with two columnsю. OWNER AND NAME TABLES WHERE F.OWNER = v_USER; --Name of tables and owner ALL_OBJECTS EXECUTE IMMEDIATE 'CREATE TABLE USER_BANCU.'||v_USER||'_'||v_table_name||'__'||v_sysdate||to_char(sysdate,'HH24_MI_SS')||' AS SELECT * FROM '||v_USER||'.'||v_table_nam; COMMIT; END; / A: Try DBMS_METADATA_GET_DDL. enter link description here
{ "language": "en", "url": "https://stackoverflow.com/questions/36285372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uninstall / remove a Homebrew package including all its dependencies I have a Homebrew formula that I wish to uninstall/remove along with all its dependencies, skipping packages whom other packages depend upon (a.k.a. Cascading package removal in Package manager parlance). e.g. Uninstall package a which depends on packages b & c, where package d also depends on package c. The result should uninstall both a & b, skipping c. How can I do that? There must be a way to uninstall a package without leaving unnecessary junk behind. A: EDIT: It looks like the issue is now solved using an external command called brew rmdeps or brew rmtree. To install and use, issue the following commands: $ brew tap beeftornado/rmtree $ brew rmtree <package> See the above link for more information and discussion. [EDIT] see the new command brew autoremove in https://stackoverflow.com/a/66719581/160968 Original answer: It appears that currently, there's no easy way to accomplish this. However, I filed an issue on Homebrew's GitHub page, and somebody suggested a temporary solution until they add an exclusive command to solve this. There's an external command called brew leaves which prints all packages that are not dependencies of other packages. If you do a logical and on the output of brew leaves and brew deps <package>, you might just get a list of the orphaned dependency packages, which you can uninstall manually afterwards. Combine this with xargs and you'll get what you need, I guess (untested, don't count on this). EDIT: Somebody just suggested a very similar solution, using join instead of xargs: brew rm FORMULA brew rm $(join <(brew leaves) <(brew deps FORMULA)) See the comment on the issue mentioned above for more info. A: brew rmtree doesn't work at all. From the links on that issue I found rmrec which actually does work. God knows why brew doesn't have this as a native command. brew tap ggpeti/rmrec brew rmrec pkgname A: You can just use a UNIX pipe for this brew deps [FORMULA] | xargs brew rm A: A More-Complete Bourne Shell Function There are a number of good answers already, but some are out of date and none of them are entirely complete. In particular, most of them will remove dependencies but still leave it up to you to remove the originally-targeted formula afterwards. The posted one-liners can also be tedious to work with if you want to uninstall more than one formula at a time. Here is a Bourne-compatible shell function (without any known Bashisms) that takes a list of formulae, removes each one's dependencies, removes all copies of the formula itself, and then reinstalls any missing dependencies. unbrew () { local formula for formula in "$@"; do brew deps "$formula" | xargs brew uninstall --ignore-dependencies --force brew uninstall --force "$formula" done brew missing | cut -f2 -d: | sort -u | xargs brew install } It was tested on Homebrew 1.7.4. Caveats This works on all standard formulae that I tested. It does not presently handle casks, but neither will it complain loudly if you attempt to unbrew a cask with the same name as a standard formula (e.g. MacVim). A: The goal here is to remove the given package and its dependencies without breaking another package's dependencies. I use this command: brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | xargs brew install Note: Edited to reflect @alphadogg's helpful comment. A: Other answers didn't work for me, but this did (in fish shell): brew remove <package> for p in (brew deps <package>) brew remove $p end Because brew remove $p fails when some other package depends on p. A: By the end of 2020, the Homebrew team added a simple command brew autoremove to remove all unused dependencies. First, uninstall the package: brew uninstall <package> Then, remove all the unused dependencies: brew autoremove A: Based on @jfmercer answer (corrections needed more than a comment). Remove package's dependencies (does not remove package): brew deps [FORMULA] | xargs brew remove --ignore-dependencies Remove package: brew remove [FORMULA] Reinstall missing libraries: brew missing | cut -d: -f2 | sort | uniq | xargs brew install Tested uninstalling meld after discovering MeldMerge releases. A: Using this answer requires that you create and maintain a file that contains the package names you want installed on your system. If you don't have one already, use the following command and delete the package names what you don't want to keep installed. brew leaves > brew_packages Then you can remove all installed, but unwanted packages and any unnecessary dependencies by running the following command brew_clean brew_packages brew_clean is available here: https://gist.github.com/cskeeters/10ff1295bca93808213d This script gets all of the packages you specified in brew_packages and all of their dependancies and compares them against the output of brew list and finally removes the unwanted packages after verifying this list with the user. At this point if you want to remove package a, you simply remove it from the brew_packages file then re-run brew_clean brew_packages. It will remove b, but not c. A: Save the following script as brew-purge #!/bin/bash #:Usage: brew purge formula #: #:Removes the package and all dependancies. #: #: PKG="$1" if [ -z "$PKG" ];then brew purge --help exit 1 fi brew rm $PKG [ $? -ne 0 ] && exit 1 while brew rm $(join <(brew leaves) <(brew deps $PKG)) 2>/dev/null do : done echo Package $PKG and its dependancies have been removed. exit 0 Now install it with the following command sudo install brew-purge /usr/local/bin Now run it brew purge package Example using gpg $ brew purge gpg Uninstalling /usr/local/Cellar/gnupg/2.2.13... (134 files, 11.0MB) Uninstalling /usr/local/Cellar/adns/1.5.1... (14 files, 597.5KB) Uninstalling /usr/local/Cellar/gnutls/3.6.6... (1,200 files, 8.9MB) Uninstalling /usr/local/Cellar/libgcrypt/1.8.4... (21 files, 2.6MB) Uninstalling /usr/local/Cellar/libksba/1.3.5... (14 files, 344.2KB) Uninstalling /usr/local/Cellar/libusb/1.0.22... (29 files, 508KB) Uninstalling /usr/local/Cellar/npth/1.6... (11 files, 71.7KB) Uninstalling /usr/local/Cellar/pinentry/1.1.0_1... (12 files, 263.9KB) Uninstalling /usr/local/Cellar/libassuan/2.5.3... (16 files, 444.2KB) Uninstalling /usr/local/Cellar/libtasn1/4.13... (59 files, 436KB) Uninstalling /usr/local/Cellar/libunistring/0.9.10... (54 files, 4.4MB) Uninstalling /usr/local/Cellar/nettle/3.4.1... (85 files, 2MB) Uninstalling /usr/local/Cellar/p11-kit/0.23.15... (63 files, 2.9MB) Uninstalling /usr/local/Cellar/gmp/6.1.2_2... (18 files, 3.1MB) Uninstalling /usr/local/Cellar/libffi/3.2.1... (16 files, 296.8KB) Uninstalling /usr/local/Cellar/libgpg-error/1.35... (27 files, 854.8KB) Package gpg and its dependancies have been removed. $ A: The answer of @jfmercer must be modified slightly to work with current brew, because the output of brew missing has changed: brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | cut -f1 -d: | xargs brew install A: Slightly refined; can supply multiple packages; has usage when none supplied. #!/bin/bash # Removes the package and all dependancies. if [ $# -eq 0 ]; then echo "$(basename $0) <pkg> [<pkg> [...]]" exit 1 fi function tree() { pkg="$1" join <(brew leaves) <(sort <(brew deps ${pkg}; echo ${pkg})) } let e=0 for pkg in "$@"; do printf "Purging %s and its dependencies...\n" "${pkg}" deps=( $(tree ${pkg}) ) while (( ${#deps[@]} > 0 )); do brew rm "${deps[@]}" deps=( $(tree ${pkg}) ) done done
{ "language": "en", "url": "https://stackoverflow.com/questions/7323261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "496" }
Q: Waking up thread from signal handler I understand that about the only thing, a signal handler in ISO/C++11 is allowed to do is to read from or write to a lock free atomic variable or a volatile sig_atomic_t (I believe, POSIX is a little bit more permissive and allows to call a bunch of system functions). I was wondering, if there is any way, to wake up a thread that is waiting on a condition variable. I.e. something like: #include <mutex> #include <atomic> #include <condition_variable> std::mutex mux; std::condition_variable cv; std::atomic_bool doWait{ true }; void signalHandler(int){ doWait = false; cv.notify_one(); } int main() { //register signal handler //Do some stuff {//wait until signal arrived std::unique_lock<std::mutex> ul(mux); cv.wait(ul, []{return !doWait; }); } //Do some more stuff } Which has at least two problems: * *I believe, I'm not allowed to call notify_one() in a signal handler (corrct me if I'm wrong) *The signal could arrive just between the check for doWait and when the thread goes to sleep, so it would never wake up (obviously, I can't lock the mutex in the signalHander to avoid that). So far, the only solution I can see is to implement busy waiting on the doWait variable (probably sleep for a couple of milliseconds in each iteration), which strikes me as quite inefficient. Note that even though, my program above has only one thread, I labeled my question with multithreading, because it is about thread control primitives. If there is no solution in standard c++ I'd be willing to accept a solution using Linux/POSIX specific functions. A: Assuming that your vendor's standard library uses the pthread_cond_* functions to implement C++11 condition variables (libstdc++ and libc++ do this), the pthread_cond_* functions are not async-signal-safe so cannot be invoked from a signal handler. From http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cond_broadcast.html: It is not safe to use the pthread_cond_signal() function in a signal handler that is invoked asynchronously. Even if it were safe, there would still be a race between the test of the Boolean pthread_cond_wait() that could not be efficiently eliminated. Mutexes and condition variables are thus not suitable for releasing a waiting thread by signaling from code running in a signal handler. If you're comfortable using semaphores, sem_post is designated async-signal-safe. Otherwise, your options for signal handling are the usual ones: the classic self-pipe, a signal handling thread blocked on sigwait/sigwaitinfo, or platform-specific facilities (Linux signalfd, etc.).
{ "language": "en", "url": "https://stackoverflow.com/questions/31117959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Website layout is broken, is empty and I can't access wp-admin (wp-login) My site's https://www.beckers-trier.de layout and code is sort of broken. I don't code, but the theme is self-developed and I also don't remember changing anything about the site, except for adding the facebook pixel code in the . The Problem is that a few errors are given, which you can see in the wp-login site of my site. I can't login either, being warned that the cookie settings are closed because of a 'surprising output' A: The error itself is quite self-explainatory, the server is trying to send some headers but some output has already started. The warnings at start of the page are very likely to be generated from the PHP interpreter on your machine, either you have a weird display_errors directive in your php.ini or the constant WP_DEBUG on your wp-config.php is set to true. Double check both configuration files and make sure the display of the errors are set to off and WP_DEBUG to false.
{ "language": "en", "url": "https://stackoverflow.com/questions/57078478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python return value prints only one value from the object instead of all the values I have a Python file with two class A and B, and I am inheriting temp from class A to B. In my class A function temp, I am getting the id value from an XML file which has values like this, [1,2,3,4,5] My Class A with temp function class A: def temp(self): id = [] for child in root: temp_id=child.get('id') id.append(temp_id) return id and I am getting the function value in class B, class B (A): fun=A value = fun.temp() for x in value: return x While printing the return value instead of printing all the values, I am getting only the first value [1,1,1,1,1] Can some one please let me know on how to solve this, thanks. A: Standard functions can only return a single value. After that, execution continues from where that function was called. So, you're trying to loop through all the values, but return upon seeing the first value, then the function exits and the loop is broken. In your case, you could simply return fun.temp(). Or, if you want to process each value, then return the new list, you could run something like: new_list = [] value = fun.temp() for x in value: # do something with x here new_list.append(x) return new_list Also, it appears you may be a bit confused about how inheritance works. DigitalOcean has a great article on it, if you want to take a look.
{ "language": "en", "url": "https://stackoverflow.com/questions/50402694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cost Query with having and > I have the next query : select code from user group by code having sum(case when name= 'A' then 1 end) > sum(case when name= 'A' then 1 end) If i check the cost of the query it says it's 180, but if I use '=' instead of >, the cost is 1 , so does anyone have any idea why this is happening? why it's only using the index with '=' and not with '<' A: Is this a real query? I'm asking because the query is invalid - having clause is equal to writing 1 > 1, so always False... And if you replace '>' with '=' the query is always true unless the result from sum() is NULL...
{ "language": "en", "url": "https://stackoverflow.com/questions/51659738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change the id format of field in a model? For example I have a field of customer IDs going from 1, 2, 3, 4, 5, ... However I want to change the format to 010101, 010102, 010103, 010104, 010105, ... As it display on my database and templates. Is there any way of doing that? I am using PostgreSQL version 12 and pgadmin 4. I have been using of the below on the query editor SELECT concat('0101', lpad(id, 2, '0')) from public.accounts_customer However receiving the error below ERROR: function lpad(integer, integer, unknown) does not exist LINE 1: SELECT concat('0101', lpad(id, 2, '0')) from public.accounts... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. SQL state: 42883 Character: 23 A: You can' t add leading 0 to an integer and store in db you can manage only the selecting result .. eg select concat('0101', lpad(yourcol,2,'0')) from your_table or try force the cast select concat('0101', lpad(yourcol,2,'0'::text)) from your_table
{ "language": "en", "url": "https://stackoverflow.com/questions/61822126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does "self-describing" in reference to Web Services really mean? I've heard a lot of buzz through the years about "Self Describing" web services and I'm curious what it means. I've flipped through the W3C standard and it doesn't really help. I understand you can say "Give me this argument and call this functionality and I'll return something like this", but how is that actually helpful? How can software know what is relevant to a client given some context? Can anyone give real world examples of this concept, and explain how it's better than some other alternative? Or maybe how useful/useless it is? A: It's really designed as a standard for describing in a cross-platform cross-language manner an interface that a developer can use to develop a SOAP based way to exchange information with a web service. Another alternative would be providing a library that provides a local interface to a blackbox communcation scheme, which is fraught with compatability/security issues. Or providing documentation, which may be difficult to find, have compatibility issues, be out of date, or incomplete. In short, it's very useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/3909761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is PGSQL not executing my index because of the ORDER BY clause? I have a rails query that looks like this: Person.limit(10).unclaimed_people({}) def unclaimed_people(opts) sub_query = where.not(name_id: nil) if opts[:q].present? query_with_email_or_name(sub_query, opts) else sub_query.group([:name_id, :effective_name]) .reorder('MIN(COALESCE(kudo_position,999999999)), lower(effective_name)') .select(:name_id) end end Translating to SQL, the query looks like this: SELECT "people"."name_id" FROM "people" WHERE ("people"."name_id" IS NOT NULL) GROUP BY "people"."name_id", "people"."effective_name" ORDER BY MIN(COALESCE(kudo_position,999999999)), lower(effective_name) LIMIT 10 Now when I run an EXPLAIN on the SQL query, what's returned shows that I am not running an index scan. Here is the EXPLAIN: QUERY PLAN -------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=728151.18..728151.21 rows=10 width=53) (actual time=6333.027..6333.028 rows=10 loops=1) -> Sort (cost=728151.18..729171.83 rows=408258 width=53) (actual time=6333.024..6333.024 rows=10 loops=1) Sort Key: (min(COALESCE(kudo_position, 999999999))), (lower(effective_name)) Sort Method: top-N heapsort Memory: 25kB -> GroupAggregate (cost=676646.88..719328.87 rows=408258 width=53) (actual time=4077.902..6169.151 rows=946982 loops=1) Group Key: name_id, effective_name -> Sort (cost=676646.88..686041.57 rows=3757877 width=21) (actual time=4077.846..5106.606 rows=3765261 loops=1) Sort Key: name_id, effective_name Sort Method: external merge Disk: 107808kB -> Seq Scan on people (cost=0.00..112125.78 rows=3757877 width=21) (actual time=0.035..939.682 rows=3765261 loops=1) Filter: (name_id IS NOT NULL) Rows Removed by Filter: 317644 Planning time: 0.130 ms Execution time: 6346.994 ms Pay attention to the bottom part of the query plan. There is a Seq Scan on people. This is not what I was expecting, in my development and production database, I have placed an index on the foreign name_id field. Here is the proof from the people table. "index_people_name_id" btree (name_id) WHERE name_id IS NOT NULL So my question is why would it not be running the index. Could it perhaps be from the ORDER BY clause. I read that it could affect the execution of an index. This is the web page where I read it from. Why isn't my index being used? In particular here is the quote from the page. Indexes are normally not used for ORDER BY or to perform joins. A sequential scan followed by an explicit sort is usually faster than an index scan of a large table. However, LIMIT combined with ORDER BY often will use an index because only a small portion of the table is returned. As you can see from the query, I am using ORDER BY combined with LIMIT so I would expect the index to be used. Could this be outdated? Is the ORDER BY really affecting the query? What am I missing to get the index to work? I'm not particularly versed with the internals of PGSQL so any help would be appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/45335203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PowerShell executing exe with arguments I wrote a PowerShell script to execute exe with arguments which has spaces but it keeps failing, not reading the full path. $now = Get-Date -format "MM_dd_yyyy" $onepath ="C:\Program Files (x86)\GoFileRoom\IWMUploadDocuments\logs\" $scpath = "F:\Program Files\NSClient++\scripts\" $onefile = "IWMUploadDocumentsLog$now.txt" $script = "check_log3.exe" & "$scpath$script" -p "Error Logging into GFR" -l "$onepath$onefile" -c 1 Write-Output "$onepath$onefile" Here is the output: PS C:\Windows\system32> F:\Program Files\NSClient++\scripts\onesource.ps1 Cannot read 'C:\Program' C:\Program Files (x86)\GoFileRoom\IWMUploadDocuments\logs\IWMUploadDocumentsLog10_22_2018.txt A: Looks to me like you need an additional set of quotes around the argument for the parameter -l: & "$scpath$script" -p "Error Logging into GFR" -l "`"$onepath$onefile`"" -c 1 Or try splatting the arguments: $params = '-p', 'Error Logging into GFR', '-l', "$onepath$onefile", '-c', 1 & "$scpath$script" @params
{ "language": "en", "url": "https://stackoverflow.com/questions/52932956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS displaying elements when thumbnails are hovered over i am attempting to display images when the corresponding thumbnail is hover over using only css and am having trouble with the logic and don't know if it is even possible. i can do it in javascript if absolutely necessary. Here is my latest attempt. <div id='img-container' class='grd12'> <img id='img1' class='slide-images' src='images/10086115704_15ab56a165_o.jpg' alt='1'> <img id='img2' class='slide-images' src='images/9917938624_0a8778f8b1_o.jpg' alt='2'> <img id='img3' class='slide-images' src='images/PIA18847.jpg' alt='3'> <img id='img4' class='slide-images' src='images/sun-large.jpg' alt='4'> </div> <!-- <div class='grd3 thumbnail'>--> <img id='thumb1' class='grd3 thumbnail' src='images/10086115704_e36e457d2b_q.jpg' alt='##'> <!-- </div>--> <!-- <div class='grd3 thumbnail'>--> <img id='thumb2' class='grd3 thumbnail' src='images/9917938624_1ed12deaa2_q.jpg' alt='##'> <!-- </div> <div class='grd3 thumbnail'>--> <img id='thumb3' class='grd3 thumbnail' src='images/PIA18847.jpg' alt='##'> <!--</div> <div class='grd3 thumbnail'>--> <img id='thumb4' class='grd3 thumbnail' src='images/sun-large.jpg' alt='##'> <!--</div>--> And the CSS #img-container{ position:relative; top:0px; left:0px; height:950px; } .slide-images{ position:absolute; top:0px; left:0px; } .thumbnail > img{ margin-left:auto; margin-right:auto; display: inherit; } img#thumb4:hover ~ #img4>#image4{ display:none; } A: I believe this is possible using CSS alone, however it is not very scaleable and it might end up being easier and more appropriate to use Javascript for this. For example: img#thumb1:hover ~ #img4>#image4{ display:none; } Your selector here is incorrect. The general sibling selector selects only elements after the first match. In this case, your image thumb is after your image, but this selector is looking for an image after an image thumb. This is the opposite of what you have. There is no 'sibling before' selector in CSS. An easier solution, rather than fiddling around with CSS selectors, would just be to bind each thumbnail to a click event that changes the source of a single image tag each time (or alternatively, scrolls across/fades, whatever animation you're looking for). This way, you save on markup, don't need to worry about positioning as much, and can dynamically generate the image display. For example, to get the ID of an image, you could bind a click event to each thumbnail and then grab the ID of the image which could stored in a data attribute: $('.thumbnail').on('hover', function() { var activeImg = $(this).data('imgid'); // From here, set the main image to have the associated image source } A: This is very possible to achieve with just CSS. The layout of your HTML is what needs to change. In this example: * *Each thumbnail and full-size image is placed inside a div container *The full-size image is hidden with opacity: 0; *When the div container is hovered, the full-size image is given opacity: 1 and will fade-in thanks to the transition *z-index: 1 keeps the full-size images above the thumbnails Full Example .item { float: left; position: relative; } img { display: block; cursor: pointer; margin: 5px; } .fullsize { position: absolute; opacity: 0; transition: opacity 0.6s; z-index: 1; top: 0; left: 0; pointer-events: none; } .item:hover .fullsize { opacity: 1; } <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div> <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div> <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div> <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div> <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div> <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/27218498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Apply type projection to a refined type Consider the following example: trait T3 trait T2{ type TT4 type TT3 <: T3 } trait T1{ type TT2 <: T2 } now I want to write a function the roughly speaking looks as def test[T <: T1](t: T#TT2{type TT4 = Int}#TT3) = println(t) //invalid syntax which unfortunately is not a valid syntax. It is perfectly possible to write a function like this def test[T <: T1](t: T#TT2#TT3) = println(t) But I'd like to add a bit stricter restriction on T#TT2 making it to be a refined type T#TT2{ type TT4 = Int}. Is there any workaround? A: Try wrapping type T#TT2 { type TT4 = Int } in parenthesis before the final projection like so def test[T <: T1](t: (T#TT2 { type TT4 = Int })#TT3) = ??? Types can always be wrapped in parentheses SimpleType ::= SimpleType TypeArgs | SimpleType ‘#’ id | StableId | Path ‘.’ ‘type’ | Literal | ‘(’ Types ‘)’ <======= note the parentheses for example scala> val xs: (List[(Int)]) = List(42) val xs: List[Int] = List(42)
{ "language": "en", "url": "https://stackoverflow.com/questions/66851577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add a folder Jetty will run a site from? I have Jetty running on an Oracle VBox VM (Win7) Guest. I need Jetty to run a site from a shared folder, so I can edit it on the host. How can I do that? Edit: The site is HTML/JS, not a war file. I see from the docs I can copy a war to $JETTY_HOME. What I'm wondering is if I can add a path to $JETTY_HOME for Jetty to look in? The path is \\VBOXSVR\MyCoolSite
{ "language": "en", "url": "https://stackoverflow.com/questions/44927903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VBA for altering PowerPoint 2003 Presentations- Active not new If I set up a template on PowerPoint slides, that contain all the text boxes I need, the what Visual Basic do I use to enter text that I want into those text boxes? It is easier for me to use a template, because these ppt briefs contain (or need to contain) a lot of data: * *how do I enter text into those text boxes *how do you alter the font, size, fontbold, etc of a particular text box? *is there a way for determining the "name" of a text box/shape ("text box 52") other than recording macros after macros and selecting the text box, just to get the object name from selection? *if I use a macro to determine the vba, why will it not work to use that as vba? the vb I get from a macro seems to have active.selection which just doesn't seem to work as a vba procedure because it doesn't know what to select???? i think what i am looking to do is create the end game ppt from access, using the template. on an access form I want to have multiple text boxes that relay the information into the ppt text boxes on the slide. i know how to launch a template (or new presentation) from access, and how to add new items (slides, graphs, charts, text) but I do not know how to alter pre-existing text boxes!! Please help....my work is needing this like yesterday! Thanks as always! A: You can access shapes by name, as in: Dim oSlide As Slide Set oSlide = ActivePresentation.Slides(1) Dim oShape As Shape Set oShape = oSlide.Shapes(strShapeName) Dim oTextRange As TextRange Set oTextRange = oShape.TextFrame.TextRange oTextRange.Text = "this is some text" oTextRange.Font.Bold = msoTrue Note that whatever you're looking to do, just record a macro of you doing it via the UI, and copy that. You're right that the recorded macro will use the Selection object a lot, but that's easily fixed - just get a reference to the appropriate Shape object (or whatever) and then subsitute that in the generated code. So, for example, if the recorded macro for changing the fill color of a shape is this: With ActiveWindow.Selection.ShapeRange .Fill.Visible = msoTrue .Fill.Solid .Fill.ForeColor.RGB = RGB(255, 0, 0) .Fill.Transparency = 0# End With ... and you want to apply the fill color to a shape which you already have a reference to as oShape, then change the code to this: With oShape .Fill.Visible = msoTrue .Fill.Solid .Fill.ForeColor.RGB = RGB(255, 0, 0) .Fill.Transparency = 0# End With To get the current name of a shape, you can enter this in the "immediate" window in the VBA editor: ?ActiveWindow.Selection.ShapeRange(1).Name You could turn that into a (single) macro very easily: Sub ShowMeTheName() MsgBox ActiveWindow.Selection.ShapeRange(1).Name End Sub Note that I would personally rename the shapes to something meaningful rather than using the default names. Simply turn do this in the immediate window: ActiveWindow.Selection.ShapeRange(1).Name = "MyName" ...or create a macro to prompt for a name. A: When I need to automate Word or Excel (nobody I know or work with has any use for PowerPoint), I open the app in question, turn on Macro recording and do the task I want to automate. Then I use the generated code as the basis for my Access code. It's often a pretty straightforward process, sometimes as simple as copying and pasting and then prefacing each line with the application object I'm using from Access. If I had to do what you're doing, that's exactly how I'd start, by doing recording the task being performed interactively, and then experimenting with what part of the code is essential.
{ "language": "en", "url": "https://stackoverflow.com/questions/1197239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to compound a series of consequential subscriptions in RxJS I have approach according to the below. this.service1.info .subscribe(a => this.service2.getDetails(a.id) .subscribe(b => { this.doStuff(b); }) ); Recently, I noticed that we're going to have quite a few steps that gradually push more details to the client, so I'm anticipating the following atrocious pattern emerge. this.service1.info .subscribe(a => this.service2.getDetails(a.id) ... .subscribe(z => { this.doStuff (z); }) ); Is there a nice trick in RxJS to handle such situations? I only need to perform an operation once all the steps in the consequential chain have been emitted/received. I've browsed through the docs but didn't find something that felt quite right. I suspect that it's there, just that my ignorance confuses me so I'm missing it. A: Yes, you are right. It is indeed an anti-pattern within RxJS to chain multiple subscribes. A more elegant way of chaining these observable calls would be to make use of pipeable operators. In this scenario, the switchMap() operator would suffice. As stated on the documentation, switchMap() will Map to observable, complete previous inner observable, emit values. this.service1.info .pipe( switchMap((a) => this.service2.getDetails(a.id)), switchMap((a) => this.service3.getDetails(a.id)), // switchMap((a) => this.service4.getDetails(a.id)), // subsequent chained methods ).subscribe(z => { // handle the rest when observables are returned this.doStuff(z); }); As you can see from the above pipe statement, we only call subscribe() once, and that will return the observable values. That is when we call the doStuff method.
{ "language": "en", "url": "https://stackoverflow.com/questions/59446712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TransactionScope not rolling back although no complete() is called I'm using TransactionScope to rollback a transaction that fail bool errorReported = false; Action<ImportErrorLog> newErrorCallback = e => { errorReported = true; errorCallback(e); }; using (var transaction = new TransactionScope()) { foreach (ImportTaskDefinition task in taskDefinition) { loader.Load(streamFile, newErrorCallback, task.DestinationTable, ProcessingTaskId); } if (!errorReported) transaction.Complete(); } I'm sure there is no TransactionScope started ahead or after this code. I'm using entity framework to insert in my DB. Regardless the state of errorReported the transaction is never rolled back in case of error. What am I missing ? A: TransactionScope sets Transaction.Current. That's all it does. Anything that wants to be transacted must look at that property. I believe EF does so each time the connection is opened for any reason. Probably, your connection is already open when the scope is installed. Open the connection inside of the scope or enlist manually. EF has another nasty "design decision": By default it opens a new connection for each query. That causes distributed transactions in a non-deterministic way. Be sure to avoid that.
{ "language": "en", "url": "https://stackoverflow.com/questions/30914358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: multiple pages are overlapping in ngx-extended-pdf-viewer I am using ngx-extended-pdf-viewer for my angular app and looks like multiple pdf pages are overlapping during viewing. here is my viewer code <ngx-extended-pdf-viewer *ngIf="isVisible" [src]="pdfData" useBrowserLocale="true" [textLayer]="true" [showPrintButton]="true" [showDownloadButton]="true" [showOpenFileButton]="false" [showBookmarkButton]="false" [showPresentationModeButton]="false" height='90%' [zoom]="'100%'"> </ngx-extended-pdf-viewer> I tried setting stylesheets for page and viewer classes but no luck. A: Sounds like you've got CSS rules interfering with the CSS rule of ngx-extended-pdf-viewer. Create a greenfield project to check if it's a general problem: * *Open a terminal and navigate to the root folder of your project. *Run this command and accept the defaults: ng add ngx-extended-pdf-viewer *Add the new component <app-example-pdf-viewer> to your <app-component> to display the PDF file. Now you've got a working project that almost certainly does not suffer from your bug. Use the developer tools of your browser to compare the CSS code of the two projects to hunt down the bug.
{ "language": "en", "url": "https://stackoverflow.com/questions/71027596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: no sound in a push notification on Android(Ionic capacitor) I have a problem when i implemented a plugin PushNotification in capacitor, the problem is that when te phone receive a push notification don´t make any sound. This is my code. PushNotifications.addListener('pushNotificationReceived', (notification: PushNotification) => { console.log('Push received: ',JSON.stringify(notification)); } this is the settings in capacitor.config.json "PushNotifications": { "presentationOptions": ["badge", "sound", "alert"] } thanks for your help. A: show me the created the Notification channel Details. Then don't test in Redmi or mi Phones. addListenersForNotifications = async () => { await PushNotifications.addListener('registration', 'registration Name'); await PushNotifications.addListener('registrationError', 'error'); await PushNotifications.createChannel({ id: 'fcm_default_channel', name: 'app name', description: 'Show the notification if the app is open on your device', importance: 5, visibility: 1, lights: true, vibration: true, }); await PushNotifications.addListener('pushNotificationReceived', this.pushNotificationReceived); await PushNotifications.addListener('pushNotificationActionPerformed', this.pushNotificationActionPerformed); };
{ "language": "en", "url": "https://stackoverflow.com/questions/61990880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Pandas Regression Model Replacing Column Values I have a data frame "df" with columns "bedrooms", "bathrooms", "sqft_living", and "sqft_lot". I want to create a regression model by filling the missing column values based on the values of the other columns. The missing value would be determined by observing the other columns and making a prediction based on the other column values. As an example, the sqft_living column is missing in row 12. To determine this, the count for the bedrooms, bathrooms, and sqft_lot would be considered to make a prediction on the missing value. Is there any way to do this? Any help is appreciated. Thanks! A: import pandas as pd from sklearn.linear_model import LinearRegression # setup dictionary = {'bedrooms': [3,3,2,4,3,4,3,3,3,3,3,2,3,3], 'bathrooms': [1,2.25,1,3,2,4.5,2.25,1.5,1,2.5,2.5,1,1,1.75], 'sqft_living': [1180, 2570,770,1960,1680,5420,1715,1060,1780,1890,'',1160,'',1370], 'sqft_lot': [5650,7242,10000,5000,8080,101930,6819,9711,7470,6560,9796,6000,19901,9680]} df = pd.DataFrame(dictionary) # setup x and y for training # drop data with empty row clean_df = df[df['sqft_living'] != ''] # separate variables into my x and y x = clean_df.iloc[:, [0,1,3]].values y = clean_df['sqft_living'].values # fit my model lm = LinearRegression() lm.fit(x, y) # get the rows I am trying to do my prediction on predict_x = df[df['sqft_living'] == ''].iloc[:, [0,1,3]].values # perform my prediction lm.predict(predict_x) # I get values 1964.983 for row 10, and 1567.068 row row 12 It should be noted that you're asking about imputation. I suggest reading and understanding other methods, trade offs, and when to do it. Edit: Putting Code back into DataFrame: # Get index of missing data missing_index = df[df['sqft_living'] == ''].index # Replace df.loc[missing_index, 'sqft_living'] = lm.predict(predict_x)
{ "language": "en", "url": "https://stackoverflow.com/questions/71878382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace all characters in a regex match with the same character in Vim I have a regex to replace a certain pattern with a certain string, where the string is built dynamically by repeating a certain character as many times as there are characters in the match. For example, say I have the following substitution command: %s/hello/-----/g However, I would like to do something like this instead: %s/hello/-{5}/g where the non-existing notation -{5} would stand for the dash character repeated five times. Is there a way to do this? Ultimately, I'd like to achieve something like this: %s/(hello)*/-{\=strlen(\0)}/g which would replace any instance of a string of only hellos with the string consisting of the dash character repeated the number of times equal to the length of the matched string. A: As an alternative to using the :substitute command (the usage of which is already covered in @Peter’s answer), I can suggest automating the editing commands for performing the replacement by means of a self-referring macro. A straightforward way of overwriting occurrences of the search pattern with a certain character by hand would the following sequence of Normal-mode commands. * *Search for the start of the next occurrence. /\(hello\)\+ *Select matching text till the end. v//e *Replace selected text. r- *Repeat from step 1. Thus, to automate this routine, one can run the command :let[@/,@s]=['\(hello\)\+',"//\rv//e\rr-@s"] and execute the contents of that s register starting from the beginning of the buffer (or anther appropriate location) by gg@s A: %s/\v(hello)*/\=repeat('-',strlen(submatch(0)))/g
{ "language": "en", "url": "https://stackoverflow.com/questions/7338794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Create menu in main layout like in action bar I want to know is it possible to create menu like this? A: Most likely, your screenshot is of an ExpandableListView, or possibly a RecyclerView that uses a library to add expandable contents. A: Yes, and it's called Expandable List View.
{ "language": "en", "url": "https://stackoverflow.com/questions/45058261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }