_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d8401
train
start with these tutorials http://www.tutorialspoint.com/android/android_php_mysql.htm http://www.tutorialspoint.com/android/android_php_mysql.htm after that here is how to repeate every 60 seconds boolean run=true; Handler mHandler = new Handler();//sorry forgot to add this ... ... public void timer() { new Thread(new Runnable() { @Override public void run() { while (run) { try { Thread.sleep(60000);//60000 milliseconds which is 60 seconds mHandler.post(new Runnable() { @Override public void run() { //here you send data to server } }); } catch (Exception e) { } } } }).start();} call it like this to start it timer() and to stop it just do run=false;
unknown
d8402
train
To install the SSH in the image, you need to more than you have done. Here is the example: FROM ubuntu:16.04 RUN apt-get update && apt-get install -y openssh-server RUN mkdir /var/run/sshd RUN echo 'root:THEPASSWORDYOUCREATED' | chpasswd RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config # SSH login fix. Otherwise user is kicked off after login RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd ENV NOTVISIBLE "in users profile" RUN echo "export VISIBLE=now" >> /etc/profile EXPOSE 22 CMD ["/usr/sbin/sshd", "-D"] When you have built the image, I suggest you push it into the ACR. Then you can use it in the Logic App and it will work fine. For more details, see Dockerize an SSH service.
unknown
d8403
train
This was fixed in https://github.com/encode/django-rest-framework/pull/6207 and released as part of DRF 3.9.2. More complete context can be read at https://github.com/encode/django-rest-framework/issues/6206.
unknown
d8404
train
You could expose IsFirstInSelection property in your ViewData class (I suppose you have it). Then you could place DataTrigger for monitoring changes like this: <Style.Triggers> <DataTrigger Binding="{Binding IsFirstInSelection}"> <Setter Property="Background" Value="Blue"/> </DataTrigger> </Style.Triggers> Also in your case I'd recommend to avoid changing HighlightBrushKey, but achieve your goal via changing Background property. You could also expose IsSelected property in ViewData class, so it looks this: public class ViewData: ObservableObject { private bool _isSelected; public bool IsSelected { get { return this._isSelected; } set { if (this._isSelected != value) { this._isSelected = value; this.OnPropertyChanged("IsSelected"); } } } private bool _isFirstInSelection; public bool IsFirstInSelection { get { return this._isFirstInSelection; } set { if (this._isFirstInSelection != value) { this._isFirstInSelection = value; this.OnPropertyChanged("IsFirstInSelection"); } } } } And your style sets Background based on both properties: <Style x:Key="TreeItemStyle" TargetType="{x:Type TreeViewItem}"> <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/> <Setter Property="IsFirstInSelection" Value="{Binding Path=IsFirstInSelection}"/> <Setter Property="Background" Value="Green"/> <Style.Triggers> <DataTrigger Binding="{Binding IsSelected}" Value="True"> <Setter Property="Background" Value="Red"/> </DataTrigger> <DataTrigger Binding="{Binding IsFirstInSelection}"> <Setter Property="Background" Value="Blue"/> </DataTrigger> </Style.Triggers> </Style> Of course in model or in view code behind you should monitor IsSelected property changed notifications and set/reset IsFirstInSelection according to selected items. I hope you understand my idea. ------- EDITED -------- At first I continue to insist that you should develop proper ViewData class: public class ViewData : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var ev = this.PropertyChanged; if (ev != null) { ev(this, new PropertyChangedEventArgs(propertyName)); } } public ViewData(string name) { this._personName = name; } private string _personName; public string PersonName { get { return this._personName; } set { if (this._personName != value) { this._personName = value; this.OnPropertyChanged("PersonName"); } } } private bool _isFirstSelected; public bool IsFirstSelected { get { return this._isFirstSelected; } set { if (this._isFirstSelected != value) { this._isFirstSelected = value; this.OnPropertyChanged("IsFirstSelected"); } } } } During handling SelectionChanged event you should modify property IsFirstSelected like this: public ObservableCollection<ViewData> MyList { get; set; } private void SelectionChanged(object sender, SelectionChangedEventArgs e) { var lb = sender as ListBox; if (lb != null) { MyLabel.Content = lb.SelectedItem; foreach (var item in this.MyList) { if (item == lb.SelectedItem) { item.IsFirstSelected = true; } else { item.IsFirstSelected = false; } } } } But default ListViewItem template doesn't react on Background setters so you should override its template in style: <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListViewItem"> <Grid Background="{TemplateBinding Background}"> <ContentPresenter Content="{Binding PersonName}"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="Yellow"/> </Trigger> <DataTrigger Binding="{Binding IsFirstSelected}" Value="True"> <Setter Property="Background" Value="Aqua" /> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> If this solution isn't acceptable, please tell me. I've some ideas but have no enough time to check them in code right now.
unknown
d8405
train
First: You should escape the fore slash by a backslash. Second: You should put the semicolon at the end of code. This will work: <?php $string = 'hello<span id="more-32"></span>world'; $pattern = '/<span id="more-\d+"><\/span>/'; $out = preg_split($pattern,$string); ?> Print the splitted string: foreach ($out as $value) { echo $value . '<br />'; } Output: hello world or: print_r($out); Output: Array ( [0] => hello [1] => world )
unknown
d8406
train
You need to pass trace_id as input argument def root(trace_id): return trace_id And trace_id is part of the url, not the query part: requests.get('http://my-service/' + trace_id) A: We have to look closer at your code. @app.route('/<trace_id>') String argument inside brackets is a path part after 'http://my_service/'. Full path of this API endpoint will be 'http://my_service/value_of_trace_id'. And this part 'value_of_trace_id' will be stored as 'trace_id' variable and passed to function body so you have to pass it as function (API endpoint) arg. @app.route('/<trace_id>') def api_endpoint(trace_id): return trace_id So, you have to use: requests.get('http://my-service/' + trace_id) I highly recommend read that or that.
unknown
d8407
train
I implemented something very similar to this for another project. This form allows you to popup a modal dialog from within a worker thread: public partial class NotificationForm : Form { public static SynchronizationContext SyncContext { get; set; } public string Message { get { return lblNotification.Text; } set { lblNotification.Text = value; } } public bool CloseOnClick { get; set; } public NotificationForm() { InitializeComponent(); } public static NotificationForm AsyncShowDialog(string message, bool closeOnClick) { if (SyncContext == null) throw new ArgumentNullException("SyncContext", "NotificationForm requires a SyncContext in order to execute AsyncShowDialog"); NotificationForm form = null; //Create the form synchronously on the SyncContext thread SyncContext.Send(s => form = CreateForm(message, closeOnClick), null); //Call ShowDialog on the SyncContext thread and return immediately to calling thread SyncContext.Post(s => form.ShowDialog(), null); return form; } public static void ShowDialog(string message) { //Perform a blocking ShowDialog call in the calling thread var form = CreateForm(message, true); form.ShowDialog(); } private static NotificationForm CreateForm(string message, bool closeOnClick) { NotificationForm form = new NotificationForm(); form.Message = message; form.CloseOnClick = closeOnClick; return form; } public void AsyncClose() { SyncContext.Post(s => Close(), null); } private void NotificationForm_Load(object sender, EventArgs e) { } private void lblNotification_Click(object sender, EventArgs e) { if (CloseOnClick) Close(); } } To use, you'll need to set the SyncContext from somewhere in your GUI thread: NotificationForm.SyncContext = SynchronizationContext.Current; A: Another option: Use ProgressWindow.Show() & implement the modal-window behavior yourself. parentForm.Enabled = false, position the form yourself, etc. A: You probably start your lengthy operation in a separate worker thread (e.g. using a background worker). Then show your form using ShowDialog() and on completion of the thread close the dialog you are showing. Here is a sample - in this I assume that you have two forms (Form1 and Form2). On Form1 I pulled a BackgroundWorker from the Toolbox. Then I connected the RunWorkerComplete event of the BackgroundWorker to an event handler in my form. Here is the code that handles the events and shows the dialog: public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { Thread.Sleep(5000); e.Result = e.Argument; } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { var dlg = e.Result as Form2; if (dlg != null) { dlg.Close(); } } private void button1_Click(object sender, EventArgs e) { var dlg = new Form2(); this.backgroundWorker1.RunWorkerAsync(dlg); dlg.ShowDialog(); } }
unknown
d8408
train
Well-formed. The using-directive doesn't introduce the name i in the global namespace, but it is used during lookup. The using-declaration uses qualified lookup to find i; qualified lookup in the presence of using-directives is specified in [3.4.3.2 p1, p2] (quotes from N4527, the current working draft): If the nested-name-specifier of a qualified-id nominates a namespace (including the case where the nested-name-specifier is ::, i.e., nominating the global namespace), the name specified after the nested-name-specifier is looked up in the scope of the namespace. [...] For a namespace X and name m, the namespace-qualified lookup set S(X,m) is defined as follows: Let S'(X,m) be the set of all declarations of m in X and the inline namespace set of X (7.3.1). If S'(X,m) is not empty, S(X,m) is S'(X,m); otherwise, S(X,m) is the union of S(Ni,m) for all namespaces Ni nominated by using-directives in X and its inline namespace set. So, for qualified lookup, the first step is to look for declarations of i made directly in the namespace indicated by the nested-name-specifier (:: in this case). There are no such declarations, so lookup then proceeds to the second step, which is to form the set of all declarations of i found by qualified lookup in all namespaces nominated by using-directives in the global namespace. That set is comprised of N::i, which is the result of name lookup, and is introduced as a name in global namespace by the using declaration. I find it worth noting (although pretty obvious) that this definition of qualified lookup is recursive: using the notation in the quote, qualified lookup in each namespace Ni will first look for declarations made directly in Ni, then, if none is found, will in turn proceed to look in the namespaces nominated by using-directives in Ni, and so on. For what it's worth, MSVC accepts the code as well. A: GCC is wrong. Qualified name lookup does consider N::i; §3.4.3.2/2 & /3: For a namespace X and name m, the namespace-qualified lookup set S(X, m) is defined as follows: Let S'(X, m) be the set of all declarations of m in X and the inline namespace set of X (7.3.1). If S'(X, m) is not empty, S(X, m) is S'(X, m); otherwise, S(X, m) is the union of S(Ni, m) for all namespaces Ni nominated by using-directives in X and its inline namespace set. Given X::m (where X is a user-declared namespace), or given ::m (where X is the global namespace), […] if S(X, m) has exactly one member, or if the context of the reference is a using-declaration (7.3.3), S(X, m) is the required set of declarations of m. There is only one namespace nominated by a using-directive in your program: N. It's therefore included in the union and ::i is resolved to N::i. Note that GCC is inconsistent with its lookup: Using ::i in another context is fine. namespace N { int i; } using namespace N; int main() { ::i = 5; } This compiles. The only difference that a using-declaration makes as a context is shown in the above quote and does not affect the established conclusion.
unknown
d8409
train
static IEnumerable<DateTime> AllDatesBetween(DateTime start, DateTime end) { for(var day = start.Date; day <= end; day = day.AddDays(1)) yield return day; } Edit: Added code to solve your particular example and to demonstrate usage: var calculatedDates = new List<string> ( AllDatesBetween ( DateTime.Parse("2009-07-27"), DateTime.Parse("2009-07-29") ).Select(d => d.ToString("yyyy-MM-dd")) ); A: The easiest thing to do would be take the start date, and add 1 day to it (using AddDays) until you reach the end date. Something like this: DateTime calcDate = start.Date; while (calcDate <= end) { calcDate = calcDate.AddDays(1); calculatedDates.Add(calcDate.ToString()); } Obviously, you would adjust the while conditional and the position of the AddDays call depending on if you wanted to include the start and end dates in the collection or not. [Edit: By the way, you should consider using TryParse() instead of Parse() in case the passed in strings don't convert to dates nicely] A: for( DateTime i = start; i <= end; i = i.AddDays( 1 ) ) { Console.WriteLine(i.ToShortDateString()); } A: You just need to iterate from start to end, you can do this in a for loop DateTime start = DateTime.Parse(startDate); DateTime end = DateTime.Parse(endDate); for(DateTime counter = start; counter <= end; counter = counter.AddDays(1)) { calculatedDates.Add(counter); } A: An alternative method public static class MyExtensions { public static IEnumerable EachDay(this DateTime start, DateTime end) { // Remove time info from start date (we only care about day). DateTime currentDay = new DateTime(start.Year, start.Month, start.Day); while (currentDay <= end) { yield return currentDay; currentDay = currentDay.AddDays(1); } } } Now in the calling code you can do the following: DateTime start = DateTime.Now; DateTime end = start.AddDays(20); foreach (var day in start.EachDay(end)) { ... } Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.
unknown
d8410
train
Even though I frequently use regular expressions (RE), I would be reluctant to use one complex RE for this job. The chances that it misses some of the tags, or wrongly converts others, seem too high and too risky. I would approach this sort of task using a series of simple REs that jointly give me confidence that I have done all the changes correctly. Thus, with "Regular expression" and "Wrap around" selected: Change <keepTime>(\d+)</keepTime> to <done>${1}000</done> Change <keepTime>(\d+)\.(\d)</keepTime> to <done>${1}${2}00</done> Change <keepTime>(\d+)\.(\d\d)</keepTime> to <done>${1}${2}0</done> To remove all leading zeros but retain a single zero, use Change <done>0+([1-9]\d*)</done> to <done>${1}</done> For a variation on the above to remove some leading zeros but keep three digits, use: Change <done>0+(\d\d\d)</done> to <done>${1}</done> It is simple to modify it to keep two digits or four, etc. Now do a search for any remaining occurrences of </?keepTime> and change them in the style above. Then when they are all changed, convert the "done"s with: Change <done>(\d+)</done> to <keepTime>\1</keepTime>. Now do a final check that all of the "done"s have been done, searching for </?done> Note that done should be replaced throughout by some tag that is not used in the original file. Note also that this is complex editing, so make a backup before doing the changes. A: Doing numeric multiplication using regular expressions feels like attempting to drive a nail using a screwdriver, and I certainly wouldn't attempt it in a single replace() call, but if you're allowed a bit of conditional logic then it's not too difficult: (a) if there's no ".", append "000" (b) otherwise: (i) append "000" (ii) replace ".xxx" by "xxx." (iii) delete trailing zeroes (iv) delete trailing "."
unknown
d8411
train
Every time you call WriteToFile.write, it reopens the file for writing, truncating the file's original contents. You should open the file once, in the constructor (and store the PrintWriter in a field), and add a close method that calls close for the PrintWriter. On the calling side, do this: WriteToFile writer = new WriteToFile(filename); try { // writer.write(...); } finally { writer.close(); } By having the close call in a finally block, you ensure the file is closed even if an exception causes the function to quit early. A: Look at the 2nd argument of the FileWriter constructor in your code. FileWriter filewrite = new FileWriter(path, append); See, it says "append". Guess what it does. Read the documentation if you're unsure. Now, look how you initialized append. private boolean append = false; This code is fully behaving as expected. It's just a developer's fault. Fix it :) A: Just set fileName on System using the method System.setOut(fileName); Then whenever we want to print using System.out.println() it will directly print to the fileName you mention.
unknown
d8412
train
You can do it like this: library(dplyr) library(zoo) df %>% group_by(sp) %>% mutate(SMA_wins=rollapplyr(wins, 3, mean, partial=TRUE)) It looks like your use of df and df_zoo in your mutate call was messing things up.
unknown
d8413
train
It seems you are adding more than one relation of the same. Before adding software to a client, make sure a relation does not exist yet, then you can go ahead and add software to client. Also, you can improve your entities. Use better naming for the primary keys and add [Key] attribute to Software class as well. Client: public class Client { public Client() { Softwares = new HashSet<Software>(); } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ClientId { get; set; } [Required] public string Hostname { get; set; } public ICollection<Software> Softwares { get; set; } } Software: public class Software { public Software() { Clients = new HashSet<Client>(); } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int SoftwareId { get; set; } public string Name { get; set; } public ICollection<Client> Clients { get; set; } } Check if relation already exists: // Get the client including its related softwares var client = dbContext.Clients.Include(x => x.Softwares) .FirstOrDefault(x => x.Hostname == "Ibrahim"); if (client != null) { // Check with unique property such as name of software // If it does not exist in this current client, then add software if (!client.Softwares.Any(x => x.Name == software.Name)) client.Softwares.Add(software); dbContext.SaveChanges(); } Note: If you update your entities, remember to create new migration and database. A: Q: Do you make a new one with new() every time? A: no, its a software that already exists Then that is the error. The first SaveChanges() will start tracking it as Existing. You can check: The Id will be != 0. When you then later add it to the same Client you'll get the duplicate error. So somewher in your code: await add(software); // existing software = new Software(); // add this Related, change: public async void add(Software software) to public async Task Add(Software software) Always avoid async void.
unknown
d8414
train
Try $(".login-btn").hover( function() { clearTimeout($(this).data('hoverTimeoutId')); $(".login-content").show(); $(this).addClass('hovered'); }, function() { clearTimeout($(this).data('hoverTimeoutId')); $(this).data('hoverTimeoutId', setTimeout(function () { $(".login-content").hide(); $(this).removeClass('hovered'); } ,500)); }); $('.login-content').hover( function(){ clearTimeout($(".login-btn").data('hoverTimeoutId')); }, function(){ $(".login-content").hide(); $(".login-btn").removeClass('hovered'); }); Instead of using :hover psedoclass use a class like hover assign the hovered state to login-btn as shown in the demo Demo: Fiddle A: Use setTimeout $(".login-btn").hover( function() { clearTimeout($(this).data('animator')); $(this).data('animator', setTimeout(function () { $(".login-content").show(); } ,1000)); }, function() { clearTimeout($(this).data('animator')); $(this).data('animator', setTimeout(function () { $(".login-content").hide(); } ,1000)); }); http://jsfiddle.net/uDm64/ A: If you don't want to worry about the user having the cursor away for a moment, then I would suggest a little more state checking. Also, if you want your button to appear as hovered, in your CSS selector '.login-btn:hover', change it to: '.login-btn:hover, .login-btn.hover' Fiddle: http://jsfiddle.net/qhAus/ (function() { var timer = 0, open = false, loginBtn = $('.login-btn'), loginContent = $('.login-content'), startTimeout = function(state, duration) { timer = setTimeout(function() { timer = 0; loginContent[state](); open = state === 'show'; if(!open) { // If it's closed, remove hover class loginBtn.removeClass('hover'); } }, duration || 1000); }; loginBtn.hover(function(e) { $(this).addClass('hover'); if(open && timer) { // If about to close but starts to hover again clearTimeout(timer); } if(!(open || timer)) { // Don't start to open again if already in the process startTimeout('show'); } }, function() { // When not hovering anymore, hide login content startTimeout('hide', 2000); }); loginContent.mousemove(function(e) { // If cursor focus on the login content, stop any closing timers if(timer) { clearTimeout(timer); } }); loginContent.mouseleave(function(e) { // When cursor leaves login content, hide it after delay startTimeout('hide'); }); })();
unknown
d8415
train
So you would have 2 different folders values and values-es. The best way for you is to create config.xml file in both folders with different url e.g.: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="endpoint">http://endpoint.com/en/index.html</string> </resources> To get the value for particular language you would get it like ordinary string: context.getString(R.string.endpoint); A: Flavours is not what you want to use because then you will build different APK file. You probably want to have a unique app with different languages capability. The Android doc has a great explanation about how to do this : http://developer.android.com/training/basics/supporting-devices/languages.html
unknown
d8416
train
The issue might be caused by the relative path to the public directory because the path is relative to the directory from where you launch your app. If this is the case, then providing the absolute path should fix it: const path = require('path'); app.use('/', express.static(path.join(__dirname, '../public')))
unknown
d8417
train
it looks you are using the old way to translate PDF then load it to viewer. In the old way, the PDF is translated to tiled images. So snapping may not be working, and zoom has max limit due to the max resolution of tiled images. Actually, Forge Viewer has supported to load native PDF directly, without translation. Since it is native, it is vector graphics. The snapping will work, and it can be zoomed to large/much small scale. To play it, please download the sample project, https://github.com/Autodesk-Forge/viewer-javascript-offline.sample and replace the line to your local pdf file var options = { 'env' : 'Local', 'document' : './my_PDF_folder/mytest.pdf' }; This feature is from the extension Autodesk.PDF, but it will be loaded de default, you do not need to load it explicitly.
unknown
d8418
train
Wrap your Comparators in Comparator.nullsFirst to avoid dealing with possibly nullable parameters. You need two Comparators merged with Comparator#thenComparing: * *nullsFirst(naturalOrder()) to compare IProducts first; *nullsFirst(comparing(p -> p...getVintage()) to compare their Vintages secondly. Comparator<IProduct> comparator = nullsFirst(Comparator.<IProduct>naturalOrder()) .thenComparing(nullsFirst( comparing(p -> p.getProvidedProductData().getVintage()) ) ); This approach compares IProduct naturally which you apparently don't want to do. (You didn't compare them at all). Then you might write IProduct p1, IProduct p2) -> 0 to continue comparing Vintages after neither of two IProducts is null. Comparator<IProduct> comparator = nullsFirst((IProduct p1, IProduct p2) -> 0) .thenComparing(nullsFirst( comparing(p -> p.getProvidedProductData().getVintage()) ) ); If getVintage returns an int, you could use Comparator.comparingInt instead of Comparator.comparing: comparingInt(p -> p.getProvidedProductData().getVintage()) A: Simply use (I assume you are on Java8+ since you tagged the question with lambda) either of the following methods from Comparator: public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) A: You can use Comparator methods introduced in Java 8 and use a method reference e.g.: Comparator.comparing(IProductData::getVintage, Comparator.nullsLast(Comparator.naturalOrder())) A: How about this one?: Comparator<IProduct> comparator = (p1, p2) -> { Integer v1 = p1 != null ? p1.getProvidedProductData() : null; Integer v2 = p2 != null ? p2.getProvidedProductData() : null; if (v1 == null ^ v2 == null) return v1 != null ? 1 : -1; return v1 != null ? v1.compareTo(v2) : 0; }; A: One possibility is to generalise the null checks. public int compare(IProduct product1, IProduct product2) throws ProductComparisonException { Integer diff = nullCompare(product1, product2); if(diff != null) return diff; IProductData productData1 = (IProductData)product1.getProvidedProductData(); IProductData productData2 = (IProductData)product2.getProvidedProductData(); diff = nullCompare(productData1.getVintage(), productData2.getVintage()); if(diff != null) return diff; return productData2.getVintage().compareTo(productData2.getVintage()); } // Using Integer so I can return `null`. private Integer nullCompare(Object o1, Object o2) { if (o1 == null && o2 == null) { return 0; } else if (o1 == null && o2 != null) { return -1; } else if (o1 != null && o2 == null) { return 1; } return null; }
unknown
d8419
train
Here are some details about template relative paths in the documentation that may help: https://angular.io/docs/ts/latest/cookbook/component-relative-paths.html A: Try placing a "./" before your relative path like: import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'my-app', templateUrl: './app.component.html' }) export class AppComponent { } A: This is the best solution that I could find so far: moduleId: module.id.replace("/dist/", "/src/"); where src in my case is app. Taken from here.
unknown
d8420
train
SQLite will be the best storage option for large data sets on the device. Ensure that where possible you use the correct SQLite query to get the data you need rather then using a general query and doing processing in your own code. A: This is a bit too much to add in the comments, so I'll add it here. 4,000,000 rows of integers is not that much. Assuming that the integers will use the maximum size of a signed int (8 bytes), your database will be: 4000000 * 8 / 1024 / 1024 = ~30.5mb That is large, but not game breaking. Now that also assumes you will need a full 8 bytes per number. We know that we want to store 13 digits per entry, so a 6 byte integer column would suffice: 4000000 * 6 / 1024 / 1024 = ~23mb A: Hi d3cima may be too late answer but it's help other's. Myself Realm is the best option. Realm Realm’s developer-friendly platform makes it easy to build reactive apps, realtime collaborative features, and offline-first experiences. Advantage's: * *faster than SQLite (up to 10x speed up over raw SQLite for normal operations) *easy to use *object conversion handled for you *convenient for creating and storing data on the fly I used my project it's more than 10 x then Sqlite.
unknown
d8421
train
Your test case needs to specify a particular case; it's not intended to be done interactively as you are trying to do. Something like this would do: require 'test/unit' class YearTest < Test::Unit::TestCase def test_hours y = Year.new assert_equal 8760, y.hours(2001) assert_equal 8784, y.hours(1996) end end
unknown
d8422
train
Question is uncler, but either way, either click the video button or Webbrowser.Navigate("webpage url")
unknown
d8423
train
Coordinating multiple asynchronous operations is a job best solved with tools like promises. So, in the long run, I'd suggest you read up about promises and how to use them. Without promises, here's a brute force way you can tell when all your handleFiles() operations are done by using a counter to know when the last async operation is done and then using the urls variable INSIDE that last callback or calling a function from there and passing the urls variable to that function: document.getElementById('question-file-selector').addEventListener('change', handleFileSelect, false); function handleFileSelect(evt) { var files = evt.target.files; //File list object var urls = ""; // Loop through file list, render image files as thumbnails var doneCnt = 0; for (var i = 0, f; f = files[i]; i++) { handleFiles(f, function (url) { urls = urls + url + ','; console.log("urls is " + urls); ++doneCnt; if (doneCnt === files.length) { // The last handleFiles async operation is now done // final value is in urls variable here // you can use it here and ONLY here // Note: this code here will get executed LONG after the // handleFileSelect() function has already finished executing } }); // Only process image files if (!f.type.match('image.*')) { $('#list').append('<img class="file-thumb" src="/static/download168.png"/>'); continue; } var reader = new FileReader(); //Closure to capture file information reader.onload = (function (theFile) { return function (e) { //Render thumbnail $('#list').append('<img class="thumb" src="' + e.target.result + '" title="' + escape(theFile.name) + '"/>'); }; })(f); reader.readAsDataURL(f); } } // You can't use the urls variable here. It won't be set yet. Ohhh. Please remove the async: false from your ajax call. That's a horrible thing to code with for a variety of reasons. Here's a version using the promises built into jQuery: document.getElementById('question-file-selector').addEventListener('change', handleFileSelect, false); function handleFileSelect(evt) { var files = evt.target.files; //File list object // Loop through file list, render image files as thumbnails var promises = []; for (var i = 0, f; f = files[i]; i++) { promises.push(handleFiles(f)); // Only process image files if (!f.type.match('image.*')) { $('#list').append('<img class="file-thumb" src="/static/download168.png"/>'); continue; } var reader = new FileReader(); //Closure to capture file information reader.onload = (function (theFile) { return function (e) { //Render thumbnail $('#list').append('<img class="thumb" src="' + e.target.result + '" title="' + escape(theFile.name) + '"/>'); }; })(f); reader.readAsDataURL(f); } $.when.apply($, promises).then(function() { var results = Array.prototype.slice.call(arguments); // all handleFiles() operations are complete here // results array contains list of URLs (some could be empty if there were errors) }); } function handleFiles(file) { var filename = file.name; return $.ajax({ type: 'GET', data: { "filename": file.name, "FileType": "question_file" }, url: '/dashboard/generateuploadurl/', contentType: "application/json", dataType: "json" }).then(function(data) { if (data.UploadUrl) { console.log("upload url successfully created for " + file.name + " file"); console.log(data.UploadUrl); return handleUpload(data.UploadUrl, file, data.Filename); } }, function(err) { console.log("error occured while creating upload url for " + file.name + ' file'); console.log(err); // allow operation to continue upon error }); } function handleUpload(UploadUrl, file, Filename) { return $.ajax({ xhr: xhr_with_progress, url: UploadUrl, type: 'PUT', data: file, cache: false, contentType: false, processData: false }).then(function(data) { console.log('https://7c.ssl.cf6.rackcdn.com/' + Filename); return 'https://7c.ssl.cf6.rackcdn.com/' + Filename; }, function(err) { console.log("error occured while uploading " + file.name); console.log(err); // allow operation to continue upon error }); } Since I can't run this code to test it, there could be a mistake or two in here, but you should be able to debug those mistakes or tell us where the errors occur and we can help you debug it. These are conceptually how you solve these types of problems of coordinating multiple async operations.
unknown
d8424
train
You've given a model with a go predicate. The trick is that you get a loop by calling a predicate again recursively if R='y' doesn't fail. again :- write('Do you want to continue? (Y/ N)'), res(R), R='y', go, again. again :- write('OK, bye'),nl.
unknown
d8425
train
The two properties in the abstract class are private, which means they are NOT present and known in any class that extends this one. So MyCalc does not write to these properties, and you cannot read them in the AddNumbers function. The MyCalc constructor actually creates new, public properties instead. Make the properties "protected", and it will work. A: The private keyword defines that only the methods in Calc can modify those variables. If you want methods in Calc and methods in any of its subclasses to access those variables, use the protected keyword instead. You can access $this->x because PHP will let you create a member variable on the object without declaring it. When you do this the resulting member variable is implicitly declared public but it doesn't relate to the private variable defined in Calc, which is not in scope in myCalc.
unknown
d8426
train
I suggest you use GSkinner's REGEX builder and experiment with a lot of the examples on the right hand side. There are are many variations to get this job done. If you want to be explicit you can use: /[a-zA-Z!@#$%¨&*()-=+/*.{}]/ Tony's answer will also work, but includes more extra characters than the ones you've defined in your comment. A: This $str = $_REQUEST["htmlstringinput"]; preg_match("([\w\-]+[@#%.])", $str); for letters, numbers and special characters in this special character range [@#%.] are allowed and this $str = $_REQUEST["htmlstringinput"]; preg_match("([-a-zA-Z]+[@#%.])", $str); for only letters and special characters in the same special character range as above Worked for me. For further reading and research you can go to : http://gskinner.com/RegExr/ A: /[\p{L}\p{P}]+/u matches letters and punctuation characters. Or what did you mean by "special characters"? A: all characters not a number? how bout this: /[^\d]*/ A: Use following code in .htaccess to block all URLs with number (as per OP's comments) Options +FollowSymlinks -MultiViews RewriteEngine on RewriteCond %{REQUEST_URI} ![0-9] RewriteRule ^user/ /index.php?goto=missed [NC,L]
unknown
d8427
train
this appears to work: function timeStampM() { SpreadsheetApp.getActiveSheet() .getActiveCell() .setValue(new Date()); var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getDataRange(); var actCell = sheet.getActiveCell(); var actData = actCell.getValue(); var actRow = actCell.getRow(); if (actData != '' && actRow != 1) //Leaving out empty and header rows { actCell.setBackground('Red'); } }
unknown
d8428
train
For more better way use with toggleClass() instead of color value matching with in dom function changeBg(el) { $(el).toggleClass('red') } .red { background-color: red; } button{ background-color: yellow; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button onclick="changeBg(this)">change</button> A: Try This: $(document).ready(function(){ $('button').click(function(){ $(this).toggleClass('redColor'); }) }) button { background-color: yellow; } .redColor { background-color: red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <button>Click Me!</button> A: Try this $(document).ready(function() { $('.container').on('click',function(){ var el = ".container"; if ($(el).css("background-color") === "rgb(255, 255, 0)") { $(el).css("background-color", "red"); } else { $(el).css("background-color", "rgb(255, 255, 0)"); } }); }); .container { background-color: rgb(255, 255, 0); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> Test </div>
unknown
d8429
train
"many books say that we should avoid using any raw pointer in modern C++" It is only owning raw pointers that should be avoided. In your case you need to std::free() the pointer so you own it. Therefore you should definitely put it in a std::unique_ptr but with a custom deleter to call std::free(). // some type aliases to make life shorter... struct malloc_deleter{void operator()(void* vp) const { std::free(vp); }}; using malloc_uptr = std::unique_ptr<char, malloc_deleter>; auto ptr = malloc_uptr(static_cast<char*>(std::malloc(sizeof(char)*512*1024))); .... do_something(ptr.get()); // pass to other functions .... do_something(ptr.get()+sizeof(int)*4); // random access may be needed .... // no need to free, gets done when ptr` goes out of scope.
unknown
d8430
train
Here htmlString will is holding you html content. TextView textView = (TextView)findViewById(R.id.tv_string); textView.setText(Html.fromHtml(htmlString));
unknown
d8431
train
Your Collection is always valid, because it contains fields. You can't do this that way. You should considering to add Validators to DocAand DocBfields instead. This will work as follow to set correct input filters : $form->getInputFilter()->get('docs')->get('DocA')->getValidatoChain()->attachByName('YourValidatorName'); for a custom validator. OR : $form->getInputFilter()->get('docs')->get('DocA')->setRequired(true); $form->getInputFilter()->get('docs')->get('DocA')->setAllowEmpty(false); And you can also add Zend validators to them. $form->getInputFilter()->get('docs')->get('DocA')->getValidatorChain()->attach(new NotEmpty([with params look docs for that]) Careful if you don't use ServiceManager for retrieve validators you'll need to set the translator as options. Don't forget to set your validationGroup correctly or don't specify one to use VALIDATE_ALL. The same way as validators you can also add Filters as follow : $form->getInputFilter()->get('docs')->get('DocA')->getFilterChain()->getFilters()->insert(new StripTags())->insert(new StringTrim())
unknown
d8432
train
Go to https:///systemInfo >> javax.net.ssl.trustStore. This is the truststore where the certificate should be added. You can open the keystore with keytool or if you prefer a GUI take a look at Keystore Explorer The default password of the truststore is changeit.
unknown
d8433
train
Just add these 2 line. import time time.sleep(2) Then It'll work properly generally it take only 0.65sec but it's better to give 2 sec. To make it better you can add some cool stuffs like some print statement in for loop and sleep inside it something like that. A: The following worked for me. Check out the API documentation for how to update the default delays and max attempts at https://boto3.amazonaws.com. from botocore.exceptions import WaiterError ssm_client = boto3.client( "ssm", region_name=REGION, aws_access_key_id=KEY, aws_secret_access_key=SECRET, ) waiter = ssm_client.get_waiter("command_executed") try: waiter.wait( CommandId=commands_id, InstanceId=instance_id, ) except WaiterError as ex: logging.error(ex) return A: I had the same issue, I fixed it by adding a time.sleep() call before calling get_command_invocation(). A short delay should be enough. A: time.sleep does the job 99% of the time. Here is a better way to do this: MAX_RETRY = 10 get_command_invocation_params = { 'CommandId': 'xxx', 'InstanceId': 'i-xxx' } for i in range(MAX_RETRY): try: command_executed_waiter.wait(**get_command_invocation_params) break except WaiterError as err: last_resp = err.last_response if 'Error' in last_resp: if last_resp['Error']['Code'] != 'InvocationDoesNotExist' or i + 1 == MAX_RETRY: raise err else: if last_resp['Status'] == 'Failed': print(last_resp['StandardErrorContent'], file=sys.stderr) exit(last_resp['ResponseCode']) continue
unknown
d8434
train
You've defined your user function like this: def user(usr) This says that it requires a single positional argument. You have two routes pointing at this function: - @app.route('/home', methods=["GET","POST"]) - @app.route("/<usr>") Only the second route provides the necessary usr variable. When you visit the route /home, you'll get the TypeError you've shown in your question. Depending on how you want the function to behave when no user is specified, it may make more sense to have a second function handling /home. Maybe that was supposed to be an alternate route for the home function instead?
unknown
d8435
train
With GNU sed for -z and using all 3 blocks of input you provided together in one file as input: $ sed -z ' s:@:@A:g; s:}:@B:g; s:</a>:}:g; s:<a[^<>]* href="legacy/[^}]*}:<!--&-->:g; s:}:</a>:g; s:@B:}:g; s:@A:@:g ' file <!--<a class="other-sim-page" href="legacy/wave-on-a-string.html" dir="ltr"> <table> <tr> <td> <img style="display: block;" src="../../images/icons/sim-badges/flash-badge.png" alt="Flash Logo" width="44" height="44"> </td> <td> <span class="other-sim-link">原始模擬教學與翻譯</span> </td> </tr> </table> </a>--> ... <p>瀏覽<!--<a href="legacy/wave-on-a-string.html#for-teachers-header">更多活動</a>-->。</p> ... <!--<a href="legacy/radiating-charge.html" class="simulation-link"> <img class="simulation-list-thumbnail" src="../../sims/radiating-charge/radiating-charge-128.png" id="simulation-display-thumbnail-radiating-charge" alt="Screenshot of the simulation 電荷輻射" width="128" height="84"/><br/> <strong><span class="simulation-list-title">電荷輻射</span></strong><br/> <span class="sim-display-badge sim-badge-flash"></span> </a>--> The first line turns } into a character than can't be present in the input afterwards by converting all }s to @Bs and then turns all </a>s into } so that char can be negated in a bracket expression as [^}] in the regexp for the string you want to replace, the second line does the actual replacement you want, and the third line restores all }s to </a>s and then @Bs to }s. Manipulating the input to create a char that can't exist in the input is a fairly common sed idiom to work around not being able to negate strings in regexps. See https://stackoverflow.com/a/35708616/1745001 for another example with additional explanation. This will of course fail if you have strings in your input that resemble the strings you're trying to match but in reality it's probably good enough for your specific input - you'll just have to think about what it does and check it's output to verify. A: You are not using the proper tool for this task. sed is a great tool to perform find and replace using regex, however regex (based on DFA) are unable to parse nested structures like JSON or XML trees (as there is no limit to the depth of the nesting). I would therefore recommend using a XML/HTML parser. For example you can use XSLT: Input: $ cat webpage.html <!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> <a href="https://www.w3schools.com">Visit W3Schools</a> <p>My second paragraph.</p> <a href="legacy/radiating-charge.html" class="simulation-link"> <img class="simulation-list-thumbnail" src="../../sims/radiating-charge/radiating-charge-128.png" id="simulation-display-thumbnail-radiating-charge" alt="Screenshot of the simulation 電荷輻射" width="128" height="84"/><br/> <strong><span class="simulation-list-title">電荷輻射</span></strong><br/> <span class="sim-display-badge sim-badge-flash"></span> </a> </body> </html> Stylesheet: $ cat remove_legacy.xslt <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" encoding="UTF-8" omit-xml-declaration="yes"/> <!-- copy the whole structure recursively --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- when you meet a tag a that contains href --> <xsl:template match="//a[contains(@href,'legacy')]"> <!-- add comment starting tag --> <xsl:text disable-output-escaping="yes">&#xa;&lt;!--&#xa;</xsl:text> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> <!-- add comment ending tag --> <xsl:text disable-output-escaping="yes">&#xa;--&gt;&#xa;</xsl:text> </xsl:template> </xsl:stylesheet> Output: $ xsltproc --html remove_legacy.xslt webpage.html <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> <a href="https://www.w3schools.com">Visit W3Schools</a> <p>My second paragraph.</p> <!-- <a href="legacy/radiating-charge.html" class="simulation-link"> <img class="simulation-list-thumbnail" src="../../sims/radiating-charge/radiating-charge-128.png" id="simulation-display-thumbnail-radiating-charge" alt="Screenshot of the simulation 電荷輻射" width="128" height="84"><br> <strong><span class="simulation-list-title">電荷輻射</span></strong><br> <span class="sim-display-badge sim-badge-flash"></span> </a> --> </body> </html> As you can see the href that does not contain legacy is not commented. A: try gnu sed sed -E '/<a\s+.*href=.*legacy\/.*<\/a>/d; /<a\s+.*href=.*legacy\//,/<\/a>/d' wave-on-a-string.html
unknown
d8436
train
What you need is token pasting. try the following: #define W(x,ad,val) k_target_socket.write##x(ad,val) The ## will paste the x with the function name. More details here
unknown
d8437
train
That's because your Tabs class is defined after your Tab class and classes in javascript aren't hoisted. So you have to use forwardRef to reference a not yet defined class. export class Tab { @Input() tabTitle: string; public active:boolean; constructor(@Inject(forwardRef(() => Tabs)) tabs:Tabs) { this.active = false; tabs.addTab(this); } } A: You have two solutions: Inject your Tabs class globally at bootstrap: bootstrap(MainCmp, [ROUTER_PROVIDERS, Tabs]); On inject Tabs locally with a binding property, @Component({ selector: 'tab', bindings: [Tabs], // injected here template: ` <ul> <li *ngFor="#tab of tabs" (click)="selectTab(tab)"> [...]
unknown
d8438
train
If you have a lot of data going into it you might want to use it in virtual mode, by setting the VirtualMode property of the ListView control to true. That means that the ListView will not be populated in the traditional sense, but you will hook up event handlers where you deliver the information to the list view in small chunks as the items are being displayed. Very simple example: private List<string> _listViewData = new List<string>(); private void toolStripButton1_Click(object sender, EventArgs e) { _listViewData = GetData(); // fetch the data that will show in the list view listView1.VirtualListSize = _listViewData.Count; // set the list size } // event handler for the RetrieveVirtualItem event private void listView_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) { if (e.ItemIndex >= 0 && e.ItemIndex < _listViewData.Count) { e.Item = new ListViewItem(_listViewData[e.ItemIndex]); } } You should also look into using the CacheVirtualItems event. A: You can also use BeginUpdate and EndUPdate methods listView1.BeginUpdate(); //Add Values listView1.EndUpdate(); A: My comments got quite long, so I decided to make this a separate post. First, +1 for Fredrik Mörk, using VirtualMode is the way to go. However, you do lose some functionality, e.g. column autosize, and sorting is easier handled on your own. If that is a problem, populating from a worker thread may sound sounds tempting. However, the population will still take place in the thread that owns the list control (i.e. virtually always the main thread) - .NET makes that visible by enforcing you to use (Begin)Invoke. Additionally, the context switches will notably increase the total time you need to fill all items if you fill one by one, so you want to fill in chunks (say 50 items at a time, or even better fill as many as you can in 20 milliseconds). Add to that the additional synchronization required when contents changes, you have a quite complex solution for a not-so-stellar result.
unknown
d8439
train
Keep it simple from your local branch: git fetch origin && git merge origin/master
unknown
d8440
train
When creating a recycler view, you need to create a RecyclerView adapter which (among other things) implements methods for creating and binding a viewholder to the item in the recycler view. Somewhere in your code (oftentimes within this recycler view adapter class), you need to define the viewholder that you will use for your recyclerview items. This is where you should assign the onClickListener to your imageView. Here is an example of a viewholder definition that I think may help you: public class YourViewHolder extends RecyclerView.ViewHolder { protected ImageView yourImage; public YourViewHolder(View v) { super(v); final View theView = v; yourImage = (ImageView) v.findViewById(R.id.yourImage); yourImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // image clicked... do something } }); } } Let me know if you need more information on how to set up the recycler view adapter class (I have assumed that you already have done this, but I could be mistaken).
unknown
d8441
train
The problem you have here is that cpdf is not a string interpreter like echo or printf and so on. In your case cpdf doesn't know how to interpret your escaped string and when you pass this "so called" variable (cropstring) to cpdf binary you actually tell to bash like this: pass to cpdf script this argument in which you close double-quote and after \"10pt you have a space which means cpdf jump to next argument (input file) and leave away this part of string 10pt 200pt 500pt\" (that means that your script will take 10pt as a single argument and that is unfortunate because your binary script expect other 3 arguments). This is why your binary raise an error because it cannot crop a window having just one argument 10pt. It expects yet 3 arguments in a string. This is how your binary script will exit (with an error) and tell you that there is a Bad rectangle specification "10pt. The arguments that you pass to cpdf are good in first example but in the second example are wrong. I described earlier how bash interpret parameters. In the first example your binary script treat cropstring as a string variable and in the second example it will pass only the first argument which is 10pt. To respond to your answer, it is the way bash interpret strings and your script and not a problem of cpdf binary. The line in which you write: cropstring="\"10pt 10pt 200pt 500pt\"" can be interpreted well only by a text interpreter (you can play writing echo -e $cropstring) but NEVER in bash command line. When you pass your variable as an argument to some bash script, bash see your variable like cpdf -crop ""10pt. That's all because the rest of the string will be seen as file.in argument. The error occurs because your string parameter asked by crop argument is just 10pt and thus, the binary doesn't know how to crop that window.
unknown
d8442
train
is there anyway to do it in linq or other .net way? Sure: List<User> list = ...; // Make your user list List< UserProtectedDetails> = list .Select(u => new UserProtectedDetails{name=u.name}) .ToList(); EDIT: (in response to a comment) If you would like to avoid the {name = u.name} part, you need either (1) a function that makes a mapping for you, or (2) a constructor of UserProtectedDetails that takes a User parameter: UserProtectedDetails(User u) { name = u.name; } One way or the other, the name = u.name assignment needs to be made somewhere. A: Well, it could be as easy as var userList = new List<User>(); var userProtectedDetailsList = userList.Select(u => new UserProtectedDetails { name = u.name } ) .ToList();
unknown
d8443
train
findParentNode(parentName, childObj) { let tempNodeObj = childObj.parentNode; while(tempNodeObj.tagName != parentName) { tempNodeObj = tempNodeObj.parentNode; } return tempNodeObj; } this.findParentNode('DATATABLE-BODY-ROW',$event.target); this will help to find you the data table row element this.render.addClass(findParentNode,"row-expanded");
unknown
d8444
train
select [colour code], [size code], row_number() over (partition by [colour code], [size code] order by 1/0) [group id] from tbl order by [group id], [colour code], [size code];
unknown
d8445
train
The alternative for parallel execution is to allow the dependency injection system which specflow uses to provide you with the ScenarioContext instance. To do that have your steps class accept an instance of the ScenarioContext and store it in a field: [Binding] public class StepsWithScenarioContext { private readonly ScenarioContext scenarioContext; public StepsWithScenarioContext(ScenarioContext scenarioContext) { if (scenarioContext == null) throw new ArgumentNullException("scenarioContext"); this.scenarioContext = scenarioContext; } [Given(@"I put something into the context")] public void GivenIPutSomethingIntoTheContext() { scenarioContext.Set("test-value", "test-key"); } } A fuller explanation of how to use parallel execution can be found here A similar approach needs to be taken to get the tags. Again add a constructor which takes a ScenarioContext to your class which holds your [BeforeScenario] method, and save the ScenarioContext in a field and use this filed instead of the ScenarioContext.Current
unknown
d8446
train
There is no way to do that with PostgreSQL alone - you'd have to write your own C function. With the PostGIS extension, you can cast the path to geometry and perform the operation there: SELECT array_agg(CAST(geom AS point)) FROM st_dumppoints(CAST(some_path AS geometry)); A: Try a variant of this.. CREATE OR REPLACE FUNCTION YADAMU.YADAMU_make_closed(point[]) returns point[] STABLE RETURNS NULL ON NULL INPUT as $$ select case when $1[1]::varchar = $1[array_length($1,1)]::varchar then $1 else array_append($1,$1[1]) end $$ LANGUAGE SQL; -- CREATE OR REPLACE FUNCTION YADAMU.YADAMU_AsPointArray(path) returns point[] STABLE RETURNS NULL ON NULL INPUT as $$ -- -- Array of Points from Path -- select case when isClosed($1) then YADAMU.YADAMU_make_closed(array_agg(point(v))) else array_agg(point(v)) end from unnest(string_to_array(left(right($1::VARCHAR,-2),-2),'),(')) v $$ LANGUAGE SQL; -- Eg yadamu=# select * from unnest(YADAMU.YADAMU_asPointArray(Path '((0,1),(1,0),(4,0))')); unnest -------- (0,1) (1,0) (4,0) (3 rows)
unknown
d8447
train
After researching I found that I couldn't do that
unknown
d8448
train
You can use  '[\x{0590}-\x{05FF}\/\w.-]*' It matches zero or more chars defined inside [...], a character class: * *\x{0590}-\x{05FF} - a range of Unicode code points that constitute a Hebrew character range *\/ - a literal forward slash *\w- word chars, i.e. ASCII letters, digits and an underscore *. - a dot *- - a hyphen.
unknown
d8449
train
I know Grails very well (right now I'm working on a Grails project), but not JRuby, so take this as a probably biased opinion: looking at the JRuby documentation, it looks that JRubys integration with Java is a bit more cumbersome, since Java is more native in Groovy than it is in Ruby; therefore, in JRuby, you have a lot of java-specific keywords and methods (e.g. java_import, java_send). Put simply, Groovy is a language targeted specifically at the Java world, while JRuby is, well, Ruby put on the JVM. Grails has JUnit tests built in. Can't say much about performance and scalability, but given the good integration with Java, one can always write performance-critical parts in Java when Groovy is too slow. A: * *ease of integration with existing Java components: it's easier with groovy, cause groovy is basically java. you do not have big context-switches * *support for functional testing frameworks ruby has it's own pile of testing frameworks like rspec/shoulda/cucumber/steak and tons more. since i like ruby syntax i would prefer those * *performance on a single machine as far as i know, grails is better in multithreading, because rails did not fokus too much on that in the past. they are currently catching up, so it might be tie. * *scalability both scale with the jvm environement. if you have a running infrastructure for java, grails is easier to integrate. A: * *As phoet said, Grails has first-class Spring support, so it's typically very easy to integrate Spring libraries - that's what many plugins do, including the JMS plugin. Java code can either be provided in JARs or put in to the project's src/java directory. Groovy classes can reference Java classes which can reference Groovy classes. It's pretty seamless. *Grails has support for HtmlUnit, Selenium-rc & WebDriver through various plugins. Geb has a lot of interest at the moment, especially when combined with Spock. *Test them. I don't know if there are any recent comparisons, but performance typically depends heavily on your application. http://grails.org/ and http://beta.grails.org/ are both running on a single machine - and both are Grails applications. *I gather it's pretty easy to cluster Grails via Terracotta. You can also do it with plain Tomcat if you want. There are options for distributed caching - SpringSource has its own (commercial) offering in the form of GemFire. Hope that helps, and in the interests of full disclosure I'm a member of the Grails team. A: In the end, you are going to make a decision on personal choice, comfort with the two languages and the availability of resources, but in the end, the fact that Grails is based on Spring led me to the conclusion that it was the right choice for me. I knew that if all else failed I could fall back to utilizing the tried and true Spring Framework A: Try both, and pick the language and environment that suits you best. It's true that the Grails stack out of the box is more suited towards Java integration, but many components are just a few lines of Ruby code away from integration with Rails. Rails 3 is a great release that doesn't require you to use ActiveRecord, in fact it would be trivial to use Hibernate for your models instead. See also DataMapper, MongoMapper and a whole host of database adapters for SQL and NoSQL databases alike. Also, JUnit != functional testing. Instead, have a look at Cucumber + Cucumber-Rails + Capybara + Selenium for an integrated browser automation testing experience. Take a look at https://github.com/elabs/front_end_testing for an example application that demonstrates this stack. I'll suggest that Ruby is better suited as a web integration language, and JRuby hits the sweet spot of making integration with Java easy as well as pleasing while making a wealth of non-Java libraries available to you. Don't think that Groovy automatically wins because it's "closer" to Java. Sometimes you need to step into a refreshingly different environment in order to have a new look at how to solve a problem. Disclosure: as a member of the JRuby team my bias is evident in my answer. A: For newcomers interested in this question in 2012... "With the @CompileStatic, the performance of Groovy is about 1-2 times slower than Java, and without Groovy, it's about 3-5 times slower. (...) This means to me that Groovy is ready for applications where performance has to be somewhat comparable to Java." Performance Test: Groovy 2.0 vs. Java http://java.dzone.com/articles/groovy-20-performance-compared And besides the autor, I've used Groovy since 2008 with great success, not only for CV, just to make job done in time business need. Performance is ever relative to what you want to do. About integration, Grails is really "that good". I've never needed to make one step further to integrate it with existing libraries. On the contrary, the Spring-based nature of Grails made the job even easier. For those who could complain about micro-benchmarks and real use cases, here is a somewhat old (Grails 1.8) but good one with web frameworks (Grails 1.3.7): http://www.jtict.com/blog/rails-wicket-grails-play-lift-jsp/ Hope this helps! PS.: I would like to see recent benckmarks with JRuby and other really dynamic JVM languages.
unknown
d8450
train
If you ant compare strings you have to use equals method: if (str2.equals(str3)) A: == compares the Object Reference String#equals compares the content So replace str2==str3 with String str2 = "abcdefg"; String str3 = str1 + "efg"; str2.equals(str2); // will return true A: You know, you need to differentiate between string equality and object idendity. The other answers already told you that it would work with .equals(). But if you actually asking on how to get the same object by your string expressions: if it is a compile time constant expression it will be the same object. The str3 would come from the constant pool if it is a constant expression, and in order for that, you may only use final string variables or string literals: public class FinalString { final static String fab = "ab"; static String ab = "ab"; static String abc = "abc"; static String nonfin = ab + "c"; // nonfinal+literal static String fin = fab + "c"; // final+literal public static void main(String[] args) { System.out.println(" nonfin: " + (nonfin == abc)); System.out.println(" final: " + (fin == abc)); System.out.println(" equals? " + fin.equals(nonfin)); } } prints nonfin: false final: true equals? true
unknown
d8451
train
That is because you are not calling right statement on 'onchange' event. You just call the getVAlue(n) function which does nothing except return a value that you also use for var XBurgNum = getValue(BurgNum); var XCocNum = getValue(CocNum); var XSalNum = getValue(SalNum); But you are not updating the output on change event. A: You are calling a function onchange which returns a value, but does nothing with it. Instead, your onchange function can get the values needed for the calculation and update the price accordingly. var burg = document.getElementById('Bnum'), coc = document.getElementById('Cnum'), sal = document.getElementById('Snum'), totalPrice = 0; document.getElementById('price').value = totalPrice; var updatePrice = function() { var burgNum = burg.value, cocNum = coc.value, salNum = sal.value; var xNums = []; [burgNum, cocNum, salNum].forEach(function(n, i) { xNums[i] = (n >= 2 && n < 5) ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1; }); totalPrice = xNums[0]*10 + xNums[1]*5 + xNums[2]*4; document.getElementById('price').value = totalPrice; } How many Burgers do you want to order? <input type="number" id="Bnum" value ="0" onchange="updatePrice()"/><br> How many Cocas do you want to order? <input type="number" id="Cnum" value ="0" onchange="updatePrice()"/><br> How many Salads do you want to order? <input type="number" id="Snum" value="0" onchange="updatePrice()"/><br> Price: <input type="number" id="price" readonly="readonly"/> A: Try this, It will help you... function getValue(val) { var BurgNum = parseInt(document.getElementById('Bnum').value); var CocNum = parseInt(document.getElementById('Cnum').value); var SalNum = parseInt(document.getElementById('Snum').value); BurgNum = (BurgNum>=2 && BurgNum<5)?BurgNum*0.9:(BurgNum<2)?BurgNum:BurgNum-1; CocNum = (CocNum>=2 && CocNum<5)?CocNum*0.9:(CocNum<2)?CocNum:CocNum-1; SalNum = (SalNum>=2 && SalNum<5)?SalNum*0.9:(SalNum<2)?SalNum:SalNum-1; Totalprice = BurgNum*10 + CocNum*5 + SalNum*4; document.getElementById('price').value = (Totalprice>0 && Totalprice!=='NaN')?Totalprice:0; } <html> How many Burgers you want to order? <input type="number" id="Bnum" value ="0" onChange="getValue(this.value);"></input> <br> How many Cocas you want to order? <input type="number" id="Cnum" value ="0" onChange="getValue(this.value);"></input> <br> How many Salads you want to order? <input type="number" id="Snum" value="0" onChange="getValue(this.value);"></input> <br> Price: <input id="price" readonly="readonly"></input> </html> Happy Coding...
unknown
d8452
train
I wrote a library just for this kind of purpose (drawing colour gradients in Processing) called PeasyGradients — download the .jar from the Github releases and drag-and-drop it onto your sketch. It renders 1D gradients as 2D spectrums into your sketch or a given PGraphics object. Here's an example of drawing linear and radial spectrums using your desired gradient: PeasyGradients renderer; PGraphics rectangle, circle, circleMask; final Gradient pinkToYellow = new Gradient(color(227, 140, 185), color(255, 241, 166)); void setup() { size(800, 800); renderer = new PeasyGradients(this); rectangle = createGraphics(100, 400); renderer.setRenderTarget(rectangle); // render into rectangle PGraphics renderer.linearGradient(pinkToYellow, PI/2); // gradient, angle circle = createGraphics(400, 400); renderer.setRenderTarget(circle); // render into circle PGraphics renderer.radialGradient(pinkToYellow, new PVector(200, 200), 0.5); // gradient, midpoint, zoom // circle is currently a square image of a radial gradient, so needs masking to be circular circleMask = createGraphics(400, 400); circleMask.beginDraw(); circleMask.fill(255); // keep white pixels circleMask.circle(200, 200, 400); circleMask.endDraw(); circle.mask(circleMask); } void draw() { background(255); image(rectangle, 50, 50); image(circle, 250, 250); } A: What you can try is make a PGraphics object for each rectangle you are drawing, fill it with gradient color using linear interpolation and then instead of using rect(x1, y1, x2, y2), in drawPaddle() use image(pgraphic, x, y). Here is how you can create a gradient effect using lerpColor() in processing: * *Make a start point say (x1, y1) and end point say (x2, y2) of the gradient. *Make a starting and a ending color say c1 and c2. *Now for a point P (x, y), calculate the distance between start point and P and divide it by the distance between the start point and and end point. This will be the 'amount' to lerp from start color and end color. float t = dist(x1, y1, x, y) / dist(x1, x2, y1, y2) *Put this value in lerpColor() as lerpColor(c1, c2, value). This will give you the color for point P. *Repeat the same for every point you want to calculate the gradient for. Here's an example: Note: here, i am taking t which is the amount to be lerped as the distance between the starting point of gradient divided by the distance between the start and end point of gradient, as it will always be a value in between 0 and 1. PGraphics g = createGraphics(50, 200); // set these values to the size(width, height) of paddle you want color startColor = color(255, 25, 25); // color of start of the gradient color endColor = color(25, 25, 255); // color of end of the gradient g.beginDraw(); //start drawing in this as you would draw in the screen g.loadPixels();//load pixels, as we are going to set the color of this, pixel-by-pixel int x1 = g.width/2; int y1 = 0; int x2 = g.width/2; int y2 = g.height; // (x1, y1) is the start point of gradient // (x2, y2) is the end point of gradient // loop through all the pixels for (int x=0; x<g.width; x++) { for (int y=0; y<g.height; y++) { //amout to lerp, the closer this is to (x2, y2) it will get closer to endColor float t = dist(x1, y1, x, y) / dist(x1, y1, x2, y2); // you need to convert 2D indices to 1D, as pixels[] is an 1D array int index = x + y * g.width; g.pixels[index] = lerpColor(startColor, endColor, t); } } g.updatePixels(); // update the pixels g.endDraw(); // we are done drawing into this // Now, you can draw this using image(g, x, y); Here is the result when i created this in the global scope and then drew it in draw() using image(g, width/2 ,height/2): Now, you can modify everything to your preference. Please mark this as answer if it helped you in any way. A: Nice question and great mycycle and void main's answers are great already. The PeasyGradients library looks great! I would like to contribute a minor workaround: using the P2D renderer to handle the gradient via shapes: size(100,100,P2D);// render via OpenGL noStroke(); // draw the rect by manually setting vertices beginShape(); // gradient start fill(#fef1a6); vertex(0 , 0); // TL vertex(100, 0); // TR // gradient end fill(#e28ab9); vertex(100,100); // BR vertex( 0,100); // BL endShape(); For more complex shapes this could be used be used in conjuction with mask(). Not only PImage can be masked, but also PGraphics, since they inherit from PImage: PGraphics gradient; PGraphics mask; void setup() { size(640, 360, P2D); gradient = getGradientRect(width, height, #fef1a6, #e28ab9); mask = getMaskRect(width, height); } void draw() { background(#483b6c); drawPongShapes(); // apply pong shapes mask to gradient gradient.mask(mask); // render masked gradient image(gradient, 0, 0); } // draw white shapes (masks) on black background void drawPongShapes(){ mask.beginDraw(); mask.background(0); mask.ellipse(width * 0.5, height * 0.5, 60, 60); mask.rect(width * .25, mouseY, 30, 150); mask.rect(width * .75, height-mouseY, 30, 150); mask.endDraw(); } PGraphics getMaskRect(int w, int h) { PGraphics layer = createGraphics(w, h, P2D); layer.beginDraw(); layer.background(0); layer.noStroke(); layer.fill(255); layer.ellipseMode(CENTER); layer.rectMode(CENTER); layer.endDraw(); return layer; } PGraphics getGradientRect(int w, int h, color grad1, color grad2) { PGraphics layer = createGraphics(w, h, P2D); layer.beginDraw(); layer.noStroke(); // draw rect as shape quad layer.beginShape(); // gradient start layer.fill(grad1); layer.vertex(0, 0); // TL layer.vertex(w, 0); // TR // gradient end layer.fill(grad2); layer.vertex(w, h); // BR layer.vertex(0, h); // BL layer.endShape(); layer.endDraw(); return layer; }
unknown
d8453
train
Here is a non Controller version that you can use to get some ideas from. I suggest you use TimeLine instead of Timer. This is not a complete program! import java.util.concurrent.atomic.AtomicInteger; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.util.Duration; /** * * @author blj0011 */ public class JavaFXApplication267 extends Application { @Override public void start(Stage primaryStage) { AtomicInteger timeInSeconds = new AtomicInteger(); TextField textField = new TextField(); Label label = new Label(Integer.toString(timeInSeconds.get())); Button btn = new Button("Play"); textField.setPromptText("Enter the number of minutes"); textField.textProperty().addListener((obs, oldValue, newValue) -> { //This assume the input is corret! timeInSeconds.set(Integer.parseInt(newValue) * 60);//Number of minutes times 60 seconds label.setText(getMinsSeconds(timeInSeconds.get())); }); Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), (event) -> { if (timeInSeconds.get() > 0) { label.setText(getMinsSeconds(timeInSeconds.decrementAndGet())); } })); timeline.setCycleCount(Timeline.INDEFINITE); btn.setOnAction((ActionEvent event) -> { switch (btn.getText()) { case "Play": timeline.play(); btn.setText("Pause"); textField.setEditable(false); break; case "Pause": timeline.pause(); btn.setText("Play"); textField.setEditable(true); break; } }); VBox root = new VBox(label, btn, textField); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } String getMinsSeconds(int seconds) { return String.format("%02d:%02d", (seconds / 60), (seconds % 60)); } }
unknown
d8454
train
Most of the jQuery methods (that don't return a value) are automatically applied to each element in the collection, so each() is not necessary. Combining siblings() and andSelf(), the code can be simplified to: $('.mySelector').siblings('img').andSelf().click(function (e) { e.preventDefault(); doStuffTo($(this)); }); A: Instead, you could do this: $('mySelector').each(function(){ $(this).siblings('img').andSelf()).bind('click', function(e){ e.preventDefault(); doStuffTo($(this)); }); }); A: It's not entirely clear what you're trying to do, but perhaps it's this: var f = function(e){ e.preventDefault(); doStuffTo($(this)); }; $('mySelector').each(function() { $(this).bind('click', f); $(this).siblings('img').bind('click', f); });
unknown
d8455
train
Since NuGet currently does not support this out of the box your options are either to use PowerShell or to use a custom MSBuild target. PowerShell * *Leave your resources outside of the Content directory in your NuGet package (as you already suggested). *Add the file link using PowerShell in the install.ps1. You should be able to avoid the project reload prompt if you use the Visual Studio object model (EnvDTE). I would take a look at Project.ProjectItems.AddFromFile(...) to see if that works for you. MSBuild target * *NuGet supports adding an import statement into a project that points to an MSBuild .props and/or .targets file. So you could put your resources into the tools directory of your NuGet package and reference them from a custom MSBuild .props/.targets file. Typically the custom .props and .targets are used to customise the build process. However they are just MSBuild project files so you could add items for your resources into these project files. Note that .props are imported at the start of the project file when a NuGet package is installed, whilst .targets are imported at the end of the project. Customising NuGet Another option, which would take more work, would be to modify NuGet to support what you want to do.
unknown
d8456
train
.... .... ddlCust.DataBind(); ddlCust.Items.Insert(0, new ListItem("Select Value:", "0"));
unknown
d8457
train
Or is list comprehension with modelforms my best workaround? Yes, or maps and filters: valid_forms = filter(lambda fm: fm.is_val(), map(ArticleForm, some_list_of_dictionaries)) If you're using Python3, this will return a generator object, which you can iterate over or you can immediately evaluate using something like the following: valid_forms = list(filter(lambda fm: fm.is_val(), map(ArticleForm, some_list_of_dictionaries))) If you're only interested in finding out if all of them are valid, you can do: all_forms_are_valid = all(lambda fm: fm.is_val(), map(ArticleForm, some_list_of_dictionaries)) But if you want to access them later on (and you're on Python3), it seems like a list comprehension is a better way to go because otherwise you're inefficiently building the same generator object twice. Edit with a question: Is there any difference between map(ArticleForm, some_list_of_dictionaries) and [ArticleForm(dict) for dict in some_list_of_dictionaries]? It depends on if you're using Python3 or not. In Python3, map will return a generator while in Python2, it will evaluate the expression (return a list), whereas either will evaluate the complete list in your list comprehension. In Python3, there can be some advantages to doing something like this: valid_forms = filter(lambda fm: fm.is_valid(), map(ArticleForm, some_list_of_dictionaries)) Because you end up with a generator that pulls data through it instead of first evaluating into a list with the map and then evaluating into another list with the filter. Edit 2: Forgot to mention that you can turn your list comprehension into a generator by using parentheses instead: all_valid = all(ArticleForm(fm).is_valid() for fm in some_list_of_dictionaries)
unknown
d8458
train
Issues in the asp.net button <asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="btn btn-block org" Style="margin-top: 0px" OnClick="btnLogin_Click" ValidationGroup="Login" OnClientClick="showalertmsg(); return false;" /> A: you can't call javascript fuction like this OnClick="btnLogin_Click showalertmsg();" But use OnClientClick="showalertmsg();" and also call return false at the end to stop postback function showalertmsg(message, alerttype) { $('#alert_placeholder').append('<div id="alertdiv" class="alert ' + alerttype + '"><a class="close" data-dismiss="alert">×</a><span>' + message + '</span></div>') setTimeout(function () { $("#alertdiv").remove(); }, 5000); return false; }
unknown
d8459
train
Your error can be reproduced by doing the following: $ cpan ... cpan shell -- CPAN exploration and modules installation (v2.10) Enter 'h' for help. cpan[1]> "install PDF::Create" Catching error: "Can't locate object method \"Create\" via package \"install PDF\" (perhaps you forgot to load \"install PDF\"?) ... The problem is you putting quotes around the whole command, apparently. Solution: Remove the quotes: cpan[2]> install PDF::Create ... works fine here. Also, you can just do cpan PDF::Create without entering the cpan shell.
unknown
d8460
train
Finally i got answer after 3 days of struggling just send your array of dictionary into this class func JSONStringify(value: AnyObject,prettyPrinted:Bool = false) -> String{ let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0) if NSJSONSerialization.isValidJSONObject(value) { do{ let data = try NSJSONSerialization.dataWithJSONObject(value, options: options) if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return string as String } }catch { print("error") //Access error here } } return "" } Hope this will help some one else Thank you.. A: First, it might come from the capital "C" instead of "c" in "config_id" ? Secondary, you are actually missing [], your code should look like this : let param : [String : AnyObject] = ["trf_id" : Constant.constantVariables.trfID, "mode" : Constant.modeValues.createMode, "to_city" : Constant.constantVariables.to_city, "from_city" : Constant.constantVariables.from_city, "description" : Constant.constantVariables.descrption, "request_type" : Constant.constantVariables.request_type, "to_date" : Constant.constantVariables.to_date!, "from_date" : Constant.constantVariables.from_date!, "travel_configs" : [["Config_id" : "9","values" : "train", "Config_id" : "10","values" : "bus"]]] Why? Because your server is expecting an array of dictionary, and you are sending only a dictionary ;)
unknown
d8461
train
It may be because when you create a windows form application, it is actually using managed c++ (uses .net), which I don't think lua is compatible with. Take a look at http://luaplus.org/ that might be what you're looking for. It seems like it's lua for ANY .net language (which managed c++ is)
unknown
d8462
train
You can cause the box to appear on top of the graphed line by using Z-order. Artists with higher Z-order are plotted on top of artists with lower Z-order. The default for lines is 2, so add zorder = 3 to mark_inset. Full code: from matplotlib import pyplot as plt import numpy as np from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset fig, ax = plt.subplots() time_list = np.linspace(0, 7, 1000) data = np.random.random(1000) - .5 plt.plot(time_list, data, color='red') plt.axvline(x=0, color='black') plt.axhline(y=0, color='black') axins = zoomed_inset_axes(ax, 4.5, loc=4) axins.plot(time_list, data, color='red') axins.axvline(x=0, color='black') axins.axhline(y=0, color='black') axins.axis([2, 3, -0.01, 0.01]) plt.yticks(visible=False) plt.xticks(visible=False) mark_inset(ax, axins, loc1=3, loc2=1, fc="none", ec="0.0", zorder = 3) plt.show()
unknown
d8463
train
I think you can do this by modifying where your for loop is located. I'm not familiar with the libraries you're using so I've left a comment where you might need to modify the code further, but something along these lines should work: names = json.loads(open(namelist + '.json').read()) for name in names: req = grequests.get('https://steamcommunity.com/id/' + name) # May need to modify this line since only passing one req, so are assured of only one response resp=grequests.imap(req, grequests.Pool(10)) # There should only be one response now. soup = BeautifulSoup(resp.text, 'lxml') findelement = soup.find_all('div', attrs={'class':"error_ctn"}) if (findelement): print(name) else: print('trying')
unknown
d8464
train
You have: * *An initial state *A terminating state *An iterative operation So you have everything needed to use a for loop (albeit without a body): for (int[] arr = {0}; arr.length < 9999; arr = evolve(arr)); Another solution, but nowhere near as neat, is to add this after the loop: arr = null; which still allows the allocated memory to be garbage collected and has a similar practical effect to restricting scope. Sometimes you need this approach if you can't refactor the code another way. A: You have a couple of ways. You can declare boolean token outside of a cicle and check against it. You can encapsulate the whole thing in a method that ends right after do while. A: @Bohemian's solution is elegant. But, if you still wan't to achieve this using do.. while, then following solution should work int l = 9999; do { int[] arr = { 0 }; // causes "cannot find symbol" on `while` line arr = evolve(arr); // modifies array, saves relevant results elsewhere l = arr.length; } while (l < 9999); A: You could also define the array outside the do-while loop and wrap the whole thing in a small method. The array will then be garbage collected when the method ends. This also helps to structure your code. A: Yet another option - although arguably not better than any of those already mentioned - would be to wrap it into a block: { int[] arr = {0}; // this works, but the scope is outside the loop do { int[] arr = {0}; arr = evolve(arr); // modifies array, saves relevant results elsewhere } while (arr.length < 9999); } I'd prefer @martinhh's solution though - just extract it to a method with a meaningful name. The body-less for loop is fine, too - but it would probably be a good idea to leave a comment there that it was indeed intentional to omit the body - things like that tend to get highlighted by static analysis tools and may cause some confusion.
unknown
d8465
train
$stdin and $stdout can be interchangeably used as IO objects. You may pass them to the SSLSocket. Does that help? Otherwise I'd need more code to help you out.
unknown
d8466
train
Extend DefaultTreeCellRenderer and invoke setToolTipText() as required. The tutorial project TreeIconDemo2, discussed in Customizing a Tree's Display, demonstrates the approach. Addendum: You can supply the desired text for each node in a TreeCellRenderer, e.g. MyRenderer: setToolTipText(value + " is in the Tutorial series."); A: you will have to use setToolTipText(null) to remove the tool tip - it will not disappear with our explicitly doing so.
unknown
d8467
train
http://agner.org/optimize/ for lots of details. On x86, an array of 1-byte data should be good. It can be loaded with movzx (zero-extend) just as fast as with a plain mov. x86 has bit ops to support atomic bitfields, if you want to pack your data by another factor of 8. I'm not sure how well compilers will do at making efficient code for that case, though. Even a write-only operation requires a slow atomic RMW cycle for the byte holding the bit you want to write. (On x86, it would a lock OR instruction, which is a full memory barrier. It's 8 uops on Intel Haswell, vs. 1 for a byte store. A factor of 19 in throughput.) This is probably still worth it if it means the difference between lots of cache misses and few cache misses, esp. if most of the access is read-only. (Reading a bit is fast, exactly the same as the non-atomic case.) 2-byte (16bit) operations are potentially slow on x86, esp. on Intel CPUs. Intel instruction decoders slow down a lot when they have to decode an instruction with a 16bit immediate operand. This is the dreaded LCP stall from the operand-size prefix. (8b ops have a whole different opcode, and 32 vs. 64bit is selected by the REX prefix, which doesn't slow down the decoders). So 16b is the odd-one-out, and you should be careful using it. Prefer to load 16b memory into 32b variables to avoid partial-register penalties and 16bit immediates when working with a temporary. (AMD CPUs aren't quite as efficient at handling movzx loads (takes an ALU unit and extra 1 cycle latency), but the savings in memory are still almost always worth it (for cache reasons)). 32b is the "optimal" size to use for local scratch variables. No prefix is needed to select that size (increasing code density), and there won't be partial-register stalls or extra uops when using the full register again after using the low 8b. I believe this is the purpose of the int_fast32_t type, but on x86 Linux that type is unfortunately 64bit.
unknown
d8468
train
"apply" is available to Any object in kotlin. You don't need to import anything to use "apply" Apply in Kotlin But, if IDE is suggesting you to import anything for apply, that means kotlin library is not properly configured. Check your app/build.gradle dependencies whether kotlin-stdlib exists or not. implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" A: that is because RecyclerView is not an instance. You can't use "apply" on a class. You may want to do something like this val recyclerView = findViewById<RecyclerView>(R.id.your_recycler) recyclerView.apply { layoutManager = LinearLayoutManager(activity) } A: Here's how apply works: val recyclerView = RecyclerView(context) recyclerView.adapter = MyAdapter() recyclerView.layoutManager = LinearLayoutManager() recyclerView.hasFixedSize = true vs val recyclerView = RecyclerView(context).apply { adapter = MyAdapter() layoutManager = LinearLayoutManager() hasFixedSize = true } you run it on an instance of an object, which becomes this in the lambda, so you can do all the calls on the object without referring to it by name. And the original object pops out of the end, so you can assign the whole thing to val recyclerView - it gets the RecyclerView() you created, with a few settings applyed to it. So it's common to configure objects like this. So like people have said, you weren't calling apply on a RecyclerView instance, you were calling it on the class itself, which doesn't work. You need to create a thing. Kotlin synthetic binding is magic code that automatically creates objects for you, from the XML it inflates, and assigns them to a variable named after the view's ID in the XML. So your tutorial is referring to an instance, using a variable name that the synthetics declared in the background. It's confusing if you're not aware of it, and I wonder if that's part of the reason it's deprecated. Sinner of the System's answer is the easiest (and normal) way to grab an object from your layout, by looking it up by ID yourself.
unknown
d8469
train
I think there are three potential issues I think in porting your app to Table Storage. * *The lack of reporting - including aggregate functions - which you've already identified *The limited availability of transaction support - with 100,000 orders per year I think you'll end up missing this support. *Some problems with costs - $1 per million operations is only a small cost, but you can need to factor this in if you get a lot of page views. Honestly, I think a hybrid approach - perhaps EF or NH to SQL Azure for critical data, with large objects stored in Table/Blob? Enough of my opinion! For "in depth": * *try the storage team's blog http://blogs.msdn.com/b/windowsazurestorage/ - I've found this very good *try the PDC sessions from Jai Haridas (couldn't spot a link - but I'm sure its there still) *try articles inside Eric's book - http://geekswithblogs.net/iupdateable/archive/2010/06/23/free-96-page-book---windows-azure-platform-articles-from.aspx *there's some very good best practice based advice on - http://azurescope.cloudapp.net/ - but this is somewhat performance orientated A: Have you seen this post ? http://blogs.msdn.com/b/windowsazurestorage/archive/2010/11/06/how-to-get-most-out-of-windows-azure-tables.aspx Pretty thorough coverage of tables A: If you have start looking at Azure storage such as table, it would do no harm in looking at other NOSQL offerings in the market (especially around document databases). This would give you insight into NOSQL space and how solution around such storages are designed. You can also think about a hybrid approach of SQL DB + NOSQL solution. Parts of the system may lend themselves very well to Azure table storage model. NOSQL solutions such as Azure table have their own challenges such as * *Schema changes for data. Check here and here *Transactional support *ACID constraints. Check here A: All table design papers I have seen are pretty much exclusively focused on the topics of scalability and search performance. I have not seen anything related to design considerations for reporting or BI. Now, azure tables are accessible through rest APIs and via the azure SDK. Depending on what reporting you need, you might be able to pull out the information you require with minimal effort. If your reporting requirements are very sophisticated, then perhaps SQL azure together with Windows Azure SQL Reporting services might be a better option to consider?
unknown
d8470
train
You can try as follows import pandas as pd df = pd.DataFrame({ "column1":["A", "A", "A", "A", "A", "A", "A"], "column2":["B", "B", "B", "B", "B", "B", "B"], "column3":[5, 2, 10, 1, 1, 1, 1], "column4":[4234, 432, 123, 123, 124, 125, 126], "column5":[123, 3243, 43, 45, 23243, 234, 23] }) df column1 column2 column3 column4 column5 0 A B 5 4234 123 1 A B 2 432 3243 2 A B 10 123 43 3 A B 1 123 45 4 A B 1 124 23243 5 A B 1 125 234 6 A B 1 126 23 row_index = df.loc[df["column3"]==(df.groupby(["column1", "column2"])["column3"].min()).min()]["column4"].idxmax() val_index = df["column5"].iloc[(df.loc[df["column3"]==(df.groupby(["column1", "column2"])["column3"].min()).min()]["column4"].idxmax())] df.loc[row_index, "column6"] = val_index df column1 column2 column3 column4 column5 column6 0 A B 5 4234 123 NaN 1 A B 2 432 3243 NaN 2 A B 10 123 43 NaN 3 A B 1 123 45 NaN 4 A B 1 124 23243 NaN 5 A B 1 125 234 NaN 6 A B 1 126 23 23.0 If you want it in one line df.loc[df.loc[df["column3"]==(df.groupby(["column1", "column2"])["column3"].min()).min()]["column4"].idxmax(), "column6"] = df["column5"].iloc[(df.loc[df["column3"]==(df.groupby(["column1", "column2"])["column3"].min()).min()]["column4"].idxmax())] Another option df.loc[(df[df['column4'] == df.loc[df['column3'] == df['column3'].min(), 'column4'].max()]["column5"]).index, "column6"] = df[df['column4'] == df.loc[df['column3'] == df['column3'].min(), 'column4'].max()]["column5"] A: * *find the rows with the min of column3 df.loc[df["column3"].eq(df["column3"].min())] *of these rows find rows with max of column4 *rename and join back together import io import pandas as pd df = pd.read_csv(io.StringIO("""column1 | column2 | column3 |column4 | column5 A | B | 5 | 4234 | 123 A | B | 2 | 432 | 3243 A | B | 10 | 123 | 43 A | B | 1 | 123 | 45 A | B | 1 | 124 | 23243 A | B | 1 | 125 | 234 A | B | 1 | 126 | 23 """), sep="|").pipe(lambda d: d.rename(columns={c:c.strip() for c in d.columns})) df.groupby(["column1", "column2"], as_index=False).apply( lambda df: df.join( df.loc[df["column3"].eq(df["column3"].min())] .loc[lambda d: d["column4"].eq(d["column4"].max()), "column5"] .rename("column6") ) ) column1 column2 column3 column4 column5 column6 0 A B 5 4234 123 nan 1 A B 2 432 3243 nan 2 A B 10 123 43 nan 3 A B 1 123 45 nan 4 A B 1 124 23243 nan 5 A B 1 125 234 nan 6 A B 1 126 23 23 A: Another way is to groupby 2 times: minval=df.groupby(['column1','column2'])['column3'].min().tolist() maxval=df.loc[df['column3'].isin(minval)].groupby(['column1','column2'])['column4'].max().tolist() df['column6']=df['column5'].where(df['column4'].isin(maxval)) output of df: column1 column2 column3 column4 column5 column6 0 A B 5 4234 123 NaN 1 A B 2 432 3243 NaN 2 A B 10 123 43 NaN 3 A B 1 123 45 NaN 4 A B 1 124 23243 NaN 5 A B 1 125 234 NaN 6 A B 1 126 23 23.0
unknown
d8471
train
Oooold question, I know, but I did it with the following: In a custom module, you can add it to _form_alter, i.e. function mymodule_form_alter((&$form, $form_state, $form_id) { $form['panes']['customer']['primary_email']['#description'] = t('Your custom message goes here.'); }
unknown
d8472
train
If I'm correct in thinking, you just want to check if the link is there, before outputting, otherwise, just show the image. Try the following: <?php // START SLIDER ?> <div class="slider"> <ul class="rslides"> <?php $args = array( 'posts_per_page' => 0, 'post_type' => 'slide'); $alert = new WP_Query( $args ); ?> <?php if( $alert->have_posts() ) { while( $alert->have_posts() ) { $alert->the_post(); ?> <!-- Get a link --> <?php $theLink = get_post_meta($post->ID, "_location", true); ?> <li> <!-- Check for a link --> <?php if($theLink != ''): ?> <a href="<?php echo $theLink; ?>" title="More Info"> <?php endif; ?> <?php the_post_thumbnail('full'); ?> <div class="caption"> <p class="captiontitle"> <?php the_title(); ?> </p> <p class="caption"> <?php the_content(); ?> </p> </div> <!-- Close the link --> <?php if($theLink != ''): ?> </a> <?php endif; ?> </li> <?php } } ?> </ul> </div> <?php wp_reset_query(); ?> <?php // END SLIDER ?>
unknown
d8473
train
How do you get the predicted values in the first place? The model you use to get the predicted values is probably based on minimising some function of prediction errors (usually MSE). Therefore, if you calculate your predicted values, the residuals and some metrics on MSE and MAPE have been calculated somewhere along the line in fitting the model. You can probably retrieve them directly. If the predicted values happened to be thrown into your lap and you have nothing to do with fitting the model, then you calculate MSE and MAPE as per below: You have only one record per week for every item. So for every item, you can only calculate one prediction error per week. Depending on your application, you can choose to calculate the MSE and MAPE per item or per week. This is what your data looks like: real <- matrix( c(.5, .7, 0.40, 0.6, 0.3, 0.29, 0.7, 0.09, 0.42, 0.032, 0.3, 0.37), nrow = 4, ncol = 3) colnames(real) <- c("week1", "week2", "week3") predicted <- matrix( c(.55, .67, 0.40, 0.69, 0.13, 0.9, 0.47, 0.19, 0.22, 0.033, 0.4, 0.37), nrow = 4, ncol = 3) colnames(predicted) <- c("week1", "week2", "week3") Calculate the (percentage/squared) errors for every entry: pred_error <- real - predicted pct_error <- pred_error/real squared_error <- pred_error^2 Calculate MSE, MAPE: # For per-item prediction errors apply(squared_error, MARGIN = 1, mean) # MSE apply(abs(pct_error), MARGIN = 1, mean) # MAPE # For per-week prediction errors apply(squared_error, MARGIN = 0, mean) # MSE apply(abs(pct_error), MARGIN = 0, mean) # MAPE
unknown
d8474
train
SQL_CALC_FOUND_ROWS . This will allow you to use LIMIT and have the amount of rows as no limit was used.
unknown
d8475
train
Answering my own question after more experimentation and sifting through the source. The way SDL handles events is that when you call SDL_WaitEvent/SDL_PeekEvent/SDL_PeepEvents, it pumps win32 until there's no messages left. During that pump, it will process the win32 messages and turn them into SDL events, which it queues, to return after the pump completes. The way win32 handles move/resize operations is to go into a message pump until moving/resizing completes. It's a regular message pump, so your WndProc is still invoked during this time. You'll get a WM_ENTERSIZEMOVE, followed by many WM_SIZING or WM_MOVING messages, then finally a WM_EXITSIZEMOVE. These two things together means that when you call any of the SDL event functions and win32 does a move/resize operation, you're stuck until dragging completes. The way EventFilter gets around this is that it gets called as part of the WndProc itself. This means that you don't need to queue up messages and get them handed back to you at the end of SDL_Peek/Wait/Peep Event. You get them handed to you immediately as part of the pumping. In my architecture, this fits perfectly. YMMV.
unknown
d8476
train
This is the answer To help for all function get_Example( $content = false, $echo = false ){ if ( $content === false ) $content = get_the_content(); $regexp = '/href=\"https:\/\/example\.com\/([^\"]*)"/i'; if(preg_match_all($regexp, $content, $link)) { $content = $link[1][0]; } if ( empty($content) ) { $content = false; } return $content; }
unknown
d8477
train
Mark all your editable input fields with the class "editable". (Change to suit.) $('.editable').each(function() { $(this).editable('mysaveurl.php'); }); That's all you need for the basic functionality. Obvious improvements can be made, depending on what else you need. For example, if you are using tooltips, stick them in the title attribute in your HTML, and use them when you call editable(). Your actual PHP/Ruby/whatever code on the server is just going to look at the id parameter coming in, and use that to save to the appropriate field in the database. A: Just use a class to make them all editable, and using their id (or a attribute that you have attached to the tag) you can specify the field you are updating. Then just pass the field and the value to your DB. i don't know the plugin you are using but, assuming it has some sort of event handling in it... something like this maybe? $(".editable").editable({ complete : function() { var _what = $(this).attr("id"); var _with = $(this).val(); $.post("yourPostPage.php",{what:_what, where:_where}); } }); Without knowing more about your environment I wouldn't be able to help further. A: The jQuery way of assigning some common code to a bunch of objects is to either give all the objects the same class so you can just do this: $(".myEditableFields").editable("enable"); This will call the editable add-on method for all objects in your page with class="myEditableFields". If you just have a list of IDs, you can just put them all in the single selector like this and they will each get called for the editable jQuery method: $("#edit_first_name, #edit_birthday, #edit_last_name, #edit_address").editable("enable"); Sometimes, the easy way it to create a select that just identifies all editable fields within a parent div: $("#editForm input").editable("enable"); This would automatically get all input tags inside the container div with id=editForm. You can of course, collect common code into your own function in a traditional procedural programming pattern and just call that when needed like this: function initEditables(sel) { $(sel).editable("enable"); // any other initialization code you want here or event handlers you want to assign } And, then just call it like this as needed: initEditables("#edit_first_name"); To help further, we would need to know more about what you're trying to do in your code and what your HTML looks like.
unknown
d8478
train
Because Base and Pow aren't bound to anything yet (they are parts of the X that you pass), you can't compute NewX (and the betweens might not work, either). A: When you enter factors(2,X), Factor1 is not bound and is_list(Factor1) fails. I think your code is_list(Factor1), length(Factor1, 2), Factor1 = [Base|A], A = [Pow] can be abbreviated to Factor1 = [Base,Pow]. Since Factor1 is not used anywhere else, you can move [Base,Pow] into the head of the clause. You can omit true, it has no effect here. The parenthesis haven't any effect, neither. So your code could be written as: factors(1,[[1,1]]) :- !. factors(X,[[Base,Pow]|T]) :- X > 0, between(2,X,Base), between(1,100,Pow), NewX is X / (Base ** Pow), (X mod Base) =:= 0, (NewX mod Base) =\= 0, factors(NewX,T), !. On my system (using SICStus), one must use NewX is X // floor(Base ** Pow) to prevent that NewX becomes a float which leads to an error when passed to mod as argument. Edit: I originally wrote that the last cut had no effect. That is not true because between/2 creates choice points. I removed that part of my answer and put the cut back into the code.
unknown
d8479
train
There is no iris package in the pypi. If you have iris correctly installed then it should find the plot module irrespective of whether your dependencies are correctly installed or not. The following gives guidance on installing iris on the Mac OS: https://github.com/SciTools/installation-recipes/tree/master/osx10.9 A: If I'm not mistaken, you can't import a function as something else, only modules. If you want to import just plot, do from iris import plot A: I'd thoroughly recommend installing Iris through Conda (or Anaconda if you already have it). Once you have conda installed, it should be as simple as doing a: conda install -c rsignell iris We are working on formalising and automating the build process, and once that is complete, it should be a matter of using the "scitools" (maintained by the developers of Iris) channel as such: conda install -c scitools iris (The latter may not work just yet though) This will work for Linux and Mac (and apparently Windows). If this does not work for you, then it is a bug, and is probably best addressed in the Iris google group (a thread already exists). HTH
unknown
d8480
train
Cython code is (strategically) statically typed, but that doesn't mean that arrays must have a fixed size. In straight C passing a multidimensional array to a function can be a little awkward maybe, but in Cython you should be able to do something like the following: Note I took the function and variable names from your follow-up question. import numpy as np cimport numpy as np cimport cython @cython.boundscheck(False) @cython.cdivision(True) def cooccurance_probability_cy(double[:,:] X): cdef int P, i, j, k P = X.shape[0] cdef double item cdef double [:] CS = np.sum(X, axis=1) cdef double [:,:] D = np.empty((P, P), dtype=np.float) for i in range(P): for j in range(P): item = 0 for k in range(P): item += X[i,k] * X[j,k] D[i,j] = item / max(CS[i], CS[j]) return D On the other hand, using just Numpy should also be quite fast for this problem, if you use the right functions and some broadcasting. In fact, as the calculation complexity is dominated by the matrix multiplication, I found the following is much faster than the Cython code above (np.inner uses a highly optimized BLAS routine): def new(X): CS = np.sum(X, axis=1, keepdims=True) D = np.inner(X,X) / np.maximum(CS, CS.T) return D A: Have you tried getting rid of the for loops in numpy? for the first part of your equation you could for example try: (data[ np.newaxis,:] * data[:,np.newaxis]).sum(2) if memory is an issue you can also use the np.einsum() function. For the second part one could probably also cook up a numpy expression (bit more difficult) if you've not already tried that.
unknown
d8481
train
Composition! Establish an interface that you are okay with people extending. This class would contain the logic for MethodD1 and D2, and for everything else just a simple call to the other methods in your currently existing class. People won't be able to modify the calls to change the underlying logic. A: The static methods can not be overridden! If a subclass defines a static method with the same signature as a static method in the superclass, the method in the subclass hides the one in the superclass. The distinction between hiding and overriding has important implications.
unknown
d8482
train
I have encountered the same problem. After googling I found out that this bug was fixed in Scilab 6.0.2. You can download it here: https://www.scilab.org/download/6.0.2 Current version of Scilab, that you can get from sudo apt-get scilab is 6.0.1 (for me scilab-cli was working, but GUI was not) Currently Scilab 6.0.2 works in GUI mode and CLI under Ubuntu 18.04.4 LTS. XCOS works too. It is a little bit laggy after start, but it might be my setup.
unknown
d8483
train
Many-to-many conditions should not be enforced using a trigger. Many-to-many conditions are enforced by creating a junction table containing the keys in question, which are then foreign-keyed back to the respective parent tables. If your intention is to allow many employees to be in a department, and to allow an employee to be a member of many departments, the junction table in question would look something like: CREATE TABLE EMPLOYEES_DEPARTMENTS (DEPARTMENTNAME VARCHAR2(99) CONSTRAINT EMPLOYEES_DEPARTMENTS_FK1 REFERENCES DEPARTMENT.DEPARTMENTNAME, EMPLOYEENUMBER NUMBER CONSTRAINT EMPLOYEES_DEPARTMENTS_FK2 REFERENCES EMPLOYEE.EMPLOYEENUMBER); This presumes that DEPARTMENT.DEPARTMENTNAME and EMPLOYEE.EMPLOYEENUMBER are either primary or unique keys on their respective tables. Get rid of the column EMPLOYEE.DEPARTMENT as it's no longer needed. Now by creating rows in the EMPLOYEES_DEPARTMENTS table you can relate multiple employees with a department, and you can relate a single employee with multiple departments. The business logic requiring that only departments with one or fewer employees can be deleted should not be enforced in a trigger. Business logic should be performed by application code, NEVER by triggers. Putting business logic in triggers is a gatèw̢ay to unending debugging sessions. M̫̣̗̝̫͙a̳͕̮d̖̤̳̙̤n̳̻̖e͍̺̲̼̱̠͉ss̭̩̟ lies this way. Do not give in. Do not surrender. ̬̦B҉usi͢n̴es̡s logic ̶in triggers opens deep wounds in the fabric of the world, through which unholy beings of indeterminate form will cross the barrier between the spheres, carryi͞n̨g o̡f͠f t͢h̶e ̕screaming͡ sou͏ĺs o͜f͜ ̢th͜e̴ ̕de͏v́e̡lop͏e͜r͝s to an et͞er͜n̸it̶y ́of͢ pain̶ ąn̨d͢ ̨to͟r̨ment͟. Do not, as I have said, put b́u͜siness͞ ̸log̛i͘ç ̵in͢ ͞trigge͠rs͞.̡ Be firm. Resist.You must resist. T̷he ̢Tem͟p͞t̶at͏i͝o̶n҉s͘ ̢m͘a̶y ́śing hymns̷ ́o͢f̴ ̸un͘hol̵y r̶ev͢ęla͠t̡ion̴ ͢buţ ́yo͠u̵ mu͏s͝t ͝n͜͏͟o҉t̶͡͏ ̷l̸̛͟͢ì̧̢̨̕s̵̨̨͢t̵̀͞e̶͠n̶̴̵̢̕. Only by standing firmly in the door between the worlds and blocking out the hideous radiance cast off by bú̧s̷i̶̢n̵̕e̵ş͝s ́l̴ó̢g̛͟i̕͏c i͞n̕ ͏t̵͜r͢͝i̸̢̛ģ͟ge̸̶͟r̶s͢͜, which perverts the very form of the world ąnd̴̀͝ ç͞a̧͞l̶l͟͜s̕͘͢ Z̶̴̤̬͈̤̬̲̳͇ͯ̊ͮ͐̒̆͂͠Â̆́̊̓͛́̚͏̮̘̗̻̞̬̱ͅL̛̄̌͏̦͕̤͎̮̦G̷͖̙̬͛̇ͬ̍͒̐̅O̡̳͖͎̯̯͍ͫ̽ͬ͒͂̀ i͜҉nt͝ǫ̴ ̸b̷͞è͢ì̕n̴g͏,̛̀͘ ̴c҉á̴͡ń ̀͠youŕ̨ ̧̨a̸p͏̡͡pl̷͠ic͞a̢t̡i͡҉ǫn̴ ̸s̶͜u̶͢ŗv̛í̴v́ȩ.͘͘ Resist. R͏͢͝e͏͢͟s̸͏͜ì̢̢s͠ţ̀. T̶̀h̨̀e̶r̀͏e͢͞ ̶i̶̡͢s̴ ͞͞n̵͝o̡ ́ẁ҉̴a̡y̕҉ ̶b́͏u̵̶̕t͜ ̨s͘͢t͘͠į͟l͘l̷̴ ̴͜͜ỳò͜u҉̨ ̨͏mus̸͞t̸̛͜ ̧rȩ̴s̢͢i͘͡s͏t̸.̛̀͜ Your very śo͡u̧̧͘ļ͟͡ is compromised by p͝u͘͝t̢͜t͠i̸ņ̸̶g͟͡ ̵̶̛b̴҉u̶̡̨͜͞s̷̵̕͜͢i͝҉̕͢ǹ͏e̡͞ś̸͏ş̕͜͡҉ ̴̨ĺ̵̡͟͜o̶̕g͠i͢͠c̕͝ ̕͞i̧͟͡n̡͘͟ ̶̕͞t̡͏͟҉̕r̸̢̧͡͞i̴̡͏̵͜g̵̴͟͝ģ̴̴̵ę̷̷͢r̢̢ś̸̨̨͜. T̀͜͢o̷͜ny̕ ͟͡T̨h̶̷̕e ̢͟P̛o̴̶n͡y shall rise from his dark stable and d͞ę̡v̶̢ó͟u̸̸r̴͏ ̷t͞h̀e̛ ̨͜s̷o̧͝u҉l̀ ͟͡o͢͏f̵͢ ̛t͢h̶̛e̢̢ ̡̀vi͜͞r̢̀g̶i̢n͞, and yet y͢ơú͝ m̷̧u͏s͡t̡͠ ̛s̷̨t̸̨i̴̸l̶̡l ͝ǹot̵ ͞p̧u̵t̨ ͜͏b̀̕u̕s̨í̵ņ̀͠ȩs̵͟s ́͞l̛҉o̸g̨i̴͟c ͘͘i͘nt̛o͡ ͘͘͞t̶͞r̀̀i̕ǵ̛g̵̨͞e̸͠҉r̵͟ś! It is too much to bear, we cannot stand! Not even the children of light may put business logic into their triggers, for b̴̸̡̨u͜͏̧͝ş̶i̷̸̢̛҉ń̸͟͏́e̡͏͏͏s̷̵̡s̕͟ ͏̴҉͞l̷̡ǫ̷̶͡g҉̨̛i͘͠͏̸̨c̕͢͏ ̸̶̧͢͢i̸̡̛͘n͢͡ ̀͢͝t̷̷̛́ŗì̴̴̢g̶͏̷ǵ͠ȩ̀́r̸̵̢̕͜s͞͏̵ is the very es̵s̕͡ę̢n͞c̨e̢͟ ̴o̶̢͜f͏ ͟d́ar͟͞͠k̡͞n̢̡es̵̛͡s̀̀͡ and dev͘ou͝͡r̨̡̀s͢͝ ҉͝t҉h̴e̡͘ l̫̬i̤͚ͅg̞̲͕̠͇̤̦̹h̩̙̘̭̰͎͉̮̳t͙̤̘̙! Yea, yea, the blank-faced ones rì͢s̨͘e from the f͟͢͏o̵͜͝n̶t̨ ̵o͏f̸̡͠ ͏͝fl͟͞a̵̷҉me̶̵͢ and ca͝s͜t́ down the p̹̤̳̰r̮̦̥̥̞̫͑͂ͤ͑ͮ͒̑ï̄̌ͬͨe̦̗͔ͥͣ̆̾̂s̬̭̮̮̜ͭt̻̲̍sͫͣ̿ ̐͗̈ͤ͂ͦ̅f̭͚̪̻̣̩ͮ̒ṟͨ͌ͮ̅̓ỏ̝͓̝̣̟̼m̳͇̱̝͔͒ ͒ͫͧ͂̓̈̈́t̲̔̅̎͐h̺͈͍ͣͧ̿ē̪̼̪̻͉̪̙̐̽̎̉i̠͎̗͕̗̣̬̐̎͛r͓̫͌ͅ ̼a͑̈ͯͦ̍l̪͉͖̥͚̤͌ͨ͊ͦͤ̔t̫͎̹ͯa̼̻͍̳̟̤̬̓ͪ̀r̭͖̓ͬ̉̉ͤ͊ṡ̐ͪ̊̋̄̅! A̵̵̛v͝é͜ŕt̶͏ ̶y̸͝͠o̶u̧͘r͏̡ ̧e͞y҉e̕͝s,̀ ͡t̛h̛o̢͞ug̸̢h̵͟ ̡y̷o͢҉͢u̧͡ ̕͡c҉̵̶an͠͏n҉o̧͢t!̸̨͘ ͡H̵e̸͢͡ ̧̕c̶ơm̷̢̢e̶͞ś͢!̨́ ̷H̕ȩ ̵c̨̡͟o̴҉m̷͢es͠!̷͘͞ P̱̼̯̟͈h̝̳̞̖͚'͉̙͉̰̲̺n̪̦͕̗͜g͔̹̟̰̰̻̩l̬͈̹̥͕͖ͅụ̻̺̤̤̬̳i̸̯̬̝̻̣͚̫ ̰̹̞̞m͟g̷̝͓͉̤l̩͇̙͕w̪̦̰͔'̮̟̱̀n̢̜a̦f̘̫̤̘̬͓̞h̠͍͖̯ͅ ̩̠͓̯̘̫C̟̘̗̘͘ṭ͍͕ͅh̤ͅu̼̦̘̥ͅl҉̦hu̠̤̤̘͚ ̘̕R̶̟'̠͔̞̻͇l̩̺̗̻͖͓̕ͅy̛̖ȩ͉̭̖ẖ̡̥̼͈̖ w̟̫̮͇͔͞ͅg͈̘̱̻a̰͟h̘͙͖͢'̮̲̯͞n̤̜͍̯̳a͓͓̲̲g̱̻͈ĺ͍ ̷̣̞̲͖͍̲̺f̲ͅh͇͕̪̘͟t͔͈̙a͓͢g҉̳̜̲͚n͓͚͎̱̠̜! Don't ask me how I know. Best of luck.
unknown
d8484
train
use nestedScrollEnabled in inner Flatlist for enabling the scrolling activity A: You can use the nestedScrollEnabled prop but I would recommend using a <SectionList> since this is somehow buggy!
unknown
d8485
train
If I understand your question correctly this might help : df.columns[df.columns.str.startswith('Fee_')] it gives you the list of columns that start with Fee_, if you want the last one you can add df.columns[df.columns.str.startswith('Fee_')][-1]
unknown
d8486
train
My observations with Firebase realtime database. It caches data on server side before adding to database (for a few milliseconds). Result: Read operations are few milliseconds faster than write operations. * *What's happening with your request: * *It reaches server and asks for data which is still not available in realtime database. *Why that so: * *because its cached and still to be added to realtime database. *all this caching and adding data to realtime database takes only milliseconds of time, but its significant when you immediately invoke data after adding because your Get Data request has reached the server before the node is created. *That's why it shows permission denied. *When this does not happen: * *When your device is using low speed internet connectivity, your request reaches Firebase server with a delay of 1-3 seconds, this happens naturally. So this problem will not arise there. *What to do now: * *Just introduce a delay of 2-3 seconds before requesting data for the first time. *This gives the whole operation of authentication, node creation and adding data enough time to complete. *Everything will be smooth from there. A: Thanks to the suggestion from Mr Frank I've managed to pinpoint the culprit. The problem occurs when the user signs in with Google while being already signed in anonymously (which I didn't take into account). So a workaround would be to sign out the anonymous user (FirebaseAuth.getInstance().sign_out()) before trying to sign in with Google, although I believe it's still undesired behavior, because it makes linking accounts problematic. Here's an example to reproduce the problem: public class TestAuthGoogle extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener { static private final String TAG = TestAuthGoogle.class.getSimpleName(); private GoogleApiClient mGoogleApiClient; public static final int RC_SIGN_IN = 9001; private Handler mHandler = new Handler(); @Override public void onStart() { super.onStart(); signInAnonymously(); mHandler.postDelayed(new Runnable() { @Override public void run() { signInGoogle(); } },5000); } void signInAnonymously() { FirebaseAuth.getInstance().signInAnonymously() .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful()); if (!task.isSuccessful()) { Log.w(TAG, "signInAnonymously", task.getException()); } } }); } void signInGoogle() { GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.my_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(TestAuthGoogle.this) .enableAutoManage(TestAuthGoogle.this, TestAuthGoogle.this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) { GoogleSignInAccount account = result.getSignInAccount(); firebaseAuthWithGoogle(account); Log.d(TAG,"Authenticated"); } else { Log.d(TAG,"Authentication failed"); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); FirebaseAuth.getInstance().signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); if (task.isSuccessful()) { Log.d(TAG,"Signed in"); mHandler.postDelayed(new Runnable() { @Override public void run() { readFromDatabase(); } },5000); } else { Log.w(TAG, "signInWithCredential: " + task.getException().getMessage()); } } }); } void readFromDatabase() { Log.d(TAG,"read from db"); DatabaseReference uRef = FirebaseDatabase.getInstance().getReference("users"); uRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot data) { Log.d(TAG, "fb onDataChange: " + data.getValue()); } @Override public void onCancelled(DatabaseError error) { Log.w(TAG, "fb onCancelled: " + error.getMessage()); } }); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.d(TAG,"onConnectionFailed"); } }
unknown
d8487
train
There is no one answer to how to set up your repository. It depend on your specific needs. Some questions you should ask yourself include: * *Are all projects going to be released and versioned separately? *Are the projects really independent of each other? *How is your development team structured? Do individual developers stick to a single project? *Is your framework project stable? *Does your build process build each project separately? Assuming that the answers to all of the above is "yes", then I would set it up like so: * *Continue maintaining the framework code in its own repository, and publish it to an internal server using NuGet (as suggested in ssube's comment). *Create a separate repository for each project, each with their own solution file. If you can say "yes" to all except #5 (and possibly #1), above, then I would add one more repository that consists of submodules of each of the individual projects and a global solution file that your build server can use. If you add a new project, you have to remember to also update this repository! If you have to say "no" to #2, then just build a single repository. If you have to say "no" to #3, then you'll have to make a judgement call, between separation of the code and developers' need to switch between repos. You could create a separate repository including submodules, but if all your developers wind up using that repo, you are really only introducing new maintenance with little gain. If your framework is not stable (#4), then you may want to include that as a submodule in any of these cases. I recommend that once it becomes stable, then you look into removing the submodule and switching to NuGet at that time. A: What i have done for such a situation was the following. Note that in my case there were 2-3 developers. So i have 3 things in this: * *The empty project structure that i would like to replicate [OPTIONAL] *The common library projects *The actual end projects that use common library projects 1) I just create my scaffold development directory structure and i am putting a .gitkeep file in each and everyone of them in order for git to include it. In this way when i want to setup myself in a new pc i just clone this and i have my empty development "universe" structure. Then i populate (git clone) with the projects i need. 2) The common libraries project is just a normal repo. 3) My end projects reference the common library projects. There are prons and cons about it and depends on your situation, but i what i gain is that i can change the common libraries either directly from the common library project, or from the end project which references it. In both ways i get the changes in git and commit normally and separately. In your case i would have my empty structure and then do 2 separate clones. The framework project in the correct place and then the entire webservices repo. Its up to you if you want to have a separate repo for each web service or one for all. It depends on your person count and work flow. Also do not forget a proper .gitignore Here: LINK A: If * *you really want to have all projects in the same solution *the common project "Framework" is in active development (and some modifications for one project could break others...) i think you must have each WebService as a git project with his own copy of Framework project as submodule: WebServices/ |- WebServices.sln |- WebService1/ `|-.git |-WebService1.csproj |-Framework (as submodule) |- WebService2/ `|-.git |-WebService2.csproj\ |-Framework (as submodule) This way each WebService will use the Framework version that is compatible with. (of course you must be aware of git submodule workings... you could read for example this, specially the section "Issues with Submodules"!) Important: with this configuration each deployed webservice must reference the Framework library with the actual version it is using! A: Depending on "how independent" development going to be for each of your projects you might consider two option. * *in case you are mostly working on entire solution - create one repo for entire solution *in case some projects are really independent , create separate repos for those projects and create solution file for each project aside project file, then use git submodules to reference those repos in the repo of the main solution, that make use of those projects. Git Submodules Tips
unknown
d8488
train
You first need to split the filename from the extension. import os filename = path2 + f # Consider using os.path.join(path2, f) instead root, ext = os.path.splitext(filename) Then you can combine them correctly again doing: filename = root + "r" + ext Now filename would be imgr.png instead of img.pngr. A: You could do this as follows: import os listing = os.listdir(path1) for f in listing: im = Image.open(os.path.join(path1, f)) red, green, blue = im.split() red = red.convert('LA') green = green.convert('LA') blue = blue.convert('LA') file_name, file_ext = os.path.splitext(f) red.save(os.path.join(path2, "{}r.png".format(file_name)) green.save(os.path.join(path2, "{}g.png".format(file_name)) blue.save(os.path.join(path2, "{}b.png".format(file_name)) I would recommend you make use of the os.path.split() and os.path.join() functions when working with paths and filenames.
unknown
d8489
train
var rows = $('tr.classname:first', tbl); or var rows = $('tr.classname', tbl).first(); Docs here: http://api.jquery.com/category/selectors/ A: var firstRow = $('tr.classname:first', tbl) A: You can use the :first selector along with the class selector, Try this: var rows = $('tr.someclass:first', tbl); A: var row = $("tr.className:first", tbl); should do the trick. A: If you keep the proprietary :first selector out of it, you'll have a valid querySelectorAll selector. var rows = tbl.find('tr.someClass').slice( 0, 1 ); or var rows = tbl.find('tr.someClass').eq( 0 ); Also, using the context parameter $( selector, context ) is just a slower way of using the find()[docs] method. A: You can even use eq method of jquery if you want to loop through a list of elements. var rows = $('tr.classname'); rows.eq(0);//first row rows.eq(1);//second row
unknown
d8490
train
So the answer was to trim the result var result = $.trim(html);
unknown
d8491
train
Spring can inject into abstract classes too. So you can move the injection of the SampleState to the abstract class, if each AbstractSingletonBean descendant needs just a SampleState (as in your example). A: It doesn't look like this was available out of the box so I created an annotation I call @AnonymousRequest that I put on the field I want, and a BeanDefinitionRegistryPostProcessor to do the work of creating the bean. It basically goes like this: for each bean in the BeanFactory if bean class has AnonymousRequest annotation create request scoped bean from field class create singleton bean to be request scoped bean wrapper set the annotated property value to the singleton wrapper This took a lot of work to figure out how Spring registers request scoped beans. You create the bean definition you want as a request scoped bean. Then you create a singleton bean of type RootBeanDefinition that acts as a wrapper to the request scope bean and set a property on the wrapper called "targetBeanName" to whatever you named the request scoped bean ("scopedTarget." + the singleton bean name by convention). So this could probably be improved by someone who actually knows this stuff but here's what I came up with: public void createRequestBeanFromSetterMethod(String containingBeanName, BeanDefinition containingBean, Method method, BeanDefinitionRegistry registry) { String fieldName = ReflectionUtil.getFieldNameFromSetter(method.getName()); String singletonBeanName = containingBeanName+"_"+fieldName; String requestBeanName = "scopedTarget."+singletonBeanName; BeanDefinition requestBean = createAnonymousRequestBean(ReflectionUtil.getFieldTypeFromSetter(method), containingBean); RootBeanDefinition singletonBean = new RootBeanDefinition(); singletonBean.setBeanClass(ScopedProxyFactoryBean.class); singletonBean.getPropertyValues().addPropertyValue("targetBeanName", requestBeanName); registry.registerBeanDefinition(singletonBeanName, singletonBean); registry.registerBeanDefinition(requestBeanName, requestBean); beanDefinition.getPropertyValues().addPropertyValue(fieldName, new RuntimeBeanReference(singletonBeanName)); } private BeanDefinition createAnonymousRequestBean(Class<?> beanType, BeanDefinition parentBean) { BeanDefinition newBean = null; if (parentBean != null) { newBean = new GenericBeanDefinition(parentBean); } else { newBean = new GenericBeanDefinition(); } if (beanType != null) { newBean.setBeanClassName(beanType.getName()); } newBean.setScope("request"); newBean.setAutowireCandidate(false); // This would have come from the Proxy annotation...could add support for different values String proxyValue = "org.springframework.aop.framework.autoproxy.AutoProxyUtils.preserveTargetClass"; BeanMetadataAttribute attr = new BeanMetadataAttribute(proxyValue, true); newBean.setAttribute(proxyValue, attr); return newBean; } It seems to work! I effectively have now a request scoped bean created just before the context initialization that is localized to this one containing bean. It's a request-scoped property, more or less. A: You can try defining single SampleState request scope bean and then use spring's lookup method to inject this bean wherever you want to.That's works just fine with prototype-scope beans. Fingers crosses it would work with request scope as well. AFAIK, there is no annotation support for lookup method as of now, so either use it's xml vis-a-vis or have a look at javax.inject.Provider relevant question here
unknown
d8492
train
You have two problems. The first is in this line: | otherwise = searchHelp xs n-1 The compiler interperets this as (searchHelp xs n) - 1, not searchHelp xs (n-1), as you intended. The second problem is in you use of guards: | searchHelp xs 0 = -1 -- no pairs found Since searchHelp xs 0 is not a boolean expression (you wanted to use it as a pattern), the compiler rejected it. I can see two easy solutions: searchForPairs xs = searchHelp xs ((genericLength xs) - 1) where searchHelp xs n | n == 0 = -1 -- no pairs found | (xs !! n) == (xs !! (n - 1)) = n | otherwise = searchHelp xs (n-1) and searchForPairs xs = searchHelp xs ((genericLength xs) - 1) where searchHelp xs 0 = -1 -- no pairs found searchHelp xs n | (xs !! n) == (xs !! (n - 1)) = n | otherwise = searchHelp xs (n-1) Now, unfortunately, although this works, it is terribly inefficient. This is because of your use of !!. In Haskell, lists are linked lists, and so xs !! n will take n steps, instead of 1. This means that the time your function takes is quadratic in the length of the list. To rectify this, you want to loop along the list forward, using pattern matching: searchForPairs xs = searchHelp xs 0 where searchHelp (x1 : x2 : xs) pos | x1 == x2 = pos | otherwise = searchHelp (x2 : xs) (pos + 1) searchHelp _ _ = -1 A: @gereeter already explained your errors, I would just like to point out that you should not return -1 in case the answer is not found. Instead, you should return Nothing if there is no answer and Just pos if the answer is pos. This protects you from many kinds of errors. A: I couldn't quite grok what you want to do, but from the code, it looks like you're trying to find two consecutive elements in a list that are equal. Instead of using !! to index the list, you can use pattern matching to extract the first two elements of the list, check if they are equal, and continue searching the remainder (including the second element) if they are not. If the list doesn't have at least two elements, you return Nothing searchForPairs xs = go 0 xs where go i (x1:xs@(x2:_)) | x1 == x2 = Just i | otherwise = go (i+1) xs go _ _ = Nothing A: For what it's worth, here is a somewhat idiomatic (and point-free) implementation of what you are trying to do: searchPairs :: Eq a => [a] -> Maybe Int searchPairs = interpret . span (uncurry (/=)) . (zip <*> tail) where interpret (flag, res) = if null flag then Nothing else Just $ length res Explanation: zip <*> tail creates a list of pairs of successive elements (using the reader Applicative type class). uncurry (/=) tests if such a pair is made of identical elements. Finally, interpret translates the result in a value of Maybe Int type.
unknown
d8493
train
I have now figured out how to do what I want to do. I know the columns I will need at design time, so in the IDE I add the columns to my datagridview and format them as desired. I then set the AutoGenerateColumns property of the grid view to false. For some unknown reason, that property is not available in the designer and has to be set in code. Finally, I can set the DataPropertyName of each column to the name of the corresponding field in the structure I will be linking to. For example, here is the LINQ code I will be using to generate the data source: taskArray = from task in tasks select new { StartDate = task.m_start_task_date.ToString("M/dd H:mm"), EndDate = task.m_task_date.ToString("M/dd H:mm"), Description = task.m_short_desc, Object = task.m_device_id, InitialLocation = task.m_initial_location, FinalLocation = task.m_final_location }; .DataSource = taskArray.ToArray(); And here is the code in my form's constructor to set the DataPropertyName properties: dgvFutureTasks.AutoGenerateColumns = false; dgvFutureTasks.Columns["colStartTime"].DataPropertyName = "StartDate"; dgvFutureTasks.Columns["colFinishTime"].DataPropertyName = "EndDate"; dgvFutureTasks.Columns["colDescription"].DataPropertyName = "Description"; dgvFutureTasks.Columns["colObject"].DataPropertyName = "Object"; dgvFutureTasks.Columns["colInitialLocation"].DataPropertyName = "InitialLocation"; dgvFutureTasks.Columns["colFinalLocation"].DataPropertyName = "FinalLocation"; At this point, the DataGridView displayed the data as expected. RobR
unknown
d8494
train
Try <script type="text/javascript"> paypal.Buttons({ env: 'sandbox', style: { layout: 'vertical', size: 'responsive', shape: 'pill', color: 'blue', label: 'pay' }, createOrder: function() { return fetch('/checkout/paypal', { method: 'post', headers: { 'content-type': 'application/json' } }).then(function(response) { console.log(response); }); } }).render('#paypal-button-container'); </script> what will return on Console
unknown
d8495
train
You are not protecting your critical section from exceptions. When the client disconnects, an exception will be raised by either ReadLn() or WriteLn() (depending on timing) to terminate the thread for that client. The next time the OnExecute event is called for a different thread, the critical section will still be locked and cannot be re-entered again, deadlocking your code. Add a try/finally to your code to guard against that, eg: procedure TTaifun.svExecute(AContext: TIdContext); var ... begin CSection.Enter; //Enter critical section try ... finally CSection.Leave; //Leave critical section end; end; With that said, why are you using a critical section to begin with? The code you showed is thread-safe by itself, it does not need to be protected from concurrent access: procedure TTaifun.svExecute(AContext: TIdContext); var cmds, flist: TStringList; i: Integer; tmp: string; begin cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn, '|'); if cmds[0] = 'FILE_LIST' then //Check command received begin tmp := ''; flist := TStringList.Create; try flist.LoadFromFile(MyPath + 'files.dat'); for i := 0 to flist.Count - 1 do begin tmp := tmp + flist[i] + ',' + GetFileSize(flist[i]) + ',' + BoolToStr(FileExists(MyPath + 'Thumbs\' + ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true) + '|'; //Do some parsing end; finally flist.Free; end; AContext.Connection.IOHandler.WriteLn(tmp); //Send the string end; end; Alternatively: procedure TTaifun.svExecute(AContext: TIdContext); var cmds, flist: TStringList; i: Integer; begin cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn, '|'); if cmds[0] = 'FILE_LIST' then //Check command received begin flist := TStringList.Create; try flist.LoadFromFile(MyPath + 'files.dat'); for i := 0 to flist.Count - 1 do begin flist[i] := flist[i] + ',' + GetFileSize(flist[i]) + ',' + BoolToStr(FileExists(MyPath + 'Thumbs\' + ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true); //Do some parsing end; flist.Delimiter := '|'; flist.StrictDelimiter := True; AContext.Connection.IOHandler.WriteLn(flist.DelimitedText); //Send the string finally flist.Free; end; end; end;
unknown
d8496
train
It's usually happend because SystemWeb package is not installed on your project. Use this command at your Package Manager Console: Install-Package Microsoft.Owin.Host.SystemWeb In the other hand you may use this configuration on your app.config or web.config if the above solution is not work: <appSettings> <add key="owin:AutomaticAppStartup" value="true"/> </appSettings> A: Using <add key="owin:AutomaticAppStartup" value="true"/> Is the answer. A: Try removing [assembly: OwinStartup(typeof(MVCSite.Startup))] and give a shot
unknown
d8497
train
The microphone won't show any activity until it is attached to a NetStream connection. You can use a MockNetStream to fake the connection using OSMF - see my answer here.
unknown
d8498
train
you can read form array in way as below frmRefer = document.getElementByTagName("form")[0]; for(i= 0 ; i<frmRefer.elements["ite[]"].length;i++){ alert(frmRefer.elements["ite[]"][i].value ); } for(i= 0 ; i<frmRefer.elements["quant[]"].length;i++){ alert(frmRefer.elements["quant[]"][i].value ); } for(i= 0 ; i<frmRefer.elements["pr[]"].length;i++){ alert(frmRefer.elements["pr[]"][i].value ); } A: Assuming you want to generate the sum of the prices for all the products and quantities you bought, you would first rewrite your HTML as: <form id="example_form"> <div class="row"> <input type="text" name="item" class="item"></input> <input type="text" name="quant" class="quant"></input> <input type="text" name="price" class="price"></input> </div> <div class="row"> <input type="text" name="item" class="item"></input> <input type="text" name="quant" class="quant"></input> <input type="text" name="price" class="price"></input> </div> <!-- ... many more rows --> <input type="text" disabled id="sum" name="sum"></input> </form> Use jQuery to make field access easier. Using JQuery, you would use the following JS: function update() { var total = 0; $("#example_form div.row").each(function(i,o){ total += $(o).find(".quant").val() * $(o).find(".price").val(); }); $("#example_form #sum").val(total); } This will update totals for you. To do this each time any number is changed, you would need to register it with the corresponding fields, using something like $("#example_form div.row input").change(update); Have I convinced you of using JQuery? See it working at http://jsfiddle.net/UnYJ3/2/
unknown
d8499
train
I'm fairly certain this is not possible directly (because AKS can only stream to OMS), but this link outlines some principles. So you can create a function\logic app to do that for you.
unknown
d8500
train
As Alex says, you'll just recreate the anonymous type. To geth a specific author to the top of the list, you can use orderby clause (or OrderBy extension method), which I think, is a bit easier then using Where and Union: new { ... Authors = from a in record.Authors orderby a.AuthorID == 32 descending select a }; The only trick is that you can use boolean value (AuthorID == 32) as a key for the ordering. In this way, you'll first get all elements for which the predicate returns true (the one with ID=32) and then all other values (for which the predicate returned false). A: You can just recreate object of anonymous type, because its readonly property can not be changed. Something like this: record = new { record.BookId, record.AuthorId, Authors = record.Authors.Where(author => author.Id==32).Union( record.Authors.Where(author => author.Id!=32)) };
unknown