text
stringlengths
15
59.8k
meta
dict
Q: Style for naming a function that is setting an argument by reference? So pretend I'm developing a car class and I want one of the car class's functions to return a list of passengers, except I'd like to put a list reference as an argument and just set that list instead of returning a list. void GetPassengerList(PassengerList &passengerList); //sets the list I don't know if I should call it GetPassengerList or SetPassengerList, or something else. I feel like using the words get / set make it seem like there is a private variable that is being manipulated like the typical getter / setter methods. What's a good naming convention to use here? A: In our team for input/output arguments we either use void AdjustPassengerList(PassengerList&); or void AddPassengersTo(PassengerList&); Depending on the use-case. For example the first one could be used if you want a list created from more than one car. The second usually reads well in code, something like: car.AddPassengersTo(list);
{ "language": "en", "url": "https://stackoverflow.com/questions/32414149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Julia - How to get the minimum of each row of matrix? I tried to make that code but it get the value of the last index in the row function heuristicCalculate(distanceBetweenCities,numOfCities) #distanceBetweenCities is a 29*29 array #Use this function to calculate the tour length using nearest neighbor heuristic Lnn mindist=zeros(29,1) for i=1:29 for j=1:29 mindist[i,1]=Base.minimum(distanceBetweenCities[i,j]) end end mindist return Lnn, tau0 #Lnn tour length using nearest neighbor heuristic #tau0 a value representing the initial phermone amount =1/(n*Lnn) end A: The simplest solution would probably be mindist = minimum(distanceBetweenCities,2) where the ,2 denotes the dimension over which the minimum is searched.
{ "language": "en", "url": "https://stackoverflow.com/questions/30005131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: import error in django-sendsms I'm trying to use django-sendsms based on this documentation I downloaded the package,copied it's folder in c: and ran this command in shell c: cd django-sendsms python setup.py install these commands installed django-sms in sitepackages folder.then based on the documentation I added this backend to settings.py: SENDSMS_BACKEND = 'sendsms.backends.console.SmsBackend' and in views.py : from sendsms import api api.send_sms(body='I can haz txt', from_phone='+41791111111', to=['+41791234567']) but I get this error: No module named importlib every thing is based on the documentation,I don't know what's wrong with it! A: Which version of Python are you using? It seems that module (in sendsms/util.py) will import the library called importlib which only exists in Python 2.7. If you are using Python 2.6 or lower, that library do not exist.
{ "language": "en", "url": "https://stackoverflow.com/questions/11673689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: heroku cannot connect to MySQL server I am using flask-sqlalchemy to connect to mysql app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:''@127.0.0.1/pharmbase' While this works fine locally, heroku cannot connect to MySQL server when deployed. Below is a trackback message 2021-01-19T15:36:19.137152+00:00 app[web.1]: sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 111] Connection refused)") Please any solution on how to solve this A: 127.0.0.1 as an IP address means "this machine". More formally, it's the loopback interface. On your laptop you have a MySQL server running. Your heroku dyno does not, so your connection attempt fails. You won't be able to connect from your program running on your heroku dyno to your laptop's MySQL server without some network configuration work on your office or home router / firewall. But to begin doing that work you'll need to come up to speed on networking. (Teaching you how is beyond the scope of a Stack Overflow answer.) You can add a MySQL add-on to your Heroku app from a third party. Heroku themselves offer a postgreSQL add-on with a free tier, but not MySql. For US$10 per month you can subscribe to one of these MySQL add-ons and you'll be up and running.
{ "language": "en", "url": "https://stackoverflow.com/questions/65794943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Right Click event not firing in VSTO code for PowerPoint 2010 I'm attempting to add a Context Menu option to PowerPoint 2010 that only appears when text is selected. Unfortunately the WindowBeforeRightClick event does not seem to fire if the mouse is inside of a TextBox. Is there a different event I need to be listening to or a better way to add that context menu?
{ "language": "en", "url": "https://stackoverflow.com/questions/5481808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can you group data by multiple fields with separate totals in SQL or Power query I have a set of data that I want to count by multiple characteristics. I am starting with something likes this (True/False for catagories) week PP SEN 1 T F 1 T T 1 F F 2 T F 2 T T 2 F F 2 F F 3 T F 3 F F I want to end up with something along the lines of week PP SEN Total 1 2 1 3 2 2 1 4 3 1 0 2 As far as I can see I can only get something that would give me nested results eg week PP SEN Total 1 T T 1 1 T F 1 1 F T 0 1 F F 1 It may be that this is really straight forward and I just have not found the correct search term, or it's just impossible via a query...but all suggestions welcome. A: I think you just want conditional aggregation: select week, count(*) as total, sum(case when pp = 'T' then 1 else 0 end) as num_pp, sum(case when sen = 'T' then 1 else 0 end) as num_sen from t group by week; A: In powerquery, something like this let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], #"Added Custom" = Table.AddColumn(Source, "Total", each "1"), #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Added Custom", {"week"}, "Attribute", "Value"), #"Changed Type1" = Table.TransformColumnTypes(#"Unpivoted Other Columns",{{"Value", type text}}), #"Replaced Value" = Table.ReplaceValue(#"Changed Type1","T","1",Replacer.ReplaceText,{"Value"}), #"Replaced Value1" = Table.ReplaceValue(#"Replaced Value","F","0",Replacer.ReplaceText,{"Value"}), #"Changed Type" = Table.TransformColumnTypes(#"Replaced Value1",{{"Value", type number}}), #"Pivoted Column" = Table.Pivot(#"Changed Type", List.Distinct(#"Changed Type"[Attribute]), "Attribute", "Value", List.Sum) in #"Pivoted Column"
{ "language": "en", "url": "https://stackoverflow.com/questions/67949273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Dailymotion API request returning blank result I am using the following code to retrieve video ID, title, thumbnail, duration and tags. $dailymotion = "https://api.dailymotion.com/video/xreczc?fields=title,duration,thumbnail_url,id,tags"; $curl = curl_init($dailymotion); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $return = curl_exec($curl); curl_close($curl); $results = json_decode($return, true); print_r($results); However it returns empty/blank page. I am using this on my localhost what could be wrong? I can call https://api.dailymotion.com/video/xreczc?fields=title,duration,thumbnail_url,id,tags directly in the browser and it works. Any help, or ideas? A: Please try with this one. $dailymotion = file_get_contents("https://api.dailymotion.com/video/xreczc?fields=title,duration,thumbnail_url,id,tags"); $results = json_decode($dailymotion, true); print_r($results); A: You are trying to fetch a https link via curl which has known issues. See the following links to see if they help your issue. Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do? http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/ Regards, A: This code seems to fix it. $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.dailymotion.com/video/".$id."?fields=id,title,thumbnail_url,tags,duration,embed_url"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 20); $results = curl_exec($ch); curl_close($ch); $results = json_decode($results); if (!$results || $results->error->code) { return false; } else { return $results; }
{ "language": "en", "url": "https://stackoverflow.com/questions/10949927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: echo anchor tag with query string php and output $date in a calendar This is my first time asking a question, so please take that into consideration if I have done this wrong. Please look this over and explain where I am going wrong. I can display the ending dates of the previous month in the first week of the current month for a calendar row. But I need to include a query string in the anchor tag that is being echo'd with the current $print_date. These are the different ways I have already attempted without success. The date is formatted 'YYYY-M-D' while ( $start_point > 0 ) { // Returns what day of the week 'w' (numeric 0-6), using the date function. $day_of_week = date('w', mktime(0, 0, 0, $month, 1, $year)); // To get the last Sunday of the previous month use: $sun_prev_month = date('d', mktime(0, 0, 0, $month, (1 - $day_of_week), $year)); // Fills the dates, starting on Sunday for the end of previous month $print_date = $sun_prev_month; for ($i = 0; $i < $day_of_week; ++$i) { //echo '<td class="shade"><a href="/~seeleyja/CSCI-2910/calendar4.php?date=' . $year . '-' . ($month-1) . '-' . $print_date . '">'. $print_date . '</a></td>'; ?> <td><a href="/~seeleyja/CSCI-2910/calendar4.php?<?=htmlspecialchars($prev_month);?>"> $print_date </a></td>; <?php //echo '<td class="shade"><a href="/~seeleyja/CSCI-2910/calendar4.php?date=$prev_month">'. $print_date . '</a></td>'; //echo '<td class="shade"><a href="/~seeleyja/CSCI-2910/calendar4.php?date=' . $year . '-' . ($month-1) . '-' . $print_date . '">'. $print_date . '</a></td>'; --$start_point; $print_date++; $day_of_week_counter++; } } A: You are currently using an undefined variable $prev_month, and have forgotten the "date" parameter in the URL. Is it possible you meant to use $sun_prev_month or $print_date?
{ "language": "en", "url": "https://stackoverflow.com/questions/14819071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ranger syncing with unix users I have created two empty groups on two differentt nodes of my cluster, just one on each node. My ranger service uses unix user synchronization, when I restart the Ranger service I cant see my added groups to cluster nodes in Ranger UI, I use HDP 2.5. How to sync my ranegr with unix users? A: As you try to sync users, you already seem to understand that there are users for the os, and users for the hadoop platform. Typically OS users are admin/ops people who need to manage the environment, while most platform users are engineers, analysts, and other who want to do something on the platform. This large group of users is something you typically want to sync. As already indicated by @cricket you can integrate with LDAP/AD as explained here: https://community.hortonworks.com/articles/105620/configuring-ranger-usersync-with-adldap-for-a-comm.html
{ "language": "en", "url": "https://stackoverflow.com/questions/53217208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change site level configuration in Apache Tomcat I have build a rest service in Java. For that there is a configuration file that I have to place in /home/user1/ where user1 in the one where tomcat is running. If I change the path and move it to the /home/user1/workspace/myRest/ (it is eclipse workspace where I build project) then tomcat gave exception that file not found. How do I inform tomcat that where you should look for the configuration file ? This file is being accessed by a jar in my project. A: you can define a system varible when starting tomcat. and access it from your library. for example inside your catalina.bat(on windows)/setenv.sh(linux) windows set JAVA_OPTS=%JAVA_OPTS% -Dconfig.path=%CATALINA_HOME%/{path to conf file} linux JAVA_OPTS="$JAVA_OPTS -Dconfig.path=$CATALINA_HOME/{path to conf file}" then access it from your code System.getProperty("config.path")
{ "language": "en", "url": "https://stackoverflow.com/questions/51208779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to stop firebase logout on back button? Before you remove my question from stackoverflow, please hear me out. I know that problem is very common but none that i tried helped me. i already saw available solutions on stackoverflow and other websites but they didn't resolved my issue. So even if you choose to remove my question from this forum please help me resolve my question first, atleast mail me. button1.setOnClickListener(view -> { login(); }); } public void login() { Intent intent = new Intent(this, IndexActivity.class); String mail = et1.getText().toString(); String password = et2.getText().toString(); if (mail.isEmpty()) { error.setText(e1); } else if (password.isEmpty()) { error.setText(e2); } else if (password.length() < 6) { error.setText("Invalid Password Length!!"); et2.setError("Password length must be at least 6!!"); } else { mAuth.signInWithEmailAndPassword(mail, password).addOnCompleteListener(task -> { if (task.isSuccessful()) { Toast.makeText(MainActivity.this, "Welcome Back",Toast.LENGTH_LONG).show(); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); error.setText(""); et1.setText(""); et2.setText(""); } else { Toast.makeText(MainActivity.this, " "+ Objects.requireNonNull(task.getException()).getMessage(),Toast.LENGTH_LONG).show(); error.setText(e3); } }); } if (error.getText().toString().isEmpty()) { error.setVisibility(View.INVISIBLE); } else { error.setVisibility(View.VISIBLE); } } } This above is my login page and below is my child activity logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mAuth.getCurrentUser() != null) { Intent intent = new Intent(getApplicationContext(), MainActivity.class); mAuth.signOut(); startActivity(intent); finish(); } else { Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } } }); i have tried everything on internet. sharedPreferences, onBackPressed override, onSaveInstanceState, onRestoreInstanceState, onStart and onResume override, but i don't know what exactly to use. A: check if user is already logged in or not by if (auth.getCurrentUser() != null) //user logged in already, do your work here for logged in user else //user is not logged in, let user login A: The back button most likely does not log the user out, but rather the UI elements have not updated with the user information. If you suspect the user is being logged out, this would be an Auth refresh, which will trigger an onAuthStateChanged() event if you have one registered. Otherwise, checking the current auth for the current user with auth().currentUser should yield null or a user object Get current user FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { // User is signed in } else { // No user is signed in } Auth State Listener mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in } else { // User is signed out } Log.d("LOG_Login", "onAuthStateChanged:signed_out"); } } }; mAuth.addAuthStateListener(mAuthListener);
{ "language": "en", "url": "https://stackoverflow.com/questions/68873786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What happens when we enable defender for key vault? We expect to enable Azure Defender for Key vault for approximately 200 key Vaults. I would like to know, Will there be any repercussions if I turn on Defender for Key Vault? Will this stop applications from reaching the vault? Has anyone ever experienced an incident or service disruption as a result of allowing the Defender for the key vault? In the past, we have experienced an incident after activating the same for the SQL server. A: Enabling Microsoft Defender for Key Vault does not require any agent or extension and is an Azure-native threat protection service, which detects unusual and potentially harmful access to Key Vault accounts. It provides an additional layer of security intelligence for the keys, secrets and certificates stored in the Microsoft Key Vault by alerting you to suspicious or malicious access. This layer of security allows you to address threats without being a security expert, and without the need to manage third-party security monitoring systems. We’re not aware of any repercussions or similar you can find more information here : https://learn.microsoft.com/en-us/azure/defender-for-cloud/defender-for-key-vault-introduction
{ "language": "en", "url": "https://stackoverflow.com/questions/73265885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to check if radiobutton is selected (javascript, html) I am trying to check if a radio button is selected or not. If the "morn_before" radiobutton is selected, the data will be stored as "2", but if the "morn_after" radiobutton is selected instead, the data will be stored as "1". Currently my code show below is not working. For example when i select the "morn_before" radiobutton, it doesnt print "morn_before checked true" in the console, despite me putting console.log("morn_before checked true") in that if statement. HTML: <div class="radiobutton"> <input type="radio" id="morn_before" name="morn_time" value="morn_before"> <label for="morn_before">Before Food</label><br> <input type="radio" id="morn_after" name="morn_time" value="morn_after"> <label for="morn_after">After Food</label><br><br> </div> Javascript: function check() { let user=firebase. auth().currentUser; let uid; if(user!=null){ uid=user.uid; } var firebaseRef = firebase.database().ref(); if(document.getElementById("morn_before").checked){ console.log("morn_before checked true"); firebase.database().ref(uid).child('/radiobutton/').child('/morn_time/').set("2"); } else if(document.getElementById("morn_after").checked){ firebase.database().ref(uid).child('/radiobutton/').child('/morn_time/').set("1"); } } check(); A: You don't need any JavaScript for this. You can have a completely different display than the stored value. <div class="radiobutton"> <input type="radio" id="morn_before" name="morn_time" value="2"> <label for="morn_before">Before Food</label><br> <input type="radio" id="morn_after" name="morn_time" value="1"> <label for="morn_after">After Food</label><br><br> </div> Should produce the same result. The only improvement would be to set one of these to default true, in case the user chose neither. But that'd be up to you. ADDITIONAL INFO: You are not supposed to read a radio button group that way. You should go over some basics of HTML INPUT tag such as https://www.geeksforgeeks.org/how-to-get-value-of-selected-radio-button-using-javascript/
{ "language": "en", "url": "https://stackoverflow.com/questions/61848009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIWebView - creating custom context menu? I added UIWebView control to my application. To disable default context menu, I implemented webViewDidFinishLoad. - (void) webViewDidFinishLoad:(UIWebView *)theWebView { NSString *varMySheet = @"var mySheet = document.styleSheet[0];"; NSString *addCSSRule = @"function addCSSRule(selector, newRule) {" "if (mySheet.addRule) {" "mySheet.addRule(selector, newRule);" "} else {" "ruleIndex = mySheet.cssRules.length;" "mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex;" "}" "}"; ... NSString *insertRule = @"addCSSRule('body', '-webkit-touch-callout: none;')"; [webView stringByEvaluatingJavaScriptFromString:varMySheet]; [webView stringByEvaluatingJavaScriptFromString:addCSSRule]; [webView stringByEvaluatingJavaScriptFromString:insertRule]; ... } But context menu of webview doesn't disappear. Anyone help me. I also tried [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.webkitTouchCallout='none';"]; It didn't work. Thanks. A: Could you explain why you are trying to do with all this javascript ? Just doing the following is not enough for you ? - (void) webViewDidFinishLoad:(UIWebView *) sender { // Disable the defaut actionSheet when doing a long press [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.webkitTouchCallout='none';"]; [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"]; } A: You just need to subclass the UIWebView. In your custom view, just implement the method canPerformAction:withSender like this: - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { return NO; } then all menu items will disappear. If you just wanna show some of items, you should return YES for the specified item. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { BOOL ret = NO; if (action == @selector(copy:)) ret = YES; return ret; } That gives you only "copy" when you long press a word in the view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7346565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to groupby pandas dataframe on some condition I have a pandas dataframe like following buyer_id item_id order_id date 139 57 387 2015-12-28 140 9 388 2015-12-28 140 57 389 2015-12-28 36 9 390 2015-12-28 64 49 404 2015-12-29 146 49 405 2015-12-29 81 49 406 2015-12-29 140 80 407 2015-12-30 139 81 408 2015-12-30 There are lot of rows in above dataframe. What I am trying to achieve is, whether introducing new dishes driving my users to come back. item_id is mapped to a dish name. What I want to see is if a specific user is ordering different dish on different day. e.g buyer_id 140 has ordered two dishes item_id (9,57) on 28th Dec and same buyer has ordered different dish (item_id = 80) on 30th Dec Then I want to flag this user as 1 How I am doing it in python is like this item_wise_order.groupby(['date','buyer_id'])['item_id'].apply(lambda x: x.tolist()) it gives me following output date buyer_id 2015-12-28 139 [57] 140 [9,57] 36 [9] 2015-12-29 64 [49] 146 [49] 81 [49] 2015-12-30 140 [80] 139 [81] Desired output buyer_id item_id order_id date flag 139 57 387 2015-12-28 1 140 9 388 2015-12-28 1 140 57 389 2015-12-28 1 36 9 390 2015-12-28 0 64 49 404 2015-12-29 0 146 49 405 2015-12-29 0 81 49 406 2015-12-29 0 140 80 407 2015-12-30 1 139 81 408 2015-12-30 1 A: Similar to Anton's answer, but using apply users = df.groupby('buyer_id').apply(lambda r: r['item_id'].unique().shape[0] > 1 and r['date'].unique().shape[0] > 1 )*1 df.set_index('buyer_id', inplace=True) df['good_user'] = users result: item_id order_id date good_user buyer_id 139 57 387 2015-12-28 1 140 9 388 2015-12-28 1 140 57 389 2015-12-28 1 36 9 390 2015-12-28 0 64 49 404 2015-12-29 0 146 49 405 2015-12-29 0 81 49 406 2015-12-29 0 140 80 407 2015-12-30 1 139 81 408 2015-12-30 1 EDIT because I thought of another case: suppose the data shows a buyer buys the same two (or more) goods on two different days. Should this user be flagged as 1 or 0? Because effectively, he/she does not actually choose anything different on the second date. So take buyer 81 in the following table. You see they only buy 49 and 50 on both dates. buyer_id item_id order_id date 139 57 387 2015-12-28 140 9 388 2015-12-28 140 57 389 2015-12-28 36 9 390 2015-12-28 64 49 404 2015-12-29 146 49 405 2015-12-29 81 49 406 2015-12-29 140 80 407 2015-12-30 139 81 408 2015-12-30 81 50 406 2015-12-29 81 49 999 2015-12-30 81 50 999 2015-12-30 To accomodate this, here's what I came up with (kinda ugly but should work) # this function is applied to all buyers def find_good_buyers(buyer): # which dates the buyer has made a purchase buyer_dates = buyer.groupby('date') # a string representing the unique items purchased at each date items_on_date = buyer_dates.agg({'item_id': lambda x: '-'.join(x.unique())}) # if there is more than 1 combination of item_id, then it means that # the buyer has purchased different things in different dates # so this buyer must be flagged to 1 good_buyer = (len(items_on_date.groupby('item_id').groups) > 1) * 1 return good_buyer df['item_id'] = df['item_id'].astype('S') buyers = df.groupby('buyer_id') good_buyer = buyers.apply(find_good_buyers) df.set_index('buyer_id', inplace=True) df['good_buyer'] = good_buyer df.reset_index(inplace=True) This works on buyer 81 setting it to 0 because once you group by date, both dates at which a purchase was made will have the same "49-50" combination of items purchased, hence the number of combinations = 1 and the buyer will be flagged 0. A: You could groupby by buyer_id, then aggregate column with np.unique. Then you'll get np.ndarrays for rows where you have several dates and item_ids. You could find that rows with isinstance of np.ndarray and you'll get bool series which you could pass to aggregated dataframe and find interested buyer. By filtering original dataframe with obtained buyers you could fill rows for flag with loc: df_agg = df.groupby('buyer_id')[['date', 'item_id']].agg(np.unique) df_agg = df_agg.applymap(lambda x: isinstance(x, np.ndarray)) buyers = df_agg[(df_agg['date']) & (df_agg['item_id'])].index mask = df['buyer_id'].isin(buyers) df['flag'] = 0 df.loc[mask, 'flag'] = 1 In [124]: df Out[124]: buyer_id item_id order_id date flag 0 139 57 387 2015-12-28 1 1 140 9 388 2015-12-28 1 2 140 57 389 2015-12-28 1 3 36 9 390 2015-12-28 0 4 64 49 404 2015-12-29 0 5 146 49 405 2015-12-29 0 6 81 49 406 2015-12-29 0 7 140 80 407 2015-12-30 1 8 139 81 408 2015-12-30 1 Output from first and second steps: In [146]: df.groupby('buyer_id')[['date', 'item_id']].agg(np.unique) Out[146]: date item_id buyer_id 36 2015-12-28 9 64 2015-12-29 49 81 2015-12-29 49 139 [2015-12-28, 2015-12-30] [57, 81] 140 [2015-12-28, 2015-12-30] [9, 57, 80] 146 2015-12-29 49 In [148]: df_agg.applymap(lambda x: isinstance(x, np.ndarray)) Out[148]: date item_id buyer_id 36 False False 64 False False 81 False False 139 True True 140 True True 146 False False
{ "language": "en", "url": "https://stackoverflow.com/questions/35526501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AppleScript: Delimiters not working, and tab separated URLS I'm trying to obtain a list of Financial Times URL's for today's newspaper. I've done this by getting the source code from FT.com, then by used delimiters to parse the html source code, and now I'm trying to save each url as comma-separated value file (.txt extension). I've been able to get as far as parsing the html source code. But my problem lies with saving the urls as a csv file (or a list of urls, separated by paragraphs). here is my applescript: on run set query_url to "http://www.ft.com/uk-edition" set query_url_source to do shell script "/usr/bin/curl " & quoted form of query_url set p to query_url_source set ex to extractBetweenLong(p, "><a href=\"/cms/s", ".html") return ex end run --delimiters subroutine: to extractBetweenLong(SearchText, startText, endText) set tid to AppleScript's text item delimiters -- save them for later. set AppleScript's text item delimiters to startText -- find the first one. set liste to text items of SearchText set AppleScript's text item delimiters to endText -- find the end one. set extracts to {} repeat with subText in liste if subText contains endText then copy text item 1 of subText to end of extracts end if end repeat set AppleScript's text item delimiters to tid -- back to original values. return extracts end extractBetweenLong My output is as follows: {"^!DOCTYPE html ... subs5", "/0/0130d092-c473-11e1-9c1e-00144feabdc0", "/0/cb8a70a0-c469-11e1-a98c-00144feabdc0", ..., "/0/02eaa328-c468-11e1-9c1e-00144feabdc0",} * *My first question is why does the first string (^!DOCTYPE html...) exist? There must be something wrong with my delimiter subroutine, since my first 'startText' delimiter should not include the the "DOCTYPE ... subs5" (the subs5 HTML tab ends with .html), so that might be an indication that my subroutine star *Second How can I save each URLs as a list, separated by commas or line-breaks? I first would like to put the string: "www.ft.com/cms/s" before each URL, but I believe I can figure that out myself. Thank you for you help in advance. A: AppleScript's text item delimiters define the substrings to use when breaking up strings into a list of text items, and the substring that is used when reassembling a list of text items back into a string. * *The text item delimiters just define where the string is broken up, not which pieces to keep or discard. In your script, you can throw away the first text item in your extraction handler with something like: set liste to rest of text items of SearchText *Getting the text items results in a list of strings (the text items). *Just as you use text item delimiters to break the strings apart, you can use them when putting the pieces back together, for example setting the text item delimiters to a comma or line-break before coercing the list back to text. The "www.ft.com/cms/s" part can also be put in there, although (like #1 above), you will also need to add it before the first item, for example: set tempTID to AppleScript's text item delimiters set AppleScript's text item delimiters to ("," & return & "www.ft.com/cms/s") set ex to ex as text set AppleScript's text item delimiters to tempTID return "www.ft.com/cms/s" & ex
{ "language": "en", "url": "https://stackoverflow.com/questions/11312079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Identify CD drive and eject using bat or vbs while in WinPE without external files I need to identify the CD drive and eject the tray. This is executed while booted in WinPE, so the WMP eject function is not available. This script will be used on various computer models/configurations. I'm currently using this: For Each d in CreateObject("Scripting.FileSystemObject").Drives CreateObject("Shell.Application").Namespace(17).ParseName("D:\").InvokeVerb("Eject") Next It works, but sometimes it errors and requires user interaction before it ejects. I suspect that it's because of the hardcoded D:\ drive letter, but I could be completely wrong. I need this to work without 3rd party utilities. A: Use the DriveType property of the Drive object: For Each d in CreateObject("Scripting.FileSystemObject").Drives WScript.sleep 60 If d.DriveType = 4 Then CreateObject("Shell.Application").Namespace(17).ParseName(d.DriveLetter & ":\").InvokeVerb("Eject") End If Next A: Here is code that uses Media Player to eject; I'm not sure how easy it would be to invoke from your WinPE environment: ' http://www.msfn.org/board/topic/45418-vbscript-for-openingclosing-cd/ ' http://waxy.org/2003/03/open_cdrom_driv/ Set oWMP = CreateObject("WMPlayer.OCX.7" ) Set colCDROMs = oWMP.cdromCollection For d = 0 to colCDROMs.Count - 1 colCDROMs.Item(d).Eject Next 'null Plan B would be to download a copy of "eject.exe", and include it on your WinPE media: * *http://www.911cd.net/forums/index.php?showtopic=2931&hl=cd+eject
{ "language": "en", "url": "https://stackoverflow.com/questions/14220273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Azure Portal - adding role groups is not working properly I'm trying to add a Developers group to the Reader role, for a Website, in the new Azure Portal and assign users to that group. When I add a specific user to the Reader role of a Website the user can see everything fine but when I remove that user and add them to the Developers group the Website doesn't show up for them in the portal. Is there a step I am missing? A: I just tried the same steps: * *Added a new group 'Developers' to Azure AD *Assigned user A to this group *Assigned this group to Readers role of a website *Logged in with user A to portal.azure.com User A can now see the website. So it works as expected. Update: when using a Microsoft Account (Microsoft Live Id), I have the same issue and that user is not able to see the website. Looks like a bug. A workaround would be to use an Azure AD user.
{ "language": "en", "url": "https://stackoverflow.com/questions/27725001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AWS Glue job to merge columns into a timestamp I'm very new to using AWS Glue and Spark. I'm trying to run an ETL job so my data which is currently parsed as three separate columns(year, month and day) and I need to merge these columns into a datetime(or timestamp) format. Glue generated a basic script that I'm trying to add this logic to but I'm having little success. Here is the relevant part of the code: timestampedDf = dropnullfields3.toDF() timestampedDf = timestampedDf.withColumn("snap_timestamp", datetime.date(year=int(timestampedDf['year']),day=int(timestampedDf['day']),month=int(timestampedDf['month'])) timestamped4 = DynamicFrame.fromDF(timestampedDf, glueContext, "timestamped4") And the logger gives me back the following error: Syntax Error: File "/tmp/g-8b0c4794d23f8afeb757fae2a20be7a4b9222fef-5379414877065320437/script_2019-03-20-14-12-14.py", line 40 timestamped4 = DynamicFrame.fromDF(timestampedDf, glueContext, "timestamped4") SyntaxError: invalid syntax And here is the complete code for reference. import sys from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job import datetime ## @params: [JOB_NAME] args = getResolvedOptions(sys.argv, ['JOB_NAME']) sc = SparkContext() glueContext = GlueContext(sc) spark = glueContext.spark_session job = Job(glueContext) job.init(args['JOB_NAME'], args) ## @type: DataSource ## @args: [database = "perseus-reporting-db", table_name = "charges_dev_perseus_reporting", transformation_ctx = "datasource0"] ## @return: datasource0 ## @inputs: [] datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "perseus-reporting-db", table_name = "charges_dev_perseus_reporting", transformation_ctx = "datasource0") ## @type: ApplyMapping ## @args: [mapping = [("amount", "double", "amount", "double"), ("customerid", "string", "customerid", "string"), ("status", "string", "status", "string"), ("createdat", "string", "createdat", "string"), ("year", "string", "year", "string"), ("month", "string", "month", "string"), ("day", "string", "day", "string")], transformation_ctx = "applymapping1"] ## @return: applymapping1 ## @inputs: [frame = datasource0] applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [("amount", "double", "amount", "double"), ("customerid", "string", "customerid", "string"), ("status", "string", "status", "string"), ("createdat", "string", "createdat", "string"), ("year", "string", "year", "string"), ("month", "string", "month", "string"), ("day", "string", "day", "string")], transformation_ctx = "applymapping1") ## @type: ResolveChoice ## @args: [choice = "make_cols", transformation_ctx = "resolvechoice2"] ## @return: resolvechoice2 ## @inputs: [frame = applymapping1] resolvechoice2 = ResolveChoice.apply(frame = applymapping1, choice = "make_cols", transformation_ctx = "resolvechoice2") ## @type: DropNullFields ## @args: [transformation_ctx = "dropnullfields3"] ## @return: dropnullfields3 ## @inputs: [frame = resolvechoice2] dropnullfields3 = DropNullFields.apply(frame = resolvechoice2, transformation_ctx = "dropnullfields3") timestampedDf = dropnullfields3.toDF() timestampedDf = timestampedDf.withColumn("snap_timestamp", datetime.date(year=int(timestampedDf['year']),day=int(timestampedDf['day']),month=int(timestampedDf['month'])) timestamped4 = DynamicFrame.fromDF(timestampedDf, glueContext, "timestamped4") ## @type: DataSink ## @args: [catalog_connection = "s3-rds-conn-perseus", connection_options = {"dbtable": "charges_dev_perseus_reporting", "database": "reporting-db"}, transformation_ctx = "datasink4"] ## @return: datasink4 ## @inputs: [frame = dropnullfields3] datasink4 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = timestamped4, catalog_connection = "s3-rds-conn-perseus", connection_options = {"dbtable": "charges_dev_perseus_reporting", "database": "reporting-db"}, transformation_ctx = "datasink4") job.commit() Thanks in advance! A: Try using to_date() with concat() Spark functions from pyspark.sql.functions import concat, to_date, col, lit timestampedDf = dropnullfields3.toDF() timestampedDf = timestampedDf.withColumn("snap_timestamp", to_date(concat(col('year'), lit('-'), col('month'), lit('-'), col('day')))) timestamped4 = DynamicFrame.fromDF(timestampedDf, glueContext, "timestamped4")
{ "language": "en", "url": "https://stackoverflow.com/questions/55263317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to limit the child process in perl? I have written a script which includes generation of gcov in parallel.I succeeded in that but it is creating 17 child process at a time.But i want to create only 6 child processes at a time,the 7th child should create after 1child process terminate. sub gcov_parallel() 2 { 3 print "Generating Gcov...\n"; 4 my $kid; 5 my $pid; 6 @list = (@iucall,@iurcall_init,@iurcall_term,@iurcall_uti,@nob,@nobcch,@nobcell,@nobrrc,@nobcall,@rnccall,@cellin fo,@rnccom,@cellrrm,@uerrm,@uerrc,@uecall,@iupcded); 7 my $len_list = scalar(@list); 8 my $maxlen =0; 9 my $count = 0; 10 my $process = 0; 11 $total_components = scalar(@comp_list); 12 13 for(my $comp_count=0; $comp_count < $len_list ; ($comp_count=$comp_count+$no_of_machines)) 14 { 15 #limiting child process to 6 16 if($process == 6) 17 { 18 $pid = wait(); 19 $process=$process-1; 20 } 21 else 22 { 23 $pid = fork(); 24 if($pid eq 0) 25 { 26 for(my $files_count = 0; $files_count < $no_of_machines; $files_count++) 27 { 28 $count = $files_count+$comp_count; 29 if($count < $len_list) 30 { 31 chomp($list[$count]); 32 my @list_gcda =`ls $list[$count]/*.gcda | sort`; &generate_gcov("$list[$count]",@list_gcda); 34 } 35 } 36 wait(); 37 exit; 38 } 39 $process=$process+1; 40 } 41 } 42 do 43 { 44 $kid = waitpid(-1, 0); 45 }while $kid > 0; 46 } But i observed while running the script it is skipping files while generating gcov. A: I think you could use Paralel::ForkManager to do this. There is a good tutorial on PerlMonks about Paralel::ForkManager. It could be this simple: my $manager = Parallel::ForkManager->new( 6 ); foreach my $command (@commands) { $manager->start and next; system( $command ); $manager->finish; };
{ "language": "en", "url": "https://stackoverflow.com/questions/16538708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can't use ng2-bootstrap-modal in Angular 4 I'm trying to use ng2-bootstrap-modal in Angular 4 and ASP NET 5(VS 2017). I've followed instructions provided there: In systemjs.config.js I've added: map: {.... 'ng2-bootstrap-modal': 'npm:ng2-bootstrap-modal', ... packages: { .... 'ng2-bootstrap-modal': {main: 'index.js', defaultExtension: 'js' } } But,after importing in app.module: ... import { BootstrapModalModule } from 'ng2-bootstrap-modal'; .... @NgModule({ declarations: [ AppComponent ], imports: [ .... BootstrapModalModule ], bootstrap: [AppComponent] }) export class AppModule {} my app doesn't start,in console I have: Error: (SystemJS) XHR error (403 Forbidden) loading http://localhost:3590/node_modules/ng2-bootstrap-modal thanks EDIT: I've found this plnkr example and I've updated my systemjs.config.js(see it above),now the erorr is Error: (SystemJS) XHR error (403 Forbidden) loading http://localhost:3590/node_modules/rxjs
{ "language": "en", "url": "https://stackoverflow.com/questions/45770256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting multiple LinkedIN members using API Is it possible to get basic profile data from a list of people, using one app, akin to the LinkedIN Member Profile Plugin? I want to get the basic profile information of about 40 people, for which the Profile Plugin is too slow, but I can only find how to get my own account information using the API. I've gotten no further than the following: https://api.linkedin.com/v1/people/~?format=json Which is the only reference to basic profile information. But I need that from other users, instead of myself. I have found no references to it's possibilities since the change in the API of may 2015. This is a follow up question to this one
{ "language": "en", "url": "https://stackoverflow.com/questions/45739621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Querying a 1 to many table where the many side has at least one row Have a common schema, with two tables. users table contains the columns id, name. checkins table contains the columns user_id, checkin_date. in this hypothetical, users can have many instances of rows in the checkins table. checkin_date in this case is of type date I want to be able to query for all users who have at minimum 1 checkin in the checkins table where the checkin is after 2016. A: I would suggest using exists: select u.* from users u where exists (select 1 from checks c where c.user_id = u.id and c.checkin_date >= '2016-01-01' );
{ "language": "en", "url": "https://stackoverflow.com/questions/35236198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to "properly" override a base class method? Whenever i override a method of a base class, other than my implementation of this method, i seem to have 3 choices. 1) Call base.Method(), and then provide my implementation. 2) Provide my implementation and then call base.Method() 3) Just provide my implementation. Recently while using a library i have realized few bugs that were introduced because of not implementing the method as expected by the library. I am not sure if that is bad on part of library, or something wrong in my understanding. I will take one example. public class ViewManager { public virtual void Customize(){ PrepareBaseView(); } } public class PostViewManager { public override void Customize(){ base.Customize(); PreparePostView(); } } public class PreViewManager { public override void Customize(){ PreparePreView(); base.Customize(); } } public class CustomViewManager { public override void Customize(){ PrepareCustomView(); } } My question here is that how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class? Is there a way in which parent class could enforce one of the three alternates to all the deriving classes? A: how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class? There is no way to "know" this when you are subclassing and overriding a method. Proper documentation is really the only option here. Is there a way in which parent class could enforce one of the three alternates to all the deriving classes? The only option here is to avoid the issue. Instead of allowing the subclass to override the method, it can be declared non-virtual, and call a virtual method in the appropriate place. For example, if you want to enforce that subclasses "call your version first", you could do: public class BaseClass { public void Method() // Non-virtual { // Do required work // Call virtual method now... this.OnMethod(); } protected virtual void OnMethod() { // Do nothing } } The subclasses can then "override" OnMethod, and provide functionality that happens after "method"'s work. The reason this is required is that virtual methods are designed to allow a subclass to completely replace the implementation of the parent class. This is done on purpose. If you want to prevent this, it's better to make the method non-virtual. A: This is why I feel virtual methods are dangerous when you ship them in a library. The truth is you never really know without looking at the base class, sometimes you have to fire up reflektor, read documentation or approach it with trial and error. When writing code myself I've always tired to follow the rule that says: Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called. This is taken from http://msdn.microsoft.com/en-us/library/ms229011.aspx, however this is for Event design though I believe I read this in the Framework Design Guidelines book (http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321246756). However, this is obviously not true, ASP.NET web forms for example require a base call on Page_Load. So, long and short, it varies and unfortunately there is no instant way of knowing. If I'm in doubt I will omit the call initially. A: The short answer is no. You can't enforce in what order the child calls the base method, or if it calls it at all. Technically this information should be included in the base object's documentation. If you absolutely must have some code run before or after the child class' code than you can do the following: 1) Create a non-virtual function in the base class. Let's call it MyFunction 2) Create a protected virtual function in the base class. Let's call it _MyFunction 3) Have deriving classes extend the _MyFunction method. 4) Have MyFunction call _MyFunction and run the code it needs to run before or after calling it. This method is ugly and would require a lot of extra code, so I recommend just putting a notice in the documentation. A: The requirements of the base class should be documented by the library designer. This issue is the reason why some libraries contain mainly sealed classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/3152996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Calculated summary field based on child table I have two tables, Order and OrderItem. There is a one-to-many relationship on Order.Order_ID=OrderItem.Order_ID I want a query to return a list showing the status of each Order, COMPLETE or INCOMPLETE. A COMPLETE Order is defined as one where all the related OrderItem records have a non-NULL, non-empty value in the OrderItem.Delivery_ID field. This is what I have so far: SELECT Order.Order_ID, 'INCOMPLETE' AS Order_status FROM Order WHERE EXISTS (SELECT * FROM OrderItem WHERE OrderItem.Order_ID=Order.Order_ID AND (OrderItem.Delivery_ID IS NULL OR OrderItem.Delivery_ID='')) UNION SELECT Order.Order_ID, 'COMPLETE' AS Order_status FROM Order WHERE NOT EXISTS (SELECT * FROM OrderItem WHERE OrderItem.Order_ID=Order.Order_ID AND (OrderItem.Delivery_ID IS NULL OR OrderItem.Delivery_ID='')) ORDER BY Order_ID DESC It works, but runs a bit slow. Is there a better way? (N.B. I've restated the problem for clarity, actual table and field names are different) A: I would suggest you have a column status on your Order table and update the status to complete when all order items get delivered. It will make simple your query to get status as well improve performance. A: Put it into a subquery to try to make the case statement less confusing: SELECT Order_ID, CASE WHEN incomplete_count > 0 THEN 'INCOMPLETE' ELSE 'COMPLETE' END AS Order_status FROM ( SELECT o.Order_ID ,SUM( CASE WHEN OrderItem.Delivery_ID IS NULL OR OrderItem.Delivery_ID='' THEN 1 ELSE 0 END ) AS incomplete_count FROM Order o INNER JOIN OrderItem i ON (i.Order_ID = o.Order_ID) GROUP by o.Order_ID ) x ORDER BY ORder_ID DESC The idea is to keep a counter every time you encounter a null item. If the sum is 0, there were no empty order items. A: Try this one - SELECT o.Order_ID , Order_status = CASE WHEN ot.Order_ID IS NULL THEN 'COMPLETE' ELSE 'INCOMPLETE' END FROM dbo.[Order] o LEFT JOIN ( SELECT DISTINCT ot.Order_ID FROM dbo.OrderItem ot WHERE ISNULL(ot.Delivery_ID, '') = '' ) ot ON ot.Order_ID = o.Order_ID
{ "language": "en", "url": "https://stackoverflow.com/questions/17310693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Want to extend from java.sql.ResultSet I would like to create myRecordSet object that extends java.sql.ResultSet and to implement a method that returns UTC date from SQL statement. How can I extend from java.sql.ResultSet, I need an example. 10X A: Do not extend ResultSet. Create your entity class, let say Person. And implement 'get some date' method. Like so class Person { public Person(ResultSet resultSet) { this.resultSet = resultSet; } ... public Date getBirthday() { resultSet.getDate("BIRTHDAY_COLUMN"); } ... } You should be aware that this Person class is more like wrapper then pure entity. And using it is OK only in a scope where you have established connection and valid ResultSet object. while (resultSet.next()) { Person person = new Person(resultSet); someAction(person); someMoreActions(person); } To make Person more entity-like you could consider using JPA A: First, you don't extend interfaces, but you do implement interfaces :) That said, you are likely looking in the wrong direction for the solution. Forget about implementing your ResultSet and just create a DAO class which does all the the ResultSet <--> Entity mapping tasks and do the desired date conversion just there. The DAO method may look like public Person find(Long id) throws SQLException { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Person person = null; try { connection = database.getConnection(); preparedStatement = connection.prepareStatement(SQL_FIND); preparedStatement.setLong(1, id); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { person = new Person(); person.setId(resultSet.getLong("id")); person.setName(resultSet.getString("name")); person.setBirthDate(resultSet.getDate("birth_date")); // ... } } finally { close(connection, preparedStatement, resultSet); } return person; } You see, if the database column type is DATE, DATETIME or TIMESTAMP, then you can just use ResultSet#getDate() to obtain it as a java.util.Date object. To display the date in the desired format in the presentation layer, use the therefore supplied tools like SimpleDateFormat for "plain Java", fmt:formatDate for JSP pages, f:convertDateTime for JSF, etcetera. Tight-coupling the ResultSet inside the model (entity, the "Person" in this example) is a bad idea. The model doesn't need to know anything about how it is been created and doing it may only potentially leak DB resources (because that approach may require the ResultSet to be open all the time) and may cause your app to crash sooner or later because the DB has run out of resources. Don't do that. To get more ideas and insights about the DAO you may find this article useful. A: I would like to create myRecordSet object that extends java.sql.ResultSet Easy enough. A decent IDE will do it for you. and to implement a method that returns UTC date from SQL statement. Impossible, because you can't get your database to create an instance of your class instead of its own. So you don't want to do that. What you really want to do is write a wrapper for ResultSet that talks to whatever you get from the database and adds whatever functionality you need. This is called the Delegate pattern.
{ "language": "en", "url": "https://stackoverflow.com/questions/2445828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: The following _TypeError was thrown building -Exception caught by widgets library The following _TypeError was thrown building BlurImagePageScaffold(dirty): type 'List' is not a subtype of type 'Widget' I'm getting above error when Im trying to run my code. I have included my codes files below. how to solve this. blur_image_page_scaffold.dart import 'dart:ui'; import 'package:flutter/material.dart'; class BlurImagePageScaffold extends StatelessWidget { const BlurImagePageScaffold({Key? key,this.imagePath, this.body}) : super(key: key); final body; final imagePath; @override Widget build(BuildContext context) { return Container( height: double.infinity, width: double.infinity, decoration: BoxDecoration( shape: BoxShape.rectangle, image: DecorationImage( image: AssetImage(imagePath),fit: BoxFit.fill), ), child: BackdropFilter( filter: ImageFilter.blur(sigmaX:10, sigmaY:10), child: Container( color: Colors.black.withOpacity(0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ body ], ) ), ), ); } } hello.dart import 'package:flutter/material.dart'; import 'package:new_chat_app/components/blur_image_page_scaffold.dart'; import 'package:new_chat_app/components/lets_start.dart'; import 'package:new_chat_app/components/logo.dart'; import 'package:new_chat_app/components/terms_and_conditions.dart'; class Hello extends StatelessWidget { const Hello({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlurImagePageScaffold(imagePath: 'images/bg.jpg', body: [ Logo(), Column( children: [ Text('Hello'), Column( children: [ Text("Whatsapp is a Cross-Platform"), Text("mobile messaging with friends"), Text("all over the world"), ], ), TermsAndConditions(), LetsStart(), ], ), ]); } } A: Simply set children to body Like so: BackdropFilter( filter: ImageFilter.blur(sigmaX:10, sigmaY:10), child: Container( color: Colors.black.withOpacity(0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: body, ) ), ), )
{ "language": "en", "url": "https://stackoverflow.com/questions/70930487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Opencart Filter Pagination Issue I have assigned a filter(default) in my opencart(1.5.6.4) store. I have 16 product displaying at single page. So whenever I select a filter module & refine search it worked ok for first 16 product but when page 2 is clicked it shows all product.Suppose I have selected 27 product in filter..it shows 1to 16 product of 27 but when I clicked page 2 its showing 17 to 32 of 368 products.
{ "language": "en", "url": "https://stackoverflow.com/questions/38182255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel injections and services I have two services with business logic: ItemService and BagService. And each service have writeOff method. And i can't figure out how to implement logic when ItemService writeOff method needs to use BagService service writeoff method and BagService writeoff method need to use ItemService writeoff method. Is it even possible to have this logic with services and injections? Because now i get infinite loop. class EstoreItemService { protected $bagService; public function __construct(BagService $bagService) { $this->bagService = $bagService; // ... other injections } public function writeOff(int $id) { //find item and its bag (with bag items) by given item id $item = Item::with('bag.items')->find($id); $item->delete(); // ... item write off logic, like notifications, summary updates and other //if item bag is empty write off bag if ($item->bag->items->count() == 0) { $this->bagService->writeOff($item->bag); } return true; } // ... other methods } class EstoreItemService { protected $itemService; public function __construct(ItemService $itemService) { $this->itemService = $itemService; // ... other injections } public function writeOff(int $id) { //find bag and its items by given bag id $bag = Bag::with('items')->find($id); $bag->delete(); // ... bag write off logic, like notifications, summary updates and other //write off all item in bag foreach ($bag->items as $item) { $this->itemService->writeOff($item->id); } return true; } // ... other methods } A: Peppermintology offered 2 ways and both has problems: Maybe extract the writeOff function into a service of its own which is injected into your ItemService and BagService it works only on situations like this, when you need to use "writeoff" on both services, but when you need to use some method like "updateProductPrice" (which is only used in product) then you should have this method in "ProductSercice"? or in third service? I think it will be confusion when to use third service and when to use main Product or Bag service. It might also be that ItemService and BagService can and should be combined into a single service with a writeOff method I think it is more clear solution to split "resources" in separate services (like ProductService, BagService), combined service will have a lot of code in single file and I think it is not clear solution. I am also interested if there is any other solutions or how to solve problems of offered solutions.
{ "language": "en", "url": "https://stackoverflow.com/questions/70032581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to capture html frame as an image I need to open a webpage from Python and capture what I see in browser as an image(or rather what should be seen, because I want to execute it in background). The webpage contains JavaScript - one frame has caption dependent on script evaluation and I want it also to be captured. A: It's feasible, at least, using PyQt + QWebKit (an example here and here).
{ "language": "en", "url": "https://stackoverflow.com/questions/4948945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SignalR Azure function with input binding returning value An azure function with signalR input binding can get some parameters. For example [FunctionName("SignalRTest")] public async Task SendMessage([SignalRTrigger]InvocationContext invocationContext, string message, ILogger logger) { logger.LogInformation($"Receive {message} from {invocationContext.ConnectionId}."); } In the function it can invoke the clients e.g. [FunctionName("SendMessage")] public static Task SendMessage( [HttpTrigger(AuthorizationLevel.Anonymous, "post")]object message, [SignalR(HubName = "chat")]IAsyncCollector<SignalRMessage> signalRMessages) { return signalRMessages.AddAsync( new SignalRMessage { // the message will only be sent to this user ID UserId = "userId1", Target = "newMessage", Arguments = new [] { message } }); } But is it possible for the azure function with input binding to return something? I'd like to have [FunctionName("SignalRTest")] public async Task<string> SendMessage([SignalRTrigger]InvocationContext invocationContext, string message, ILogger logger) { return "123"; } and id = connection.invoke("SendMessage", "test"); but it does not seem to work. Thank you. A: My team set it up so that a hub operation actually "returns" twice, and maybe this is what you're looking for. When a hub operation is invoked, we have synchronous code do whatever it needs to do and return a result object, which is usually a model from a backend service we're calling. That is pushed to the client via client.SendAsync where client is IClientProxy. That's going to ultimately invoke a JS handler on your front end. However, should something break, we may not get that callback to the JS handler. In that case, we also have our hub operations return a Task<IActionResult> that the front JS can handle. That acts more like a HTTP status code response. In the end, each hub operation we invoke has at least 1 response, which is the IActionResult: {"type":3,"invocationId":"0","result":{"statusCode":200}} This approach allows us to setup a reusable client that behaves more like a normal REST client in that we can use the IActionResult response to trigger exception handling. Example: try { const result = await this.connection.invoke(callSettings.operation, callSettings.args); if (responseHandler){ const apiResponse = new ApiResponse({ statusCode: result.statusCode }); responseHandler.handleStatusCode(apiResponse, callSettings.operation, callSettings.args); } hubResponse.success = result.statusCode < 300; hubResponse.httpStatusCode = result.statusCode; hubResponse.body = result; } catch (err) { hubResponse.success = false; this.loggerService.logException(err, callSettings.operation); throw(err); }
{ "language": "en", "url": "https://stackoverflow.com/questions/67726114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pushing to state array in ReactNative I have my code where I assign an onPress event the following function (please mind the annotation): export default class App extends React.Component { state = { noteArray: [], noteText: "", }; constructor(props: any) { super(props); } addNote() { if (this.state.noteText) { var d = new Date(); let noteArray = [...this.state.noteArray]; noteArray.push({ date: d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate(), note: this.state.noteText, }); //If I place a "console.log(noteArray); return;" here I get the object I expect. this.setState({ noteArray }); //If I set the same "console.log" here I will get an empty array in console (because the "valuated just now" but if I do console.log(noteArray[0]) I get the correct object) return true; } } } I havent been able to modify the variable "this.state.noteArray". If I console.log the variable in the end, I always end with an empty array. Here is the object that's calling it: <TouchableOpacity style={styles.addButton} onPress={this.addNote.bind(this)} > <Text style={styles.addButotnText}>+</Text> </TouchableOpacity> And I also have another object modifying the state, but this is successfuly doing it: <TextInput style={styles.textInput} placeholderTextColor="white" underlineColorAndroid="transparent" placeholder=">Note" value={this.state.noteText} onChangeText={(noteText) => this.setState({ noteText })} ></TextInput> Thank you for your kind insight A: I think this is probably because you are not using setState in the right way, you should do : this.setState({ noteArray: noteArray }) and not : this.setState({ noteArray }); hope I helped you ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/64617040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: onClick are open all Text here is my code, when I click on an Icon(4 icons) they all show text, my 4 icons have the same code structure, I don't know maybe I should add some id ? or do you have a more good choice? can you help me, please :) const [showText, setShowText] = useState(false) const toggleText = () => setShowText((text) => !text) <div className="inline-flex justify-center items-center"> <Button className=" border-none bg-white" onClick={toggleText}> <IconUsers size={30} stroke={1} /> </Button> {showText && ( <Text className=" inline-flex justify-center items-center align-text-top "> devenir member </Text> )} </div> <div className="inline-flex justify-center items-center"> <Button className=" border-none bg-white" onClick={toggleText}> <IconHeart size={30} stroke={1} /> </Button> {showText && ( <Text className="flex justify-center items-center align-text-top "> favorites </Text> )} </div> <div className="inline-flex justify-center items-center"> <Button className=" border-none bg-white" onClick={toggleText}> <IconMail size={30} stroke={1} /> </Button> {showText && ( <Text className="flex justify-center items-center align-text-top "> notification </Text> )} </div> <div className="inline-flex justify-center items-center"> <Button className=" border-none bg-white" onClick={toggleText}> <IconMathSymbols size={30} stroke={1} /> </Button> {showText && ( <Text className="flex justify-center items-center align-text-top "> total </Text> )} </div> how can I fix it? like click on 1 icon and will only show his own text open 1 A: Hi you will need to store more information in state. Instead of boolean true false you should store something that can be used as ID, unique to all buttons. For example const [selected, setSelected] = useState() And then toggleText could become toggleSelected and needs to take the id of the element that was selected as an argument. const toggleText = (id) => setSelected(id) Then in the code for one of the buttons it becomes //assuming we call this one with id favorite <div className="inline-flex justify-center items-center"> <Button className=" border-none bg-white" onClick={()=>toggleText("favorite")}> <IconHeart size={30} stroke={1} /> </Button> {selected==="favorite" && ( <Text className="flex justify-center items-center align-text-top"> favorites </Text> )} </div> You can then make similar changes for the rest of the buttons giving whatever ids you want. If using typescript you can ensure the state is correct assigned an expected value with something like type Option = "favorite" | "membership" | "total" | "notification" ... const [selected,setSelected] = useState<Option>() ... const toggleText = (id:Option) => setSelected(id) This will work and keep the structure as it is. Then eventually what you would probably want is to create a component for that and remove some repetition for the logic. Best A: All of your button/text is using the same set of function setter and state, so it will behave the same way when you click on one. The easiest way is just to extract them into a component like this //TextWithButton.jsx (multiple codes r removed) const [showText, setShowText] = useState(false) const toggleText = () => setShowText((text) => !text) <div className="inline-flex justify-center items-center"> <Button className=" border-none bg-white" onClick={toggleText}> <IconUsers size={30} stroke={1} /> </Button> {showText && ( <Text className=" inline-flex justify-center items-center align-text-top "> devenir member </Text> )} </div> // parent.tsx (multiple codes r removed) <TextWithButton /> <TextWithButton /> <TextWithButton /> <TextWithButton /> However, I feel like you are missing an understanding of the concept of components in React. I would recommend you to read this article through :)
{ "language": "en", "url": "https://stackoverflow.com/questions/74849263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android BLE: server side changes for onCharacteristicChanged callback? I have an ios app in which I am doing BLE communication with a medical device. I am creating android version of same app. In my android application for implementing BLE communication with that medical device I have written following gatt callback: private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { super.onConnectionStateChange(gatt, status, newState); switch (newState) { case BluetoothProfile.STATE_CONNECTED: Log.d(TAG, "Connected"); gatt.discoverServices(); break; case BluetoothProfile.STATE_DISCONNECTED: Log.d(TAG, "Disconnected"); break; default: Log.d(TAG, "State Other"); break; } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); Log.d(TAG, "onServicesDiscovered"); BluetoothGattCharacteristic mCharacteristic = gatt.getService(SNORECOACH_SERVICE_UUID).getCharacteristic(BODY_MOVEMENT_UUID); if ( mCharacteristic.getUuid().equals(BODY_MOVEMENT_UUID)) { Log.d(TAG, "Characteristic Found"); } mBluetoothGatt.setCharacteristicNotification(mCharacteristic, true); BluetoothGattDescriptor descriptor = mCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID); if (descriptor.getUuid().equals(CLIENT_CHARACTERISTIC_CONFIG_UUID)) { Log.d(TAG, "Descriptor Found"); } descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mBluetoothGatt.writeDescriptor(descriptor); } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicRead(gatt, characteristic, status); Log.d(TAG, "onCharacteristicRead"); } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); Log.d(TAG, "onCharacteristicWrite"); } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { super.onCharacteristicChanged(gatt, characteristic); Log.d(TAG, "onCharacteristicChanged"); } @Override public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { super.onDescriptorRead(gatt, descriptor, status); Log.d(TAG, "onDescriptorRead"); } @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { super.onDescriptorWrite(gatt, descriptor, status); Log.d(TAG, "onDescriptorWrite"); } }; All the operations like pairing, unpairing, read-write characteristics are working fine except onCharacteristicChange callback. I have tried all the possible options at following links 1) https://developer.android.com/guide/topics/connectivity/bluetooth-le.html 2) http://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/ 3) http://toastdroid.com/2014/09/22/android-bluetooth-low-energy-tutorial/ and many more other links. But onCharacteristicChanged is not getting called. I have been trying for this more than 5 days but no luck. But in ios app callback equivalent to onCharacteristicChanged is getting called properly. What I would like to know is - any coding/implementation(i.e. any server side implementation) specific to Android I have to do in that device so that it can send characteristic change notification, which I can receive at onCharacteristicChanged callback.
{ "language": "en", "url": "https://stackoverflow.com/questions/41339991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error LNK2019 external I can't quite make sense of the errors i get when trying to get my project to work. Can someone maybe point me in the right direction? I am fairly new to C++, so I might be doing something crucially wrong here without being aware of it. The errormessages I get are as following: Fehler 6 error LNK2019: Verweis auf nicht aufgelöstes externes Symbol ""public: struct Camera __thiscall Scene::getCamera(void)" (? getCamera@Scene@@QAE?AUCamera@@XZ)" in Funktion ""public: void __thiscall Renderer::render(void)" (?render@Renderer@@QAEXXZ)". ...\source\renderer.obj raytracer Fehler 4 error LNK2019: Verweis auf nicht aufgelöstes externes Symbol ""public: class std::vector<class std::shared_ptr<class Shape>,class std::allocator<class std::shared_ptr<class Shape> > > __thiscall Scene::getShapes(void)const " (?getShapes@Scene@@QBE?AV?$vector@V?$shared_ptr@VShape@@@std@@V?$allocator@V?$shared_ptr@VShape@@@std@@@2@@std@@XZ)" in Funktion ""public: void __thiscall Renderer::render(void)" (?render@Renderer@@QAEXXZ)". ...source\renderer.obj raytracer Here is my code: #include "color.hpp" #include "pixel.hpp" #include "ppmwriter.hpp" #include <string> #include <glm/glm.hpp> #include <map> #include <shape.h> #include "sdfloader.h" #include <optional_hit.h> #include <scene.h> Renderer::Renderer(Scene const& scene, unsigned w, unsigned h, std::string const& file) : width_(w) , height_(h) , colorbuffer_(w*h, Color(0.0, 0.0, 0.0)) , filename_(file) , ppm_(width_, height_) , scene_(scene) {} void Renderer::render() { camera_ = scene_.getCamera(); shapes_ = scene_.getShapes(); lights_ = scene_.getLights(); camera_.position = glm::vec3(0, 0, tan((90.0 - camera_.opening_angle / 2.0) * M_PI / 180.0) * (double(width_) / 2.0)); testOutput(); Ray first_ray; for (unsigned y = 0; y < height_; ++y) { for (unsigned x = 0; x < width_; ++x) { Pixel p(x, y); //first ray is created here glm::vec3 poip = glm::vec3(double(x) - double(width_) / 2.0, double(y) - double(height_) / 2.0, 0); first_ray.origin = camera_.position; first_ray.direction = poip - camera_.position; double delta = -1; Shape *closest_obj; for (unsigned int i = 0; i < shapes_.size(); ++i) { double d = shapes_[i]->intersect(first_ray); if (d > 1.0 && (d < delta || delta == -1)) { delta = d; closest_obj = shapes_[i].get(); } } if (delta == -1) { p.color = Color(0.0, 0.0, 0.0); } else { glm::vec3 hit_point = first_ray.origin + (float) delta * first_ray.direction; p.color = calculateColor(closest_obj, hit_point, first_ray); } // draw pixel write(p); } } ppm_.save(filename_); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (width_*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } /*Optional_hit Renderer::intersect(Ray const& ray) const{ Optional_hit o; Optional_hit temp; std::vector<float> hits;*/ void Renderer::testOutput() { std::cout << "Objects in scene:" << std::endl; for (unsigned int i = 0; i < shapes_.size(); ++i) { std::cout << "Object names: " << shapes_[i]->getName() << std::endl; } for (unsigned int i = 0; i < lights_.size(); ++i) { std::cout << "Lightsource: " << lights_[i].getName() << std::endl; } std::cout << "Camera used: " << camera_.name << " | Focal Length: " << camera_.position.z << std::endl; } Color Renderer::calculateColor(const Shape* hit_obj, glm::vec3 const& hit_point, Ray const& first_ray) { Color final_color = Color(0.0, 0.0, 0.0); for (unsigned int i = 0; i < lights_.size(); ++i) { glm::vec3 n = hit_obj->getNormalAt(hit_point); glm::vec3 l = lights_[i].getPosition() - hit_point; Ray sec_ray = Ray(hit_point, l); Color diffuse_light; Color specular_light; if (!Shadow(sec_ray) && glm::dot(glm::normalize(n), glm::normalize(l)) > 0) { Color Ip = lights_[i].getLD(); Color kd = hit_obj->getMaterial().getKD(); diffuse_light = (Ip * kd * glm::dot(glm::normalize(n), glm::normalize(l))); glm::vec3 r = 2 * glm::dot(glm::normalize(n), glm::normalize(l)) * glm::normalize(n) - glm::normalize(l); glm::vec3 v = glm::normalize(first_ray.direction); v *= -1; if (glm::dot(r, v) > 0) { double m = hit_obj->getMaterial().getM(); Color ks = hit_obj->getMaterial().getKS(); specular_light = ks * pow(glm::dot(r, v), m); } else { specular_light = Color(0.0, 0.0, 0.0); } } else { diffuse_light = Color(0.0, 0.0, 0.0); specular_light = Color(0.0, 0.0, 0.0); } final_color += diffuse_light + specular_light; } Color Ia = lights_[0].getLA(); Color ka = hit_obj->getMaterial().getKA(); Color ambient_light = Ia * ka; final_color += ambient_light; return final_color; } the scene header file: #define SCENE_HPP #include <vector> #include <memory> #include <material.h> #include <camera.h> #include <light.h> #include <shape.h> #include <map> struct Scene { Scene(); void render() const; void add(std::shared_ptr<Material> material); void add(std::shared_ptr<Shape> shape); void add(std::shared_ptr<Light> light); void add(std::shared_ptr<Camera> camera); std::vector<std::shared_ptr<Shape>> const& shapes() const; std::vector<std::shared_ptr<Material>> const& materials() const; std::vector<std::shared_ptr<Light>> const& lights() const; std::vector<std::shared_ptr<Camera>> const& cameras() const; void readFile(std::string file); std::map<std::string, std::shared_ptr<Material>> getMaterials() const; std::vector<std::shared_ptr<Shape>> getShapes() const; std::vector<Light> getLights() const; //std::vector<Camera> getCamera(); Camera getCamera(); Material checkMaterialName(std::string name); std::vector<std::shared_ptr<Shape>> shapes_; std::map<std::string, Material> materials_; std::vector<std::shared_ptr<Light>> lights_; std::vector<std::shared_ptr<Camera>> camera_; unsigned width = 600; unsigned height = 600; }; #endif and the renderer header: #include "color.hpp" #include "pixel.hpp" #include "ppmwriter.hpp" #include <string> #include <glm/glm.hpp> #include <map> #include <shape.h> #include "sdfloader.h" #include <optional_hit.h> #include <scene.h> class Renderer { public: Renderer(Scene const& scene, unsigned w, unsigned h, std::string const& file); void render(); void write(Pixel const& p); void testOutput(); Color calculateColor(const Shape* hit_obj, glm::vec3 const& hit_point, Ray const& prim_ray); bool Shadow(Ray sec_ray); inline std::vector<Color> const& colorbuffer() const { return colorbuffer_; } unsigned get_width() const; unsigned get_height() const; std::string get_filename() const; Scene get_scene() const; std::vector<std::shared_ptr<Shape>> const& shapes() const; // OptionalHit intersect(Ray const& ray) const; //void render_scene(std::string file); private: unsigned width_; unsigned height_; std::vector<Color> colorbuffer_; std::string filename_; PpmWriter ppm_; Scene scene_; Camera camera_; std::vector<Light> lights_; std::vector<std::shared_ptr<Shape>> shapes_; }; If anyone can make any sense of this, any help is really appreciated!
{ "language": "en", "url": "https://stackoverflow.com/questions/38362656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create exact type d-dimension points, segments, etc... in using CGAL Here is how I create 2D points with various precisions by using CGAL #include <CGAL/Cartesian.h> #include <CGAL/Exact_predicates_exact_constructions_kernel.h> typedef CGAL::Cartesian<float> Kernel_float; typedef Exact_predicates_exact_constructions_kernel Kernel_exact; typedef Kernel_float::Point_2 Point_2_float; typedef Kernel_exact::Point_2 Point_2_exact; Here is how I create d-dimension 32-bit floating-point type point #includee <CGAL/Cartesian_d.h> typedef CGAL::Cartesian_d<float> Kernel_d_float; typedef Kernel_d_float::Point_d Point_d_float; However, I cannot create exact type of Point_d... Since there is no header file like CGAL/Exact_predicates_exact_constructions_kernel_d.h Doesn't CGAL support exact type of d-dimension kernels? A: To get an exact dD-kernel, use a exact number type with CGAL::Cartesian_d, for example: #include <CGAL/Cartesian_d.h> #include <CGAL/Gmpq.h> typedef CGAL::Cartesian_d<CGAL::Gmpq> Exact_kernel_d;
{ "language": "en", "url": "https://stackoverflow.com/questions/25496334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Boost Filesystem: recursive_directory_iterator constructor causes SIGTRAPS and debug problems I want to use the recursive_directory_iterator offered by boost::filesystem to delete a directory. But at construction time the debugger stops with the message Signal Received: Sigtrap . I can choose to continue ( have to do it several times because multiple Sigtraps are caught ) and the program will work as expected, but debugging with custum break points doesn't work anymore. The path the "fs::path dir" points to is valid, and I've also tried to use a string like fs::... dirIter( "D:/validPath" ), but the problem stays. #include <boost/filesystem.hpp> namespace boost::filesystem = fs; void recursiveDeleteDir( fs::path dir ) fs::recursive_directory_iterator endIter; //At this point debugging is stopped with the message //Signal Received: SIGTRAP fs::recursive_directory_iterator dirIter( dir ); for(;dirIter != endIter ; ++dirIter) { // do something } } When I try to find out exactly where the Sigtrap is coming from I get lost in the depths of the boost::filesystem implementation details. Does anyone have an Idea why these Sigtraps exist or how they are activated and even more important: Is there a way to get rid of them ( Of course they only occur in Debug Mode and the program works fine in Release Mode, but I have to be able to continue Debugging somehow ) Thanks for your help! edit: I'm working with the NetBeans IDE and don't have access to the full Call Stack. But this is what it contains when the sigtrap Signal is Received: 01: ntdll!RtlpNtMakeTemporaryKey() 02: ntdll!RtlpNtMakeTemporaryKey() 03: ntdll!RtlpNtMakeTemporaryKey() 04: ntdll!LdrFindEntryForAddress() 05: Address:[@0x003e0000] 06: Address:[@0x50000061] 07: std::basic_string, std::allocator>::_Rep::_S_empty_rep_storage() 08: Address:[@0x003e0000] 09: std::basic_string, std::allocator>::_Rep::_S_empty_rep_storage() 10: Address:[@0x40000060] 11: Address:[@0x0022f968] 12: Address:[@0x00000000] A: After a lot of searching and asking around I solved the problem. This question (or rather the answer) gave me a hint: Does getting random SIGTRAP signals (in MinGW-gdb) is a sign of memory corruption? It seems to be a matter of trying to access corrupted memory, which is caused by using an uninitialized dynamic library. By using the static (debug) versions of the boost::filesystem and boost::system library, and activating the -static switch for the linker, one can get rid of the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/3469463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Do I need service to do something when app is in background? I have to write an app that is supposed to send user location to server. I have class that is listening events from Android and it sends data to server bia webservice. Do I have to put that in some service, or I can just put it into my MainActivity class code? Im asking, because Android is still weird for me. It pauses activities and I don't know if this will work "from the background" or not. Of course I want to update location when application is in foreground and background too. A: Yes you will have to use a Service to send data in the background as well as foreground. You can use android Service or Background Service, based on your requirements I would suggest using the Background Service. Here are the links for both: Service: http://developer.android.com/guide/components/services.html Background Service: https://developer.android.com/training/run-background-service/create-service.html A: if you want the location irrespective of the fact that the application is open or not then you need to have a service which will keep on posting your location to the server. Here's how you can do it ... Read this answer Note : Activities can't do what you want to achieve as they exist till the user exits them (by pressing the back button, killing them or clearing the stack[Need not think of it for now if a newbie]). A: There is a good article on android.com website https://developer.android.com/training/location/receive-location-updates.html
{ "language": "en", "url": "https://stackoverflow.com/questions/28771686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IShellDispatch NameSpace-call fails, don't know why First time working with COM from C++, been using C# and Delphi before. So here's the code HRESULT Result; Result = CoInitialize(nullptr); if (!SUCCEEDED(Result)) return Result; IShellDispatch* API; Result = CoCreateInstance(CLSID_Shell, nullptr, CLSCTX_INPROC_SERVER, IID_IShellDispatch, (void **)&API); if ((!SUCCEEDED(Result)) || (nullptr == API)) goto Cleanup; VARIANT Source1, Source2, Destination, Options; VariantInit(&Destination); Destination.vt = VT_BSTR; Destination.bstrVal = SysAllocString(OutFile.c_str()); Folder* PDestination; Result = API->NameSpace(Destination, &PDestination); if (!SUCCEEDED(Result)) goto Cleanup; VariantInit(&Source1); VariantInit(&Source2); Source1.vt = VT_BSTR; Source2.vt = VT_BSTR; Source1.bstrVal = SysAllocString(InFile1.c_str()); Source2.bstrVal = SysAllocString(InFile2.c_str()); VariantInit(&Options); Options.vt = VT_I4; Options.lVal = FOF_NO_UI; PDestination->CopyHere(Source1, Options); Sleep(1000); PDestination->CopyHere(Source2, Options); Sleep(1000); PDestination->Release(); API->Release(); Cleanup: CoUninitialize(); return Result; OutFile, InFile1 and InFile2 are of type wstring as the program is (mostly) C++. I've managed to create an empty ZIP file, that's not the issue. The issue is that I get an exception claiming that PDestination is nullptr. If it helps, the variants themselves seems to work. Inspecting them in the debugger yields the paths I provided. I've noticed though how the NameSpace-call returns an S_FALSE. Does anyone know what I can do about that? Using a library doesn't exactly work, it's corporate code and there's some truly draconian rules when it comes to linking external code so using the Windows API is the easiest way.
{ "language": "en", "url": "https://stackoverflow.com/questions/52705339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: anchor tag getting appended multiple times to child div I have the following html that has images embedded into links.I am trying to append an achor tag into the div,however the anchor tags gets added multiple times. this is my code original <div id="Banner" style="display: block; position: relative;"> <div id="Settings" style="height: auto; width: 100%;"></div> <div > <a href="/id=10052&;way=ban"> <img src="/hours.jpg"> </a> </div> <div> <a href="/id=10220&amp;way=ban"> <img src="/rq.jpg"> </a> </div> </div> now i am trying to add in another anchor tag as follows the expected outcome <div id="Banner" style="display: block; position: relative;"> <div id="Settings" style="height: auto; width: 100%;"></div> <div > <a href="#" class="previous"></a> // tag to come in <a href="/id=10052&;way=ban"> <img src="/hours.jpg"> </a> </div> <div> <a href="#" class="previous"></a> // tag to come in <a href="/id=10220&amp;way=ban"> <img src="/rq.jpg"> </a> </div> </div> this is my code i tried var container = $($('#Banner').children('div')); var previous = $('<a href="#" class="previous">'); previous.appendTo(container); and this is what is happening <div id="Banner" style="display: block; position: relative;"> <div id="Settings" style="height: auto; width: 100%;"></div> <div > <a href="#" class="previous"></a> // tag to come in <a href="#" class="previous"></a> //added multiple times <a href="#" class="previous"></a> <a href="#" class="previous"></a> <a href="#" class="previous"></a> <a href="/id=10052&;way=ban"> <img src="/hours.jpg"> </a> </div> <div> <a href="#" class="previous"></a> // tag to come in <a href="#" class="previous"></a> <a href="#" class="previous"></a> //added multiple times <a href="#" class="previous"></a> <a href="#" class="previous"></a> <a href="#" class="previous"></a> <a href="#" class="previous"></a> <a href="#" class="previous"></a> <a href="#" class="previous"></a> <a href="/id=10220&amp;way=ban"> <img src="/rq.jpg"> </a> </div> </div> it keeps appending the tag multiple times. what am i doing wrong? A: I feel like your function keeps repeating. So, you may possibly set a simple check to make sure it's done only once: var container = $('#Banner').children('div'); var previous = $('<a href="#" class="previous">'); // Check if element already exists before appending. if (container.find(".previous").length === 0) previous.appendTo(container); This way, it checks if the DOM element exists before it appends. I really feel that the big picture needs some alteration, but for this case, this solution should work out.
{ "language": "en", "url": "https://stackoverflow.com/questions/58434024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Trying to convert data in one column from string to integer I have a dataframe called df['code'] which looks like this. 0 1 1 2 2 3 3 6 4 9 5 12 6 15 in which the first column are indexes and the second one is the column I wanted to convert to integers. What I tried to do is: for i in range(len(df['code'])): df['code'][i] = int(df['code'][i]) which did not work. Any ideas? Thanks A: I think one way to do this would be: for i in range(len(df['code'])): df['code'].iloc[i] = int(df['code'].iloc[i] ) Instead of using the index itself, it uses the index position.
{ "language": "en", "url": "https://stackoverflow.com/questions/56159638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Call a method of specific child classes I have these following interfaces interface Driveable{ public void drive(); } interface Flies{ public void isFlying(); public Integer fliesKmPerHour(); } Abstract class abstract class WarMachine{ ... class Vehlice extends WarMachine implements Driveable{ ... class Airoplane extends WarMachine implements Driveable,Flies{ ... And i have the main class public class War public ArrayList<WarMachine> warMachineArrayList; public War() { warMachineArrayList = new ArrayList<>(); } But in the main class i have a method that i want to return an Airoplane with the highest fliesKmPerHour public Airoplane getMaxAiroplane(){ Airoplane airoplane = null; //.. } My question is how can i access the fliesKmPerHour by calling from the warMachineArrayList A: First what we should do in these situation we should go to the Source where the fliesKmPerHour(); method is coming from. As we see here this method is coming from Flies interface What we know here is that this method belongs to the Airoplane class so in the arrayList we should check for instance of Flies Interface and typecast elements to Flies so then we can call the method So with the if(warMachineArrayList.get(i) instanceof Flies){ we check for Flies instances in the arrayList then we try to get the Airoplane that has the hightest speed with if(((Flies)warMachineArrayList.get(i)).fliesKmPerHour() > speedKmh){ airoplane = (Airoplane) warMachineArrayList.get(i); speedKmh = ((Flies)warMachineArrayList.get(i)).fliesKmPerHour(); And in the end we return an airoplane object public Airoplane getMaxAiroplane(){ Airoplane airoplane = null; int speedKmh = 0; for(int i=0;i<warMachineArrayList.size();i++){ if(warMachineArrayList.get(i) instanceof Flies){ if(((Flies)warMachineArrayList.get(i)).fliesKmPerHour() > speedKmh){ airoplane = (Airoplane) warMachineArrayList.get(i); speedKmh = ((Flies)warMachineArrayList.get(i)).fliesKmPerHour(); } } } return airoplane; } A: You can find instance with desired value by iteration over warMachineArrayList. Then you get some war mashine then check and cast and do what you need. Somting like that: for (WarMachine warMashine : warMachineArrayList ) { if (warMashine instanceof Airoplane ) { Airoplane airplane = (Airoplane) warMashine; // do with airplane anything you need } }
{ "language": "en", "url": "https://stackoverflow.com/questions/66374731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: React Native error: Cannot find module 'jest-serializer' any one can help me? i have a problem when i run 'npm start'. this is the Error Message A: Try to run npm install jest-serializer before doing npm start. If that is still not working, rm -rf node modules npm install npm start
{ "language": "en", "url": "https://stackoverflow.com/questions/53751008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: adb and multiple device simultaneously I am automating some test on android devices. I am using Jenkins in order to run the tests (via jobs) each job runs with a 95% success rate when only 1 device is connected to the machine but when I plug 2 android devices or more, it seems adb has some trouble and I get a 5% success rate. is it ok to run multiple instances of adb command? here is the command I run for each job: adb -s DEVICESERIAL shell am force-stop com.myapp.test adb -s DEVICESERIAL shell am force-stop com.myapp adb -s DEVICESERIAL uninstall com.myapp adb -s DEVICESERIAL uninstall com.myapp.test adb -s DEVICESERIAL install -r com.myapp adb -s DEVICESERIAL install -r com.myapp.test adb -s DEVICESERIAL shell am instrument -w TESTNAME/android.test.InstrumentationTestRunner adb -s DEVICESERIAL logcat -d -v time all command run with success but when the test starts and when I have multiple devices connected i get errors like for example: - Unable to find instrumentation target package - INSTRUMENTATION_STATUS_CODE: 0 - Failure [INSTALL_FAILED_INVALID_URI] at first I thought the test apk was not installed correctly, but when trying manually after the failure, it worked fine (so the test file is installed) again. Using 1 device only, everything is stable. Is there something special to do in order to install and run the test on different devices simultaneously? note that I have tried different usb ports, different cables etc... thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/16969490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: CMPLX Yields Undefined Symbol with GCC I'm trying to hunt down a problem using complex literals when compiling with GCC. Consider the following #include <stdio.h> #include <complex.h> int main(void) { double complex z = CMPLX(0.0, -1.0); printf("z = %.1f%+.1fi\n", creal(z), cimag(z)); return 0; } (slightly modified from the reference page). If I compile with Clang, it works as expected. However, if I use GCC I get an undefined reference error gcc -std=c11 mwe.c mwe.c: 6:24 warning: implicit declaration of function 'CMPLX' ... mwe.c:(...) undefined reference to `CMPLX' I have tried this with GCC 4.7 and 7.2 on Linux and GCC 9 on MacOS. The error messages change, but the net result remains the same. Reviewing the reference for CMPLX, this should be valid C11. Based on this answer and this post, it appears like GCC accepted this construct before. My bottom line question is: Why can't I use CMPLX with GCC? A: It appears like this is caused by a header/library disconnect on the systems I have. Compiling with the -save-temps flag, it appears GCC uses the system header for complex.h. This means the selected Xcode SDK's usr/include/complex.h on MacOS and /usr/include/complex.h on Linux. On MacOS, the CMPLX macro is only defined when using Clang. The Linux I have is RHEL 6 meaning the header is aimed at GCC 3 which did not have CMPLX. Based on the discussion on this bug report, it looks like making sure the macro is defined is not up to GCC. The short answer is: The compiler/platform combination doesn't support it. Use the native compiler or update the system.
{ "language": "en", "url": "https://stackoverflow.com/questions/58937664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Adding labels to graphs I am dealing with an excel file. I am plotting two graphs and trying to add labels. But in the first one labels do not show up. Here is my code: import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_excel("C:/Users/Jack/Desktop/Final Excel.xlsx") fig_1 = plt.figure(1, figsize=(70, 10)) ax1 = fig_1.add_subplot(121) ax2 = fig_1.add_subplot(122) t = list(df.iloc[[-1]]) r = np.array(t) arrow1 = df. iloc[[0,1,2]].mean() arrow2 = df.iloc[[9,10,11]].mean() arrow3 = df.iloc[[18,19,20]].mean() arrow4 = df.iloc[[36,37,38]].mean() ax1.plot(r,arrow1, label='1') plt.legend(loc='upper right') ax1.plot(r,arrow2, label='2') plt.legend(loc='upper right') ax1.plot(r,arrow3, label='3') plt.legend(loc='upper right') ax1.plot(r,arrow4, label='4') plt.legend(loc='upper right') stone1 = df.iloc[[3,4,5]].mean() stone2 = df.iloc[[12,13,14]].mean() stone3 = df.iloc[[21,22,23]].mean() stone4 = df.iloc[[39,40,41]].mean() ax2.plot(r,stone1, label='1') plt.legend(loc='upper center') ax2.plot(r,stone2, label='2') plt.legend(loc='upper center') ax2.plot(r,stone3, label='3') plt.legend(loc='upper center') ax2.plot(r,stone4, label='4') plt.figure() plt.show() I am only getting labels in the second chart but not in the first one. How could I add the desired labels on the first one as well? Thank you in advance! Have a nice day.
{ "language": "en", "url": "https://stackoverflow.com/questions/66387202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: String concatenation error? [PHP] i want to upload and then move a video to a directory i just created. Instead of moving the video to /var/www/html/ProductVideos/lazar108@hotmail.com it sends the video to /var/www/html/ProductVideos/ It works if i make $location = "/var/www/html/ProductVideos/lazar108@hotmail.com" but the location will change so i am trying to make the PHP script dynamic ProductAccountName = lazar108@hotmail.com Before PHP: After PHP: PHP code: <?php $ProductAccountName = $_POST['ProductAccountName']; $NewDirectory = "/var/www/html/ProductVideos/" . $ProductAccountName; if (!file_exists($NewDirectory)) { mkdir($NewDirectory, 0777, true); } if($_SERVER['REQUEST_METHOD']=='POST'){ $file_name = $_FILES['myFile']['name']; $file_size = $_FILES['myFile']['size']; $file_type = $_FILES['myFile']['type']; $temp_name = $_FILES['myFile']['tmp_name']; $location = $NewDirectory . $file_name; //"/var/www/html/ProductVideos/$ProductAccountName/" . $file_name; move_uploaded_file($temp_name, $location); A: Maybe $_POST['ProductAccountName'] is not set, so following code $ProductAccountName = $_POST['ProductAccountName']; $NewDirectory = "/var/www/html/ProductVideos/" . $ProductAccountName; causes $ProductAccountName to be empty. Make sure you add <input type="text" name="ProductAccountName" value="lazar108@hotmail.com"> inside your HTML form. A: I think there is no / after $ProductAccountName in creating $NewDirectory variable. Try rewerite location like this: $location = $NewDirectory . '/' . $file_name;
{ "language": "en", "url": "https://stackoverflow.com/questions/36005960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flex ArgumentError: Error #2025 in ItemRenderer I've got a problem in an ItemRenderer in Flex 3.5. I've looked at the other posts regarding this error but still can't figure it out. The ItemRenderer is part of an AdvancedDataGrid who's data provider is HierarchicalData. I'm getting the ArgumentError but the trace doesn't go to any of my code. I've gone through in debug mode tons of times but it looks like it doesn't happen until after my code runs. Quite strange. The item renderer has a couple different parts. It figures out what row it should be drawing for based on the xml data and then adds labels and sprites appropriately. If anyone can help, that would be a great help! Thanks! Here is one of the methods that gets called if the itemrenderer is on a certain row. private function addLabels(planList:ArrayCollection):void { height = 0; var sprite:Sprite = new Sprite(); var curX:Number = (width / planList.length); height = 110; for each (var plan:Plan in planList) { var label:Label = new Label(); label.text = plan.planner.label; label.rotationZ = 270; label.visible = true; label.x = curX - 7; //Draw line divider curX += (width / planList.length); addChild(label); label.move(label.x, height - 30); //Draw divider line sprite.graphics.lineStyle(.5, 0x000000); sprite.graphics.moveTo(label.x - ((width / planList.length) / 2) + 10.5, 0); sprite.graphics.lineTo(label.x - ((width / planList.length) / 2) + 10.5, height - 28); //Draw meatball sprite.graphics.beginFill(0x00FF33); sprite.graphics.drawCircle(label.x + 10, height - 15, 10); sprite.graphics.endFill(); } rawChildren.addChild(sprite); } There's another function that gets called on a different row, but if I comment out the code above everything works fine, so my guess is that the problem definitely lies there. Thanks for the help! Here is where addLabels gets called: override protected function createChildren():void { removeAllChildren(); var count:int = rawChildren.numChildren; for (var i:int = 0; i < count; i++) { if (rawChildren.getChildAt(0).parent) { rawChildren.removeChildAt(0); } } var allPlans:ArrayCollection = new ArrayCollection(); if (_plan) { getAllPlans(_plan, allPlans); } if (_name == "capability") { } else if (_name == "components") { height = 130; width = 335; addLabels(allPlans); // <-- RIGHT HERE! var sprite:Sprite = new Sprite(); sprite.graphics.lineStyle(.5, 0x000000); sprite.graphics.moveTo(0, 0); sprite.graphics.lineTo(width, 0); sprite.graphics.moveTo(0, height - 28); sprite.graphics.lineTo(width, height - 28); rawChildren.addChild(sprite); } } A: I've seen this kind of thing before. This error could be happening in the AdvancedDataGrid itself, not the itemRenderer. See http://www.judahfrangipane.com/blog/?p=196 for more information. If you simply want to draw something on specific rows, you might try extending the AdvancedDataGrid to override two functions: override protected function drawHorizontalLine(s:Sprite, rowIndex:int, color:uint, y:Number):void { // do some drawing } override protected function drawRowBackground(s:Sprite, rowIndex:int, y:Number, height:Number, color:uint, dataIndex:int):void { // do some drawing } A: Here's the answer if anyone was looking at this.. I'm still not exactly sure what the problem was, but the AdvancedDataGrid certainly did not like me adding a Label as a child to the renderer. Here's how I got around it.. add a TextField as a child to the sprite, as shown: var newLabel:TextField = new TextField(); newLabel.text = plan.planner.label; newLabel.rotationZ = 270; newLabel.visible = true; newLabel.x = curX - (dividerWidth / 2) - ((newLabel.textHeight) / 1.5); newLabel.y = height - (RADIUS * 2.5); newLabel.antiAliasType = AntiAliasType.ADVANCED; sprite.addChild(newLabel); Hope this helps someone!
{ "language": "en", "url": "https://stackoverflow.com/questions/3215159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handling loyalty credits with different expiry date and calculation I'm creating a membership system with loyalty point for a restaurant. Every member spend at the restaurant the merchant will issue loyalty point for member as cashback, and they were able to use the loyalty point in their account and act as money for transaction. And every points has its expiration date which is 3 months. Here's the problem im facing: The logic I write could not calculate the remaining points and add on to the rest if they were only use partial point. This is my table CREATE TABLE `transaction_record_tpg` ( `trans_id` int(15) NOT NULL, `collected_datetime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `expired_date` datetime NOT NULL, `user_id` int(15) NOT NULL, `m_debit` decimal(6,2) NOT NULL, `m_credit` decimal(6,2) NOT NULL, `collect_outlet` varchar(255) NOT NULL, ) I would like to create a table that can automatically calculate user's debit/credit transaction record with different expiration date. Below are the test case that I created: From the table, you can see that the member gained 15 pts at sept 1, and used 11 pts on sept 10 and oct 10 respectively. So the user actually still has 4 pts left and the expiry date and collect date should remain the same which is (sept 1-dec 4). Then the user gained 25 pts on oct 31 and dec 5 respectively, and on jan 10 used 10 pts, but by now the 4 pts from above CANNOT add into the calculate as the pts is already expired. So we should only use 20pts that we gain from oct 31 to minus 10 pts, which left us 10pts plus 5 points from dec 5th. So by now (25th feb 2020), the 10pts left from oct 31 is expired, which only left 5 pts in total. So the computer should show me 5 points. However the computer calculate as -16 pts which is obviously not the answer. Here's the logic i use to pull out the result from database: <?php $member_session = $_SESSION['u_id']; $get_member = "SELECT(SELECT SUM(m_debit) AS metallic_point FROM transaction_record_tpg WHERE user_id = $member_session AND expired_date >= CURRENT_DATE()) - (SELECT SUM(m_credit) AS metallic_point FROM transaction_record_tpg WHERE user_id = $member_session) "; ?> Can anyone tell me what went wrong and what should i do to fix the bug? Or is there a better way to record and do this kind of function? A: To elaborate my suggestion in the comments, I would implement the following algorithm for spending points: * *Find the oldest still valid rows (say A and B) with a sum equal or larger than the required amount (X). How to select rows that sum to a certain value *If such rows do not exist, return an error. *Mark rows A and B as "spent" *Calculate the remaining points (C = A + B - X) *If C == 0 go to the end *Find max expiration date (D) between A and B *Create a new row with expiration date D and amount C. *The end Make sure to wrap all database calls into one transaction, or you could create a room for weird bugs and exploits.
{ "language": "en", "url": "https://stackoverflow.com/questions/60389943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Postman only runs half of the requests in my collection There are 107 requests in my collection folder (postman). This collection was running perfectly fine before with all 107 requests executed. Now, i only see half of the requests running in the collection folder and no error prompted anywhere. is there a limit on how many requests you can run now? or what's the issue?
{ "language": "en", "url": "https://stackoverflow.com/questions/56769444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pass Commands to a Server with C++ I am working on a project utilizes an Android tablet/smartphone as an IP Camera and uses Open CV to process that video feed on a Windows PC. I want to be able to send data back to the phone application depending on the results of the image processing. I have managed to get on to the IP Camera Server URL and post data to the phone by submitting a simple HTML form, but I do not know how to pass data to that form and submit it through C++ (nor do I know if this is even a good method of doing this). I would not consider myself an expert in C++ by any means, and a lot of the resources I could find online were confusing. If you need any of the code from my app, html page, or C++ code just ask! It would be a lot to put up and I do not know what would help. Thanks a million!
{ "language": "en", "url": "https://stackoverflow.com/questions/19817966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UICollectionView received layout attributes for a cell in ios 7 I'm using custom UICollectionView on my app. However, I have a problem that make my app crash. The log for the crash: Note: This bug doesn't occur on iOS 8 2015-05-29 11:49:26.316 app9to5[1834:607] Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView recieved layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0x7fca0e00> {length = 2, path = 0 - 14}' > First throw call stack: ( CoreFoundation 0x039b61e4 __exceptionPreprocess + 180 libobjc.A.dylib 0x036808e5 objc_exception_throw + 44 CoreFoundation 0x039b6048 +[NSException raise:format:arguments:] + 136 Foundation 0x016954de -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116 UIKit 0x02be0866 __45-[UICollectionViewData validateLayoutInRect:]_block_invoke + 1793 UIKit 0x02bdfaed -[UICollectionViewData validateLayoutInRect:] + 1376 UIKit 0x02ba5603 -[UICollectionView layoutSubviews] + 173 UIKit 0x025c8964 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355 libobjc.A.dylib Please help me to resolve. Thank you so much! A: Try invalidating the layout before you call reloadData on collection View. [self.collectionView.collectionViewLayout invalidateLayout]; [self.collectionView reloadData]; A: You should try this: In -(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect you put this: for(NSInteger i=0 ; i < self.collectionView.numberOfSections; i++) { for (NSInteger j=0 ; j < [self.collectionView numberOfItemsInSection:i]; j++) { NSIndexPath* indexPath = [NSIndexPath indexPathForItem:j inSection:i]; [attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]]; } } Hope this could help. A: Or you can do this override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.collectionView.collectionViewLayout.invalidateLayout() }
{ "language": "en", "url": "https://stackoverflow.com/questions/30523728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to hide the textbox and float up when an item is selected from listview? I have a WPF application in which there are certain listview items.Like in the image there are 3 items, A, B, C. initially when user does not select any item, textbox will be hidden. ListView Items when the TextBox is hidden When the user clicks on any of the item, I want a Textbox with description of that item to be displayed. TextBox displays , when items from listview is selected A: Use data binding to bind the visibility flag of the text box to the current selected ListView Item. In your Controller or ViewModel implement a property for the SelectedItem public object SelectedItem { get; set; } Bind it in the ListView to the SelectedItem property <ListView ... SelectedItem={Bining Path=SelectedItem}/> Use a second property to determine if a ListView item is selected public Visibility TextBoxVisibility=> SelectedItem != null ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden; In your xaml bind the Visibility property to the IsSelected property <TextBox ... Visibility={Bining Path=TextBoxVisibility}/> hope this helps. A: Try this in the code behind (MainWindow.xaml.cs): using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace WpfApp7 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private MyViewModel m_MyViewModel; public MainWindow() { InitializeComponent(); m_MyViewModel = new MyViewModel(); myGrid.DataContext = MyVM; } public MyViewModel MyVM { get { return m_MyViewModel; } } } public class MyViewModel : ViewModelBase { public List<string> MyCollection { get { return new List<string> { "A", "B", "C" }; } } private bool isListViewItemSelected; public bool IsListViewItemSelected { get { return isListViewItemSelected; } set { isListViewItemSelected = value; RaisePropertyChanged("IsListViewItemSelected"); } } private string selectedItem; public string SelectedItem { get { return selectedItem; } set { if (value != selectedItem) { selectedItem = value; if (selectedItem == null) { IsListViewItemSelected = false; } else { IsListViewItemSelected = true; } RaisePropertyChanged("SelectedItem"); RaisePropertyChanged("SelectedTxtString"); } } } public string SelectedTxtString { get { //return SelectedItem; return "\"" + SelectedItem + "\" is selected!"; } } } public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable { #region DisplayName /// <summary> /// Returns the user-friendly name of this object. /// Child classes can set this property to a new value, /// or override it to determine the value on-demand. /// </summary> public virtual string DisplayName { get; protected set; } #endregion // DisplayName #region Debugging Aides /// <summary> /// Warns the developer if this object does not have /// a public property with the specified name. This /// method does not exist in a Release build. /// </summary> [Conditional("DEBUG")] [DebuggerStepThrough] public void VerifyPropertyName(string propertyName) { // Verify that the property name matches a real, // public, instance property on this object. if (TypeDescriptor.GetProperties(this)[propertyName] == null) { string msg = "Invalid property name: " + propertyName; if (this.ThrowOnInvalidPropertyName) throw new Exception(msg); else Debug.Fail(msg); } } /// <summary> /// Returns whether an exception is thrown, or if a Debug.Fail() is used /// when an invalid property name is passed to the VerifyPropertyName method. /// The default value is false, but subclasses used by unit tests might /// override this property's getter to return true. /// </summary> protected virtual bool ThrowOnInvalidPropertyName { get; private set; } #endregion // Debugging Aides #region INotifyPropertyChanged Members /// <summary> /// Raised when a property on this object has a new value. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises this object's PropertyChanged event. /// </summary> /// <param name="propertyName">The property that has a new value.</param> protected virtual void RaisePropertyChanged(string propertyName) { VerifyPropertyName(propertyName); PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion // INotifyPropertyChanged Members #region IDisposable Members /// <summary> /// Invoked when this object is being removed from the application /// and will be subject to garbage collection. /// </summary> public void Dispose() { this.OnDispose(); } /// <summary> /// Child classes can override this method to perform /// clean-up logic, such as removing event handlers. /// </summary> protected virtual void OnDispose() { } #endregion // IDisposable Members } } And this in the MainWindow.xaml <Window x:Class="WpfApp7.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp7" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.Resources> <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/> </Window.Resources> <Grid x:Name="myGrid"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <ListView ItemsSource="{Binding MyCollection, Mode=OneWay}" SelectedItem="{Binding SelectedItem}"> </ListView> <TextBox Grid.Row="1" Text="{Binding SelectedTxtString, Mode=OneWay}" Visibility="{Binding IsListViewItemSelected, Converter={StaticResource BooleanToVisibilityConverter}}"/> </Grid>
{ "language": "en", "url": "https://stackoverflow.com/questions/55336729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What properties of sound can be represented / computed in code? This one is probably for someone with some knowledge of music theory. Humans can identify certain characteristics of sounds such as pitch, frequency etc. Based on these properties, we can compare one sound to another and get a measure pf likeliness. For instance, it is fairly easy to distinguish the sound of a piano from that of a guitar, even if both are playing the same note. If we were to go about the same process programmatically, starting with two audio samples, what properties of the sounds could we compute and use for our comparison? On a more technical note, are there any popular APIs for doing this kind of stuff? P.S.: Please excuse me if I've made any elementary mistakes in my question or I sound like a complete music noob. Its because I am a complete music noob. A: There are two sets of properties. The "Frequency Domain" -- the amplitudes of overtones in a specific sample. This is the amplitudes of each overtone. The "Time Domain" -- the sequence of amplitude samples through time. You can, using Fourier Transforms, convert between the two. The time domain is what sound "is" -- a sequence of amplitudes. The frequency domain is what we "hear" -- a set of overtones and pitches that determine instruments, harmonies, and dissonance. A mixture of the two -- frequencies varying through time -- is the perception of melody. A: The Echo Nest has easy-to-use analysis apis to find out all you might want to know about a piece of music. You might find the analyze documentation (warning, pdf link) helpful. A: Any and all properties of sound can be represented / computed - you just need to know how. One of the more interesting is spectral analysis / spectrogramming (see http://en.wikipedia.org/wiki/Spectrogram). A: Any properties you want can be measured or represented in code. What do you want? Do you want to test if two samples came from the same instrument? That two samples of different instruments have the same pitch? That two samples have the same amplitude? The same decay? That two sounds have similar spectral centroids? That two samples are identical? That they're identical but maybe one has been reverberated or passed through a filter? A: Ignore all the arbitrary human-created terms that you may be unfamiliar with, and consider a simpler description of reality. Sound, like anything else that we perceive is simply a spatial-temporal pattern, in this case "of movement"... of atoms (air particles, piano strings, etc.). Movement of objects leads to movement of air that creates pressure waves in our ear, which we interpret as sound. Computationally, this is easy to model; however, because this movement can be any pattern at all -- from a violent random shaking to a highly regular oscillation -- there often is no constant identifiable "frequency", because it's often not a perfectly regular oscillation. The shape of the moving object, waves reverberating through it, etc. all cause very complex patterns in the air... like the waves you'd see if you punched a pool of water. The problem reduces to identifying common patterns and features of movement (at very high speeds). Because patterns are arbitrary, you really need a system that learns and classify common patterns of movement (i.e. movement represented numerically in the computer) into various conceptual buckets of some sort.
{ "language": "en", "url": "https://stackoverflow.com/questions/3365934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is my encryption example secure? A while ago I was developing a little encryption technique to learn more about computer security. Well, this was about 8 months ago now and I kind of never went back to it. That has changed! I'm writing a small asp.net website for my works Intranet where a login system will be needed, so I'm going to want to encrypt the passwords and store them in a database. So, i'll run you through my notes I did a while ago with examples and I'm wondering if I could get some feedback / if what I've done is basically pointless / very insecure (Not counting the fact I'm running you through how it works...) Moving on! The first thing I do is break the inputted string down to each character value, so if for example the user has the password "Hello" it would be broken down as follows... "H" = 104, "E" = 101, "L" = 108, "L" = 108, "O" = 111 The next thing I do is generate a random number, lets just say between 50 and 100 to keep things simple, then I find the nth prime number from that pseudo random number, so if the generated number was 70 it would give me 349 The next thing I do is then add up all the decimal numbers from the converted inputted string. 104 + 101 + 108 + 108 + 111 = 532 Then I multiply the given number by the found nth prime number, so 532 * 349 giving me 185668. Then, that number is stored in the database with the hash (or whatever you call it) - nth prime number - in another column. A: Is this secure? No. Does this protect the users' password? No. It's vulnerable to rudimentary cryptanalysis. For example, with a simple SQL Injection the attacker could get both the "hash" and the prime number. From there, the attacker could simply divide the hash by the prime and get the sum of the characters. The interesting thing here is that while the original password is protected, collisions are not. So the attacker could generate a trivial collision and use it to log into your site. For example, let's say after dividing the "hash" was 532. We could get that same hash by a 7 character string of repeating > characters (">>>>>>>"). Good hash functions have 3 fundamental properties: * *Pre-image resistance (given h(m) it should be hard to find m) *Second-pre-image resistance (given m it should be hard to find n such that h(m) == h(n)) *Collision Resistance (it should be difficult to find a pair of messages such that h(m) == h(n). Your given function only possibly does the first, but only in that there are so many possible permutations (collisions) that it's impossible to tell what the original was... So definitely not. I recommend using approved and vetted crypto, and take the Coursera Cryptography Course.
{ "language": "en", "url": "https://stackoverflow.com/questions/29607917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: 3D model (.gltf format) from a local file is not being read through aframe Please help why the local version of aframe code is not working. from flask import Flask, render_template app = Flask(__name__) @app.route('/') def main(): return render_template('tree1.html') return render_template('tree2.html') 'Version 2 if __name__ == '__main__': app.run(port = 8080) Version 1: tree1.html <!DOCTYPE html> <html> <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script> <!-- we import arjs version without NFT but with marker + location based support --> <script src="https://raw.githack.com/AR-js-org/AR.js/master/aframe/build/aframe-ar.js"></script> <body style="margin : 0px; overflow: hidden;"> <a-scene embedded arjs> <a-marker preset="hiro"> <a-entity position="0 0 0" scale="0.05 0.05 0.05" gltf-model="https://arjs-cors-proxy.herokuapp.com/https://raw.githack.com/AR-js-org/AR.js/master/aframe/examples/image-tracking/nft/trex/scene.gltf" ></a-entity> </a-marker> <a-entity camera></a-entity> </a-scene> </body> </html> Output: Open I show the marker "hiro" in front of the webcame and trex pops up fine. Version2: tree2.html <!DOCTYPE html> <html> <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script> <!-- we import arjs version without NFT but with marker + location based support --> <script src="https://raw.githack.com/AR-js-org/AR.js/master/aframe/build/aframe-ar.js"></script> <body style="margin : 0px; overflow: hidden;"> <a-scene embedded arjs> <a-marker preset="hiro"> <a-entity position="0 0 0" scale="0.05 0.05 0.05" gltf-model="file:///C:/Users/user123/Desktop/scene.gltf" <!--gltf-model="https://arjs-cors-proxy.herokuapp.com/https://raw.githack.com/AR-js-org/AR.js/master/aframe/examples/image-tracking/nft/trex/scene.gltf"--> ></a-entity> </a-marker> <a-entity camera></a-entity> </a-scene> </body> </html> Output: Nothing happens here Appreciate if you can advise how to present the local version of scene.gltf into the AR program in the version 2. A: Even though you are developing locally, the assets still need to be delivered securely and pass the CORS policy to load in a-frame. Your scene is most likely throwing some errors related to not being able to load that file securely, timing out in the process. Ideally you would want to load that gltf file via the asset management system and then reference it in an entity below. Helps avoid scene timeouts and crashing as well. I don't know the Flask environment, but you will want a way to declare a specific asset or a local folder of assets for the app to host(again locally) to be pulled from in your a-scene. Otherwise you may want to look into other local hosting environments like the popular and free XAMPP. A-Frame Asset Management System : https://aframe.io/docs/1.3.0/core/asset-management-system.html#sidebar CORS docs : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS CORS Simplified breakdown exmaple : https://riptutorial.com/aframe/example/30904/cross-origin-resource-sharing--cors- Free Local hosting development application (XAMPP) : https://www.apachefriends.org/index.html Asset Management Test Example : <!DOCTYPE html> <html> <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script> <!-- we import arjs version without NFT but with marker + location based support --> <script src="https://raw.githack.com/AR-js-org/AR.js/master/aframe/build/aframe-ar.js"></script> <body style="margin : 0px; overflow: hidden;"> <a-scene embedded arjs> <!-- Asset management system. --> <a-assets timeout="10000"> <a-asset-item id="sceneAsset" src="file:///C:/Users/user123/Desktop/scene.gltf" preload="auto" crossorigin="anonymous"></a-asset-item> </a-assets> <a-marker preset="hiro"> <a-entity position="0 0 0" scale="0.05 0.05 0.05" gltf-model="#sceneAsset" ></a-entity> </a-marker> <a-entity camera></a-entity> </a-scene> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/73078335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Read Specific Strings from Text File I'm trying to get certain strings out of a text file and put it in a variable. This is what the structure of the text file looks like keep in mind this is just one line and each line looks like this and is separated by a blank line: Date: 8/12/2013 12:00:00 AM Source Path: \\build\PM\11.0.64.1\build.11.0.64.1.FileServerOutput.zip Destination Path: C:\Users\Documents\.NET Development\testing\11.0.64.1\build.11.0.55.5.FileServerOutput.zip Folder Updated: 11.0.64.1 File Copied: build.11.0.55.5.FileServerOutput.zip I wasn't entirely too sure of what to use for a delimiter for this text file or even if I should be using a delimiter so it could be subjected to change. So just a quick example of what I want to happen with this, is I want to go through and grab the Destination Path and store it in a variable such as strDestPath. Overall the code I came up with so far is this: //find the variables from the text file string[] lines = File.ReadAllLines(GlobalVars.strLogPath); Yeah not much, but I thought perhaps if I just read one line at at a time and tried to search for what I was looking for through that line but honestly I'm not 100% sure if I should stick with that way or not... A: If you are skeptical about how large your file is, you should come up using ReadLines which is deferred execution instead of ReadAllLines: var lines = File.ReadLines(GlobalVars.strLogPath); The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient. A: As weird as it might sound, you should take a look to log parser. If you are free to set the file format you could use one that fits with log parser and, believe me, it will make your life a lot more easy. Once you load the file with log parse you can user queries to get the information you want. If you don't care about using interop in your project you can even add a com reference and use it from any .net project. This sample reads a HUGE csv file a makes a bulkcopy to the DB to perform there the final steps. This is not really your case, but shows you how easy is to do this with logparser COMTSVInputContextClass logParserTsv = new COMTSVInputContextClass(); COMSQLOutputContextClass logParserSql = new COMSQLOutputContextClass(); logParserTsv.separator = ";"; logParserTsv.fixedSep = true; logParserSql.database = _sqlDatabaseName; logParserSql.server = _sqlServerName; logParserSql.username = _sqlUser; logParserSql.password = _sqlPass; logParserSql.createTable = false; logParserSql.ignoreIdCols = true; // query shortened for clarity purposes string SelectPattern = @"Select TO_STRING(UserName),TO_STRING(UserID) INTO {0} From {1}"; string query = string.Format(SelectPattern, _sqlTable, _csvPath); logParser.ExecuteBatch(query, logParserTsv, logParserSql); LogParser in one of those hidden gems Microsoft has and most people don't know about. I have use to read iis logs, CSV files, txt files, etc. You can even generate graphics!!! Just check it here http://support.microsoft.com/kb/910447/en A: Looks like you need to create a Tokenizer. Try something like this: Define a list of token values: List<string> gTkList = new List<string>() {"Date:","Source Path:" }; //...etc. Create a Token class: public class Token { private readonly string _tokenText; private string _val; private int _begin, _end; public Token(string tk, int beg, int end) { this._tokenText = tk; this._begin = beg; this._end = end; this._val = String.Empty; } public string TokenText { get{ return _tokenText; } } public string Value { get { return _val; } set { _val = value; } } public int IdxBegin { get { return _begin; } } public int IdxEnd { get { return _end; } } } Create a method to Find your Tokens: List<Token> FindTokens(string str) { List<Token> retVal = new List<Token>(); if (!String.IsNullOrWhitespace(str)) { foreach(string cd in gTkList) { int fIdx = str.IndexOf(cd); if(fIdx > -1) retVal.Add(cd,fIdx,fIdx + cd.Length); } } return retVal; } Then just do something like this: foreach(string ln in lines) { //returns ordered list of tokens var tkns = FindTokens(ln); for(int i=0; i < tkns.Length; i++) { int len = (i == tkns.Length - 1) ? ln.Length - tkns[i].IdxEnd : tkns[i+1].IdxBegin - tkns[i].IdxEnd; tkns[i].value = ln.Substring(tkns[i].IdxEnd+1,len).Trim(); } //Do something with the gathered values foreach(Token tk in tkns) { //stuff } }
{ "language": "en", "url": "https://stackoverflow.com/questions/18256653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Writing to a file in a for loop and def is not defined In Python, This can not loop many times and cannot find ID number in def. Every time I try to run the program I get the error "NameError: name 'askname' is not defined" and in textfile Keep only the latest data * *I expect the output of #def new_booking to be Keep data in files continuously but the actual output is kept data in files just one sentence *I expect the output of #def pre_booked to be Extract data from a file but the actual output is "NameError: name 'askname' is not defined" import random # total=0 # people=0 total1 = 0 total2 = 0 # mini bar def mini_bar(): mini_bar_total = 0 print("£50 for the Bar") askbar = input("Would you like a mini bar? Y/N") if askbar.upper() == "Y": mini_bar_total = mini_bar_total + 50 return mini_bar_total # breakfast def breakfast(people, asknights): breakfast_total = 0 print("£25 for breakfast") askdinner = input("Would you like dinner? Y/N") if askdinner.upper() == "Y": breakfast_total = (people * 25) * asknights print("total: £", breakfast_total) return breakfast_total # dinner def dinner(people, asknights): dinner_total = 0 print("£25 for Dinner") askdinner = input("Would you like dinner? Y/N") if askdinner.upper() == "Y": dinner_total = (people * 25) * asknights return dinner_total # number customers def num_customers(): customer_total = 0 print("£50 an Adult") askadult = int(input("How many adults? ")) customer_total = askadult * 50 print("total: £", customer_total) print("£25 a Child") askchild = int(input("How many children? ")) customer_total = (askchild * 25) + customer_total print("total: £", customer_total) return customer_total, askadult, askchild # number of nights (multiplier) def num_nights(customer_total): nights_total = 0 waiting = True while waiting == True: try: asknights = int(input("How many nights are you staying for? ")) nights_total = customer_total * asknights print("total: £", nights_total) break except ValueError: print("invalid input!") return nights_total, asknights # New Booking ********* def new_booking(): askname = str(input("Please enter your name? ")) idnumber = random.randint(100, 999) customer_total, numAdults, numChild = num_customers() Num_people = numAdults + numChild nights_total, asknights = num_nights(customer_total) askbar = mini_bar() askbreakfast = breakfast(Num_people, asknights) askdinner = dinner(Num_people, asknights) total = askdinner + askbreakfast + askbar + asknights detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner) for i in detailslist: f = open('newbooking.txt', 'w') f.write(str(detailslist) + '\n') print(i) print("your total amount is: £", total) print("your Name & ID number is: ", askname, idnumber) # Pre booking ***** is not defind def pre_booked(): name = input("enter your name or ID number: ") if name == (askname) or (idnumber): detailslist = [idnumber, askname, askadult, askchild, asknights, askbar, askbreakfast, askdinner] for i in detailslist: print(i) print("total: £", total) # main menu, start of program. def main_menu(): print("##################### WELCOME TO BAY HOTEL ###########################") print('''Please see what is available at the Hotel,\nAdult Prices per night: £50pp,\nChild price: £25pp,\nMiniBar price: £50 per room,\nBreakfast: £20pp,\nDinner: £25pp''') while True: prebook = input("Have you booked? Y/N") if prebook.upper() == "N": new_booking() elif prebook.upper() == "Y": pre_booked() main_menu() - I expect the output of #def new_booking to be Keep data in files continuously but the actual output is keep data in files just one sentence - I expect the output of #def pre_booked to be Extract data from file but the actual output is "NameError: name 'askname' is not defined" A: I think it's because your way to writing data in files. Working with files has 3 step: 1) Opening file 2) Read [from] / Write [to] file 3) Closing file third step is what you don't handled it. You want to write a list in file and you are opening that file in each iteration. It's not a good idea (opening and closing files have their overhead) when you can do it once. I changed some of your new_booking function and wrote it here: # New Booking ********* def new_booking(): askname = str(input("Please enter your name? ")) idnumber = random.randint(100, 999) customer_total, numAdults, numChild = num_customers() Num_people = numAdults + numChild nights_total, asknights = num_nights(customer_total) askbar = mini_bar() askbreakfast = breakfast(Num_people, asknights) askdinner = dinner(Num_people, asknights) total = askdinner + askbreakfast + askbar + asknights detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner) # I handled opening and closing file with [python with statement] # It close files automatically at the end with open('newbooking.txt', 'w') as f: for i in detailslist: f.write(str(detailslist) + '\n') print(i) print("your total amount is: £", total) print("your Name & ID number is: ", askname, idnumber) A: The problem here is that you havent actually defined askname in your pre_booked() function so you cant compare against it. In new_booking() you are asking for the username with askname = str(input("Please enter your name? ")) however in the pre_booked() case you dont so you cant use it there without first getting the values from somewhere. Seeing that you save the new_booking() to a file you probably want to load the data from your file like this: accounts = [] with open(r"<FILEPATH", "r") as booking_file: for line in booking_file: accounts.append(line) In your new_booking function it might be better to put all the related data in line by line or maybe even use dicts so you can later be sure which values belong together instead of writing all the values into their own line. So you might want to do this instead: with open('newbooking.txt', 'w') as booking_file: f.write(detailslist) Then you can read line by line and possibly use ´eval()´ to get a list or dictionary right from your string or atleast you know the values in one line belong together later on. You might also want to consider using "a" for append instead of w for write in your bookings file depending if you want to have multiple booking values in your file or just the one.
{ "language": "en", "url": "https://stackoverflow.com/questions/58793235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Death of the Cell processor in the last times I heard lots of people claiming that the Cell processor is dead, mainly due to the following reasons: * *Lack of support in the new playstation 3, as the user can not install linux *The increasing processing power of the GPU's and its costs sinking *The existence of a unified programming approach (openCL) for different GPU's and not for the CBE (well today was announced for the Cell!) *Carency of real world examples of use of the cell (apart from the academic circles) *Global feeling of unsuccess What do you think? If you started two or three years ago to program the cell, will you continue on this or are you considering switching to GPU's? Is a new version of the cell coming? Thanks A: It's easier to write parallel programs for 1000s of threads than it is for 10s of threads. GPUs have 1000s of threads, with hardware thread scheduling and load balancing. Although current GPUs are suited mainly for data parallel small kernels, they have tools that make doing such programming trivial. Cell has only a few, order of 10s, of processors in consumer configurations. (The Cell derivatives used in supercomputers cross the line, and have 100s of processors.) IMHO one of the biggest problems with Cell was lack of an instruction cache. (I argued this vociferously with the Cell architects on a plane back from the MICRO conference Barcelona in 2005. Although they disagreed with me, I have heard the same from bigsuper computer users of cell.) People can cope with fitting into fixed size data memories - GPUs have the same problem, although they complain. But fitting code into fixed size instruction memory is a pain. Add an IF statement, and performance may fall off a cliff because you have to start using overlays. It's a lot easier to control your data structures than it is to avoid having to add code to fix bugs late in the development cycle. GPUs originally had the same problems as cell - no caches, neither I nor D. But GPUs did more threads, data parallelism so much better than Cell, that they ate up that market. Leaving Cell only its locked in console customers, and codes that were more complicated than GPUs, but less complicated than CPU code. Squeezed in the middle. And, in the meantime, GPUs are adding I$ and D$. So they are becoming easier to program. A: Why did Cell die? 1) The SDK was horrid. I saw some very bright developers about scratch their eyes out pouring through IBM mailing lists trying to figure out this problem or that with the Cell SDK. 2) The bus between compute units was starting to show scaling problems and never would have made it to 32 cores. 3) OpenCl was about 3-4 years too late to be of any use. A: I'd say the reasons for the lack of popularity for cell development are closer to: * *The lack of success in the PS3 (due to many mistakes on Sony's part and strong competition from the XBOX 360) *Low manufacturing yield, high cost (partly due to low yield), and lack of affordable hardware systems other than the PS3 *Development difficulty (the cell is an unusual processor to design for and the tooling is lacking) *Failure to achieve significant performance differences compared to existing x86 based commodity hardware. Even the XBOX 360's several year old triple core Power architecture processor has proven competitive, compared to a modern Core2 Quad processor the cell's advantages just aren't evident. *Increasing competition from GPU general purpose computing platforms such as CUDA A: If you started two or three years ago to program the cell, will you continue on this or are you considering switching to GPU's? I would have thought that 90% of the people who program for the Cell processor are not in a position where they can arbitrarily decide to stop programming for it. Are you aiming this question at a very specific development community?
{ "language": "en", "url": "https://stackoverflow.com/questions/1660391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: python mocking open method using mox When I try to mock open method, I am facing issue. Please find the sample code : import glob import re #from __builtin__ import open class DiskManager: def __init__(self): print("Called init method") def __get_xyz_from_serial(self, serial): for host in glob.glob("dir/*/host"): for target in glob.glob(host + "/target*/*/filename"): try: with open(target) as f: serial_num = f.read().strip() except: print("Failed to read : %s " % target) continue serial_num = (unicode(("".join(i for i in serial_num if (32 < ord(i) < 127 ))) .encode("utf8"))) if(serial == serial_num): host_num = re.split(r"(\d+)", host)[1] return host_num print("No host detected") return None Test Method : # - *- coding: utf- 8 - *-i from mox import Mox, IgnoreArg, Func, Comparator, StrContains from mock import patch, Mock, mock_open import unittest #import disk_manager as disk_mgr from disk_manager import DiskManager import __builtin__ import glob import StringIO class DiskManagerTest(unittest.TestCase): def setUp(self): self.mox = Mox() def tearDown(self): self.mox.UnsetStubs() self.mox.ResetAll() def test_hba_serial_using_mox(self): my_text = "¥C010" disk_mgr = DiskManager() #self.mox.StubOutClassWithMocks(disk_mgr,"DiskManager") #self.mox.StubOutWithMock(disk_mgr, "_DiskManager__get_xyz_from_serial") self.mox.StubOutWithMock(glob,"glob") directory_list = ['dir1','dir2'] glob.glob("dir/*/host").AndReturn(directory_list) file_list = ['file3','file2'] #glob.glob(directory_list[0]+ "/target*/*/filename").AndReturn('file1') #glob.glob(directory_list[1]+ "/target*/*/filename").AndReturn('file2') file3 = glob.glob(directory_list[0]+ "/target*/*/filename").AndReturn(file_list) file4 = glob.glob(directory_list[1]+ "/target*/*/filename").AndReturn(file_list) print(file3) my_text = "AAAAAA" self.mox.ReplayAll() self.assertEqual(disk_mgr._DiskManager__get_xyz_from_serial("AAAAAA"), 'file3') self.mox.VerifyAll() For mocking open method I tried : self.mox.StubOutWithMock(__builtin__, 'open') But this does not solved the issue. I am getting this error : File "/usr/lib64/python2.7/linecache.py", line 127, in updatecache with open(fullname, 'rU') as fp: Can someone guide me the correct process to mock file opening. I have tried these combinations : self.mox.StubOutWithMock(__builtin__, 'open') #self.mox.StubOutWithMock(fl, "close") # f1 = self.mox.CreateMockAnything(file) # self.mox.StubOutWithMock(fl, "read") #__builtin__.__call__(IgnoreArg()).AndReturn(f1) #open(file_path).AndReturn("") #__builtin__.open('file3', 'r').AndReturn(f1) # f1.read().AndReturn("C010") #op.open('file1', 'a').AndReturn(f1) # fl.__enter__().AndReturn("010") # f1.read().AndReturn("C010") # fl.__exit__(IgnoreArg(), IgnoreArg(), IgnoreArg()) # f1.close() #open('file1', 'r').AndReturn(StringIO("fake file content")) #open('file2', 'r').AndReturn(StringIO("fake file content")) #open('file3', 'r').AndReturn(StringIO("C010")) Any insight / solution will be appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/57118325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RStudio - blank screen on Mac I got blank screen in RStudio - it's first launch. Got already installed R, tried to reinstall, but it didn't work to me. I already found a lot answers for Windows, but still no solution for OS X with the same problem. OS X 10.10.3 RStudio Desktop 0.99.441
{ "language": "en", "url": "https://stackoverflow.com/questions/30732031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Angularjs pass value from one page to another In the following code i am trying to change to another page on click and want to pass the object i how can i do it. In the following code i get it as undefined.how to go about this <button ng-href="#/page1" value="{{i.display}}"></button> app.controller("ctrls",['$scope','$location',function($scope,$location){ $scope.func = function(i) { $scope.var=i $location.path("/rel"); }; ]); app.controller("ctrls",'$scope',function($scope) { console.log($scope.var) //undefined ]); A: Pages normally have controller(s), a service can be created to share data between pages ( by injecting service in associated controllers). Like: app.factory('myService', function() { var savedData = {} function set(data) { savedData = data; } function get() { return savedData; } return { set: set, get: get } }); In your controller A: myService.set(yourSharedData); In your controller B: $scope.desiredLocation = myService.get(); Happy Helping! A: Use a service (best) https://docs.angularjs.org/guide/services Or $rootScope (bad, but simpler) https://docs.angularjs.org/api/ng/service/$rootScope
{ "language": "en", "url": "https://stackoverflow.com/questions/29099969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL - getting record with maximum value I am trying to retrieve the product with the highest price: SELECT ProductName, Price FROM [Products] ORDER BY Price DESC LIMIT 1 I wanted to know if there is another way of doing this in a more efficient way, with MAX for example. A: Use MAX and GROUP BY SELECT ProductName, MAX(Price) [Price] FROM [Products] GROUP BY ProductName ORDER BY MAX(Price) DESC LIMIT 1; A: I've always done it with the following SELECT top 1 Name FROM tableName ORDER BY Price DESC A: select top 1 * from [Products] order by Price desc A: You can use TOP 1 but you always have to consider the possibility of having a tie, so: SELECT TOP 1 WITH TIES ProductName, Price FROM [Products] ORDER BY Price DESC
{ "language": "en", "url": "https://stackoverflow.com/questions/37132341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unexpected CORS issue for normal images in Chrome and iOS Safari I'm facing a CORS issue that is driving me insane. Allow me to share an example URL: http://www.jungledragon.com/image/19905/mature_female_eastern_forktail.html/zoom As the issue can only be reproduced once per page, here is a list of other images: http://www.jungledragon.com/all/recent From that overview, you can open any photo page. Next, from that photo page click the image once more to launch it fullscreen, as that is where the issue lies. Now allow me to explain the setup, and the problem. The site itself is hosted on a Linux server within my control. The site is at www.jungledragon.com. The images, however, are stored at Amazon S3, where the image bucket has an alias of media.jungledragon.com. The basic situation is simple: <div id="slideshow-image-container"> <div class="slideshow-image-wrapper"> <img src="http://media.jungledragon.com/images/1755/19907_large.jpg?AWSAccessKeyId=05GMT0V3GWVNE7GGM1R2&Expires=1409788810&Signature=QH26XDrVuhyr1Qimd7IOBsnui5s%3D" id="19907" class="img-slideshow img-sec wide" data-constrained="true" data-maxheight="2056" crossorigin="anonymous"> </div> </div> As you can see, I'm just using the normal 'html' way of loading an image. The image URL is signed and can time out, but that shouldn't be relevant. It is my understanding that CORS does not apply to this situation, since loading images from an external domain this way has been supported for decades. The image is not loaded using javascript, after all. Just to be sure though, the crossorigin attribute is set in HTML. Furthermore, as a way of testing, I have set a very liberal CORS policy on the image bucket: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Content-Type</AllowedHeader> <AllowedHeader>x-amz-acl</AllowedHeader> <AllowedHeader>origin</AllowedHeader> </CORSRule> </CORSConfiguration> Now, the situation gets a bit more complicated. The fullscreen image viewer is supposed to get a background color that is the dominant/average color of the actual image on screen. That color is calculated using canvas, yet it is only calculated once. The first time it is calculated for that image, the result is communicated to the back-end using an ajax call and then stored forever. Subsequent visits to the image will not run the calculation logic again, it will simply set the background color of the body element and all is good. Here is the logic that does the calculation: <script> $( document ).ready(function() { <?php if (!$bigimage['dominantcolor']) { ?> $('#<?= $bigimage['image_id'] ?>').load(function(){ var rgb = getAverageRGB(document.getElementById('<?= $bigimage['image_id'] ?>')); document.body.style.backgroundColor = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')'; if (rgb!==false) { $.get(basepath + "image/<?= $bigimage['image_id'] ?>/setcolor/" + rgb.r + "-" + rgb.g + "-" + rgb.b); } }); <?php } ?> }); Yes, I'm mixing in back-end code with front-end code. The above code says that if we do not yet know the dominant color in the scene, calculate it. The load function is used because at document ready, the actual image from the normal html may not have been loaded completely. Next, if the dominant color is not known yet, and the image is loaded, we trigger the function that calculates the dominant color. Here it is: function getAverageRGB(imgEl) { var blockSize = 5, // only visit every 5 pixels defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs canvas = document.createElement('canvas'), context = canvas.getContext && canvas.getContext('2d'), data, width, height, i = -4, length, rgb = {r:0,g:0,b:0}, count = 0; if (!context) { return defaultRGB; } height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height; width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width; imgEl.crossOrigin = "anonymous"; context.drawImage(imgEl, 0, 0); try { data = context.getImageData(0, 0, width, height); } catch(e) { /* security error, img on diff domain */ return false; } length = data.data.length; while ( (i += blockSize * 4) < length ) { ++count; rgb.r += data.data[i]; rgb.g += data.data[i+1]; rgb.b += data.data[i+2]; } // ~~ used to floor values rgb.r = ~~(rgb.r/count); rgb.g = ~~(rgb.g/count); rgb.b = ~~(rgb.b/count); return rgb; } The following line is CORS-relevant: data = context.getImageData(0, 0, width, height); Although I believe I have set up CORS correctly, I can live with this code failing in some browsers. It seems to work fine in Firefox and IE11, for example. If it fails, I would expect it to fail calculating the dominant color. However, something far worse is happening in highly specific cases: the image is not shown alltogether. My thinking is that my 'classic' loading of the image via img src tags should have nothing to do with this script working or failing, in all cases at least the image should just load, irrespective of the canvas trick. Here are the situations I discovered where the image does not load alltogether, which I consider a major issue: On iOS7 on iPhone 5, the first load works fine. The calculation may fail but the image loads. Refreshing the page often breaks the image. 3rd and 4th tries then continue to succeed, and so on. Worse, at work in Chrome 36 the image does not load alltogether. I say at work, since at home it is not an issue. Possibly a proxy makes the difference. I can refresh all I want, for images that do not have the calculation ran yet, it keeps failing. The natural thing to do then is to debug it using Chrome's inspector. Guess what? With the inspector open, it always succeeds. The image will always load and the CORS request headers and responses look perfectly fine. This leaves me with virtually no way to debug this. I can tell though that when opening the inspector when the image does not load does give me the "CORS error" in the console, from the previous request I made. Refreshing with the inspector open will then make that go away. From reading other questions I've learned that cache may be an influence, yet more likely the issue lies in the origin header not sent by the browser. I believe the issue may be in that direction, yet I fail to understand this: * *How it influences my "normal" loading of the image using img tags *How it is only an issue behind a proxy (supposedly) in Chrome, and only when the inspector windows is closed *How it works so unreliably and inconsistently in Safari on iOS As said, I can live with only some browsers succeeding with the canvas part, but I can't live with the image not being normally loaded in any case. That part should just work. I realize the situation is incredibly hard for you to debug, but I hope my explanation triggers some much-needed help. Update: I've discovered that when I remove crossorigin="anonymous" from the img tag, the image will load correctly in the specific scenarios I mentioned. However, the consequence of that move is that the color calculation will no longer work in Chrome, not at home and not at work. It continues to work in Firefox though. I'm investigating what to do next. A: I managed to solve the issue myself. I still cannot fully explain cause and effect here, but this is what I did: I removed crossorigin="anonymous" from the html's img element. This will at least make sure that the image is always loaded. The color calculation part I solved by basically rewriting its logic: var imgSrc = $('#<?= $bigimage['image_id'] ?>').attr('src'); var cacheBurstPrefix = imgSrc.indexOf("?") > -1 ? '&' : '?'; imgSrc += cacheBurstPrefix + 'ts=' + new Date().getTime(); var imagePreloader = new Image(); imagePreloader.crossOrigin = "Anonymous"; imagePreloader.src = imgSrc; $(imagePreloader).imagesLoaded(function() { var rgb = getAverageRGB(imagePreloader); document.body.style.backgroundColor = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')'; if (rgb!==false) { $.get(basepath + "image/<?= $bigimage['image_id'] ?>/setcolor/" + rgb.r + "-" + rgb.g + "-" + rgb.b); } }); Instead of reusing the img element from the html, I'm creating a new in-memory image element. Using a cache bursting technique I'm making sure it is freshly loaded. Next, I'm using imagesLoaded (a 3rd party plugin) to detect the event of this in-memory image being loaded, which is far more reliable than jQuery's load() event. I've tested extensively and can confirm that in no case does normal image loading ever break again. It works in every browser and proxy situation. As an added bonus, the color calculation part now seems to work in far more browsers, including several mobile browsers. Although I am still not confident on the root cause, after much frustration I'm very happy with the new situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/25024403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why would I want to pay my webhost for a MS SQL database over a MySQL database? I'm in the market for an ASP.NET host to start learning on and to host personal projects. I've noticed most of them provided both MySQL and MS SQL databases. However, usually they will only provided a couple MS SQL databases, but a large number (like 10) MySQL Databases. Can I use a MySQL database as a back end to a ASP.NET website? If so why would I want to pay extra to use MS SQL over MySQL? A: Yes you can use MySQL to drive a website using ASP.NET or any other web development technology for that matter. The reason for choosing SQL Server over MySQL would if there were features or performance characteristics you wanted in SQL Server that did not exist in MySQL. For example, common-table expressions do not exist in MySQL. If there are no features in either that are driving your decision, then it comes down to personal preference and cost. A: If you're more comfortable with Sql Server then clearly it'd be worth going down that route, for a small scale site it really does come down to personal preference. That said there are things such as the asp.net membership providers that come, by default, with support for Sql Server as opposed to MySql so that could be a deciding factor for you. Ultimately, it comes down to personal choice. Which do you prefer and are you willing to pay if Sql Server is your preference?
{ "language": "en", "url": "https://stackoverflow.com/questions/3592579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to print the exception in selenium and testng I have an issue that I am facing in java and selenium and testng. I am trying to locate an element, and in the test I made a mistake and the element not exists (xpath not returned answer). The problem is that the exception i printed is not the full selenium exception,(I want to be printed that the element not exists or something regarding selenium) ** the problem is in the clickelementwhenclickable method, that not find the element, however not print the full exception Here is my Code: this is the most basic method that click on element (): public void ClickElementWhenClickable(By locator) throws Exception { WebDriver driver = getWebDriver(); driver.manage().timeouts().implicitlyWait(IMPLICIT_WAITE, SECONDS); Instant now = Instant.now(); while (Instant.now().isBefore(now.plusSeconds(IMPLICIT_WAITE))) { try { new WebDriverWait(driver, IMPLICIT_WAITE).until(ExpectedConditions.elementToBeClickable(locator)).click(); return; } catch (WebDriverException e) { // do nothing, loop again } } throw new Exception("Not able to click element <" + locator + "> within " + IMPLICIT_WAITE + "s."); } this is the method that I use in the page that do something: public void selectCountry(String country,String index) throws Exception { By locator; openCountryList(index); String xpath; xpath = String.format(SELECT_FROM_DROPDOWN, country); locator = By.xpath(xpath); log.info("\n*******************************************\n try to select : " + country + " from country list " + locator.toString() + "\n*******************************************\n" ); ClickElementWhenClickable(locator); } this is the test that run the method: @Test(groups = {"supply", "ui"}, enabled = true, priority = 20) //20. public void enterDeviceTypeForVideoChild1() throws Exception { try { placementPage().scrollDown(); placementPage().SelectDeviceType(placementDataObject.getGeoBidFloors().get(4).getDeviceType().deviceTypeValue(),"5"); } catch (Exception ex) { Assert.fail("Error enter device type:\n " + ex.toString()); } } and this is the exception when the test failed, that is without unable to locate element: java.lang.AssertionError: Error enter device type: java.lang.Exception: Not able to click element <By.xpath: //li[contains(text(),'ctv')]> within 35s. at org.testng.Assert.fail(Assert.java:97) at tests.ExPubPlacementPageTest.enterDeviceTypeForVideoChild1(ExPubPlacementPageTest.java:278) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:134) at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:597) at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173) at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46) at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:816) at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146) at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128) at java.util.ArrayList.forEach(ArrayList.java:1249) at org.testng.TestRunner.privateRun(TestRunner.java:766) at org.testng.TestRunner.run(TestRunner.java:587) at org.testng.SuiteRunner.runTest(SuiteRunner.java:384) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337) at org.testng.SuiteRunner.run(SuiteRunner.java:286) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187) at org.testng.TestNG.runSuitesLocally(TestNG.java:1109) at org.testng.TestNG.runSuites(TestNG.java:1039) at org.testng.TestNG.run(TestNG.java:1007) at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66) at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110) The problem that that the actual exception is not printed, unable to locate element. so this print is useless,How can I print the exception of selenium? A: I believe that you are looking for testNG listener( ITestListener ). you will have to implement the ITestListener and in that you will have to override the method called as onTestFailure. Please check the below code out. import org.testng.ITestListener; import org.testng.ITestResult; public class TestNGListener implements ITestListener { public void onTestFailure(ITestResult result) { System.out.println(result.getThrowable().getMessage()); } } A: You can use printStackTrace() method of the java.lang.Throwable class, which is used to print this Throwable along with other details like class name and line number where the exception occurred. try { testException1(); } catch (Throwable e) { // print stack trace e.printStackTrace(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/61754931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lazy-loaded singleton: Double-checked locking vs Initialization on demand holder idiom I have a requirement to lazy-load resources in a concurrent environment. The code to load the resources should be executed only once. Both Double-checked locking (using JRE 5+ and the volatile keyword) and Initialization on demand holder idiom seems to fit the job well. Just by looking at the code, Initialization on demand holder idiom seems cleaner and more efficient (but hey, I'm guessing here). Still, I will have to take care and document the pattern at every one of my Singletons. At least to me, It would be hard to understand why code was written like this on the spot... My question here is: Which approach s is better? And why? If your answer is none. How would you tackle this requirement in a Java SE environment? Alternatives Could I use CDI for this without imposing it's use over my entire project? Any articles out there? A: To add another, perhaps cleaner, option. I suggest the enum variation: What is the best approach for using an Enum as a singleton in Java? A: As far as readability I would go with the initialization on demand holder. The double checked locking, I feel, is a dated and an ugly implementation. Technically speaking, by choosing double checked locking you would always incur a volatile read on the field where as you can do normal reads with the initialization on demand holder idiom. A: Initialisation-on-demand holder only works for a singleton, you can't have per-instance lazily loaded elements. Double-checked locking imposes a cognitive burden on everyone who has to look at the class, as it is easy to get wrong in subtle ways. We used to have all sorts of trouble with this until we encapsulated the pattern into utility class in our concurrency library We have the following options: Supplier<ExpensiveThing> t1 = new LazyReference<ExpensiveThing>() { protected ExpensiveThing create() { … // expensive initialisation } }; Supplier<ExpensiveThing> t2 = Lazy.supplier(new Supplier<ExpensiveThing>() { public ExpensiveThing get() { … // expensive initialisation } }); Both have identical semantics as far as the usage is concerned. The second form makes any references used by the inner supplier available to GC after initialisation. The second form also has support for timeouts with TTL/TTI strategies. A: Initialization-on-demand holder is always best practice for implementing singleton pattern. It exploits the following features of the JVM very well. * *Static nested classes are loaded only when called by name. *The class loading mechanism is by default concurrency protected. So when a thread initializes a class, the other threads wait for its completion. Also, you don't have to use the synchronize keyword, it makes your program 100 times slower. A: I suspect that the initialization on demand holder is marginally faster that double-checked locking (using a volatile). The reason is that the former has no synchronization overhead once the instance has been created, but the latter involves reading a volatile which (I think) entails a full memory read. If performance is not a significant concern, then the synchronized getInstance() approach is the simplest.
{ "language": "en", "url": "https://stackoverflow.com/questions/6189099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Perl regex for a digit/letter combination I'm looking for a perl regex for a combination of digits and letters, with allowing for spaces and "/" and "-" characters as possible separators. Basically, I want it to match expressions that contain a combination of letters and digits and/or separators, like this: ATG567A ATG56-7A ATG56/7A ATG56 7A But not this: ATG-A <---- letters and/or separators only 567/7 <---- digits and/or separators only A: If you're trying to validate a string, it's simpler to do it as multiple checks. m{^[A-Za-z0-9 /-]*\z} && /[A-Za-z]/ && /[0-9]/ Those can be combined into one pattern, but I advice against it. m{^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9 /-]*\z}s On the other hand, if you're trying to extract from a string, you'll need the following: m{ [ /-]*+ (?: [A-Za-z] [A-Za-z /-]*+ [0-9] | [0-9] [0-9 /-]*+ [A-Za-z] ) [A-Za-z0-9 /-]*+ }x
{ "language": "en", "url": "https://stackoverflow.com/questions/18963918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Powershell crashes on startup Ok, my powershell crashes on startup. System.TypeInitializationException: The type initializer for 'System.Management.Automation.TypeAccelerators' threw an exception. ---> System.Runtime.InteropServices.SEHException: External component has thrown an exception. at System.Management.Automation.CoreTypes.<>c.<.cctor>b__2_0() at System.Lazy`1.CreateValue() at System.Lazy`1.LazyInitValue() at System.Management.Automation.TypeAccelerators..cctor() --- End of inner exception stack trace --- at System.Management.Automation.Runspaces.EarlyStartup.<>c.<Init>b__0_1() at System.Threading.Tasks.Task.Execute() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot) at System.Threading.Tasks.Task.ExecuteEntry(Boolean bPreventDoubleExecution) at System.Threading.ThreadPoolWorkQueue.Dispatch() Any help? It just bassicly crashes. Nothing else. Please i need it.
{ "language": "en", "url": "https://stackoverflow.com/questions/62776824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: javascript code partially not executed in test environment, works in production, development (Rails 3 app) Rails 3 I have a list inside a form: <%= form_for @article do |f| %> <ul> <% @product.each do |p| %> <li id="product_<%=p.id%>"> <div> <%= f.radio_button(:p_id, p.id, class: 'hidden') %> </div> </li> <% end %> </ul> <%= f.submit 'submit', :id=>"submit_category", :class=>'hide' %> <% end %> I added a javascript function so that when the user clicks on the li element, the radio button is selected and the form is submitted. <script type="text/javascript"> $('li').click(function() { $(this).find('input[type=radio]').attr('checked', true); $('#submit_category').click(); }); </script> This works perfectly in production, development, but the test environment fails: the form IS submitted, but the radio button is not selected, so I get a validation error. My tests are done with Cucumber + Selenium + Capybara. Line of testing: When /^I click on the "(.*?)" product$/ do |product_name| @product = Product.find_by_name(product_name) page.find('li', id: "product_#{@p.id}").click end A: Guessing here, but does wrapping the code a $(function () { ..your code }) (domready) callback help?
{ "language": "en", "url": "https://stackoverflow.com/questions/12504679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET MAUI Android button pressed effect Is there a way to change the pressed effect of a button on Android in a .NET MAUI project. Now it is showing a dark ripple effect when dark mode is on and a white ripple effect when the light mode is on. I would like to have the same ripple color for both dark and light mode. I tried to change the colorPrimary and colorPrimaryDark values but nothing changes. A: The simplest way to achieve parity in both modes (and potentially across platforms) might be to override the button's default style with your own. You can look into the default button style template, make a copy in you apps resources, and change the colors used to from default staticresource or dynamicresource to your desired color palette.
{ "language": "en", "url": "https://stackoverflow.com/questions/75245604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to cache object using pickle in __new__ method? I'd like to cache an object in __new__ method so that it can load the cache when a new object is constructed, but now the following code will got an exception: RecursionError: maximum recursion depth exceeded while calling a Python object I have no idea about how to break the recursion import pickle class Cache: def __init__(self): self.d = {} def __setitem__(self, obj, val): self.d[obj] = pickle.dumps(val) def __getitem__(self, obj): return pickle.loads(self.d[obj]) class Car: cache = Cache() def __reduce__(self): return (self.__class__, (self.name,)) def __new__(cls, name): try: return cls.cache[name] except KeyError: return cls.new(name) @classmethod def new(cls, name): car = object.__new__(cls) car.init(name) cls.cache[name] = car return car def init(self, name): self.name = name def __repr__(self): return self.name a = Car('audi') b = Car('audi') A: Have a try. This may fix this, but it may not be the proper solution. If anyone have any better idea, feel free to leave comments. Just remove the __reduce__ method. Then implement __getnewargs__ and __getnewargs_ex__ import pickle class Cache: def __init__(self): self.d = {} def __setitem__(self, obj, val): self.d[obj] = pickle.dumps(val) def __getitem__(self, obj): return pickle.loads(self.d[obj]) def __contains__(self, x): return x in self.d class Car: cache = Cache() def __new__(cls, name, extra=None, _FORCE_CREATE=False): if _FORCE_CREATE or name not in cls.cache: car = object.__new__(cls) car.init(name) car.extra = extra cls.cache[name] = car return car else: return cls.cache[name] def init(self, name): self.name = name def __repr__(self): return self.name def __getnewargs__(self): return (self.name, None, True) def __getnewargs_ex__(self): # override __getnewargs_ex__ and __getnewargs__ to provide args for __new__ return (self.name, ), {"_FORCE_CREATE": True} a = Car('audi', extra="extra_attr") b = Car('audi') print(id(a), a.extra) # 1921399938016 extra_attr print(id(b), b.extra) # 1921399937728 extra_attr
{ "language": "en", "url": "https://stackoverflow.com/questions/68878621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opening android app from browser: How to specify URI-path/HOST in intent URI? I want to open an android app from the browser. I also want to pass a specific host URL (https://example.com/mypath) to the intent. My app already has an intent-filter that I'm referencing here. I'm using the following intent URI to open the app. intent://example.com/mypath#Intent;scheme=my_scheme;package=my_package;action=my_action;end" But this doesn't work. Is this the correct way to write the host URL in the intent-URI?
{ "language": "en", "url": "https://stackoverflow.com/questions/63980857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: intellij macro or live template to get breadcrumb in the clipboard or directly in template intellij has the cool breadcrumb that is shows on/below the editor window. is there a cool way to get this breadcrumb in clipboard? for example ctrl+alt+shift+C gets the file path with line number. so is there a way to copy the breadcrumb? basically i want to create my own live template/macro for a shortcut logger.info("xxx - " + breadcrumb) i already have my live template doingth the above minus the breadcrumb part A: You can get current file path as either absolute or relative using groovyScript macro: _editor variable is available inside the script. This variable is bound to the current editor. The _editor is an instance of EditorImpl which holds a reference to the VirtualFile that represents the currently opened file. Therefore, the following script gets the full path of currently opened file. groovyScript("_editor.getVirtualFile().getPath()") Or if you want to get the path relative to the project's root: groovyScript("_editor.getVirtualFile().getPath().replace(_editor.getProject().getBaseDir().getPath(), \"\")") see: Current file path in Live Template
{ "language": "en", "url": "https://stackoverflow.com/questions/45218041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: questionnaire with feedback redirect based on score I would like to add to my site a simple questionnaire with few multiple choice questions. Each question has a score and at the end tha user is redirected to a custom page based on overall score. Can somebody recommend me such php or javascript script or any other possible solution? Thank you A: Just so you know, you are not supposed to ask people to give you a code in this site. You should try to make your own first, and if you get any problems then ask for help. But, as far as your a php script for questions, then here is a an entire source code, from elanman. http://blog.elanman.com/elanzips/php-quiz.zip You also have the famous hotscripts, check it out here: http://www.hotscripts.com/category/scripts/php/scripts-programs/tests-quizzes/
{ "language": "en", "url": "https://stackoverflow.com/questions/14034113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EasyPHP custom java extension I am using EasyPHP for test purposes, and I wish to apply an XSLT 2.0 processor in my php code. EasyPHP 5.3.9 standard xslt processor is of 1.0 version though. What do I have to do to apply the xslt processor in Saxon9he.jar or XSLT2Processor.jar (found on sourceforge.net)? Stuff I would like to know: * *which directory to place the jar in *where to change config to include the jar (probably using extension functionality) *what to put into code in order to declare new instance of xslt processor Code I am currently using <?php $XML = new DOMDocument(); $XML->load('test.xml'); $xslt = new XSLTProcessor(); $XSL = new DOMDocument(); $XSL->load('test.xslt'); $xslt->importStylesheet( $XSL ); print $xslt->transformToXML( $XML ); ?> which errors because I have an XSLT 2.0 version stylesheet. The errors I get are like Warning: XSLTProcessor::importStylesheet() [xsltprocessor.importstylesheet]: compilation error: file file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www/test.xslt line 99 element function in C:\Program Files (x86)\EasyPHP-5.3.9\www\test.php on line 7
{ "language": "en", "url": "https://stackoverflow.com/questions/11011649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: string.IsNullOrEmpty(string)' has some invalid arguments I converted MVC 3.5 to MVC2 4.0, get an error The best overloaded method match for 'string.IsNullOrEmpty(string)' has some invalid arguments Here is my code: <% if (this.Model.VisitId == 0) { %> mustSave = true; <% } else { %> mustSave = false; <% } %> <% if (String.IsNullOrEmpty(Html.ValidationSummary())) { %> dataChanged = false; <% } else { %> dataChanged = true; <% } %> Thanks in advance A: In .net 4.0. ValidationSummary returns MvcHtmlString not string as with 3.5. A: Html.ValidationSummary() returns MvcHtmlString, not a normal string. So, try this: <% if (MvcHtmlString.IsNullOrEmpty(Html.ValidationSummary())) { %> A: Thanks folks. This topic helped me when I encountered the same error: "Message":"The best overloaded method match for 'string.IsNullOrEmpty(string)' has some invalid arguments","Data":null,"InnerException":null,"HelpURL":null It happened to me that I passed a dynamic object into string.IsNullOrEmpty(), where the parameter was type of JValue rather than string at runtime. So I have to firstly explicitly convert the parameter to string: var isValid = !string.IsNullOrEmpty(obj.Value); It is a similar case with MvcHtmlString. A: In the new MVC, the Html.ValidationSummary() returns a MvcHtmlString, not a normal string. You could use ValidationSummary().ToString() or ToHtmlString() to make it a string.
{ "language": "en", "url": "https://stackoverflow.com/questions/4219882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android auto update using playstore I have an Android application that is uploaded to play store. I need to use playstore to update the app, that is when there is an update for the app, I should send the user to the play store. My problem is that there is always an "Open" button in play store, and I never see "Update" button, even if I have two different versions, one on the phone and the other on the play store. And also please one more question, is this the best way to update the app? Is it the standard way? Thanks, A: Theres a few steps you'll need to follow in order to update your application on google play store, at first Version your application : http://developer.android.com/tools/publishing/versioning.html 2nd step is to sign the application for the first time : http://developer.android.com/tools/publishing/app-signing.html and the 3rd step is to update the version of your application on play store : https://support.google.com/googleplay/android-developer/answer/113476?hl=en in the last link you will guidance on how to check the application signature and if they match the previous version signature. A: I solved it! My mistake, I was trying to check the update without signing the application (I copied it directly from the bin!) Thanks,
{ "language": "en", "url": "https://stackoverflow.com/questions/34580671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Array object to php using ajax How can i send data like this to php using ajax ["{"title":"mr","fname":"john","lname":"Annah","oname":"Clement","staffid":"123"}"] A: try json_encode for more refer - http://php.net/manual/en/function.json-encode.php A: stringify before sending Eg : var postData = [ { "id":"1", "name":"bob"}, { "id":"2", "name":"jonas"}] this works, $.ajax({ url: Url, type: 'POST', contentType: 'application/json', data: JSON.stringify(postData) //stringify is important, }); A: Do it like so, using jQuery(which you need to include in your script): <script> var data={}; data= { "title":"mr", "fname":"john", "lname":"Annah", "oname":"Clement", "staffid":"123"}; $.ajax({ url:"somwhere.php", type:"POST", dataType:"JSON", data:data, async: true}); </script> And on the page where you want to catch this data, do it like this: <?php $title=$_POST['title']; $fname=$_POST['fname']; ?> And so on. A: Try this $(document).on("click", "#your element", function () { $.ajax({ type: 'POST', url: "your_url", data : {"title":"mr","fname":"john","lname":"Annah","oname":"Clement","staffid":"123"},, success: function (result) { ### your action after ajax }, }) }) A: you can pass it in data like this, $.ajax({ url: 'url', type: 'GET', data: { title:"mr",fname:"john",lname:"Annah",oname:"Clement",staffid:"123" } , contentType: 'application/json; charset=utf-8', success: function (response) { //your success code } });
{ "language": "en", "url": "https://stackoverflow.com/questions/35264211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to create two columns of cardviews in xml I want to create two columns of social media contact list cardviews in xml android kotlin. I want to apply cardview to each Email, Github, LinkedIn, Instagram and Twitter contact list. How can I achieve this? I tried this, but the cardview is applied to the whole list, instead of individual cardviews.
{ "language": "en", "url": "https://stackoverflow.com/questions/74583760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails CXF plugin not found I am trying to implement SOAP services in my app, the best plugin I found is CXF, but I couln't install it, it looks like that I should put some additional repository. I raised an issue in the source page, but if someone has faced this before, can share the solution plz? A: If you are trying to use version 3.1.2 of the plugin, you want org.grails.plugins:cxf:3.1.2, not org.grails.plugins:grails-cxf:3.1.2. A: The problem is that the plugin's documentation talks about to use the version 3.1.2, but the latest version in the repository is the 3.0.9
{ "language": "en", "url": "https://stackoverflow.com/questions/64350481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to use AWS as a web host? Is it possible to load / host an entire website using AWS? Or is it only a service that can load specific pieces of a website - such as images, etc. Obviously, I'd want to use my own domain. If you can use it, are there any limitations? Here's the AWS link, for context: http://aws.amazon.com/s3/ A: As @danben mentioned, there is a difference between S3 and EC2. One thing that may be interesting for people looking to host a website on Amazon, specially if they want to start small is that Amazon started offering a free tier some months ago. Together with services like BitNami Cloud Hosting (disclaimer, I helped design it, so it is a bit like my baby :) means you can get your site on the Amazon cloud in just minutes, for basically 0 dollars. You still need to give credit card info to Amazon, but it will not be charged if you stay within the limits of their free tier. One thing to consider too is that at the time of writing this (Jul 2011), Amazon restricts you to one IP address per server. If you need to host multiple domains, you may need to use name-based virtual hosts or some tricks using their Elastic Load Balancer (which will cost you more). But all in all, it is worth a try if you are a bit technical and want more control than what shared hosting provides you A: AWS = Amazon Web Services = a suite of different web services. S3 (which you linked to) is an object store. You can't host a web service on S3. EC2, also under the AWS umbrella, is virtualized compute space. You CAN host a web service on EC2. It is just like having a server in a rack somewhere, except that when you shut down an instance, it is gone forever. But using EBS, which is like a virtualized hard drive, will prevent you from losing your data when the EC2 instance shuts down. See http://aws.amazon.com/ec2/ and http://aws.amazon.com/ebs/ A: EDIT: Aug 12, 2016 they have a dedicated section on how to get started hosting a website on AWS. Please note S3 only allows STATIC websites but AWS provides SDKs in case you want to run PHP, ASP.NET, etc on your instance. See the links for more details. http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html https://aws.amazon.com/websites/ So guess what I just found while doing some Google searches for hosting on AWS?! A blog post by the AWS stating that you can (now) host a website on S3. (Funny enough, the StackOverflow and the AWS post were right next to each other in the SERPs!) http://aws.typepad.com/aws/2011/02/host-your-static-website-on-amazon-s3.html A: Yes it is completely possible to host websites on AWS in 2 ways: 1.) Easy - S3 (Simple Storage Solution) is a bucket storage solution that lets you serve static content e.g. images but has recently been upgraded so you can use it to host flat .html files and your site will get served by a default Apache installation with very little configuration on your part (but also little control). 2.) Trickier - You can use EC2 (Elastic Compute Cloud) and create a virtual Linux instance then install Apache/NGinx (or whatever) on that to give you complete control over serving whatever/however you want. You use SecurityGroups to enable/disable ports for individual machines or groups of them. @danben your EC2 instance does not have a constant public IP by default. Amazon makes you use a CNAME - not an A record as your IP may change under load. You have to pay for an ElasticIP to get a consistent public IP for your setup (or use some sort of DynDNS) A: At reinvent 2018, AWS launched the Amplify Console, a continuous deployment and hosting service for single page and static apps with serverless backends. Check it out: http://console.amplify.aws A: Yes! You can easily host your website on AWS. There are two ways; * *One with Native AWS - This is a tricky method that requires expertise and a series of commands to run. You need to manage security, DNS, SSL, server protocols, and more by yourself. *Managed Cloud Platforms like Cloudways - You can easily launch an AWS server and host your website with a few clicks. Moreover, you can quickly manage your server protocols, packages, security firewalls, DNS, and more from its intuitive platform.
{ "language": "en", "url": "https://stackoverflow.com/questions/2113370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 I want to make an logharitmic fit. But I keep getting the a runtime error: Optimal parameters not found: Number of calls to function has reached maxfev = 1000 I use the following script. Can anyone tell me where I go wrong? I use Spyder an am still a beginner. import math import matplotlib as mpl from scipy.optimize import curve_fit import numpy as np #data F1=[735.0,696.0,690.0,683.0,680.0,678.0,679.0,675.0,671.0,669.0,668.0,664.0,664.0] t1=[1,90000.0,178200.0,421200.0,505800.0,592200.0,768600.0,1036800.0,1371600.0,1630800.0,1715400.0,2345400.0,2409012.0] F1n=np.array(F1) t1n=np.array(t1) plt.plot(t1,F1,'ro',label="original data") # curvefit def func(t,a,b): return a+b*np.log(t) t=np.linspace(0,3600*24*28,13) popt, pcov = curve_fit(func, t, F1n, maxfev=1000) plt.plot(t, func(t, *popt), label="Fitted Curve") plt.legend(loc='upper left') plt.show() A: Scipy's curve_fit() uses iterations to search for optimal parameters. If the number of iterations exceeds the default number of 800, but the optimal parameters are still not found, then this error will be raised. Optimal parameters not found: Number of calls to function has reached maxfev = 800 You can provide some initial guess parameters for curve_fit(), then try again. Or, you can increase the allowable iterations. Or do both! Here is an example: popt, pcov = curve_fit(exponenial_func, x, y, p0=[1,0,1], maxfev=5000) p0 is the guess maxfev is the max number of iterations You can also try setting bounds which will help the function find the solution. However, you cannot set bounds and a max_nfev at the same time. popt, pcov = curve_fit(exponenial_func, x, y, p0=[1,0,1], bounds=(1,3)) Source1: https://github.com/scipy/scipy/issues/6340 Source2: My own testing and finding that the about github is not 100% accurate Also, other recommendations about not using 0 as an 'x' value are great recommendations. Start your 'x' array with 1 to avoid divide by zero errors. A: Curve_fit() uses iterations to search for optimal parameters. If the number of iterations exceeds the set number of 1000, but the optimal parameters are still not available, then this error will be raised. You can provide some initial guess parameters for curve_fit(), then try again. A: Your original data is t1 and F1. Therefore curve_fit should be given t1 as its second argument, not t. popt, pcov = curve_fit(func, t1, F1, maxfev=1000) Now once you obtain fitted parameters, popt, you can evaluate func at the points in t to obtain a fitted curve: t = np.linspace(1, 3600 * 24 * 28, 13) plt.plot(t, func(t, *popt), label="Fitted Curve") (I removed zero from t (per StuGrey's answer) to avoid the Warning: divide by zero encountered in log.) import matplotlib.pyplot as plt import scipy.optimize as optimize import numpy as np # data F1 = np.array([ 735.0, 696.0, 690.0, 683.0, 680.0, 678.0, 679.0, 675.0, 671.0, 669.0, 668.0, 664.0, 664.0]) t1 = np.array([ 1, 90000.0, 178200.0, 421200.0, 505800.0, 592200.0, 768600.0, 1036800.0, 1371600.0, 1630800.0, 1715400.0, 2345400.0, 2409012.0]) plt.plot(t1, F1, 'ro', label="original data") # curvefit def func(t, a, b): return a + b * np.log(t) popt, pcov = optimize.curve_fit(func, t1, F1, maxfev=1000) t = np.linspace(1, 3600 * 24 * 28, 13) plt.plot(t, func(t, *popt), label="Fitted Curve") plt.legend(loc='upper left') plt.show() A: After fixing your import statements: #import matplotlib as mpl import matplotlib.pyplot as plt your code produced the following error: RuntimeWarning: divide by zero encountered in log changing: #t=np.linspace(0,3600*24*28,13) t=np.linspace(1,3600*24*28,13) produced the following output:
{ "language": "en", "url": "https://stackoverflow.com/questions/15831763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: How do I best manage SQL Server insertions from Databricks spark session and identity columns? I have a batch-processing transaction data transformation/validation pipeline written in a Scala Databricks notebook, and when the pipeline is finished, it dumps my validated data into a SQL server for later use. Ongoing requirements are beginning to focus on transaction metadata, facts about transactions rather than in-situ data transformations. These will live on a separate table in the SQL server, but will retain a 1:1 relationship with transactions. Currently, in the spark session, a unique index ID is assigned to each transaction in the batch with this function def addColumnIndex(df: DataFrame) = { spark.sqlContext.createDataFrame( df.rdd.zipWithIndex.map { case (row, index) => Row.fromSeq(row.toSeq :+ index) }, StructType(df.schema.fields :+ StructField("index", LongType, false))) } This helps some of our transformations but, because we're batch-processing, IDs are not unique across batches. Our strategy is to also have a batchID on each transaction, and then use a composite key in the sql server, a combination batch and index. This ignores the native identity column on the table in SQL. When writing to SQL, we use a simple .write .mode(SaveMode.Append) .jdbc(jdbcUrl, "Transactions", connectionProperties) On insertion, transactions are given a unique identity ID by the sql server. Is there a way to reliably use this ID for the relationship between transactions and fact tables? Is the composite key approach overcomplicating this? Basically, can we make Spark respect the unique IDs it creates?
{ "language": "en", "url": "https://stackoverflow.com/questions/69946707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: log parser for a log file on remote windows machine I have a log parser2.2 query for parsing log on remote windows machine. When the query is run, on log parser command prompt; i get successful output. Following is the query : logparser -i:Textline -rtp:-1 -stats:OFF \"SELECT EXTRACT_SUFFIX(text,0,\'(IBM PC)\') AS REPORT_SINCE from \\\\remote_machine\\remote_folder\\XXXXX.log where text like \'%IBM PC%\'\""; The same command if , used in a java program (jsp); it throws the following error: Task Aborted. Following is error trace : Cannot open : Error opening files: Error searching for files in Error = folder \\remote_machine\remote_folder: Access is denied. Any idea as to why this is happening & how to get it fixed ? A: Access denied means that the application is being run from an account that is not permitted to access that remote folder. If the command is failing within the context of a JSP, that means that the account / identity that is running the web container doesn't have the necessary permissions. This could be a deliberate security decision. Letting your web server access remote shares is asking for trouble ... if your website gets "hacked". It is prudent to run a web container with minimal privileges as a precaution. This is not a programming problem per se. Rather it is a problem of figuring out why you don't have permission, and how to get permission safely; i.e. without making your entire network more vulnerable to hackers. Talk to your local (Windows) system administrators.
{ "language": "en", "url": "https://stackoverflow.com/questions/28628914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't successfully return a const char* I have created by calling c_str() on a string. (C++) I have a class in my program that has a member variable, an int called number, and a member function, getName(), that is MEANT to return the words "Dice: #" as a const char*, but with the # replaced by the number stored in the class. const char* getName(){ return "Dice:"; } works perfectly well. const char* getName(){ std::stringstream ss; ss << number; std::string s; s = "Dice: " + ss.str(); return s.c_str(); } does NOT work fine, and returns what seems to be garbage. I can't figure out the correct way to go about this. If I use cout to print s.c_str() it prints what I expect. A: The short and sweet answer is that you can't do this, the way you've set this up. The std::string object from which you retrieve your c_str() is in the function's local scope. When the function returns that std::string object gets destroyed. That std::string s; is a local function object. When the function returns it ceases to exist. It joins the choir invisible. It is no more. It's an ex-object. And when a std::string object gets destroyed, any of its c_str()s are no longer valid. This is why you're getting garbage: undefined behavior. There is no way to do this without changing the overall design of it, in some way. There are many ways to go forward. Some of the possibilities: Return a std::string in the first place Just return the std::string from getName(). Whoever calls it can store this std::string, for a while, and grab it's c_str() if it needs it. Use a std::string with a different scope If this getName() is a class method, you could have a private std::string class member, have getName() store the string there, and return its c_str(). Because the original std::string continues to exist, the returned c_str() remains valid. Note that there are some pitfalls here. If the caller calls getName() again, the previously-returned c_str() will no longer be valid. Conclusion Just get in the habit of using and working with std::strings in your C++ code. That's what they're for. The name "c_str()" should be a clue. It gives you a string to be used with C code, if there's any C code lying around, in the near vicinity. It's a C string. Are you writing C code here? No, you're writing C++ code. Unless you're writing C code, or are talking to a C library, there's no need to use c_str() in the first place. If you're writing C++ code, you should be using std::strings. If you need to call a C library function, call c_str() to pass the appropriate C library function parameter, and speak of this C string no more. A: You are creating a local variable 's' and then returning a pointer to the strig withing the string memory. When the function returns the string goes out of scope (and so does the pointer) Best bet is probally change getname to return a std::string, and then if you need to use the c_str, use it where it is returned. std::string name = object.getName(); printf("name = %s", name.c_str());
{ "language": "en", "url": "https://stackoverflow.com/questions/38044998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multi factor authentication text message service I am in new MFA, I am looking for text message service providers i saw MS Azure is providing that service not sure who else providing that service, Can any one tell me who is best text message provider for MFA security? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/29356232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I adjust microphone input levels in HoloLens? In our communications app, some people's voices are too quiet. So we want to be able to change the system level of their microphone input. I searched through all the Windows Universal App samples and Unity documentation and I couldn't find how to change the volume of the Windows microphone (on Windows or HoloLens). A: I found that the property to adjust is the AudioDeviceController.VolumePercent property. The following code implements this: MediaCapture mediaCapture = new MediaCapture(); var captureInitSettings = new MediaCaptureInitializationSettings { StreamingCaptureMode = StreamingCaptureMode.Audio }; await mediaCapture.InitializeAsync(captureInitSettings); mediaCapture.AudioDeviceController.VolumePercent = volumeLevel; I confirmed that this code works on Desktop and HoloLens. It changes the system level, so it's automatically persisted, and would affect all apps.
{ "language": "en", "url": "https://stackoverflow.com/questions/66094556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: App Engine Endpoints Im starting a new application with AppEngine and I need a REST Service. I was looking at Endpoints and I think they are exactly what I need. I also read Google don't recommend to use Endpoints in production but my app first version is not going out until April approximately. How mature do you think App engine Endpoints are? Do you recommend to use them or should I find another REST framework. If so, Are there any other REST framework similar to App Engine Endpoints? or Which one do you recommend, Restlet? or use it with Spring MVC? Thanks A: I'm a bit biased (being a Googler and member of the App Engine team), but I think Endpoints is worth a try. With regards to the general disclaimer on using Endpoints in production, we have allowed some developers to launch in production as long as they have spoken to us first. I provided another answer to a related question on RESTful development here. The developer tried Endpoints and decided to use it over other options.
{ "language": "en", "url": "https://stackoverflow.com/questions/14609424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I extract the className from a span that is selected using javascript? I have this HTML: <span class="redColor">gold</span> And when I have the text selected that is within the span tags, I need to be able to somehow extract the className from the span using javascript. I don't know anything about the class in advance, only that it will be in a span, and the text will be selected. A: I assume you mean Text selected with the mouse or the keyboard? You can access that with window.getSelection() Then you can work your way up the DOM tree: window.getSelection().anchorNode.parentNode.className See https://developer.mozilla.org/en-US/docs/Web/API/Selection.anchorNode for documentation of the Selection class A: Use className property. Example: var x = document.getElementsByTagName('span'); document.write("Body CSS class: " + x.className);
{ "language": "en", "url": "https://stackoverflow.com/questions/21871967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hooking zend_execute() to retrieve PHP bytecode I'm trying to retrieve PHP bytecode (and saving it to a file for further analysis) but I'm not sure exactly how to do it... I'm torn between two options: 1) Extending the Zend framework. A good article I found about this was this one: https://nikic.github.io/2012/07/27/How-to-add-new-syntactic-features-to-PHP.html. Using this technique, I would directly rewrite zend_execute() to add the functionality I want. That seems little bit complicated for me, but doable. 2) Using an extension. This seems simpler, at least based on that demo: https://devzone.zend.com/303/extension-writing-part-i-introduction-to-php-and-zend/. That being said, I can't find any resources about how to hook other functions (like zend_execute()), so I'm not sure how/if I can do what I want. Is there resources you would suggest that I could read? Suggestions about which of these techniques is the easiest/best? Any other techniques I could use?
{ "language": "en", "url": "https://stackoverflow.com/questions/46719391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails: Conditionally Load Spring Security LDAP Plugin I have an app that runs in multiple production environments. In one environment we want to authenticate with LDAP, in the other we do not. If the Spring Security LDAP plugin is included in BuildConfig.groovy, the non-LDAP environment fails to authenticate because LDAP is not configured. I tried environments { devldap { plugins { compile ":spring-security-ldap:2.0-RC2" } } } but the LDAP plugin still builds with the non-LDAP environment and causes the non-LDAP environment (in this case development) to fail to authenticate if I don't include the LDAP configuration because it can't connect to LDAP. I've tried grails clean grails refresh-dependencies but the LDAP plugin only uninstalls if I completely comment it out. How can I conditionally include/exclude a plugin in my build? A: I see this question is a bit old now, however I do a similar thing with the Melody plugin. There is no value in this being installed during TEST - and can get in the way - so I do the following: plugins { // other plugins ... if( Environment.current != Environment.TEST ) compile ":grails-melody:1.56.0" // other plugins ... } So when I run 'test-app' I see the plugin 'uninstalled' and then when I do 'run-app' I see it installed and it's available. NOTE: I recently got caught out by forgetting to also do an import grails.util.Environment. If you do that, you'll find that Environment.current == [:] as does Environment.TEST etc. I believe this is due to the builder behind the config file.
{ "language": "en", "url": "https://stackoverflow.com/questions/29489443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: postgres log queries for other database/application but not mine i need to see the performance of the queries in a Java app which use JPA/Hibernate/postgres, took me a while to find the postgres log file /var/lib/pgsql/9.2/data/pg_log/postgresql-*.log however i only found the queries from other application on other database, i tried to modify the postgresql.conf to add log_statement = 'all' how can i make postgres to log my queries too? and how i can do it in my code? Thanks A: the postgresql.conf setting will log all queries on all databases. You must restart (or at least reload) PostgreSQL after editing that setting (out of habit I always do a restart). Other options are available though which are not such of a broad stroke (and these override that setting so may be also causing your issue: ALTER USER foo SET log_statements = 'all'; This will log all statements by database user foo. ALTER DATABASE foo SET log_statements = 'all'; This will log all statements in the foo database. Iirc the order of precidence is user, database, postgresql.conf value.
{ "language": "en", "url": "https://stackoverflow.com/questions/20412590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Highcharts : Single point in x-axis of datetime type shows 00:00:00:0000 I render a chart using highcharts the x-axis is of 'datetime' type . When I have single point in the chart the x-axis label is shown as 00:00:00:0000 instead of ('18 Nov') the given date value. This seems to happen in highcharts version 3.0.1 where as not in 3.0.7 I did found an issue here https://github.com/highslide-software/highcharts.com/issues/1572 But in case of datetime type for x-axis how can I fix this? Is there any workaround without upgrading to latest version because that would involve verifying all other charts, which is not possible for now in my case. Code: var data1 = Date.UTC(2013, 10, 18); var a = new Highcharts.Chart({ chart: { renderTo: 'container', animation: false, width: 600, height: 400 }, plotOptions: { series: { marker: { symbol: 'circle' } } }, series: [{ name: 'Total Points Estimated', data: [[data1,0]] }], title: { text: 'Release Burn-Up report' }, xAxis: { type: 'datetime', gridLineWidth: 1, gridLineDashStyle: 'shortdot', title: { text: 'Date' }, }, yAxis: { gridLineDashStyle: 'shortdot', min: 0, title: { text: 'Backlog Effort' } } }); Fiddle link : http://jsfiddle.net/WdDqc/1/ A: Try to set minRange, for example to one day, otherwise Highcharts won't know what kind of label should be displayed. See docs.
{ "language": "en", "url": "https://stackoverflow.com/questions/20049830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculate the space complexity and time complexity of a function As a part of my course work i need to calculate the complexity of programs. I'd like to calculate the space complexity and time complexity of the below program.How do i calculate it? It would be really helpful for me if somebody can explain it in detail. sub find_multi_string { my ($file, @strings) = @_; my $fh; open ($fh, "<$file"); #store the whole file in an array my @array = <$fh>; for my $string (@strings) { if (grep /$string/, @array) { next; } else { die "Cannot find $string in $file"; } } return 1; } A: Space complexity: Identify data that occurs "in large quantities" or "repeatedly". Assign numbers to these quantities, e.g., N = number of lines in a file, or M = number of elements in an array. Add these quantities. Watch out for the dynamic creation of data structures: if you have an array of N numbers and another one of M numbers and you create a table of all the products, then the space complexity of the table is... Time complexity: Identify repeated actions. Some may be hidden (as in Perl), some are explicit, e.g. in a for loop. Use the results of space complexity to quantify these repetititions. A loop may be terminated early: then you must estimate the average time of execution. Loops occurring one after the other add up. If you know that a loop body is executed N times and this body contains an inner loop that executes M times, then the body of that inner loop is executed - how often? Very frequently it's just a simple exercise of counting, bookkeeping and simple arithmetic, although there are several examples where a good answer requires heavy math. Not in your case!
{ "language": "en", "url": "https://stackoverflow.com/questions/24634206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How can I display an event’s time alone (without the title) on a jQuery FullCalendar? I am wondering if it's possible to just show the time reserved on the calendar, not the title of the event, using jQuery’s FullCalendar plug-in? Thank you very much for your help! A: You can do everything you want with altering CSS class : To hide event title: .fc-event-time { display: none; } If you want to keep time of events but keep the same background between title and body, you should unset opacity: .fc-event-vert .fc-event-bg { opacity: 0; } A: Somewhere along the lines of 3665 inside the fullCalendaer normal version look for this code (!event.allDay && seg.isStart ? "<span class='fc-event-time'>" + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + "</span>" :'') + "<span class='fc-event-title'>" + htmlEscape(event.title) + "</span>" + Remove "<span class='fc-event-title'>" + htmlEscape(event.title) + "</span>" + So that it still makes sense i jscript syntax and viola! no more title just time. A: With this, install the module Auto Entity Labels or Auto Nodetitles and when you go and edit the Content Type created, you'll see tabs such as "Edit", "Manage Fields", "Auto Label", etc... When you click on "Auto Label', set the Automatic Label Generation to "Automatically generate the label and hide the label field" and set the Pattern for the title to <none>. Now when you create content from the content type, i.e. FullCalendar, it will just show the timeslot you've entered without the title of the node.
{ "language": "en", "url": "https://stackoverflow.com/questions/5982203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Does there exist something like .table? I'm currently working on my thesis and it will include a lot of tables. I was wondering whether there exists an extension like .table or something so that I could fill my tables in that document and do not have all the code in my main 'script'. \begin{table} \begin{tabular}{cc} 3 3 \end{tabular} \end{table} So for example this in a separate document. I'm looking forward to some suggestions! A: Yes, you can include external files as part of your main body using \input. For example, assume you have mytable.table that contains \begin{table}[ht] \centering \begin{tabular}{cc} 3 3 \end{tabular} \caption{A table}\label{tab:mytable} \end{table} You can now use \documentclass{article} \begin{document} Look at Table~\ref{tab:mytable}. \input{mytable.table} \end{document} You wouldn't want to use \include here. See When should I use \input vs. \include?
{ "language": "en", "url": "https://stackoverflow.com/questions/37787917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove certain number of div from another div using Jquery without loop I want to remove all div after 12 div inside the parent div using jquery. The markup is like : <div id="dvNames" class="container grayBox float-left"> <div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_30" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_31" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_32" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_33" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_34" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_35" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_36" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_37" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_38" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_39" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_40" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_41" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_42" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_43" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_44" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_45" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_46" type="text"></div><br></div><div class="float-left margin-bottom-10 width-33-per divContainer"><div class="float-left"><input placeholder="LastName,FirstName" onchange="CheckVisitorName(this)" class="width-180 reset" name="name_47" type="text"></div><br></div> </div> I know we can get all div like inside parent div like $('#dvNames div'). By removing like $('#dvNames div').remove() removes all div. Also we can get each one by $('#dvNames div:first'). So I ended up with for(;$('#dvNames div').length>12;) $('#dvNames div:first').remove() It works I intended but I feel there must be some way to do it without loop. Please help me if you know the way to do it without loop. A: I think what you are looking for is .slice() $('#dvNames > div').slice(12).remove() Demo: Fiddle A: Use the :gt pseudo-selector to select all DIVs after 11 (it counts starting with 0). $('#dvNames div:gt(11)').remove();
{ "language": "en", "url": "https://stackoverflow.com/questions/19971518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jquery - filter child divs? I wound up converting a table to just divs... But, in doing that, I need to rewrite a function and I'm having some issues... I've tried to implement $(this).closest('div'), but it's not doing what I thought that would do... Still reading, but if someone knows of a solution, I'd be a happy camper... Essentially, when I click on a link, it filters the table to only display rows with a class that matches the link's class... This is the code, which was originally created to filter a table... <a href="#" class="dairy">Dairy</a> <a href="#" class="meat">Meat</a> <a href="#" class="vegetable">Vegetable</a> $('a').click(function(evt){ var myId = $(this).attr('class'); $('tr').each(function(idx, el){ if ($(el).hasClass(myId)) { $(el).show(); } else { $(el).hide(); } }); }); I've since changed the table to divs: <div id="primary-div"> <div class="child dairy"> <div class="title">Title</div> <div class="text">Lorem ipsum</div> </div> <div class="child dairy"> <div class="title">Title</div> <div class="text">Lorem ipsum</div> </div> <div class="child meat"> <div class="title">Title</div> <div class="text">Lorem ipsum</div> </div> <div class="child vegetable"> <div class="title">Title</div> <div class="text">Lorem ipsum</div> </div> </div> Like I said, I'm still looking, but I'm being horribly unsuccessful... A: Try this: (Untested) <a href="#" class="dairy">Dairy</a> <a href="#" class="meat">Meat</a> <a href="#" class="vegetable">Vegetable</a> $('a').click(function(e){ var myId = $(this).attr('class'); $('#primary-div div.child:not(.' + myId + ')').hide(); $('#primary-div div.child.' + myId).show(); return false; }); A: $('a').click(function(evt){ var myId = $(this).attr('class'); $('div#primary-div div.child').hide(); $('div#primary-div div.'+myId).show(); }); This should do it. A: Just for kicks, here is an optimized version that utilizes jQuery chaining and the end() method: $('a').click(function(e){ $("div#primary-div > div") .not('.' + this.className).hide().end() .filter('.' + this.className).show(); return false; });
{ "language": "en", "url": "https://stackoverflow.com/questions/1885661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Part of ajax responseText Can you please tell me how to obtain a certain part from ajax responseText? Example: <div id="first">Text1<div> <div id="second">I want to use this text<div> <div id="third">Text 3<div> I thought about passing the responseText to a div, and then accessing it with document.getElementById('id'), but i thing there are better ways.
{ "language": "en", "url": "https://stackoverflow.com/questions/27021239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }