_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d4101
train
SELECT * FROM ( SELECT * , row_number() over(partition by code order by Description) as id from yourTable ) temp WHERE id = 1 I think this is sql server only A: You first need to pick a column which determines what counts as 'the first result'. In my example I chose Description: SELECT * FROM YourTable first WHERE (SELECT COUNT(*) FROM YourTable previous WHERE previous.Code=first.Code AND previous.Description < first.Description) = 0
unknown
d4102
train
JSON.stringify the object on the server, and JSON.parse it on the client (will only work in IE >= 8, if you need to support older i3-browsers you could provide json-js from douglas crockford: https://github.com/douglascrockford/JSON-js
unknown
d4103
train
You can try something like this: <?php // set database connection parameters $databaseName = '<name of database>'; $username = '<user>'; $password = '<password>'; try { $db = new PDO("mysql:dbname=$databaseName", $username, $password); } catch (PDOException $e) { echo $e->getMessage(); exit(); } $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = $db->prepare('SELECT id, nama, parent_id FROM tbl_dummy'); $query->execute(); $results = $query->fetchAll(PDO::FETCH_ASSOC); $flag = true; $table = array(); $table['cols'] = array( array('label' => 'ID', 'type' => 'number'), array('label' => 'Name', 'type' => 'string'), array('label' => 'Parent ID', 'type' => 'number') ); $table['rows'] = array(); foreach ($results as $row) { $temp = array(); $temp[] = array('v' => (int) $row['id']); $temp[] = array('v' => $row['nama']); $temp[] = array('v' => (int) $row['parent_id']); $table['rows'][] = array('c' => $temp); } $jsonTable = json_encode($table); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title> Google Visualization API Sample </title> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> function drawVisualization() { // Create and populate the data table. var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>); // Create and draw the visualization. new google.visualization.OrgChart(document.getElementById('visualization')). draw(data, {allowHtml: true}); } google.setOnLoadCallback(drawVisualization); google.load('visualization', '1', {packages: ['orgchart']}); </script> </head> <body style="font-family: Arial;border: 0 none;"> <div id="visualization" style="width: 300px; height: 300px;"></div> </body> </html>
unknown
d4104
train
Did you try checking out first if there actually are so many clusters in your data as you trying to find ? Simply increasing the number of samples does not necessarily mean that the number of clusters will increase as well. If no. of clusters you are giving as input to the algorithm is greater than the actual no. of clusters in the dataset, then it is possible that the algorithm may not converge properly, or the the clusters may simply overlap (completely) over each other. To find the optimal no. of clusters for your dataset, we use a technique called as elbow method. There are different variations of this method, but the main idea is that for different values of K (no. of clusters) you find the cost function that is most appropriate for you application (Example, Sum of Squared distance of all the points in a cluster to it's centroid for all values of K say 1 to 8, or any other error/cost/variance function. Based on the function you have chosen , you will see that after a certain point, the difference in the values will be negligible. The idea is that we chose that value of 'K' at which the value of the chosen cost function changes abruptly. For the value K=4 the variance is changing abruptly. So K=4 is the chosen to be an appropriate value. Image Source : Wikipedia There are several other methods on cluster validation as well. There exists several packages in R specifically for this purpose. To learn more from the following links : * *Coursera Lecture on Elbow Method *D3js visualization of D3js *Quora answer on elbow method *Python implementation of elbow method *Wikipedia Link
unknown
d4105
train
* *Means that the as.vector(x) operation resulted in one or more elements of x being converted to NA as the conversion for those components is not defined. *When mean.default is called, x is neither numeric or logical and hence the function can't do anything with the data *Means that x or mx or both are factors and - (and other mathematical operators) is not defined for factor objects. *See 1. above. All point to an issue with the input data, usually a factor has been created. The warnings come from this line: > coun <- skew(x$Country) Warning messages: 1: In var(as.vector(x), na.rm = na.rm) : NAs introduced by coercion 2: In mean.default(x) : argument is not numeric or logical: returning NA 3: In Ops.factor(x, mx) : - not meaningful for factors 4: In var(as.vector(x), na.rm = na.rm) : NAs introduced by coercion This is because x$Country is a factor: > str(x) 'data.frame': 1362 obs. of 12 variables: $ Country : Factor w/ 227 levels "","Afghanistan",..: 19 19 19 19 19 19 166 166 166 166 ... .... Even if you made this a character you could compute the skewness of this variable. Just comment this line out.
unknown
d4106
train
I found the answer myself. What I mean by not working was that the divider was clickable. What I had to do was to override in my adapter the areAllItemsEnabled method to return false and create a condition in the isEnabled method (see the second half of the original question). A: I think the issue you are having is related to the ClickListener you are adding, since you are are putting in the XML that wont be clickable but after you set your ContentView you are putting this line: list.setOnItemClickListener(new OnItemClickListener() { ... } wich makes the list clickable. A: Redering to my answer of another post, you just have to set the OnClickListener on the View that shouldn't be clickable to null. So you would call: view.setOnClickListener(null). Of course you need the reference to the view to do this...
unknown
d4107
train
You can use the choice method of a RandomStreams instance. More on random numbers in Theano can be found in the documentation here and here. Here's an example: import numpy import theano import theano.tensor as tt import theano.tensor.shared_randomstreams n = 6 alpha = [1] * n seed = 1 w = theano.shared(numpy.random.randn(n, 2, 2).astype(theano.config.floatX)) p = theano.shared(numpy.random.dirichlet(alpha).astype(theano.config.floatX)) rng = tt.shared_randomstreams.RandomStreams(seed=seed) i = rng.choice(size=(1,), a=n, p=p) f = theano.function([], [p, i, w[i]]) print f() print f() print f() print f()
unknown
d4108
train
If ProductName is a form field that you intend displaying on the form, why not instead abstract all the fields of property into a separate Product entity. This should ease the maintenance of your app (and bring it more in line with patterns like MVC / MVVM), e.g. public class Product { public string ProductName{ get; set; } public int ProductSize{ get; set; } // etc } public partial class FormInventory : Form { public FormInventory() { } public Product Product { get; set; } } Edit : IMO, the architecture presented by Rod Cerata's blog looks OK, but I believe it would be improved via encapsulation of a "ViewModel" for your Employee. Have a look at EmployeePresenter.cs - you get lots of repetitive scraping code like this: _model.EmployeeID = _view.EmployeeID; _model.Lastname = _view.Lastname; _model.Firstname = _view.Firstname; _model.EmployeeType = _view.EmployeeType; _model.Salary = _view.Salary; _model.TAX = _view.TAX; IMO would be improved by creating a new EmployeeViewModel class (which would be more or less the same as EmployeeModel, plus any 'screen' specific fields e.g. Title, "mode" (Edit, New, Read Only etc), and then using a tool like AutoMapper, which would reduce the code above. A: 1. Yes, simply use the new keyword, like public new string ProductName { get; set; } 2. No, it simply returns the name of the assembly. 3. Its used for debugging and some "reflection". I say "reflection" because it's more like a human-made reflection. So, it's safe to go forward this way. But why don't you simply change it to MyCompanyProductName? Regards A: Using the 'new' keyword will suppress the warning. When you do this, the result of calling the ProductName property depends on Type of the variable that is used to referenced the form... for example, if you're calling the property from another class: // Notice that we're only creating one object and // assigning it to two different variables. FormInventory explicitlyNameForm = new FormInventory(); Form referenceToBaseForm = explicitlyNameForm; // Acting on the child reference (FormInventory) will // operate on YOUR implementation of ProductName explicitlyNameForm.ProductName = "Some Value"; // But acting on the parent reference (Form) will // operate on the .NET implementation of ProductName referenceToBaseForm.ProductName = "Some Other Value"; The end result will probably be what you want... the compiler knows which implementation to use based on how you've declared your variable. And since all references within the .NET framework reference the Form class, not your new class, there is no risk of affecting anything that happens within the .NET framework with respect to this property. However, as the others have suggested, it may cause less confusion if you're able to rename the property.
unknown
d4109
train
I solved this adding this script to ts_devserver bootstrap ts_devserver( name = "devserver", additional_root_paths = ["project/src/_"], bootstrap = [ "@npm//:node_modules/@angular/localize/bundles/localize-init.umd.js", ] )
unknown
d4110
train
Make sure you remove SystemNavigationManager.GetForCurrentView().BackRequested event handler before navigate to other page. Either atPage.Unloaded event or OnNavigatedFrom method. protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); SystemNavigationManager.GetForCurrentView().BackRequested -= SystemNavigationManager_BackRequested; }
unknown
d4111
train
You have a bug in your own code: public BatchRestTemplate() { .......... messageConverters.add(getBatchHTTPConverter()); .......... } But... There is no batchHTTPConverter yet!. It will appear there only after setBatchHTTPConverter(). In other words you can't use the property from the constructor because setters are called latter after the object instantiating.
unknown
d4112
train
You can get the column labels of a particular level of the MultiIndex in df by MultiIndex.get_level_values, as follows: df_ticker = df.columns.get_level_values('ticker') Then, if df1 has the same number of columns, you can copy the labels extracted to df1 by: df1.columns = df_ticker
unknown
d4113
train
Delegates are immutable. You never change a delegate. Any method that appears to mutate a delegate is in fact creating a new instance. Delegates are immutable; once created, the invocation list of a delegate does not change. There is thus no cause for concern that the invocation list may be updated whilst a delegate is being invoked. What you do have to guard against, however, and have failed to do in your method is when the delegate may in fact be null. (new MyContext()).Go(); will cause an exception. You used to have to guard against this by reading the value into a local variable, testing it for null and then invoking using it. It can now more easily be resolved as: public void Go() { _multicastDelegate?.Invoke(this); } A: The definition of thread-safe as used by MSDN documentation means code that is properly synchronized. It usually doesn't state on what it synchronizes, but it can be the class object for static members, the instance object for instance members, or it can be some inner object, such as SyncRoot in many collection types. Although delegates are immutable, you must still synchronize properly. .NET and C#, unlike Java, don't guarantee safe publication, so if you don't guarantee synchronization, you can observe a partially initialized object in other threads1. To turn your code thread-safe, you just need to use _lock when reading from the delegate field as well, but you can call Invoke outside the lock, landing onto the delegate the responsibility to keep its own thread safety. public class MyContext { private readonly object _lock = new object(); public delegate bool MyDelegate(MyContext context); private MyDelegate _delegate; public MyContext() { } public void AddDelegate(MyDelegate del) { lock (_lock) { _delegate += del; } } public void RemoveDelegate(MyDelegate del) { lock (_lock) { // You had a bug here, += _delegate -= del; } } public void Go() { MyDelegate currentDelegate; lock (_lock) { currentDelegate = _delegate; } currentDelegate?.Invoke(this); } } * *Microsoft's .NET Framework implementation always makes volatile writes (or so they say), which kind of gives you safe publication implicitly, but I personally don't rely on this.
unknown
d4114
train
We can do explode then do transform with nunqiue find the index duplicated with same value s=df.Name.explode().reset_index() v=(s.groupby('Name')['index'].transform('nunique')>1).groupby(s['index']).any() Out[465]: index 0 True 1 True 2 False 3 False Name: index, dtype: bool df['Check']=v A: Similar to Ben's answer but using duplicated instead of groupby().nunique(): s = series.explode().reset_index() df['Check'] = (s.drop_duplicates() .duplicated('Name', keep=False) .groupby(s['index']).any() ) Output: Name Check 0 [MARCIO, HAMILTON, FERREIRA] True 1 [NILSON, MARTINIANO, FERREIRA] True 2 [WALTER, MALIENI, JUNIOR] False 3 [CARLOS, ALBERTO, ARAUJO, NETTO] False
unknown
d4115
train
In order to execute the server-side script (PHP) from the client side (static HTML and JavaScript), you need to use the Ajax technology. In essence, Ajax will allow you to send and/or retrieve data from the server "behind the scenes" without affecting your page. JavaScript, a client-side scripting language used to add interactivity to your webpage, already supports Ajax. However, the syntax is rather verbose, because you need to account for differences across browsers and their versions (Internet Explorer version 5 up to 11 in particular have their own implementation different from Chrome or Mozilla). You, as a developer, can avoid these technicalities by using a front-end framework such as jQuery (other good examples are Angular.js, Vue.js, and others). jQuery is essentially a library of code written in vanilla JavaScript that simplifies common tasks such as querying DOM. It also provides expressive syntax for using Ajax. It will resolve browser incompatibilities internally. This way you can focus on your high-level logic, rather than low-level issues like that. Once again, jQuery code is also JavaScript code. So place the following <script> tag, as you would normally do with JS, somewhere in your page. <script> $( document ).ready(function() { $("form").submit(function(e) { e.preventDefault(); // prevent page refresh $.ajax({ type: "POST", url: "jump_invoicepaid.php", data: $(this).serialize(), // serialize form data success: function(data) { // Success ... }, error: function() { // Error ... } }); }); }); </script> First, this code will run once the page is loaded. Second, it will attach a submit event handler to every <form> in your HTML page. When you click on the <button type='submit'>, this event will fire. e.preventDefault() will halt the normal submission of the form and prevent page refresh. Note that e is the event object that contains info about the submit event (such as which element it originated from). Next, we are sending the actual Ajax request using $.ajax method from jQuery library. It is a generic method, and we could as well have used $.post, since we are specifically doing the POST request. It will be received by your PHP file jump_invoicepaid.php. Now, in your PHP file, you have the following line: header('Location: ./?page=pastevents'); which forces a redirect to the home page with a GET parameter. If you want to have the same behavior, then you would need to remove that line, and put window.location.replace("/?page=pastevents") to your JavaScript code: // in your Ajax request above... success: function(data) { window.location.replace("/?page=pastevents"); }, This would refresh the page however, because you are essentially requesting the home page with a GET method. I am guessing that this is done in order to update information on the page. You could do so without redirecting, by adding / changing / removing elements on your page (i.e. in DOM). This way, you would send data from the server back to the client, and if the response is received successfully, in your JavaScript you can obtain that response and manipulate your webpage accordingly. If the latter interests you, then consider using JSON format. You just need to do json_encode in your PHP, and then on the client-side, parse the JSON string using JSON.parse(...). Read on here for example. Hope this helps!
unknown
d4116
train
Now that you have shown your XML, here's how to fix your code: var ta = from tmp in loaded.Descendants("Table") select tmp.Element("E1"); You do not use . in XML as you do in C# to navigate the XML tree. You could also navigate a XML tree using XPath: var ta = from tmp in loaded.XPathSelectElements("NewDataSet/Table/E1") select tmp; Also I would recommend you to use a StringBuilder instead of string concatenations for this output variable: var ta = from tmp in loaded.Descendants("Table") select tmp.Element("E1"); var builder = new StringBuilder(); foreach (string ss in ta) { builder.Append(ss); } string output = builder.ToString(); A: var ta = from tmp in loaded.Descendants("Table") select tmp.Element("E1");
unknown
d4117
train
Just a heads-up. You are declaring pin 2 twice, first as interruptPin, then as soundSensor. This might be prone to confusion and misfiring of the ISR Inside your interrupt function, you should wrap your logic inside cli(); and sei(); to avoid false triggering during the interruption. Do not use detachInterrupt(). Review the documentation from avr/sleep.h (here). As it reads, you MUST make sure that interrupts are enabled before sending the CPU to sleep. I believe you are missing a sei() before sending the CPU to sleep I would advise you to use an external (strong) pull-up to guarantee that pin 2 won't be triggered unless is via the sensor. Finally, please observe that according to your logic, the interrupt service will be called any time the pin goes LOW. This will override the else from the conditional inside the loop() (at least this will occur after the first time you call the (mispelled) function Goint_to_sleep()). Think of another approach to accomplish what you want. Just be careful with the ISRs that you implement EDIT: I forgot to mention something extremely important: You need to be absolutely sure that the output signal from the microphone that you are connecting to is above the threshold for a digital signal (~2.60-2.8V). Having said that, are you sure that the interrupt edge detection should be LOW when clapping? I think it must be high in which case the pin should be pulled low. You can always reverse this logic and amplify the signal with an external transistor to convert the sensor's signal into an adequate digital pulse
unknown
d4118
train
I found an implementation of the PASCAL VOC2012 dataset trained for semantic segmentation that uses the following early stopping parameters: earlyStopping = EarlyStopping( monitor='val_loss', patience=30, verbose=2, mode='auto')
unknown
d4119
train
Try this : select * from ( SELECT * FROM items WHERE duration = 5 UNION SELECT * FROM items WHERE duration = 10 ) odrer by date DESC A: When you use UNION OR UNION ALL order by not allowed in each select statement. You have to apply order by in outer select statement. A: Order the UNION result by duration first, then date desc. select * from ( SELECT * FROM items WHERE duration = 5 UNION SELECT * FROM items WHERE duration = 10 ) order by duration, date DESC However, there's no need for a UNION (see e4c5's answer). A: If I understood you from the comments, you want something like this? SELECT s.* FROM ( SELECT i.*,1 as ord_col FROM items i WHERE duration = 5 UNION SELECT it.*,2 FROM items it WHERE duration = 10) s ORDER BY CASE WHEN s.ord_col = 5 THEN s.date ELSE '1000-01-01' END DESC Although this query is inefficient , you can do it with one select : SELECT i.* FROM items i WHERE i.duration IN(5,10) ORDER BY CASE WHEN s.ord_col = 5 THEN s.date ELSE '1000-01-01' END DESC If its not dynamic, and 5 will be ordered before 10 and these are constant values , you can simply add the duration column to the query , ORDER BY duration,date although this will also order the second query be date, just after the first one. A: I think you don't even need to UNION at all and you can refactor your query this way: SELECT * FROM items WHERE duration IN (5, 10) ORDER BY CASE WHEN duration = 5 THEN 1 WHEN duration = 10 THEN 2 ELSE NULL END , CASE WHEN duration = 5 THEN [date] ELSE NULL END DESC; This query will sort based on your duration first (the ones with 5 will come first, with 10 second) and then as a second order option it will sort ones with duration = 5 by date in descending order. Of course this could be more elegant, but meets OPs A/C and does the job.
unknown
d4120
train
You may try writing it like f = Quiet[Check[#1^#2,1]] &. Quiet will suppress the "Power::indet: "Indeterminate expression 0^0 encountered." message and Check will replace the result with 1 if it is indeterminate. It is probably better to use some function like s = Quiet[Check[#1, 1]] and wrap your expressions in it. A: I'm slightly surprised the trivial (albeit slightly dangerous) fix did not get mentioned earlier. If you really don't expect the expression 0^0 to come up in any context where you'd (a) be worried that it did, or (b) would like it to evaluate it to something other than 1, you can simply try Unprotect[Power]; Power[0, 0] = 1; Protect[Power]; 0^0 I needed this fix in a situation where a complicated function had a number of calls to expressions of the form x^n where x is real and n is an integer, in which case 0^0 should be seen as the limit of x^0=1 as x goes to 0. It's important to note, though, that doing this will 'contaminate' Power for the current kernel session, and may therefore break other notebooks which run concurrently and for which conditions (a) and (b) may not hold. Since Power is located in the Systemี context instead of Globalี, it may be difficult to separate the contexts of different notebooks to avoid clashes produced by this fix. A: Of course there are many ways to do things in Mathematica, but a design idiom I often use is to write the "function" (actually, a pattern) with decreasing specificity. Mathematica has the property that it will apply more specific patterns before less specific. So, for your case I'd just write: Clear[f]; f[0, 0] = 1; f[a_, b_] := a^b; I assume you expect to work with integer values since that's the usual context for this type of situation, e.g. when evaluating Bernstein basis functions. A: I agree with the answer of @Deep Yellow, but if you insist on a pure function, here is one way: f = Unevaluated[#1^#2] /. HoldPattern[0^0] :> 1 & EDIT Staying within the realm of pure functions, the situation you described in your edit can be addressed in the same way as my solution to your specific original example. You can automate this with a tiny bit of metaprogramming, defining the following function transformer: z2zProtect[Function[body_]] := Function[Unevaluated[body] /. HoldPattern[0^0] :> 1] Then, my previous code can be rewritten as: f = z2zProtect[#1^#2 &] But you can is this more generally, for example: ff = z2zProtect[#1^#2 + 2 #2^#3 + 3 #3^#4 &] In[26]:= ff[0,0,0,0] Out[26]= 6
unknown
d4121
train
from your item array just remove or add item and call your adapter's notifyDataSetChanged() A: remove/add an element and use this. ((BaseAdapter) listView.getAdapter()).notifyDataSetInvalidated();
unknown
d4122
train
I found the answer thanks to the help of prologue's creator: xflywind. The answer is prologue-events. When prologue creates a thread, it triggers a list of procs, so called events, that are registered on startup. All you need to do is define an event that sets the log-level and provides a handler. proc setLoggingLevel() = addHandler(newConsoleLogger()) logging.setLogFilter(lvlDebug) let event = initEvent(setLoggingLevel) var app = newApp(settings = settings, startup = @[event])
unknown
d4123
train
(CLAIM.emp_ssn = Patient.emp_num AND Patient.pt_ssn=Claim.pt_ssn) The second part of the clause Patient.pt_ssn=Claim.pt_ssn is already mentioned in the ON clause so you don't need to mention it again. Try this : SELECT CLAIM.* FROM CLAIM left join PATIENT on claim.pt_ssn = Patient.pt_ssn WHERE CLAIM.emp_ssn = Patient.emp_num AND CLAIM.FROM_DATE < Patient.eff_date EDIT : I'm not sure what data set you have, but I think a simple group by should resolve your query. I'll try my best to help you out : Table : CLAIM pt_ssn emp_ssn claim_name from_date 1234 1 Claim_1 2015-05-10 2345 2 Claim_2 2015-07-10 3456 3 Claim_3 2015-09-10 4567 4 Claim_4 2015-11-10 5678 5 Claim_5 2015-12-10 5678 5 Claim_5 2015-12-04 6789 6 Claim_6 2015-12-12 Table : PATIENT pt_ssn emp_num eff_date 1234 1 2015-05-12 2345 2 2015-07-08 3456 3 2015-09-15 4567 4 2015-11-07 5678 5 2015-12-09 5678 5 2015-12-12 6789 6 2015-12-02 You can see that I have created duplicate records with the pt_ssn as 5678. Now, if I use the aforementioned query, namely : SELECT CLAIM.* FROM CLAIM left join PATIENT on claim.pt_ssn = Patient.pt_ssn WHERE CLAIM.emp_ssn = Patient.emp_num AND CLAIM.FROM_DATE < Patient.eff_date then the result set I get is : pt_ssn emp_ssn claim_name from_date 1234 1 Claim_1 2015-05-10 3456 3 Claim_3 2015-09-10 5678 5 Claim_5 2015-12-04 5678 5 Claim_5 2015-12-04 /*DUPLICATE ENTRY*/ 5678 5 Claim_5 2015-12-10 SQL Fiddle : http://sqlfiddle.com/#!9/342d0/1 You can see the duplicate entry above. If you want to exclude such duplicate entries, you'll need to use Group By as follows : SELECT CLAIM.pt_ssn, CLAIM.emp_ssn, CLAIM.claim_name, CLAIM.from_date FROM CLAIM left join PATIENT on #claim.pt_ssn = Patient.pt_ssn WHERE CLAIM.emp_ssn = Patient.emp_num AND CLAIM.FROM_DATE < Patient.eff_date GROUP BY CLAIM.from_date, CLAIM.pt_ssn, CLAIM.emp_ssn, CLAIM.claim_name This will give you the result set as follows : pt_ssn emp_ssn claim_name from_date 1234 1 Claim_1 2015-05-10 3456 3 Claim_3 2015-09-10 5678 5 Claim_5 2015-12-04 5678 5 Claim_5 2015-12-10 SQL Fiddle : http://sqlfiddle.com/#!9/342d0/2 Observe that there are two entries for the pt_ssn : 5678. This is because they are for different dates. Hope this helps!!! A: I am guessing there is a patient record even if there is no claim.. so the left join should be the other order. Try this (or even list the fields you want returned): SELECT distinct * FROM PATIENT left join CLAIM on claim.pt_ssn = Patient.pt_ssn and CLAIM.emp_ssn = Patient.emp_num WHERE CLAIM.FROM_DATE < Patient.eff_date;
unknown
d4124
train
The issue was I had misplaced the return statement. I still have much fine-tuning to do, but the following code solves the issue in the question that I posed earlier today. I have been reading posts, documentation, and articles for days, and I wish I could everyone credit, but this is the blog post that ultimately helped me realize my error: https://testdriven.io/blog/retrying-failed-celery-tasks/. @shared_task(name="send_http_request_to_proctoru_task", bind=True, max_retries=6) def send_http_request_to_proctoru_task(self, api_url, headers, payload): try: response = requests.request("POST", api_url, headers=headers, data=payload) response_json = response.json() if response_json["response_code"] == 2: raise Exception() return response_json["data"]["url"] except Exception as exc: logger.warning("Exception raised. Executing retry %s" % self.request.retries) raise self.retry(exc=exc, countdown=2 ** self.request.retries)
unknown
d4125
train
When you drop the button into the table, does the 'print position' work? It should be printing out the coords of the drop position to your shell. I think you need to use those to then insert the button into the table. Got it working - change your drop event to this: position = e.pos() print position row = self.rowAt(position.y()) column = self.columnAt(position.x()) self.setCellWidget(row,column,self.butObject) e.setDropAction(QtCore.Qt.MoveAction) e.accept() Cheers Dave
unknown
d4126
train
In the properties of your project try targeting x86 instead of AnyCPU: Alternatively if you want to target AnyCPU you need to install the x64 bit Access OLEDB provider. You can download it from here.
unknown
d4127
train
A global variable is a variable that is declared at the top level in a file. So if we had a class called Bar, you could store a reference to an instance of Bar in a global variable like this: var bar = Bar() You would then be able to access the instance from anywhere, like this: bar bar.foo() A shared instance, or singleton, looks like this: class Bar { static var shared = Bar() private init() {} func foo() {} } Then you can access the shared instance, still from anywhere in the module, like this: Bar.shared Bar.shared.foo() However, one of the most important differences between the two (apart from the fact that global variables are just generally discouraged) is that the singleton pattern restricts you from creating other instances of Bar. In the first example, you could just create more global variables: var bar2 = Bar() var bar3 = Bar() However, using a singleton (shared instance), the initialiser is private, so trying to do this... var baaar = Bar() ...results in this: 'Bar' initializer is inaccessible due to 'private' protection level That's a good thing, because the point of a singleton is that there is a single shared instance. Now the only way you can access an instance of Bar is through Bar.shared. It's important to remember to add the private init() in the class, and not add any other initialisers, though, or that won't any longer be enforced. If you want more information about this, there's a great article by KrakenDev here. A: Singleton (sharing instance) Ensure that only one instance of a singleton object is created & It's provide a globally accessible through shared instance of an object that could be shared even across an app. The dispatch_once function, which executes a block once and only once for the lifetime of an app. Global variable Apple documentation says Global variables are variables that are defined outside of any function, method, closure, or type context.
unknown
d4128
train
Use Doorkeeper gem. Its easy to introduce OAuth 2 provider functionality to your application. It can be also integrated with Devise. Doorkeeper also provides a configuration option to auto-approve and skip the authorization step. This is useful when working with a set of trusted applications, so that you don't confuse your users by requiring them to "authorize" your company's trusted app. # in config/initializers/doorkeeper.rb Doorkeeper.configure do # ...other config options... skip_authorization do true end end
unknown
d4129
train
Looks like this is functionality that has been requested but has not been implemented: https://feedback.azure.com/forums/248703-api-management/suggestions/17369008-schema-validation-in-apim
unknown
d4130
train
Try this <Window.Resources> <Style x:Key="test" TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border Name="ButtonBorder" CornerRadius="10" BorderThickness="1" BorderBrush="Gray" Background="LightGray"> <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid> <Button Content="Button" Style="{StaticResource test}" Margin="0,137,0,0" /> <Grid>
unknown
d4131
train
Do you want to use a different directory than the default /var/lib/docker as Docker runtime? You can do this by starting docker daemon with -g option and path to the directory of your choice. From the man page: -g, --graph="" Path to use as the root of the Docker runtime. Default is /var/lib/docker. A: When firing up your container with "docker run": docker run -v /data/some_directory:/mount/location/in/your/container your_docker_image You cannot do this in the same way via Dockerfile because of portability.
unknown
d4132
train
Android includes some commands in code rather than XML that will move things around. There's a great guide here that will help you learn how to implement them. From there, implement an animation listener to tell when the first animation ends (as seen in the Google documentation here) ain order to start the second animation after the first.
unknown
d4133
train
The simple solution is to use the appropriate maven repository for the artifacts com.cisco.onep* which are not located in Maven central. A: As an immediate solution, but not a recommendation, you can use system dependencies to resolve artifacts on your local filesystem. As @khmarbaise implied, try to publish those corporate artifacts to your corporate Maven repository (Nexus, Artifactory, Archiva, etc.), even an FTP/HTTP server would do... Once you publish those corporate artifacts to your "corporate" repository(hopefully it's already in place), you just need a new repository declaration in your Maven POM.
unknown
d4134
train
You can use JSON.stringify(array) if you just need to create a string out of an array
unknown
d4135
train
This is unfortunately a known issue with Firefox: https://code.google.com/p/google-web-toolkit/issues/detail?id=7648
unknown
d4136
train
for updating AD password use a separate method, it seems that LdapTemplate.update() does not define the correct ModificationItem for password. public void setPassword(Person p){ String relativeDn = getRelativeDistinguishedName(person.getDistinguishedName()); LdapNameBuilder ldapNameBuilder = LdapNameBuilder.newInstance(relativeDn); Name dn = ldapNameBuilder.build(); DirContextOperations context = ldapTemplate.lookupContext(dn); Attribute attr = new BasicAttribute("unicodepwd", encodePassword(person.getPassword())); ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr); ldapTemplate.modifyAttributes(dn, new ModificationItem[] {item}); } A: In addition to aalmero answer, it seems like Spring Ldap repository can't save unicodePwd. But you can use LdapTemplate for it: UserAd userAd = new UserAd(); // set your stuff userAdRepository.save(userAd); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", encodePassword("password-respecting-policies"))); ldapTemplate.modifyAttributes(userAd.getDn(), mods);
unknown
d4137
train
You could add a Command in your ViewModel: For example the Commands Section here could help: Implementing the MVVM Pattern Using the Prism Library 5.0 for WPF . And add a parametrized Command with the help of the Prism library and as the parameter you commit the Name of your button (Internet is full of help). And bind the command to your button. A: Use command parameters in XAML file. This is simple sintax to pass object with button "CommandParameter={Binding senderObject}" add this at the end of the button tag. Access the same in the private void SelectMovie_Click(object sender, RoutedEventArgs e) { String buttonId = sender as String; // _moviePanelVM is an instance of my ViewModel _moviePanelVM.GetSelectedMovieDetails(); }
unknown
d4138
train
First off, there's lots of different home screen implementations on Android. The stock Android one, Samsung, HTC and Motorola all have their own variants, then third party ones like Launcher Pro. All use different stores as to what to keep on the home screen, may provide different profiles for the home screen (home, work, etc). Second, the home screen is prime real estate. And it is also the user's real estate. If there was programmatic access to the home screen, what happened to the Windows quick launch, desktop, favorites menu (in older versions of IE), and older pin area of the start menu (the very top of it in Win 95/98). To quote Raymond Chen "I bet somebody got a really nice bonus for that feature". So, in short, even if it was possible, please don't. As awesome as you think your program is, the user might not think the same.
unknown
d4139
train
A nicer (IMHO) way to do this would be to define your custom domains in .env files โ€“ this way it's clear that domain names are environment-specific and there won't be a need for any 'ifs': .env: URL=www.dev.co.uk SUBDOMAIN1=blog.dev.co.uk SUBDOMAIN2=careers.dev.co.uk Then add to config/app.php: 'url' => env('URL'), 'subdomain1' => env('SUBDOMAIN1'), 'subdomain2' => env('SUBDOMAIN2'), routes.php would become simpler and nicer to read: Route::group(['domain' => Config::get('app.url')] {} Route::group(['domain' => Config::get('app.subdomain1')] {} Route::group(['domain' => Config::get('app.subdomain2')] {} PS. Imagine if you get more environment-specific URLs in the future โ€“ your routes.php will get bloated and it will (it already does, actually) contain environment-specific data which is not nice!
unknown
d4140
train
Consider using pandas' read_sql and pass parameters to avoid type handling. Additionally, save all in a dictionary of dataframes with keys corresponding to original raw_data keys and avoid flooding global environment with many sepeate dataframes: raw_data = {'age1': ['ten','twenty'], 'age_num': [10, 20, 30]} df_dict = {} for k, v in raw_data.items(): # BUILD PREPARED STATEMENT WITH PARAM PLACEHOLDERS where = '{col} IN ({prm})'.format(col=k, prm=", ".join(['?' for _ in v])) sql = 'SELECT * FROM mytable WHERE {}'.format(where) print(sql) # IMPORT INTO DATAFRAME df_dict[k] = pd.read_sql(sql, conn, params = v) # OUTPUT TOP ROWS OF EACH DF ELEM df_dict['age1'].head() df_dict['age_num'].head() For separate dataframe objects: def build_query(my_dict): for k, v in my_dict.items(): # BUILD PREPARED STATEMENT WITH PARAM PLACEHOLDERS IN WHERE CLAUSE where = '{col} IN ({prm})'.format(col=k, prm=", ".join(['?' for _ in v])) sql = 'SELECT * FROM mytable WHERE {}'.format(where) return sql raw_data2 = {'age1': ['ten','twenty']} # ASSIGNS QUERY sql = build_query(raw_data2) # IMPORT TO DATAFRAME PASSING PARAM VALUES df2 = pd.read_sql(sql, conn, params = raw_data2['age1']) raw_data3 = {'age_num': [10,20,30]} # ASSIGNS QUERY sql = build_query(raw_data3) # IMPORT TO DATAFRAME PASSING PARAM VALUES df3 = pd.read_sql(sql, conn, params = raw_data3['age_num'])
unknown
d4141
train
Disable (or don't enable - doesn't it require you to set a define?) the automatic linking.
unknown
d4142
train
There seems to be a couple things wrong with the code. As it is posted I would be surprised if it compiles. In your Adapter you have: List<Order> myfoods; and public AllOrdersAdapter(List<Order> myfoods) { this.myfoods = myfoods; } but in your activity code you pass: adapter = new AllOrdersAdapter((ArrayList<String>) myfoods); one is a ArrayList of String the other of Order ! You also need to change your adapter class to something like: public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersAdapter.AllOrdersViewHolder> { private static final String TAG = AllOrdersAdapter.class.getSimpleName(); private ArrayList<Order> mData; public class AllOrdersViewHolder extends RecyclerView.ViewHolder { public TextView mTvFoodname; public TextView mTvFoodQuantity; public TextView mTvFoodId; public AllOrdersViewHolder(View v){ super(v); // TODO: You need to assign the appropriate View Id's instead of the placeholders ???? mTvFoodQuantity = v.findViewById(R.id.????); mTvFoodname = v.findViewById(R.id.????); mTvFoodId = v.findViewById(R.id.????); } } public AllOrdersAdapter(ArrayList<Order> data){ this.mData = data; } @Override public AllOrdersViewHolder onCreateViewHolder(ViewGroup parent, int viewType){ View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.business_list_card_view, parent, false); return new AllOrdersViewHolder(itemView); } @Override public void onBindViewHolder(final AllOrdersViewHolder holder, final int position){ //TODO: You need to decide whether you want to pass a string or order object Order data = mData.get(position); final String name = data.getProductName(); final String quantity = data.getQuantity(); final String id = data.getProductId(); holder.mTvFoodname.setText(name); holder.mTvFoodQuantity.setText(quantity ); holder.mTvFoodId.setText(id) } @Override public int getItemCount(){ return mData.size(); } } Note: That since I can not know, whether an ArrayList of String or of Order should be used the parameters in either the Activity or Adapter will need to be changed. Also how you assign the data to the RecyclerView will be affected in the onBindViewHolder method. You should also follow the advice given by Frank. EDIT Change your onDataChange() method to this: @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { if (postSnapshot.getValue() != null) { List ingredients = new ArrayList<>(); for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) { String name = ing.child("productName").getValue(String.class); String quantity = ing.child("quantity").getValue(String.class); String productId = ing.child("productId").getValue(String.class); // Using your overloaded class constructor to populate the Order data Order order = new Order(productId, name, quantity); // here we are adding the order to the ArrayList myfoods.add(order); Log.e(TAG, "Gained data: " + name) } } } adapter.notifyDataSetChanged(); } In your Activity you will need to change the ArrayList class variable "myfoods" to this: ArrayList(Order) myfoods = new ArrayList<>(); and in your onCreate() method you can now change: adapter = new AllOrdersAdapter((ArrayList<String>) myfoods); to simply this: adapter = new AllOrdersAdapter(myfoods); Also notice that I have made some changes in my original code above. A: You'll want to create the adapter, and attach it to the view, straight in onCreate: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); //firebase db = FirebaseDatabase.getInstance(); requests= db.getReference().child("Requests"); lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods); lstFoods.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); lstFoods.setLayoutManager(layoutManager); adapter = new AllOrdersAdapter((ArrayList<String>) myfoods); lstFoods.setAdapter(adapter); loadOrders(); } This also means you should declare myfoods as a ArrayList<String>, which saves you from having to downcast it. Something like: ArrayList<String> myfoods = new ArrayList<String>(); Now in loadOrders you simple add the items to the list, and then notify the adapter that its data has changed (so that it repaints the view): private void loadOrders() { requests.child("foods").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { for (DataSnapshot ing: postSnapshot.getChildren()) { myfoods.add(ing.child("quantity").getValue(String.class)); myfoods.add(ing.child("productName").getValue(String.class)); myfoods.add(ing.child("productId").getValue(String.class)); } } adapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { throw databaseError.toException(); // don't ignore errors } }); }
unknown
d4143
train
It's not "wrong" per se, status 404 means "Resource not found" and you can't find a resource that hasn't been specified. Status 400 (Bad Request) however might be more appropriate. It really comes down to the intended meaning of the error code and your interpretation of the error. A full list of status codes can be found in section 10 of RFC 2616. The 4xx (error) codes start in section 10.4.
unknown
d4144
train
You need to assign a new Object to Location for it to work in Chrome Location = new Object(); A: Rather than Google Chrome not working here, what's happening is that Firefox is overlooking your undefined Location namespace for some reason. Make sure you've defined it and your functions belong to it, or just use your functions this way (which seems more appropiate for your situation): function removeMe(data) { ... } function addMe() { ... } And in the onclick attributes of your links, onclick="removeMe('remove19p'); return false;" and onclick="addMe(); return false;" respectively. A: try this : function removeMe(data) { $('div').remove('#' + data); return false; }; function addMe() { $('.container').append("<div class='phoneSet' id='remove19p'>" + "<p>I am a replacement phone19</p>" + "</div>"); } AND HTML : <a href="javascript:void(0);" onclick="removeMe('remove19p');">Remove me</a> <a href="javascript:void(0);" onclick="addMe();">Add me</a>
unknown
d4145
train
I made assumptions that you can work with functional components. const Temperature = () => { const [temperature, setTemperature] = useState(); const consumerClient = new EventHubConsumerClient( "$Default", connectionString, clientOptions ); const getTemperature = async () => { consumerClient.subscribe({ processEvents: async (events, context) => { for (const event of events) { var temperature = event.body.temperature; var humidity = event.body.humidity; setTemperature(temperature); console.log(temperature); console.log(humidity); } }, processError: async (err, context) => { console.log(`Error : ${err}`); }, }); }; useEffect(() => { getTemperature().catch((error) => { console.error("Error running sample:", error); }); return () => { // cleanUpFunction if applicable // consumerClient.unsubscribe() }; }, []); return ( <div className="environment"> <p>The temperature is {temperature}&#176; Celcius.</p> </div> ); }; The useEffect() with empty dependencies [] array acts like componentDidMount as in, it only runs once. i.e calls your getTemperature on first load. After that, the setState() will keep the temperature value updated, and re-render the component whenever the temperature updates.
unknown
d4146
train
This happens because the image is interpolated from a TV screen. If you would take this image from a paper for example this is would not happen
unknown
d4147
train
Use raw_input for your paname and pbname variables. Be sure to import random at the top of your file. It would also be better to use int(raw_input("How many...")) for bulletcounter, too, I think, than input, since this can be used to evaluate any arbitrary python code. Also, it would be worth checking to see which version of Python you are using, when you invoke it using the env command. If, at the command line, you run: /usr/bin/env python -V and are getting "Python 2.x.y" instead of Python 3, and you are expecting to be using Python 3, consider changing that first line to call your Python 3 interpreter instead. The recommendations noted above assume you are using Python 2.
unknown
d4148
train
On Github for a particular repository you can go to the graphs tab: As you can see there are a number of options there. To get the number of lines that a user has changed select the Contibutions option. This will display a card for each user with the number of commits and number of lines added and removed, similarly to the below:
unknown
d4149
train
Adding multiple sources to an audio element does not create a playlist, it is to support different audio formats and your browser will simply play the first one it can, which is why you say only the last one is playing. To have multiple songs you choose between you will have to write some javascript. Here is some information on audio in javascript. It sounds like you will have to create a separate button for playing the next song, add a click event that changes the source of the audio element and plays it.
unknown
d4150
train
Out the top of my head, something like this: -(void)placeImages { NSMutableArray *images = [NSMutableArray arrayWithObjects:@"image1.png", @"image2.png", @"image3.png", @"image4.png", @"image5.png", @"image6.png", @"image7.png", @"image8.png", nil]; // etc... NSArray *buttons = [NSArray arrayWithObjects:btn1, btn2, btn3, btn4, nil]; for (UIButton *btn in buttons) { int randomIndex= random() % images.length; UIImage *img = [images objectAtIndex:randomIndex]; [btn setImage:img forState:UIControlStateNormal]; [images removeObjectAtIndex:randomIndex]; } A: -(void)randomizeArray:(NSMutableArray *)array { int i, n = [array count]; for(i = 0; i < n; i++) { int destinationIndex = random() % (n - i) + i; [array exchangeObjectAtIndex:i withObjectAtIndex:destinationIndex]; } } this is a answer for your question A: btnLetter1, btnLetter2, btnLetter3, btnLetter4 = UIButtons that should present an image. LatterArray = the array that containes all of the images. imgcounter = the current counter index if the 'imgcounter' is on '2' so one of the 'btnLetters' buttons (random one between 1-4) should containe an image from 'LettersArray' that located in index number '2' equal to the 'imgcounter'. all the other remining 3 'btnLetter' should containe a random image from 'LettersArray'. when the function called again the 'imgcounter' will be '3', now one of the 'btnLetters' (random one) should containe another image from 'LettersArray that is located at index number '3', again, equal to the 'imgcounter'. the other remining 3 'btnLetter' should containe again randome image from 'Letters Array' and so on.. -(void)PlaceWordAndPictueOnScreen2 { NSMutableArray * ButtonArray = [[NSMutableArray alloc] initWithObjects:btnLetter1,btnLetter2,btnLetter3,btnLetter4, nil]; int CorrectImg = random() % [ButtonArray count]; UIImage * img = [UIImage imageNamed:[LettersArray objectAtIndex:imgcounter]]; UIButton * btn = [ButtonArray objectAtIndex:CorrectImg]; [btn setImage:img forState:UIControlStateNormal]; [ButtonArray removeObjectAtIndex:CorrectImg]; NSLog(@"img correct: %i",CorrectImg); while ([ButtonArray count] != 0)// how many times u want to run this { int imgRand = random() % [LettersArray count]; //number for random image int btnRand = random() % [ButtonArray count]; //number for random button //get that random image UIImage * img = [UIImage imageNamed:[LettersArray objectAtIndex:imgRand]]; //get that random button UIButton * button = [ButtonArray objectAtIndex:btnRand]; //put image on that button [button setImage:img forState:UIControlStateNormal]; [ButtonArray removeObjectAtIndex:btnRand]; NSLog(@"btnrnd: %i",btnRand); NSLog(@"imgrnd: %i",imgRand); } }
unknown
d4151
train
You can't execute your js method before the elements get loaded. so wrap your code in head/body check this fiddle A: Here is a possible solution (no jQuery) : http://jsfiddle.net/wared/A6w5e/. As you might have noticed, links are not "disabled", I simply save the id of the DIV which is currently displayed in order to check the requested id before toggling : if (current !== id). Another thing to note is that toggle_visibility is overwritten (only once) inside itself. It might look weird, but it's just a way to create a closure in order to enclose the variable named current inside a private context. The goal is to avoid polluting the parent scope. Lastly, I've modified the original code to hide all divs except the one targeted by id. function toggle_visibility(id) { var current = 'Blue'; (toggle_visibility = function (id) { var div, l, i; if (current !== id) { current = id; div = document.getElementsByClassName('toggle360'); l = div.length; i = 0; for (; i < l; i++) { div[i].style.display = div[i].id === id ? 'block' : 'none'; } } })(id); } A: Wrap your code in head or body. You are executing your code before DOM is created Fiddle Demo A: A couple people have commented why it doesn't work in fiddle. To answer the question.... It easy to toggle visibility using jquery if there are only two divs: $(document).delegate('.flashlinks a', 'click', function () { $('.toggle360').toggle(); }); I would use a css class to disable the links. Then I would select what to do with the click based on if the class was present: $(document).delegate('.flashlinks a:not(".disabled")', 'click', function () { $('.toggle360').toggle(); $('.flashlinks a').toggleClass("disabled"); }); $(document).delegate('.flashlinks a.disabled', 'click', function () { e.preventDefault(); }); and in my css I would have something like .disabled { color: black; text-decoration:none; } jsfiddle
unknown
d4152
train
How this was solved: try to clear the cache first. Then if it is still not working, composer remove, composer require and composer update again. โ€“ Brewal A: When you try to clear cache but its not getting cleared you should use --no-warmup option, this will make sure that you cache is re-generated and cache is not warmed up only. I think this can help you: php app/console cache:clear --env=prod --no-warmup or php app/console cache:clear --env=dev --no-warmup
unknown
d4153
train
With the reflection solution you would suffer the N+1 effect detailed here: Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans You could use the OpenSessionInView instead, you will be affected by the N+1 but you will not need to use reflection. If you use this pattern your transaction will remain opened until the end of the transaction and all the LAZY relationships will be loaded without a problem. For this pattern you will need to do a WebFilter that will open and close the transaction.
unknown
d4154
train
Whenever you come back to your Music Play Activity Oncreate() is not called so your drawable resource load on Onpause() or Onstart(), Everytime Oncreate() is not calling.
unknown
d4155
train
Have a look at storefront/base.html.twig. There you will see, that currently the breadcrumb-template gets passed the context and the category. If you want to also use some product-information, you have to overwrite this block like this: {% block base_breadcrumb %} {% sw_include '@Storefront/storefront/layout/breadcrumb.html.twig' with { context: context, category: page.product.seoCategory, product: page.product } only %} {% endblock %} Then you can use product in the breadcrumb-template.
unknown
d4156
train
You want to compare the values of the two strings using .equals() checksum.equals(checksumFile) Using == compares the references and basically asks whether the two references point to the same object, which they don't.
unknown
d4157
train
As you already know it can be 10 calls / sec. Code can be simple as follows : public void SomeFunction() { foreach(MyEvent changedEvent in changedEvents) { service.ChangeEvent(changedEvent); Thread.Sleep(100);//you already know it can be only 10 calls / sec } } Edit : Ok got it, please see if following alternative will be helpful, it only allows 10 or less calls per second depending on how its performing : public void SomeFunction() { DateTime lastRunTime = DateTime.MinValue; foreach(MyEvent changedEvent in changedEvents) { lastRunTime = DateTime.Now; for (int index = 0; index < 10; index++) { if (lastRunTime.Second == DateTime.Now.Second) { service.ChangeEvent(changedEvent); } else { break;//it took longer than 1 sec for 10 calls, so break for next second } } } }
unknown
d4158
train
In the batch_job_execution_context table, you may have some records which are created by the spring batch version 3. While you are trying to execute new execution with spring batch version 4, it trying to compare previous records. So it trying to deserialize those older records. this is why you are getting this issue. Spring batch version 3 records are like bellow in the batch_job_execution_context table {"map":[{"entry":{"string":["key","value"]}}]} Spring batch version 4 records are like bellow in the batch_job_execution_context table {"key":"value"} Remove all the records created by version 3. This will fix the issue.
unknown
d4159
train
At first I would recommend you to use $("#outer").innerWidth() when calculating maxCount as in general if you have also a padding in container, you can use only the inner part of the element. And finally as a solution to your problem I can suggest you to add box-sizing: border-box; -moz-box-sizing: border-box; to the #outer div to maintain its width. Unfortunately this doesn't work as I expect, there is a little more space from rigth side than from left. But there is another strange thing that I don't understand, those white spaces between divs (see the screenshot), I can't find CSS affecting these parts. I think that these spaces are affecting the calculation that's why I get a little more left-padding than we need. Here is the jsFiddle link A: Here you go: http://jsfiddle.net/dan_barzilay/fy494/ What i did was instead of changing the #outer padding left to freeSpace / 2 and by that increasing the size only from the left side I changed both padding-right and padding-left by freeSpace / 4 to keep the images in the center. $("#outer").css({"padding-left": freeSpace / 4, "padding-right": freeSpace / 4});
unknown
d4160
train
you have to remove the () from values , or it will be considered as one entry . try that: INSERT INTO evraklar(evrak_tipi_grubu, evrak_tipi, evrak_konu, evrak_subeye_gelis_tarihi, evrak_gonderen, evrak_alici, evrak_tarihi, evrak_sayisi, evrak_aciklama, evrak_kurum_icindenmi, gelen_evrak_tarihi, gelen_evrak_sayi, gelen_evrak_etakip, evrak_kaydeden_ybs_kullanici_id,kaydeden_kullanici_birim_id) VALUES (6,43,'Test amaรงlฤฑ girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,566,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evraฤŸa cevaben yazฤฑlan yazฤฑdฤฑr. Alฤฑcฤฑsฤฑ:Antalya ValiliฤŸi - ฤฐl SaฤŸlฤฑk MรผdรผrlรผฤŸรผ',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaรงlฤฑ girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,612,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evraฤŸa cevaben yazฤฑlan yazฤฑdฤฑr. Alฤฑcฤฑsฤฑ:Mersin ValiliฤŸi - ฤฐl SaฤŸlฤฑk MรผdรผrlรผฤŸรผ',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaรงlฤฑ girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evraฤŸa cevaben yazฤฑlan yazฤฑdฤฑr. Alฤฑcฤฑsฤฑ:NiฤŸde ValiliฤŸi - ฤฐl SaฤŸlฤฑk MรผdรผrlรผฤŸรผ',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaรงlฤฑ girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evraฤŸa cevaben yazฤฑlan yazฤฑdฤฑr. Alฤฑcฤฑsฤฑ:NiฤŸde ValiliฤŸi - ฤฐl SaฤŸlฤฑk MรผdรผrlรผฤŸรผ',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaรงlฤฑ girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evraฤŸa cevaben yazฤฑlan yazฤฑdฤฑr. Alฤฑcฤฑsฤฑ:NiฤŸde ValiliฤŸi - ฤฐl SaฤŸlฤฑk MรผdรผrlรผฤŸรผ',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685) A: Remove () near values INSERT INTO evraklar(evrak_tipi_grubu, evrak_tipi, evrak_konu, evrak_subeye_gelis_tarihi, evrak_gonderen, evrak_alici, evrak_tarihi, evrak_sayisi, evrak_aciklama, evrak_kurum_icindenmi, gelen_evrak_tarihi, gelen_evrak_sayi, gelen_evrak_etakip, evrak_kaydeden_ybs_kullanici_id,kaydeden_kullanici_birim_id) VALUES (6,43,'Test amaรงlฤฑ girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,566,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evraฤŸa cevaben yazฤฑlan yazฤฑdฤฑr. Alฤฑcฤฑsฤฑ:Antalya ValiliฤŸi - ฤฐl SaฤŸlฤฑk MรผdรผrlรผฤŸรผ',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaรงlฤฑ girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,612,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evraฤŸa cevaben yazฤฑlan yazฤฑdฤฑr. Alฤฑcฤฑsฤฑ:Mersin ValiliฤŸi - ฤฐl SaฤŸlฤฑk MรผdรผrlรผฤŸรผ',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaรงlฤฑ girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evraฤŸa cevaben yazฤฑlan yazฤฑdฤฑr. Alฤฑcฤฑsฤฑ:NiฤŸde ValiliฤŸi - ฤฐl SaฤŸlฤฑk MรผdรผrlรผฤŸรผ',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaรงlฤฑ girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evraฤŸa cevaben yazฤฑlan yazฤฑdฤฑr. Alฤฑcฤฑsฤฑ:NiฤŸde ValiliฤŸi - ฤฐl SaฤŸlฤฑk MรผdรผrlรผฤŸรผ',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaรงlฤฑ girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evraฤŸa cevaben yazฤฑlan yazฤฑdฤฑr. Alฤฑcฤฑsฤฑ:NiฤŸde ValiliฤŸi - ฤฐl SaฤŸlฤฑk MรผdรผrlรผฤŸรผ',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685);
unknown
d4161
train
You have a fixed height for the container and overflow set to hidden. Since the divs exceed that height, the overflow can't be seen. Try this: .container { height: 500px; width: 500px; border: solid 3px black; overflow: scroll; } .header { height: 25px; background-color: #333; right: 0; left: 0; } .sidebar { position: fixed; top: 0; bottom: 0; width: 75px; margin-top: 35px; border: solid 1px grey; } .main { height: 100%; padding-left: 75px; } .main-container { width: 65%; height: 100%; } .main-content { height: 100%; overflow-y: scroll; border: solid 1px red; } .main-header { height: 20px; border: 1px solid black; } .detail-container { float: right; width: 35%; height: 100%; border: solid 1px grey; } .top-info { padding: 75px 0; } .items-container { height: 100%; overflow-y: scroll; border: solid 1px red; } .item { padding: 100px 0; } .blue { background-color: blue; } .orange { background-color: orange; } .grey { background-color: grey; } .purple { background-color: purple; } .content { width: 65%; height: 100%; } <div class="container"> <div class="header"></div> <div class="sidebar"></div> <div class="main"> <div class="detail-container"> <div class="top-info"></div> <div class="items-container"> <div class="item blue"></div> <div class="item orange"></div> <div class="item blue"></div> <div class="item orange"></div> </div> </div> <div class="main-container"> <div class="main-header"></div> <div class="main-content"> <div class="item grey"></div> <div class="item purple"></div> <div class="item grey"></div> <div class="item purple"></div> <div class="item grey"></div> <div class="item purple"></div> <div class="item grey"></div> <div class="item purple"></div> </div> </div> </div> </div> A: I could solve this with some javascript. This should addapt to any content size of your other blocks as long as the markup structure doesn't change. Good luck! $(function(){ //creating vars based on jquery objects $itemsContainer = $('.items-container'); $mainContent = $('.main-content'); $container = $('.container'); $header = $('.header'); $mainHeader = $('.main-header'); //calculating heights var containerH = $container.height(); var headerH = $header.height(); var mainHeaderH = $mainHeader.height(); //assigning new height to main-content class $mainContent.css("height", (containerH - headerH - mainHeaderH) + "px"); //similar operation for items-container //creating vars based on jquery objects $topInfo = $('.top-info'); //calculating heights var topInforH = $topInfo.outerHeight(); //since in your example top-info has no content only padding, you will need to use the method outerHeight instead of height //assigning new height to main-content class $itemsContainer.css("height", (containerH - headerH - topInforH) + "px"); }); By the way, I updated your jsfiddle with my solution, so you can test it. A: When you use a height of 100% it sets it to the full height regardless of other sibling elements. So they are at 100% of the parent element but then the headers are pushing them down. You will have to use fixed heights on all elements. Or set one to 20% and other to 80% etc. .main-content { width: 452px; } .items-container {width: 352px; }
unknown
d4162
train
Try https://github.com/swisspol/GCDWebServer#webdav-server-in-ios-apps it seems to be doing well and active. A: Try combining the DynamicServer and iPhoneHTTPServer projects in CocoaHTTPServer. Use NSFileManager to get the file contents. You have to use a web browser...
unknown
d4163
train
Since you didn't include adequate code, I'm unable to guess what your issue is. Make sure you put CSS inside a <style> HTML tag, or inside a stylesheet, neither of which are visible inside your included code. This seemed to work for me: <!DOCTYPE html> <html> <head> <style> #main{text-align: center;} </style> </head> <body> <div id="main"> <h1 id="title"> Dr.Norman Borlaug</h1> </div> <div id="img-div"> <div class="row"> <img src="img/normanwithpeople.png" alt="Norman Borlaug having a conversion with colleuges"> <img src="img/norman-borlaug.png" alt="Norman Borlaug in a field smiling" id ="image"> <p id="img-caption"></p> </div> <div class="column"> <img src="img/normanatconference.png" alt="Norman Borlaug at a confrence"> <img src="img/normanwithjimmy.png" alt="Norman_Borlaug with former President Jimmy Carter"> </div> <div class="column"> <img src="img/norman.png" alt="Norman Borlaug and his wife"> <img src="img/normangetsaward.png" alt="Norman Borlaug receives an award from president George W Bush"> </div> <div class="column"> <img src="img/normanwithgranddaughter.png" alt="Norman Borlaug with his granddaughter who is carrying his great grandchild"> <img src="img/normaninmexico.jpg" alt=" A painting of Norman Borlaug in a field in Mexico"> </body> </div> </html>
unknown
d4164
train
As per your JsFiddle, I found that there are so many silly mistakes in your HTML code. Here is your ASP.NET code:- <form id="form1" runat="server"> <div class="form-group"> <asp:TextBox ID="txtname" runat="server" CssClass="form-control"></asp:TextBox> </div> <div class="form-group"> <asp:TextBox ID="txtmobileno" runat="server" CssClass="form-control"></asp:TextBox> </div> <div class="form-group"> <asp:TextBox ID="txtEmail" runat="server" CssClass="form-control"></asp:TextBox> </div> <div class="form-group"> <asp:TextBox ID="txtSubject" runat="server" CssClass="form-control"></asp:TextBox> </div> <asp:Button ID="btnSubmit" runat="server" CssClass="btn btn-primary pull-right" OnClick="btnSubmit_OnClick" Width="100" Text="Submit" /> </form> Code behind cs code Created a SendMail() function which will fire on buttonclick Note:- I haven't added validations on the controls, so if you want it you can add as per your requirement. protected void SendMail() { // Gmail Address from where you send the mail var fromAddress = "[email protected]"; // any address where the email will be sending var toAddress = txtEmail.Text.ToString(); //Password of your gmail address const string fromPassword = "Your gmail password"; // Passing the values and make a email formate to display string subject = txtSubject.Text.ToString(); // Passing the values and make a email formate to display string body = "From: " + txtname.Text + "\n"; body += "Email: " + txtEmail.Text + "\n"; // smtp settings var smtp = new System.Net.Mail.SmtpClient(); { smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.Credentials = new NetworkCredential(fromAddress, fromPassword); smtp.Timeout = 20000; } // Passing values to smtp object smtp.Send(fromAddress, toAddress, subject, body); } Now the above function will be called on Button click so that every time you enter the details you can call that function. protected void btnSubmit_OnClick(object sender, EventArgs e) { try { SendMail(); // Send mail function to send your mail txtname.Text = ""; txtEmail.Text = ""; txtmobileno.Text = ""; txtSubject.Text = ""; } catch (Exception ex) { ex.Message.ToString(); } } For a detail explanation have a look at below link:- http://www.codeproject.com/Tips/371417/Send-Mail-Contact-Form-using-ASP-NET-and-Csharp
unknown
d4165
train
Just check if $_POST['search'] is blank then display your message else execute your query. A: <?php $con=mysql_connect('localhost', '1093913', 'tanim1996'); $db=mysql_select_db('1093913'); if(isset($_POST['button'])){ //trigger button click $numRows = 0; if(!empty($_POST['search'])) { $search = mysql_real_escape_string($_POST['search']); $query = mysql_query("select * from iconic19 where student_id like '%{$search}%' || name like '%{$search}%' || phone like '%{$search}%' || blood like '%{$search}%' || district like '%{$search}%' "); $numRows = (int)mysql_num_rows($query); } if ($numRows > 0) { while ($row = mysql_fetch_array($query)) { echo "<tbody>"; echo "<tr>"; echo "<td data-label='Student ID'>".$row['student_id']."</td>"; echo "<td data-label='Name' style='font-weight:bold;' >".$row['name']."</td>"; echo "<td data-label='Mobile No'>"."<a href='tel:".$row['phone']."'>".$row['phone']."</a>"."</td>"; echo "<td data-label='Blood' style='color:red; font-weight:bold;' >".$row['blood']."</td>"; echo "<td data-label='Email'>"."<a href='mailto:".$row['email']."'>".$row['email']."</a>"."</td>"; echo "<td data-label='District'>".$row['district']."</td>"; echo "</tr>"; echo "</tbody>"; } } else { echo "<div class='error-text'>No results</div><br><br>"; } } else { //while not in use of search returns all the values $query = mysql_query("select * from iconic19"); while ($row = mysql_fetch_array($query)) { } } mysql_close(); ?> What I have done was creating a new variable $numRows with a default value of 0. If your search is empty there is no query to the database. I escaped your $search variable. BTW: Please change to mysqli, the mysql extension is no longer supported in newer php versions.
unknown
d4166
train
Just add a negation of > sign: (<img[^>]*?photobucket.*?>) https://regex101.com/r/tZ9lI9/2 A: grep -o '<img[^>]*src="[^"]*photobucket[^>]*>' infile -o returns only the matches. Split up: <img # Start with <img [^>]* # Zero or more of "not >" src=" # start of src attribute [^"]* # Zero or more or "not quotes" photobucket # Match photobucket [^>]* # Zero or more of "not >" > # Closing angle bracket For the input file <img src="/imgs/test.jpg"> <img src="/imgs/thiswillgetpulledtoo.jpg"><p>We like photobucket</p> <img src="/photobucket/img21.png"> <img alt="photobucket" src="/something/img21.png"> <img alt="something" src="/photobucket/img21.png"> <img src="/photobucket/img21.png" alt="something"> <img src="/something/img21.png" alt="photobucket"> this returns $ grep -o '<img[^>]*src="[^"]*photobucket[^>]*>' infile <img src="/photobucket/img21.png"> <img alt="something" src="/photobucket/img21.png"> <img src="/photobucket/img21.png" alt="something"> The non-greedy .*? works only with the -P option (Perl regexes). A: Try the following: <img[^>]*?photobucket[^>]*?> This way the regex can't got past the '>' A: Try with this pattern: <img.*src=\"[/a-zA-Z0-9_]+photobucket[/a-zA-Z0-9_]+\.\w+\".*> Iยดm not sure the characters admited by the name folders, but you just need add in the ranges "[]" before and after the "photobucket".
unknown
d4167
train
set does not mutate the object on which it is working - it returns a new object with the new value set. You can use something like this: let params = new HttpParams() .set('Id', Id) .set('name', name) if (startDate != null) { params = params.set('startDate', startDate.toDateString()); } if (endDate != null) { params = params.set('endDate', endDate.toDateString()); } Note how the params object is being reassigned. Also note the use of != to protect against both null and undefined. A: Instead of using the HttpParams object you can define and mutate your own object and pass it within the http call. let requestData = { Id: Id, name: name } if (startDate) { //I am assuming you are using typescript and using dot notation will throw errors //unless you default the values requestData['startDate'] = startDate } if (endDate) { requestData['endDate'] = endDate } //Making the assumption this is a GET request this.httpClientVariableDefinedInConstructor.get('someEndpointUrl', { params: requestData })
unknown
d4168
train
I faced the same issue. This article is Gold link 1.In auth route File I had following code const CLIENT_HOME_PAGE_URL = "http://localhost:3000"; // GET /auth/google // called to authenticate using Google-oauth2.0 router.get('/google', passport.authenticate('google',{scope : ['email','profile']})); // GET /auth/google/callback // Callback route (same as from google console) router.get( '/google/callback', passport.authenticate("google", { successRedirect: CLIENT_HOME_PAGE_URL, failureRedirect: "/auth/login/failed" })); // GET /auth/google/callback // Rest Point for React to call for user object From google APi router.get('/login/success', (req,res)=>{ if (req.user) { res.json({ message : "User Authenticated", user : req.user }) } else res.status(400).json({ message : "User Not Authenticated", user : null }) }); 2.On React Side After when user click on button which call the above /auth/google api loginWithGoogle = (ev) => { ev.preventDefault(); window.open("http://localhost:5000/auth/google", "_self"); } 3.This will redirect to Google authentication screen and redirect to /auth/google/callback which again redirect to react app home page CLIENT_HOME_PAGE_URL 4.On home page call rest end point for user object (async () => { const request = await fetch("http://localhost:5000/auth/login/success", { method: "GET", credentials: "include", headers: { Accept: "application/json", "Content-Type": "application/json", "Access-Control-Allow-Credentials": true, }, }); const res = await request.json(); //In my case I stored user object in redux store if(request.status == 200){ //Set User in Store store.dispatch({ type: LOGIN_USER, payload : { user : res.user } }); } })(); 5.last thing add cors package and following code in server.js/index.js in node module // Cors app.use( cors({ origin: "http://localhost:3000", // allow to server to accept request from different origin methods: "GET,HEAD,PUT,PATCH,POST,DELETE", credentials: true // allow session cookie from browser to pass through }) ); A: Your authentication should be done server side. Here is how it works. * *You make a fetch or axios call to your authentication route. *Your authentication route sends a request to Google's Authentication servers. This is important to have on the backend because you will need to provide your clientSecret. If you were to store this on the frontend, it would make it really easy for someone to find that value and compromise your website. *Google authenticates the user and then sends you a set of tokens to your callback url to use for that user (refresh, auth, etc...). Then you would use the auth token for any additional authorization until it expires. *Once that expires, you would use the refresh token to get a new authorization token for that client. That is a whole other process though. Here is an example of what that looks like with Passport.js: https://github.com/jaredhanson/passport-google-oauth2 EDIT #1: Here is an example with comments of the process in use with Facebook, which is the same OAuth codebase: https://github.com/passport/express-4.x-facebook-example/blob/master/server.js A: Redux can really help with achieving this and this follows the same logic as Nick B already explained... * *You set up oauth on the server side and provide an endpoint that makes that call *You set up the button on you react frontend and wire that through an action to the endpoint you already setup *The endpoint supplies a token back which you can dispatch via a reducer to the central redux store. *That token can now be used to set a user to authenticated There you have it.
unknown
d4169
train
There is no canonical definition of 'empty value' for either Integer or Date. You just program what you mean, and 'empty' is not a valid answer to the question 'what do you mean'. For example: "Empty strings, the 0 integer, and sentinel instant value with epochmillis 0 (Date is a lie. It does not represent dates; it represents instants, and badly at that; use java.time.Instant instead normally)". Then, you just.. program that: for (Object obj : result) { if (obj == null) return false; if (obj instanceof Date) { if (((Date) obj).getTime() == 0) return false; } else if (obj instanceof String) { if (((String) obj).isEmpty()) return false; } else if (obj instanceof Integer) { if (((Integer) obj).intValue() == 0) return false; } else throw new IllegalStateException("Unexpected type: " + obj.getClass()); return true; } It's an if for every type because there is no such thing as CouldBeEmpty as an interface that all these types implement. Said differently, "an empty Date" isn't a thing. A: This should work. I tried it with a mock array, but I don't know if it is exactly the same as yours: public static void main(String[] args) { Object result[] = new Object[5]; result[0] = 1; result[1] = ""; result[3] = 5; result[4] = LocalDate.now(); result[5] = "string"; boolean listcontainsnullorempty = false; for(var obj: result){ if(obj == null || obj.equals("")){ listcontainsnullorempty = true; } } System.out.println(listcontainsnullorempty); } depending on your list, you might need to add || obj.isEmpty() in the if-clause.
unknown
d4170
train
Both approaches will produce SQL and execute it on the server. The SQL should be similar/identical and performance will be near identical. If you want to see the SQL being produced i suggest you open up the "SQL Server Profiler" and run a Trace! The trace will also show you execution time taken. Side note: Your performance gains will come from correctly configured Table Indexes. A: I know its old question but i would like to add some info... Even both are translated to SQL query and executed on SQL Server, the difference in performance will be related to the way that lightSwitch (oData v3) Generate the statement.. Taking in consideration between the following; 1- select * from Table where colA like ('foo') 2- select * from Table where colA = 'foo' TOP(1) general if colA is primary Key at the table then SQL will stop searching after the first match on the second if just want to retrieve only one ,, and the equal is better performance... you can trace the generated link query from each one on file msls-2.5.2.js line 6803 to 6900.
unknown
d4171
train
This doesnยดt seem to be an error in your script. You wrote in line 147 of index.html: <script src="Form Builder.js"></script>enter code here But ist should be: <script src="script.js"></script> Here is a Plunker
unknown
d4172
train
So for anybody who may be interested about this topic , here is my experience : We finally decided not to use MYSQL portioning and instead using database sharding. The reason for that is: no matter how good you implement the portioning there is still the fact that data needs to indexed and brought into the memory when needed and for our system which is handling up to 500,000 user's emails this can simply become a major hardware issue over the time as people receive mail and will force you to buy more expensive hardware . Also there is another hidden cost in MYSQL which is the altering tables schema which can simply become impossible if you have a big table and limited resources. After using MSSQL and Oracle in real world scenario I was NOT really impressed by the way MYSQL handles metadata updates and indexing. So the short answer would be do not use portioning for you database unless you are sure that you won't have major schema changes to your table/indexes and also your table will not grow too big. Although I have to say if you design a good index for your system(be very careful with primary keys because that is your clustered index in MYSQL and your queries will be much more efficient if you query on primary key index) you may not really need portioning at all (right now on one of our installations we have a table with +450,000,000 records and it is very fast when you use the primary key index to query the data) Another point is if there is a chronology in your data and you always have a date range to query it is good idea to use partitioning if your database does not grow too big and if you are intending to delete the old data after a while (like a log rotation,...) partitioning may be the best option because you can simply drop the partition instead of writing a delete process. Hope this will help you making the right decision.
unknown
d4173
train
$ tail -f app/logs/dev.log | grep "doctrine.DEBUG" A: To expand on your answer, especially on dev, I prefer to split each of my log channels so I can easily pipe each to their own output. In config_dev.yml, add: monolog: handlers: [...] doctrine: action_level: debug type: stream path: %kernel.logs_dir%/%kernel.environment%_doctrine.log channels: doctrine Then tail -f app/logs/dev_doctrine.log will give you a nice clean stream of every transaction as it happens. I add one for event, request and security also, but this is all personal preference, naturally.
unknown
d4174
train
It looks like ILinearSolverSensitivityReport.GetDualValue returns the shadow price. Hopefully this saves someone else a merry chase through dotPeek. :-)
unknown
d4175
train
By default, a restriction on mobile prevent you from playing multiple sounds. To avoid this, you need to set the ignoreMobileRestrictions property to true when setting up soundManager2.
unknown
d4176
train
As @PaulMcKenzie has rightly said, char* is not an array. I suggest using std::string instead of char* as well as in overload as follows: const bool Airplane::operator==(const std::string& str_to_be_compared) const { return this->(whatever variable stores the name of the plane) == str_to_be_compared; }
unknown
d4177
train
Good comparison you can find in Wiki: VB.NET In short: the greatest feature in VB.NET is Managed Code. It also contains a little difference between Long and Integer in VB6 and VB.NET. There are also many small syntax changes (for example, VB.NET support structured exception handling). A: VB6 is a old fashioned programming software from microsoft. It doesn't use as a base .NET framework which is used on every machine. Also visit Wkipedia VB A: .NET have multithreading and more functional components (for work with network for example). A: Visual Basic is a third-generation event-driven programming language and integrated development environment (IDE) from Microsoft for its Component Object Model (COM) programming model first released in 1991, final release was version 6 in 1998 (VB6) and declared legacy during 2008. Visual Basic.net is part of the .net framework (like C# or F#), first released in 2002, with constant Microsoft updates. You can use VB.Net in Visual Studio 2008 Express (free) or in any Visual Studio IDE, like the Visual Studio 2017 Community edition (also free). https://en.wikipedia.org/wiki/Comparison_of_Visual_Basic_and_Visual_Basic_.NET VB6 uses legagy frameworks like Dynamic Data Exchange (DDE) and DAO. The VB6 IDE is hard to install on new operating system (original setup gives errors on Windows 7, 8 or 10).
unknown
d4178
train
You can directly use the functional version of keras that will be easier for you. You will simply use all the layers to n = 18 and that output will connect to m1. Finally, you create the model. The code would be the following: model = vgg(weights="imagenet") input_ = model.input for l, n in model.layers: if n == 18: last_layer = l break #Upsampling m1 = last_layer m2 = Conv2DTranspose(512, (3, 3), strides=(2, 2), padding="same")(m1) concatenate1 = Concatenate(axis=-1)(m1, m2) new_model = Model(inputs=input_, outputs=concatenate1)
unknown
d4179
train
try to change sourceCompatibility JavaVersion.VERSION_1_6 targetCompatibility JavaVersion.VERSION_1_6 to sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 A: This can be a gradle issue. Consider deleting gradle cache and retrying. Gradle cache is at C:\Users\yourUserName\.gradle\caches (windows) or ~/.gradle/caches (linux) Note: If your area is under sanction, you must bypass this using proxy or VPN. A: At first, there is no need to inject the recyclerView's, CardView's and material libraries into the gradle file because in the android studio i.e. 3.4 and above all these libraries are already inserted by default. Just replace your this library -> implementation 'com.android.support:appcompat-v7:28.0.0' with implementation 'androidx.appcompat:appcompat:1.1.0' and plus, go into the gradle.properties file and add this line -> "android.useAndroidX=true" and your project will work fine. In my case it worked.
unknown
d4180
train
What you want to do sounds like a nearest neighbour search. K-d trees are an efficient data structure to achieve this. The CGAL library has spatial searching functions if you're looking for a library for C++.
unknown
d4181
train
You may use (?<!\S)(?:AB|CG|MS|MT|NA|OQ|TS)-?\d{1,4}(?!\S) See the regex demo Details * *(?<!\S) - the previous char should be a whitespace or start of string *(?:AB|CG|MS|MT|NA|OQ|TS) - one of the 2-letter alternative *-? - an optional hyphen *\d{1,4} - one to four digits *(?!\S) - the next char should be a whitespace or end of string. PHP: if (preg_match_all('~(?<!\S)(?:AB|CG|MS|MT|NA|OQ|TS)-?\d{1,4}(?!\S)~', $s, $matches)) { print_r($matches[0]); }
unknown
d4182
train
I don't know of a replacement, but BufferedOutputStream doesn't contain much code. Just duplicate it from the full blown JDK source to your own replacement class. There is no rocket science in the class anyway.
unknown
d4183
train
Does std::string's c_str() method always return a null-terminated string? Yes. It's specification is: Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()]. Note that the range specified for i is closed, so that size() is a valid index, referring to the character past the end of the string. operator[] is specified thus: Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type T with value charT() In the case of std::string, which is an alias for std::basic_string<char> so that charT is char, a value-constructed char has the value zero; therefore the character array pointed to by the result of std::string::c_str() is zero-terminated. A: According to this, the answer is yes. A: c_str returns a "C string". And C strings are always terminated by a null character. This is C standard. Null terminating strings.
unknown
d4184
train
Solved it using the javascript concept used pageYOffset method. Complete code JavascriptExecutor executor = (JavascriptExecutor) driver; Long value = (Long) executor.executeScript("return window.pageYOffset;"); pageYOffset method will return the vertical pixels, so as soon I logged in got the vertical pixels and then scrolled to the back to top button and after performing the action on back to top button, again got the vertical pixels and validated it. A: isDisplayed() checks if the element is actually present in the viewport so it should work. May be put some wait in between clicking and checking isDisplayed for debugging puropose . if (element.isDisplayed()) { doSomething(); } else { doSomethingElse(); }
unknown
d4185
train
You need to change the onchange to fixOrder() A: JS Fiddle Your onchange event is onchange="fixOrder" which is not really doing anything. If you change it to fixOrder() you will call the function fixOrder when the change event is fired. Furthermore: * *I don't think const is a reserved word in JavaScript. I don't think JS has constants. You should change that line from const TAX to var TAX; *Unlike parseInt, which takes two arguments (string and base/radix), parseFloat only takes one argument (string), so you can remove the , 10 from it I imagine you want something like: function fixOrder() { var TAX = 0.0975; var numPrice; var total; var tax; numPrice = parseFloat(document.getElementById("cost").value); tax = parseFloat(document.getElementById("tax").value); total = parseFloat(document.getElementById("total").value); numPrice = numPrice + (tax || numPrice * TAX); total = numPrice; var dec = new Number((total+'').split('.')[1]) || 0; total = document.getElementById("total").value = "$" + Number(parseInt(total) + '.' + Math.round( ( (dec+''.split('').reverse().join('') )/100 + '').split('').reverse().join('') )).toFixed(2); ); if (isNaN(numPrice)) { alert("Sorry,you must enter a numeric value to place order"); numPrice = 0; } } This will use the dollar amount of tax you enter, or if that doesn't exist, it will use the constant rate that you have supplied at the beginning (this was changed from .975 to .0975). Also, notice the new calculation from total, we're taking the decimal part of the number, dividing it by 100 to get to two decimal places, reversing it back so it's in the proper order again, and then rounding it to the nearest 1 (cent). HTML Body: <h1 align="left">Price Calculator</h1> <form name="form" id="form"> <p>Price: <input type="text" id="cost" name="cost" value="" onchange="fixOrder()" /></p> <p>Tax: &nbsp; <input type="text" id="tax" name="tax" value="" onchange="fixOrder()" /></p> <p>Total: <input type="text" id="total" name="total" value="" disabled="disabled" /></p> </form> A: When calling a function in JavasScript by an event, you need to mention the () after the name of the function you want to call.
unknown
d4186
train
Which "sampler" and how do you "call" it? * *Either there is a typo in your code i.e. you're trying to call the function which doesn't exist *Or there is a typo in your code in terms of passing parameters to the function, in case if it's overloaded the candidate is determined in the runtime depending on the argument types, like function expects an integer and you're passing a string to it or something like this In JMeter you can use Java code in 3 ways: * *in Java Request sampler *in JUnit Request sampler *write your own plugin
unknown
d4187
train
You need to round the user input number and not the range. So, it will be , in_array(round($number), range(65,74)); DEMO.
unknown
d4188
train
Use the contact form 7 plugin: http://wordpress.org/extend/plugins/contact-form-7/
unknown
d4189
train
BluetoothAdapter in the Android framework is declared final, so at the time you asked this question, it couldn't be mocked, neither with Mockito nor using Robolectric. However, Android unit testing has changed a lot since then. With recent versions of the tools, when you build unit tests the tools generate a patched android.jar with all the finals removed. This makes all Android classes available for mocking. Nowadays, if you want to mock any Bluetooth code, you can do so in the standard way. The code you've already tried will "just work" if you update to the latest tools. Alternatively, Robolectric has a ShadowBluetoothAdapter class built in now.
unknown
d4190
train
F") Dim rw As Range For Each rw In constData.rows If donationDict.Exists(rw(0)) Then donationDict(rw(0)).Add New Collection Else donationDict.Add rw(0), New Collection End If Next rw UserForm1.Show End Sub A: Try this out: Option Explicit Public donationDict As Scripting.Dictionary Sub ouvrir() Dim data As Range, id, ws As Worksheet Dim rw As Range, arr(), numArrCols As Long Set ws = ThisWorkbook.Worksheets("thirdSheet") Set data = ws.Range("A1:F" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row) Set donationDict = New Scripting.Dictionary numArrCols = data.Columns.Count - 1 ReDim arr(1 To numArrCols) 'empty array For Each rw In data.Rows id = rw.Cells(1).Value If Not donationDict.Exists(id) Then donationDict.Add id, New Collection 'new key: add key and empty collection End If donationDict(id).Add _ OneDimension(rw.Cells(2).Resize(1, numArrCols).Value) 'add the row value as 1D array Next rw For Each id In donationDict.Keys Do While donationDict(id).Count < 5 donationDict(id).Add arr 'add empty array Loop Next id ShowDict donationDict 'dump to Immediate window for review End Sub 'convert a 2D [row] array to a 1D array Function OneDimension(arr) OneDimension = Application.Transpose(Application.Transpose(arr)) End Function Sub ShowDict(dict) Dim k, e For Each k In dict.Keys Debug.Print "Key: " & k Debug.Print "------------------------" For Each e In dict(k) Debug.Print , Join(e, ",") Next e Next k End Sub
unknown
d4191
train
This is a known issue with Apache Cordova 6.3.1 and for the Visual Studio tools we've been working on a fix for this. To work around the issue for now, you'll need to perform the following steps: * *Add a developmentTeam property to the ios build settings in your project's build.json file (an example is shown below). *Set the build.json file's codeSignIdentity property to the static value iPhone Developer. *Setup a before_compile hook in your project to copy the developmentTeam property into the project's platforms/ios/cordova/build.xcconfig file. The project's build.json file should look something like the following: { "ios": { "debug": { "developmentTeam": "DEVELOPMENT_TEAM_NAME" }, "release": { "developmentTeam": "DEVELOPMENT_TEAM_NAME", "codeSignIdentity": "iPhone Developer" } } } To simplify the process, Darryl Pogue published a sample hook that makes the required changes to the project's build.xconfig file based on the build.json example shown above. To use this hook, copy the sample xcode8.js file to your project's hooks folder, and then modify the project's config.xml to execute it before the compilation step using the following code: <platform name="ios"> <hook type="before_compile" src="hooks/xcode8.js" /> </platform> Creating a Distribution Build At this point, the Cordova build process works, and you can run, test and debug your app. Unfortunately, the app isn't being signed with the correct development certificate needed for distribution. In order to sign them with a distribution certificate, you'll need to create an archive of the app by following the instructions found in: Uploading Your App to iTunes Connect. iOS 10 Developers building Cordova applications for iOS 10 may encounter the following errors: Http 404: Error mounting developer disk image Http 500: No devices found to debug. Please ensure that a device is connected and awake and retry. This is caused by the Mac development environment needing an update to several modules. To fix the issue, on Mac OS, open a terminal window and issue the following command: brew update && brew upgrade libimobiledevice --HEAD && brew upgrade ios-webkit-debug-proxy ideviceinstaller
unknown
d4192
train
First you need to specify proxy pass directive for your api calls - I would propose to add /api in your fetch calls. Than provide upstream using the same name for your backend service as specified in docker-compose.yml. It is important that backend service proceed the web service in docker-compose.yml, otherwise you would get connection error in nginx like this nginx: [emerg] host not found in upstream "backend:8080" You can update your nginx.conf as follows: upstream backend { server backend:8080; } server { listen 80; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html =404; } location /api { rewrite /api/(.*) /$1 break; proxy_pass http://backend; } include /etc/nginx/extra-conf.d/*.conf; } Or simply in your case provide a proxy pass to localhost as follows: server { listen 80; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html =404; } location /api { rewrite /api/(.*) /$1 break; proxy_pass http://localhost:8080; } include /etc/nginx/extra-conf.d/*.conf; } A: Sample Docker file, Included the Production build in the docker file FROM node:15.6.0-alpine3.10 as react-build # install and cache app dependencies COPY package.json package-lock.json ./ RUN npm install && mkdir /react-frontend && mv ./node_modules ./react-frontend WORKDIR /app/client/ COPY . . RUN npm run build # ------------------------------------------------------ # Production Build # ------------------------------------------------------ FROM nginx:1.16.0-alpine COPY --from=builder /react-frontend/build /usr/share/nginx/html RUN rm /etc/nginx/conf.d/default.conf COPY nginx/nginx.conf /etc/nginx/conf.d EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] To add nginx as a server to our app we need to create a nginx.conf in the project root folder. Below is the sample file server { listen 80; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
unknown
d4193
train
Seam is mainly an inversion of control (IoC) container that provides a lot of boilerplate functionality for web development. It has no real hard requirements for you to use JPA/Hibernate. It's just that the most usual scenario for Java web development is a database backend that's mapped by an ORM, of which JPA/Hibernate is probably the de-facto standard. If your data access layer (DAL) does not exist or is just wrapper around an existing API (web services, REST, etc.), Seam will also handle that scenario very easily and provide you with all its remaining functionality (session management, JSF integration, security, navigation flow management and lots more). In essence, a simple component (or set of) that exposes the API you mention and handles its state should be enough. Then again, I do not know your requirements, so I can't say that for sure. A more complex example is the Seam Social module in Seam 3. It uses Twitter, Facebook or other social web APIs to connect to those services and inject them into Seam's contexts', so that your application can leverage their functionality. I don't know if your scenario is so complex that it would require you to build an entire CDI module from scratch (as Seam Social does) but take a look at their documentation. It might give you some ideas on what further investigate.
unknown
d4194
train
Yes, your generate SQL is wrong. The query generated is: SELECT "ingredients".* FROM "ingredients" WHERE (14) LIMIT 1 whereas it should have been: SELECT "ingredients".* FROM "ingredients" WHERE id = 14 LIMIT 1 Since the condition in the first where clause always evaluates to true, it picks up 1 row randomly. Which row gets picked up depends on how your DBMS stores data internally. To know why the generated query is wrong, we'll need to see the code in your Controller's action.
unknown
d4195
train
you are right, the find wont work.. But if you know the method name and package name you can sort the list and search for your method..
unknown
d4196
train
Why not simply using new String(sd, "UTF-8"), which will return your characters. Worked on my machine, result: ์ˆ˜์ง„์ˆ˜์ง„์ˆ˜์ง„์ˆ˜์ง„์ˆ˜์ง„์ˆ˜์ง„์ˆ˜์ง„์ˆ˜์ง„์ˆ˜ A: The X in "%02X".format(sd(i) & 0xff) specifies upper case hexadecimal. Try %s to get the UTF-8 string.
unknown
d4197
train
As @Rogier Spieker mentioned, a more real world example would be something like Your code, usually in a separate file function addNumbers(a,b){ return a +b; } Your tests it('adds two numbers', function() { var actualValue = addNumbers(1,1); // toEqual() compares using common sense equality. expect(actualValue).toEqual(2); });
unknown
d4198
train
I'm bumping up against this too. I'm pretty sure the difference in the the counts is including or excluding "anonymous contributors". The GitHub endpoint accepts an anon param that can be set to True. Looking at its source, PyGithub doesn't accept any arguments for its get_contributors method, so it doesn't currently surface anon contributors. It could be forked or patched to take it. For my needs, I'm going to write my own method that makes a request for a repo, parses the "last" relation from the Link header and calculates based on the number of results on the last page. Still writing it, so I don't have a code sample for now. Sorry I don't have anything more actionable for the moment. A: This has been added since to PyGitHub. Now you just simply have to do: repo.get_contributors(anon="true")
unknown
d4199
train
You can use my example from gist or below. The idea is to have a main CompositeValidator that will be a holder of all your Validator or SmartValidator instances. It supports hints and can be also integrate with Hibernate Annotation Validator (LocalValidatorFactoryBean). And also it's possible to have more that one validator per specific Model. CompositeValidator.java @Component public class CompositeValidator implements SmartValidator { @Autowired private List<Validator> validators = Collections.emptyList(); @PostConstruct public void init() { Collections.sort(validators, AnnotationAwareOrderComparator.INSTANCE); } @Override public boolean supports(Class<?> clazz) { for (Validator validator : validators) { if (validator.supports(clazz)) { return true; } } return false; } @Override public void validate(Object target, Errors errors) { validate(target, errors, javax.validation.groups.Default.class); } @Override public void validate(Object target, Errors errors, Object... validationHints) { Class<?> clazz = target.getClass(); for (Validator validator : validators) { if (validator.supports(clazz)) { if (validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, errors, validationHints); } else { validator.validate(target, errors); } } } } } SomeController.java @Controller @RequestMapping("/my/resources") public class SomeController { @RequestMapping(method = RequestMethod.POST) public Object save( @Validated(javax.validation.groups.Default.class) // this interface descriptor (class) is used by default @RequestBody MyResource myResource ) { return null; } } Java Config @Configuration public class WebConfig { /** used for Annotation based validation, it can be created by spring automaticaly and you don't do it manualy */ // @Bean // public Validator jsr303Validator() { // LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); // // validator.setValidationMessageSource(...); // return validator; // } @Bean public WebMvcConfigurerAdapter webMvcConfigurerAdapter() { return new WebMvcConfigurerAdapter() { @Autowired private CompositeValidator validator; @Override public Validator getValidator() { return validator; } } } Or XML Config <!-- used for Annotation based validation, it can be created by spring automaticaly and you don't do it manualy --> <!--<bean id="jsr303Validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">--> <!-- <property name="validationMessageSource" ref="messageSource"/>--> <!--</bean>--> <mvc:annotation-driven validator="compositeValidator"> //... </mvc:annotation-driven> A: You can configure global Validator. http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#validation-mvc If you are using Java based spring configuration with WebMvcConfigurationSupport, you can override getValidator() /** * Override this method to provide a custom {@link Validator}. */ protected Validator getValidator() { return null; } You may call setValidator(Validator) on the global WebBindingInitializer. This allows you to configure a Validator instance across all @Controller classes. This can be achieved easily by using the Spring MVC namespace: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven validator="globalValidator"/> </beans> A: I have not found a build in Spring solution for this, but here is what I do. I declare my validator beans in the spring java configuration like so: @Bean public Validator studentValidator(){ return new StudentValidator(); } @Bean public Validator carValidator(){ return new CarValidator(); } Then I have all controllers extends a base controller like so: public abstract class BaseController <T> { public BaseController(List<Validator> validators) { super(); this.validators = validators; } //Register all validators @InitBinder protected void initBinder(WebDataBinder binder) { validators.stream().forEach(v->binder.addValidators(v)); } } The concrete class of this controller gets the List injected via dependency injection, like so: @Controller public class StudentController extends BaseController<Student>{ @Inject public StudentController(List<Validator> validators) { super(validators); } } The base Controller uses the @InitBinder call-back method to register all Validators. I am surprised that spring doesn't automatically register all objects in class path that implement the Validator interface.
unknown
d4200
train
You can do this (and a lot of other stuff) with Object.defineProperty. Here's a basic example: // our "constructor" takes some value we want to test var Test = function (value) { // create our object var testObj = {}; // give it a property called "false" Object.defineProperty(testObj, 'false', { // the "get" function decides what is returned // when the `false` property is retrieved get: function () { return !value; } }); // return our object return testObj; }; var f1 = Test(false); console.log(f1.false); // true var f2 = Test("other"); console.log(f2.false); // false There's a lot more you can do with Object.defineProperty. You should check out the MDN docs for Object.defineProperty for detail.
unknown