_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d13601
train
below link will help you to understand about how android picks up layout files on various devices http://developer.android.com/guide/practices/screens_support.html A: Are you sure the folder name is layout-xlarge and not layout-x-large ? DOC A: As per Android Documentation for the runtime rendering of layout At runtime, the system ensures the best possible display on the current screen with the following procedure for any given resource: The system uses the appropriate alternative resource Based on the size and density of the current screen, the system uses any size- and density-specific resource provided in your application. For example, if the device has a high-density screen and the application requests a drawable resource, the system looks for a drawable resource directory that best matches the device configuration. Depending on the other alternative resources available, a resource directory with the hdpi qualifier (such as drawable-hdpi/) might be the best match, so the system uses the drawable resource from this directory. If no matching resource is available, the system uses the default resource and scales it up or down as needed to match the current screen size and density The "default" resources are those that are not tagged with a configuration qualifier. For example, the resources in drawable/ are the default drawable resources. The system assumes that default resources are designed for the baseline screen size and density, which is a normal screen size and a medium density. As such, the system scales default density resources up for high-density screens and down for low-density screens, as appropriate. However, when the system is looking for a density-specific resource and does not find it in the density-specific directory, it won't always use the default resources. The system may instead use one of the other density-specific resources in order to provide better results when scaling. For example, when looking for a low-density resource and it is not available, the system prefers to scale-down the high-density version of the resource, because the system can easily scale a high-density resource down to low-density by a factor of 0.5, with fewer artifacts, compared to scaling a medium-density resource by a factor of 0.75.
unknown
d13602
train
public final class Ping implements Callable<Boolean> { private final InetAddress peer; public Ping(final InetAddress peer) { this.peer = peer; } public Boolean call() { /* do the ping */ ... } } ... final Future<Boolean> result = executorService.submit(new Ping(InetAddress.getByName("google.com"))); System.out.println("google.com is " + (result.get() ? "UP" : "DOWN")); A: In one of our projects, we have the following requirement: * *Create a record in DB. *Call a service to update a related record. *Call another service to log a ticket. To perform this in a transactional manner, each operation is implemented as a command with undo operation. At the end of each step, the command is pushed onto a stack. If the operation fails at some step, then we pop the commands from the stack and call undo operation on each of the command popped out. The undo operation of each step is defined in that command implementation to reverse the earlier command.execute(). Hope this helps. A: Command Patterns are used in a lot of places. * *Of course what you see everywhere is a very trivial example of GUI Implementation, switches. It is also used extensively is game development. With this pattern the user can configure his buttons on screen as well. *It is used in Networking as well, if a command has to be passed to the other end. *When the programmers want to store all the commands executed by the user, e.g. sometimes a game lets you replay the whole level. *It is used to implement callbacks. Here is a site which provides as example of command pattern used for callback. http://www.javaworld.com/article/2077569/core-java/java-tip-68--learn-how-to-implement-the-command-pattern-in-java.html?page=2 *Here's another link which shows command pattern with database. The code is in C#. http://www.codeproject.com/Articles/154606/Command-Pattern-at-Work-in-a-Database-Application A: You have to define undo(), redo() operations along with execute() in Command interface itself. example: interface ChangeI { enum State{ READY, DONE, UNDONE, STUCK } ; State getState() ; void execute() ; void undo() ; void redo() ; } Define a State in your ConcreteCommand class. Depending on current State after execute() method, you have to decide whether command should be added to Undo Stack or Redo Stack and take decision accordingly. abstract class AbstractChange implements ChangeI { State state = State.READY ; public State getState() { return state ; } public void execute() { assert state == State.READY ; try { doHook() ; state = State.DONE ; } catch( Failure e ) { state = State.STUCK ; } catch( Throwable e ) { assert false ; } } public void undo() { assert state == State.DONE ; } try { undoHook() ; state = State.UNDONE ; } catch( Failure e ) { state = State.STUCK ; } catch( Throwable e ) { assert false ; } } public void redo() { assert state == State.UNDONE ; try { redoHook() ; state = State.DONE ; } catch( Failure e ) { state = State.STUCK ; } catch( Throwable e ) { assert false ; } } protected abstract void doHook() throws Failure ; protected abstract void undoHook() throws Failure ; protected void redoHook() throws Failure { doHook() ;} ; } Have a look at this undo-redo command article for better understanding.
unknown
d13603
train
Maybe these changes will help you: 1) Add the error message you want to show when surname is wrong: <label for="ssurname" >Surname</label> <input type="text" id="surname" name="surname" onblur="validateSurname('surname')" /> <br /> <span id="surnameError" style="display: none;">Please enter your surname, you can only use alphabetic characters</span> 2) Pass a string to the parameter instead of a javascript var (e.g. do validateSurname('surname') instead of validateSurname(surname)), as the function you've defined is expecting a string as a parameter. Fiddle demo: http://jsfiddle.net/uzyLogc1/1/
unknown
d13604
train
According to this docs, you can write a custom formatter to alter how the data is displayed, without altering the underlying data. Example: function addTable(data) { var table = new Tabulator("#table", { height:205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value) data: data.rows, //assign data to table layout:"fitColumns", //fit columns to width of table (optional) columns:[ //Define Table Columns { title: "Work Type", field: "WorkType" }, { title: "Total", field: "total" }, { title: "On Time", field: "otperc", formatter: cell => cell.getValue() + "%" } ], }); }
unknown
d13605
train
This is a tricky problem! In WPF there exists the concept of a SharedSizeGroup, which allows you to share column widths across multiple grids, but this is not available in silverlight. There are a few workarounds on the web: http://www.scottlogic.co.uk/blog/colin/2010/11/using-a-grid-as-the-panel-for-an-itemscontrol/ http://databaseconsultinggroup.com/blog/2009/05/simulating_sharedsizegroup_in.html Although neither are simple solutions. You might also try Mike's AutoGrid: http://whydoidoit.com/2010/10/06/automatic-grid-layout-for-silverlight/ A: Here is my solution using SharedSizeGroup as suggested by ColinE. <ListBox x:Name="ResultsList"> <ListBox.Resources> <SharedSize:SharedSizeGroup x:Key="Col1Width" /> <SharedSize:SharedSizeGroup x:Key="Col2Width" /> <SharedSize:SharedSizeGroup x:Key="Col3Width" /> <DataTemplate x:Key="ResultsListItem"> <StackPanel d:DesignWidth="385" Orientation="Horizontal"> <SharedSize:SharedSizePanel WidthGroup="{StaticResource Col1Width}"> <TextBlock x:Name="textBlock" MaxWidth="100" Text="{Binding A}"/> </SharedSize:SharedSizePanel> <SharedSize:SharedSizePanel WidthGroup="{StaticResource Col2Width}"> <TextBlock x:Name="textBlock1" MaxWidth="85" Text="{Binding B}"/> </SharedSize:SharedSizePanel> <SharedSize:SharedSizePanel WidthGroup="{StaticResource Col3Width}"> <TextBlock x:Name="textBlock2" MaxWidth="200" Text="{Binding C}"/> </SharedSize:SharedSizePanel> </StackPanel> </DataTemplate> </ListBox.Resources> <ListBox.ItemTemplate> <StaticResource ResourceKey="ResultsListItem"/> </ListBox.ItemTemplate> </ListBox> Even the maximum with of each column can be controlled via the TextBlock's MaxWidth property. The SharedSizeGroups ensure that the TextBlocks have the same size in each row. A: You can use WrapPanel. Set the following ItemsPanel in the Datatemple, you can just have textblock. <ListBox.ItemsPanel> <ItemsPanelTemplate> <control:WrapPanel /> </ItemsPanelTemplate> </ListBox.ItemsPanel>
unknown
d13606
train
Using --module-path instead of the -classpath option for the module to be resolved for commons-math3-3.6.1.jar should work for you. In practice, you can detail all the dependencies into a single folder for simplicity and then treat that as modulepath such as following: In the above image, I have created a dependencies folder that includes the .jars for all dependent libraries for poi-scratchpad. Further executing the following command from the same directory works: jdeps --module-path dependencies poi-scratchpad-5.0.0.jar
unknown
d13607
train
I discovered that trying to migrate my own Users model to a CustomUser model is a non-trivial undertaking! I learned this from Will Vincent and his excellent post on this very topic! Django Best Practices: Custom User Model The Django documentation also states that migrating to the Django User in the midst of an existing project is non-trivial. Changing to a custom user model mid-project So, to solve my problem I started with a new empty project with only the CustomUser in my models.py as Mr. Vincent described, which worked perfectly. After that, I setup the rest of my model classes in models.py, referencing the CustomUser model as needed. assignee = models.ForeignKey( to=CustomUser, on_delete=models.RESTRICT, blank=True, null=True, ) And copied the rest of my template files, view source files, static files, etc. from my original project into this new project. My codebase is now working as expected using the Django User model. Huge Thanks to Mr. Will Vincent's excellent article on this issue!
unknown
d13608
train
if I remember correctly 'contain' => array('Entry', 'User.avatar,User.username')), should do the trick A: Okay, I solved it... I just had to add the proper foreignKey to my Comment model, i.e: var $belongsTo = array( 'Entry' => array('className' => 'Entry', 'foreignKey' => 'page_id'), 'User' => array('className' => 'User', 'foreignKey' => 'user_id'), ); Now it finally fetches the appropriate user information!
unknown
d13609
train
There is no reason for the compiler to complain. The return type of func throwingVoidFunction() throws { ... } is Void and therefore the type of the expression try? throwingVoidFunction() is Optional<Void>, and its value is nil (== Optional<Void>.none) if an error was thrown while evaluating the expression, and Optional<Void>.some() otherwise. You can ignore the return value or test it against nil. An example is given in An elegant way to ignore any errors thrown by a method: let fileURL = URL(fileURLWithPath: "/path/to/file") let fm = FileManager.default try? fm.removeItem(at: fileURL)
unknown
d13610
train
The reason behind your error is that the frame is None(Null). Sometimes, the first frame that is captured from the webcam is None mainly because (1) the webcam is not ready yet ( and it takes some extra second for it to get ready) or (2) the operating system does not allow your code to access the webcam. In the first case, before you do anything on the frame you need to check whether the frame is valid or not : while True: frame = image.read() if frame is not None: # add this line (H, W) = frame.shape[:2] In the other case, you need to check the camera setting in your Operating system. Also, for capturing the webcam frames there is another method based on the VideoCapure class in Opencv that might be easier to debug.
unknown
d13611
train
The syntax for iterating over a list is for i in $( ... not for i=$( ... A: Have a look at the pkill and pgrep commands. You could just pkill jboss.
unknown
d13612
train
So the mistake went from linux Server side due to ** @ini_set('display_errors', 'on');** Everything is rolling great again ! Thanks for all your concerns and support ! Jeff
unknown
d13613
train
The ProtocolError says that pip is trying to resolve /simple/jira/ as a DNS hostname instead of pypi.python.org. The problem may reside in ~/.pip/pip.conf. Are you in a container by any chance?
unknown
d13614
train
Here's a one liner to do what you want. I've tested it and it seems to be correct. var results = source .Publish(xs => xs .Select(x => Observable .Interval(TimeSpan.FromMinutes(1.0)) .Select(_ => x) .StartWith(x)) .Switch()); Let me know if this does the trick. A: I would wrap the observable in an observable that is guaranteed to return a value at least once per minute. The wrapper could do this by running a timer that is restarted whenever the wrapped observable returns a value. Thus, the wrapper returns data whenever the wrapped observable returns data or when a minute has passed after the last event. The rest of the application conveniently just observes the wrapper. A: Here's a (non-threadsafe, in case your source is multithreaded) implementation of a RepeatAfterTimeout operator: EDIT Updated as Timeout didn't work as I expected // Repeats the last value emitted after a timeout public static IObservable<TSource> RepeatAfterTimeout<TSource>( this IObservable<TSource> source, TimeSpan timeout, IScheduler scheduler) { return Observable.CreateWithDisposable<TSource>(observer => { var timer = new MutableDisposable(); var subscription = new MutableDisposable(); bool hasValue = false; TSource lastValue = default(TSource); timer.Disposable = scheduler.Schedule(recurse => { if (hasValue) { observer.OnNext(lastValue); } recurse(); }); subscription.Disposable = source .Do(value => { lastValue = value; hasValue = true; }) .Subscribe(observer); return new CompositeDisposable(timer, subscription); }); } public static IObservable<TSource> RepeatAfterTimeout<TSource>( this IObservable<TSource> source, TimeSpan timeout) { return source.RepeatAfterTimeout(timeout, Scheduler.TaskPool); } A: I had the exact same requirement once. I chose to include a default value to use if no value triggers before the first timeout. Here's the C# version: public static IObservable<T> AtLeastEvery<T>(this IObservable<T> source, TimeSpan timeout, T defaultValue, IScheduler scheduler) { if (source == null) throw new ArgumentNullException("source"); if (scheduler == null) throw new ArgumentNullException("scheduler"); return Observable.Create<T>(obs => { ulong id = 0; var gate = new Object(); var timer = new SerialDisposable(); T lastValue = defaultValue; Action createTimer = () => { ulong startId = id; timer.Disposable = scheduler.Schedule(timeout, self => { bool noChange; lock (gate) { noChange = (id == startId); if (noChange) obs.OnNext(lastValue); } //only restart if no change, otherwise //the change restarted the timeout if (noChange) self(timeout); }); }; //start the first timeout createTimer(); var subscription = source.Subscribe( v => { lock (gate) { id += 1; lastValue = v; } obs.OnNext(v); createTimer(); //reset the timeout }, ex => { lock (gate) { id += 1; //'cancel' timeout } obs.OnError(ex); //do not reset the timeout, because the sequence has ended }, () => { lock (gate) { id += 1; //'cancel' timeout } obs.OnCompleted(); //do not reset the timeout, because the sequence has ended }); return new CompositeDisposable(timer, subscription); }); } If you don't want to have to pass a scheduler every time, just make an overload that picks a default one and delegates to this method. I used Scheduler.ThreadPool. This code works by using the behavior of SerialDisposable to "cancel" the previous timeout call when a new value from the source comes in. There is also a counter I use in case the timer has already elapsed (in which case Disposing the return from Schedule will not help) but the method has not yet actually run. I investigated the possibilities of changing timeouts but did not need them for the problem I was working on. I recall that it was possible but don't have any of that code handy. A: I think this should work the Rx way (no recursion but still involving a side effect): public static IObservable<TSource> RepeatLastValueWhenIdle<TSource>( this IObservable<TSource> source, TimeSpan idleTime, TSource defaultValue = default(TSource)) { TSource lastValue = defaultValue; return source // memorize the last value on each new .Do(ev => lastValue = ev) // re-publish the last value on timeout .Timeout(idleTime, Observable.Return(lastValue)) // restart waiting for a new value .Repeat(); }
unknown
d13615
train
If you want to remove all words that contain "es", try b <- a[-grep("es", a)] If you want to remove only the words that starts with "es", try b <- a[-grep("\\bes\\w+", a)]
unknown
d13616
train
prepend() $departments = Department::pluck('name', 'id')->prepend('Select Department', '');
unknown
d13617
train
it might be related with this : KarateUI: How to Handle SSL Certificate during geckodriver configuration? I added the alwaysMatch in and it is able to pick up the capabilities. * def session = { capabilities: {alwaysMatch:{ acceptInsecureCerts:true, browserName: 'firefox' }}} * configure driver = { type: 'geckodriver', showDriverLog: true , executable: 'driver/geckodriver.exe', webDriverSession: '#(session)' } A: This is an area that may require you to do some research and contribute findings back to the community. Finally Karate passes the capabilities you define "as-is" to the driver. One thing that you should look at is if any command-line sessions should be passed to geckodriver - for example for Chrome, I remember there is some flag for ignoring these security errors. Note that you can use the addOptions flag in the Karate driver options.
unknown
d13618
train
I'll just point you to the right direction: * *https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview *https://github.com/donaldp24/CanvasCameraPlugin Try these plugins (in order) and lemme know if either of them worked out for you.
unknown
d13619
train
The error message tells you what you need to change - the --app parameter has moved from being a parameter to celery worker to being a parameter to celery instead. Your old command: celery worker --app=worker.celery --loglevel=info needs to be changed by moving --app to the left (so that it is a parameter to celery instead): celery --app=worker.celery worker --loglevel=info
unknown
d13620
train
Avoid SQL_ASCII You should be using a server encoding of UTF8 rather than SQL_ASCII. The documentation is quite clear about this matter, and even includes a warning to not do what you are doing. To quote (emphasis mine): The SQL_ASCII setting behaves considerably differently from the other settings. When the server character set is SQL_ASCII, the server interprets byte values 0-127 according to the ASCII standard, while byte values 128-255 are taken as uninterpreted characters. No encoding conversion will be done when the setting is SQL_ASCII. Thus, this setting is not so much a declaration that a specific encoding is in use, as a declaration of ignorance about the encoding. In most cases, if you are working with any non-ASCII data, it is unwise to use the SQL_ASCII setting because PostgreSQL will be unable to help you by converting or validating non-ASCII characters. Use UTF8 Use an encoding of UTF8, meaning UTF-8. This can handle the characters for any language including Chinese. And the UTF8 encoding allows Postgres to make use of the new support for International Components for Unicode (ICU) in Postgres 10 and later. Java also uses Unicode encoding. Just let your JDBC driver handle the marshaling of text between Java and the database.
unknown
d13621
train
maxActive is smaller than 1, setting maxActive to: 100 <strong> 2016-02-01 19:14:59,345 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing the application: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more 2016-02-01 19:14:59,346 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing Grails: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more feb 01, 2016 7:14:59 PM org.apache.catalina.core.StandardContext listenerStart GRAVE: Excepción enviando evento inicializado de contexto a instancia de escuchador de clase org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more 01-Feb-2016 19:14:59.347 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file 01-Feb-2016 19:14:59.349 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Falló en arranque del Contexto [/abacus] debido a errores previos feb 01, 2016 7:14:59 PM org.apache.catalina.core.ApplicationContext log INFORMACIÓN: Closing Spring root WebApplicationContext 01-Feb-2016 19:14:59.363 WARNING [localhost-startStop-1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc La aplicación web [abacus] registró el conductor JDBC [org.postgresql.Driver] pero falló al anular el registro mientras la aplicación web estaba parada. Para prevenir un fallo de memoria, se ha anulado el registro del conductor JDBC por la fuerza. </strong> 01-Feb-2016 19:14:59.371 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat8_nodo1/webapps/abacus.war has finished in 433.719 ms 01-Feb-2016 19:14:59.373 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/ROOT de la aplicación web 01-Feb-2016 19:14:59.434 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/ROOT has finished in 61 ms 01-Feb-2016 19:14:59.435 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/manager de la aplicación web 01-Feb-2016 19:14:59.479 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/manager has finished in 45 ms 01-Feb-2016 19:14:59.479 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/examples de la aplicación web 01-Feb-2016 19:14:59.726 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/examples has finished in 247 ms 01-Feb-2016 19:14:59.726 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/host-manager de la aplicación web 01-Feb-2016 19:14:59.743 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/host-manager has finished in 17 ms 01-Feb-2016 19:14:59.750 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"] 01-Feb-2016 19:14:59.760 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 442905 ms 01-Feb-2016 22:35:59.831 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:10,000 messages Sent:6.81 MB (total) Sent:6.81 MB (application) Time:2.39 seconds Tx Speed:2.85 MB/sec (total) TxSpeed:2.85 MB/sec (application) Error Msg:0 Rx Msg:10,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:6.81 MB] 01-Feb-2016 22:35:59.832 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:10,000 messages Sent:6.81 MB (total) Sent:6.81 MB (application) Time:2.39 seconds Tx Speed:2.85 MB/sec (total) TxSpeed:2.85 MB/sec (application) Error Msg:0 Rx Msg:10,001 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:6.81 MB] 02-Feb-2016 02:04:23.818 INFO [Tribes-Task-Receiver-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:20,000 messages Sent:13.62 MB (total) Sent:13.62 MB (application) Time:4.07 seconds Tx Speed:3.35 MB/sec (total) TxSpeed:3.35 MB/sec (application) Error Msg:0 Rx Msg:20,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:13.62 MB] 02-Feb-2016 02:04:23.820 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:20,000 messages Sent:13.62 MB (total) Sent:13.62 MB (application) Time:4.07 seconds Tx Speed:3.35 MB/sec (total) TxSpeed:3.35 MB/sec (application) Error Msg:0 Rx Msg:20,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:13.62 MB] 02-Feb-2016 05:32:47.761 INFO [Tribes-Task-Receiver-6] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:30,000 messages Sent:20.43 MB (total) Sent:20.43 MB (application) Time:5.72 seconds Tx Speed:3.57 MB/sec (total) TxSpeed:3.57 MB/sec (application) Error Msg:0 Rx Msg:30,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:20.42 MB] 02-Feb-2016 05:32:47.763 INFO [Tribes-Task-Receiver-6] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:30,000 messages Sent:20.43 MB (total) Sent:20.43 MB (application) Time:5.72 seconds Tx Speed:3.57 MB/sec (total) TxSpeed:3.57 MB/sec (application) Error Msg:0 Rx Msg:30,001 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:20.42 MB] 02-Feb-2016 09:01:11.617 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:40,000 messages Sent:27.23 MB (total) Sent:27.24 MB (application) Time:7.38 seconds Tx Speed:3.69 MB/sec (total) TxSpeed:3.69 MB/sec (application) Error Msg:0 Rx Msg:40,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:27.23 MB] 02-Feb-2016 09:01:11.618 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:40,001 messages Sent:27.24 MB (total) Sent:27.24 MB (application) Time:7.38 seconds Tx Speed:3.69 MB/sec (total) TxSpeed:3.69 MB/sec (application) Error Msg:0 Rx Msg:40,002 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:27.23 MB] 02-Feb-2016 12:29:35.561 INFO [Tribes-Task-Receiver-2] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:49,999 messages Sent:34.04 MB (total) Sent:34.04 MB (application) Time:8.99 seconds Tx Speed:3.79 MB/sec (total) TxSpeed:3.79 MB/sec (application) Error Msg:0 Rx Msg:50,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:34.04 MB] 02-Feb-2016 12:29:36.108 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:50,000 messages Sent:34.04 MB (total) Sent:34.05 MB (application) Time:8.99 seconds Tx Speed:3.79 MB/sec (total) TxSpeed:3.79 MB/sec (application) Error Msg:0 Rx Msg:50,001 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:34.04 MB] 02-Feb-2016 15:57:59.873 INFO [Tribes-Task-Receiver-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:59,999 messages Sent:40.85 MB (total) Sent:40.85 MB (application) Time:10.64 seconds Tx Speed:3.84 MB/sec (total) TxSpeed:3.84 MB/sec (application) Error Msg:0 Rx Msg:60,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:40.85 MB] 02-Feb-2016 15:58:00.431 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:60,000 messages Sent:40.85 MB (total) Sent:40.85 MB (application) Time:10.64 seconds Tx Speed:3.84 MB/sec (total) TxSpeed:3.84 MB/sec (application) Error Msg:0 Rx Msg:60,001 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:40.85 MB] A: There are many different possible causes to this problem. Two top suspects are: * *You are using a plug-in that is triggering a component scan of Spring classes. *Your code has added a component scan that is hitting Spring classes. A search for "component-scan" throughout your project can help you check for those two causes.
unknown
d13622
train
It is not possible to make common code for all application. There are various type of windows application for example Database Application, Client Server Application, System Utilities, etc So, the mechanism of all applications are different then how we can define a common code template for all application. It is up to you that what you want to use Database or TcpIP Socket for your application. I know my answer is not clear. Because it is very hard to define that why we could not create scaffolding.
unknown
d13623
train
Found a solution at https://github.com/dilipajm/piechart Though it's in Objective C but we can try to do the same with swift too.
unknown
d13624
train
You will want to use a service to make this happen. It is basically an activity without a view. Check out the link below for more info. http://developer.android.com/guide/topics/fundamentals/services.html
unknown
d13625
train
The 2 easy ways to think about this are either * *Call the method in your class from the event handler in your form *Have a method on your class which matches the signature of an event handler, and subscribe to the event. The first requires no major change private MyClass myClass = new MyClass(); public void ProgramsListbox_SelectedIndexChanged(object sender, EventArgs e) { myClass.DoSomething(); } The second requires your class to have a specific method that matches the signature of that event handler currently in your form public class MyClass { public void DoSomething(object sender, EventArgs e) { var listBox = (ListBox)sender; // read selected index perhaps, or selected item maybe } } And then in your form private MyClass myClass = new MyClass(); protected override void OnLoad(EventArgs e) { this.ProgramsListBox.SelectedIndexChanged += myClass.DoSomething; } A: Within your Form1.cs create instance of UnIstallItem class and use it. Then on Button Click call "RemoveSelected" method of UnInstaItem class by passing programsListBox to it and it should remove the selected item. public class Form1:Form { ListBox ProgramsListbox; UninstallItem unistall; public Form1(){ InitializeComponent(); uninstall = new UninstallItem(); button1.Click+= button1_Click; } void button1_Click(object sender, EventArgs e){ unistall.RemoveSelected(ProgramsListbox); } } Then in your external class; public class UninstallItem{ public UninstallItem{} public void RemoveSelected(ListBox list) { if(list.SelectedIndex==-1) { MessageBox.Show("Please Select Item from List"); return; } list.Items.RemoveAt(list.SelectedIndex); } }
unknown
d13626
train
Using react-native means that you have two options, * *The native implementation which depends on the OS you're working on. *If you're using a JS library for networking (Axios) or even a builtin function (fetch) you can implement a wrapper Promise which calculates the length of any input/output string, + an approximation of the length of the header.
unknown
d13627
train
What you can do is create an Encryption/Decryption Web Service and use it in BPEL, OSB and you ADF application if you want, there are many Encryption Algorithms with this solution you should be able to choose what you want to use. A: Found the answer. It was in the Oracle code examples all along. See bpel-310 Partial Message encryption https://java.net/projects/oraclesoasuite11g/pages/BPEL
unknown
d13628
train
There is the blue Anchor button up in the left corner and also an Insert anchor button on the field itself: A: This is a known issue with the Sitecore 8 SPEAK dialog. The temporary workaround is to revert to the previous dialog by commenting out (or better yet <patch:delete />) the following line in the /App_Config/Include/Sitecore.Speak.Applications.config: <override dialogUrl="/sitecore/shell/Applications/Dialogs/Internal%20link.aspx" with="/sitecore/client/applications/dialogs/InsertLinkViaTreeDialog" /> The corresponding public reference number for this issue is #407189 A: There is a solution to customise the Speak dialog to add this back in here: https://exlrtglobal.atlassian.net/wiki/display/~Drazen.Janjicek/2016/03/18/Extending+Sitecore+8.1+-+Adding+support+for+anchors+in+internal+links
unknown
d13629
train
Today, I got the same error at my project which I was working on yesterday without any problem. Some upgrade causes this error IMO, my solution is: * *Open the project via Android Studio *Open android/build.gradle and android/app/build.gradle *Just correct things what IDE warns about, it usually warns your SDK, Kotlin and Gradle versions etc. It's not mandatory but you can check your .bashrc exports or environment variables, sometimes it can fix some problems. Edit: When you are updating your SDK versions, don't forget to upgrade also your project dependencies. A: I think it depends on android emulator API level you are using. In my case I used android emulator API 30, but compileSdkVersion was 28, so i got the error! By updating compileSdkVersion to 30, everything worked correctly! OS: Ubuntu 20.04 LTS Android emulator API 30 Dart 2.10.2 Flutter 1.22.2 A: Kindly check your strings.xml and It should be like: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">App Name here</string> <string name="facebook_app_id">2206883509627625</string> <string name="fb_login_protocol_scheme">fb2206883509627625</string> </resources> Special attention to add this line: <string name="app_name">App Name here</string> A: I had the same error while using flutter, but in my case the problem was caused by an incorrect line in a file in the 'res' folder in my Adroid projects. You need to check your code, in my case it was calling a resource that doesn't exist in my android / app / src / main / res / launcher / drawable / launch_background.xml file, make sure all your resources and xml files are ok. A: check that How to fix "Execution failed for task ':app:processDebugResources'. > Android resource linking failed"[Android/Flutter] I had the same error while using flutter, but in my case the problem was caused by an incorrect line in a file in the 'res' folder in my Adroid projects. You need to check your code, in my case it was calling a resource that doesn't exist in my android / app / src / main / res / launcher / drawable / launch_background.xml file, make sure all your resources and xml files are ok. A: To resolve this issue, run your flutter project in Android Studio rather than Visual Studio Code. A: Make sure you are connected to the Internet and rebuild the project. That solves the problem for me.
unknown
d13630
train
if you need to convert your express.js app to serverless. You can use serverless framework and serverless-http module. add serverless-http moduele to app npm install --save express serverless-http Then modify your app this way const serverless = require('serverless-http'); const express = require('express') const app = express() app.get('/', function (req, res) { res.send('Hello World!') }) module.exports.handler = serverless(app) More details read this article . You can't use mongoose for dynamodb. try to use dynamoose
unknown
d13631
train
Your script could work as a CGI script, since it outputs a HTTP header, followed by the HTML content. python -m http.server, by default, does not run CGI scripts for security, but if you add the --cgi switch, it will, provided that the scripts are in the cgi-bin directory relative to the directory you start it from. In other words: * *create a cgi-bin directory *move home.py to cgi-bin/home.py *run python3 -m http.server --cgi 8000 *navigate to http://127.0.0.1:8000/cgi-bin/home.py When working with CGI scripts, you might want to enable the (soon-to-be-deprecated) cgitb handler too. Anything more intricate than that, and I would recommend looking at the Flask application framework instead, though.
unknown
d13632
train
Using dataclass and dacite from dataclasses import dataclass import dacite @dataclass class Body: day:int month:int year:int @dataclass class Dat: response_time: int body: Body data = {'response_time':12, 'body':{'day':1,'month':2,'year':3}} dat: Dat = dacite.from_dict(Dat,data) print(dat) output Dat(response_time=12, body=Body(day=1, month=2, year=3)) A: Using pymarshaler (Which is close to to golang approach) import json from pymarshaler.marshal import Marshal class Body: def __init__(self, day: int, month: int, year: int): self.day = day self.month = month self.year = year class Dat: def __init__(self, response_time: int, body: Body): self.response_time = response_time self.body = body marshal = Marshal() dat_test = Dat(3, Body(1, 2, 3)) dat_json = marshal.marshal(dat_test) print(dat_json) result = marshal.unmarshal(Dat, json.loads(dat_json)) print(result.response_time) see https://pythonawesome.com/marshall-python-objects-to-and-from-json/ A: So turns out it wasn't that hard, I just didn't want to try. For anyone with the same problem here's the code. class Typs(object): def __init__(self): self.type = int self.breed = str class Deets(object): def __init__(self): self.color = str self.type = Typs() class Base(object): def __init__(self): self.name = str self.details = Deets() d = { "name": "Hello", "details": {"color": "black", "type": {"type": 2, "breed": "Normal"}}, } h = Base() def unmarshal(d, o): for k, v in d.items(): if hasattr(o, k): if isinstance(v, dict): unmarshal(v, getattr(o, k)) else: setattr(o, k, v) return o x = unmarshal(d, h)
unknown
d13633
train
How much modification can be done to the UI that is being generated by the Swagger? Swagger UI can be tweaked in very different ways mainly via JS or CSS. You can have a look to https://swagger.io/docs/open-source-tools/swagger-ui/customization/overview/ Can "Try Out" functionality be modified to have more control? What I want to do is have few input fields which are not generated by swagger and use them as input for an api call, make UI more dynamic in nature. You should have a look to the link I shared above but not sure this is doable like this. If I had to do such kind of thing I would rather look at how to complete the original OpenAPI definition (the yaml/JSON file) before passing it to Swagger UI. Note that there is also a "interceptor" feature in Swagger UI that allow to modify requests before sending them for instance. This might interest you. Does the Swagger-UI depend on any sort of API gateway to make calls to api endpoints? Not at all. Swagger UI just uses your browser to call the API at the URL documented by the OpenAPI file. A: Stack Overflow doesn't work well when there are multiple questions as part of one "Question". Having said that, I'll answer what I know. * *As far as I can tell, you can modify the yaml or JSON source as much as you like. You can write an entire file from scratch, or import it from any editor. *For this sort of testing, I think you might want to look for a more in-depth testing tool such as Postman. That's not something I have any experience with, but from what I hear it could help with "what if I send this request?" sceanrios.
unknown
d13634
train
Why you want to fix the body width? simply use a container inside the body if you want like CSS body { height: 100%; width: 100%; } .container { width: 1000px; margin: 0 auto; } HTML <body> <div class="container"></div> </body> OR if you want your content area to be 100% than just change your CSS to this CSS body { height: 100%; width: 100%; } .container { width: 100%; }
unknown
d13635
train
You can try using Message Queues. Rabbit MQ is a good option as it supports MQTT (which is great for device to cloud communication) as well as AMQP (0.9.1) (which is great for cloud to cloud communication) You can also use any standard MQTT broker (EMQTT, Mosquito, Hive etc) and implement an MQTT to MongoDB client in between. Setting the MQTT clean_session flag to false will make the broker act as a cache.
unknown
d13636
train
Without changing the markup, if you set float: left to the red <div> then you could put the blue <div> to its right side .div { width: 100%; height: 100px; background-color: green; } .div1 { width: 100px; height: 100px; background-color: red; float: left; } .div2 { width: 100px; height: 100px; background-color: blue; display: inline-block; vertical-align: top; } .main { background-color: yellow; } <div class="main"> <div> <div class="div"></div> <div class="div1"></div> </div> <div class="div2"></div> </div> A: The previous solution which uses float on the red div works well, but here is another possible solution: Apply position: relative; to the blue div (to be able to move it in relation to its default position) and add top: -100px; left: 100px; to move it up next to the red div: .div { width: 100%; height: 100px; background-color: green; } .div1 { width: 100px; height: 100px; background-color: red; } .div2 { width: 100px; height: 100px; background-color: blue; position: relative; top: -100px; left: 100px; } .main { background-color: yellow; } <div class="main"> <div> <div class="div"></div> <div class="div1"></div> </div> <div class="div2"></div> </div> A: This can also be done with the grid CSS. Here I used a named template box and then in the "chatty verbose" CSS I put the positional related for each "block". I added classes to the CSS just for clarity but you could update to your classes. I added some color and things just for clarity and visual references but kept the "position relate" in separate CSS chunks. .main { font-size: 2rem; display: grid; grid-template: "box"; background-color: yellow; } .main *, .main::before { grid-area: box; } .green-block { place-self: start; } .red-block { width: 50%; place-self: end start; } .blue-block { width: 50%; place-self: end end; } .green-block { height: 3rem; background-color: green; } .red-block { height: 3rem; background-color: red; } .blue-block { background-color: blue; } .blue-block, .green-block, .red-block { /* color for clarity and just to super center the text in the blocks */ display: grid; color: cyan; font-family: sans-serif; text-transform: uppercase; place-items: center; } <div class="main"> <div> <div class="div green-block">green</div> <div class="div1 red-block">red</div> </div> <div class="div2 blue-block">blue</div> </div>
unknown
d13637
train
Yes, sounds possible. In the Xojo IDE you could insert a Copy Files build step after the OS X build that copies your php executable into the resources folder of your built app. Then in your App.Open you could copy that executable to wherever you want to from that SpecialFolder, or just reference it as is in your command lines depending on whether there are any restrictions imposed on how your are distributing the app (i.e. App Store). Check out http://docs.xojo.com/index.php/SpecialFolder for some guidance on where to copy any files you need to bundle or how to reference them.
unknown
d13638
train
This query will do the trick, but the number of results might be a LOT more than required. For example, if there are 5 rows satisfying your query, then the results will be 20( = n*(n-1) ) in number. SELECT ot.ID AS ID1, ot.Name AS Name1, ot2.ID AS ID2, ot2.Name AS Name FROM objecttable ot JOIN objecttable ot2 ON ot.ID > ot2.ID AND ot.posX = ot2.posX AND ot.posY = ot2.posY AND ot.posZ = ot2.posZ AND ot.rotX = ot2.rotX AND ot.rotY = ot2.rotY AND ot.rotZ = ot2.rotZ EDIT In reply to lserni's comment: ON ot.ID <> ot2.ID The above condition is there to remove the result like: ID1 | Name | ID2 | Name | 3559 | LODpmedhos5_LAe | 3559 | LODpmedhos5_LAe| A: try this: -- insert into matchtable -- uncomment to insert the data select alias1.Id, alias1.Name, alias2.Id alias2.Name from objecttable as alias1 join objecttable as alias2 on alias1.posx = alias2.posx and alias1.posy = alias2.posy and alias1.posz = alias2.posz and alias1.roty = alias2.roty and alias1.roty = alias2.roty and alias1.rotz = alias2.rotz and alias1.Id > alias2.Id
unknown
d13639
train
when you put it into CURLOPT_POSTFIELDS, you're putting it into the request body, not the request URL. furthermore, when you give CURLOPT_POSTFIELDS an array, curl will encode it in multipart/form-data-format, but you need it urlencoded (which is different from multipart/form-data). remove all the POST code, and use http_build_query to build the url, curl_setopt ( $ch, CURLOPT_URL, "https://URL.com/public/tickets.php?" . http_build_query ( array ( 'PRESET' => array ( 'Tickets' => array ( 'name' => array ( 0 => '' ), 'day' => array ( 0 => '2018-03-04' ) ) ) ) ) ); and protip, you can use parse_str() to decode urls into php arrays, and furthermore, you can use var_export to get valid php code to create that array at runtime, and finally, as shown above, you can use http_build_query to convert that array back to an url, that's what i did here.
unknown
d13640
train
You wont be able to use a protocol like with the X button. You can bind to the '<Map>' and '<Unmap>' events like this. import tkinter as tk def catch_minimize(event): print("window minimzed") def catch_maximize(event): print("window maximized") root = tk.Tk() root.geometry("400x400") root.bind("<Unmap>", catch_minimize) root.bind("<Map>", catch_maximize) root.mainloop()
unknown
d13641
train
You can try using the Xerces-C++ library from Apache, more specifically the XMLChar1_1::isValidNCName method. If you're using Visual Studio, you can also use C++/CLI, which will allow you to mix unmanaged C++ with managed C++, in which you'll be able to use the .NET functions.
unknown
d13642
train
The way you are using with_items to iterate the elb_application_lb module will not work as you have found out. Executing multiple commands will have the effect that the last one will 'win', as it will overwrite the existing elb rule set. What you would need to do is define each rule on a single call to elb_application_lb instead, you can not layer on rules with multiple calls to this module. You might be able to create a dict that defines all your rules instead like this: - name: Add HTTP listener rules elb_application_lb: state: present name: "{{ albinfo.load_balancer_name }}" subnets: - "{{ albinfo.availability_zones[0].subnet_id }}" - "{{ albinfo.availability_zones[1].subnet_id }}" - "{{ albinfo.availability_zones[2].subnet_id }}" security_groups: - "{{ albinfo.security_groups[0] }}" listeners: - Protocol: HTTP Port: 80 DefaultActions: - Type: forward TargetGroupName: default Rules: - "{{ region_rules }}" purge_listeners: no Where region rules var looks like this: region_rules: - Conditions: - Field: host-header Values: manchester.example.com Priority: 1 Actions: - TargetGroupName: manchester Type: forward - Conditions: - Field: host-header Values: surrey.example.com Priority: 2 Actions: - TargetGroupName: surrey Type: forward
unknown
d13643
train
In your background job, make sure that the report is stored in the right folder. You can try something like: report_target = Rails.root.join('public/my_report.xls') report = ... File.open(report_target, 'wb') { |file| file << report.generate }
unknown
d13644
train
You could use useRef for this. const recentlyPressedHardwareBackRef = useRef(false); useEffect(() => { const backHandler = BackHandler.addEventListener( 'hardwareBackPress', () => { // Exit app if user pressed the button within last 2 seconds. if (recentlyPressedHardwareBackRef.current) { return false; } ToastAndroid.show( 'Press back again to exit the app', ToastAndroid.SHORT, ); recentlyPressedHardwareBackRef.current = true; // Toast shows for approx 2 seconds, so this is the valid period for exiting the app. setTimeout(() => { recentlyPressedHardwareBackRef.current = false; }, 2000); // Don't exit yet. return true; }, ); return () => backHandler.remove(); }, [])
unknown
d13645
train
I am not exactly sure what you want as you didn't provide the wanted output. I hope the following is of help to you. The call to rowid_to_column generates a column with 2 rows. That is what it is intended to do. Dropping it solves your problem: df %>% # rowid_to_column() %>% spread(Jaar, Aantal_stemmen) which gives # A tibble: 1 x 5 Gemeente GMcode Partij `2014` `2018` <chr> <chr> <chr> <int> <int> 1 Stichtse Vecht GM1904 VVD 4347 0 Please let me know whether this is what you want.
unknown
d13646
train
You are going to have to extend the HtmlHelper methods and roll your own. Heres the bit of code that is important for your situation where you need a group by: //HtmlHelper being extended if(helper.ViewData.ModelState.IsValid) { foreach(KeyValuePair<string,ModelState> keyPair in helper.ViewData.ModelState) { //add division for group by here using keyPair.Key property (would be named "Person" in your case). foreach(ModelError error in keyPair.Value.Errors) { //now add message using error.ErrorMessage property } } }
unknown
d13647
train
Silverlight is a subset of WPF. Once it was known as WPF/E (WPF everywhere). In fact, the base framework is similar, but not the same. See this for further information: Silverlight "WPF/E" first steps: Getting started with simple analog clock, Introduction - What is WPF/E? A: Silverlight is Microsoft’s latest development platform for building next-generation Web client applications (WPF) is Microsoft’slatest development platform forbuilding next-generation Windows client applications Silverlight is generally considered to be a subset of WPF, and is a XAML WPF is generally considered to be a subset of .NET Framework Silverlight Support Cross OS, cross browser, cross device WPF for Windows client users. in order to run Silverlight applications at client machines, we need to install Silverlight software on the client machine once WPF, on the other hand, does notsupport any plug-in mechanism;instead, we need to install a completed WPF client application Silverlight applications are hosted within a webserver and a web page. WPF applications can be deployed as standalone applications, A: WPF is based off of the desktop CLR which is the full version of the CLR. Silverlight is based on a much smaller and more compact CLR which provides a great experience but does not have the full breadth of CLR features. It also has a much smaller version of the BCL. A: Silverlight (codenamed WPF/E) is a cross-platform, cross-browser, browser plugin which contains WPF-based technology (including XAML)[17] that provides features such as video, vector graphics, and animations to multiple operating systems including Windows Vista, Windows XP, and Mac OS X, with Microsoft sanctioned 3rd party developers working ports for Linux distributions.[18] Specifically, it is currently provided as an add-on for Mozilla Firefox, Internet Explorer 6 and above, and Apple Safari. Silverlight and WPF only share the XAML presentation layer. WIKI A: WPF is essentially the replacement to Winforms in that it is a desktop application platform built on the .Net (3+) platform. Silverlight represents a subset of WPF that is delivered through a browser plug-in, much like Flash/Flex. A: Silverlight is a subset of WPF and therefore has fewer features but is more portable. WPF can be ran in both a browser or as a WinForms style application in Windows while Silverlight can only be ran in a browser. WPF is intended to run on Windows systems while Silverlight runs on Windows or Mac, also Linux via Moonlight. If confused on when to use each, I found a useful blog better explaining this: http://blogs.msdn.com/b/jennifer/archive/2008/05/06/when-should-i-use-wpf-vs-silverlight.aspx A: wpf is window application and Silverlight is web application A: A detailed comparison can be found here: http://wpfslguidance.codeplex.com/
unknown
d13648
train
Do you just want to have a CASE statement in your query? SELECT requisitions.received_date AS "Received Date" ,(CASE WHEN panels.panel_id IN (1,3) THEN 'Panel 1' ELSE panels.PANEL_NAME END) AS "Panel Name" If that is not what you're asking, it would be very helpful to post some sample data and the expected output of your query.
unknown
d13649
train
Your processing is very slow because you're calling autoSizeColumn for every row. From the Javadocs for the autoSizeColumn method: This process can be relatively slow on large sheets, so this should normally only be called once per column, at the end of your processing. Place the calls to autoSizeColumn outside of the loop that creates the rows, in its own for loop only on the columns. This will minimize calls to this method and improve your performance. A: Just for reference... In my case, I had 1 millions plus, and the AutoSizeColumn still slow (even in the end). So, I considerely boost the performance, just storing the column index and content length of every values (in a Dictionary), when it is large than last stored. In the end of all process, just "foreach" the list and set the width of the column with sheet.SetColumnWidth. * *With autosize: never end; *With witdh: 3 seconds. Pseudo-code if(!dictionary.Any(a => a.Key == columnIndex)) { dictionary.Add(columnIndex, columnContent.Length); } else if(dictionary.Any(a => a.Key == columnIndex && a.Value < columnContent.Length)) { dictionary[columnIndex] = columnContent.Length; } And in the end foreach (KeyValuePair<int, int> column in dictionary) { sheet.SetColumnWidth(column.Key, column.Value*300); } A: try this... for (int j = 0; j < this.myDataValues.size(); j++) { row = sheet.createRow(rownum++); temp = this.finalRowValues.get(j); for (int i = 0; i < 4; i++) { cell = row.createCell(i); dataVal = temp[i]; if (NumberUtils.isNumber(dataVal)) { double d = Double.valueOf(dataVal); cell.setCellValue(d); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellStyle(styles.get("currency")); } else if (isValidDate(dataVal)) { cell.setCellValue(dataVal); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellStyle(styles.get("date")); } else { cell.setCellValue(temp[i]); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellStyle(styles.get("data")); } } } for (int i = 0; i < 4; i++) { sheet.autoSizeColumn(i); }
unknown
d13650
train
you use POST method and in php code you should use $_POST try this foreach($_POST['stop_data'] as $stop) { // do something } this way is using GET method http://www.myURL/myPHPScript.php?stop_data[]=768&stop_data[]=1283
unknown
d13651
train
In my case, it was simpler to just check Logcat, rather than listen to that recommendation A: For others encountering this issue, as @antek pointed out the files might not be accessible on a non-rooted device. You might try using an emulator running a non-Google Play API where you can obtain a root shell. adb root adb shell ls /data/data/androidx.test.orchestrator/files Alternatively, you could try running the tests using the debugger. A: I could not find the text file, but I was able to get logcat and view the fatal that caused the orchestrator to crash first I clear the logcat adb logcat -c then I run the test, then I grab the logcat adb logcat > ~/Desktop/logcat then I open logcat file and search for string FATAL A: If you are working with an emulator, in A.S open Device File Explorer and go to: /data/user_de/0/android.support.test.orchestrator/files/, then you can look for a particular file there EDIT: June 25 - 2019 >> If you have updated to AndroidX dependencies, then the .txt file is located in /data/user_de/0/androidx.test.orchestrator/files/ A: * *I just did wipe data in Android studio for my emulator using Device manager. *Restarted the emulator and run the test works for me
unknown
d13652
train
Finally i keep the client part based on 6.15 Odata version and Simple.OData.Client 4.20, Server part will be upgraded to odata 7.0 It works well provided you use the timestamp type on client in remplacement of system.DateTime or Microsoft.OData.Edm.Library.Date Types
unknown
d13653
train
Take a look at the reference of string::substr. It clearly states that len takes the number of characters to include in the substring. In your code you are passing the index of ' ' which is simply wrong because it does not correspond to len. Instead of using s.substr(start,i), simply use s.substr(start,i - start + 1). That should fix the problem.
unknown
d13654
train
I found out where to add a pre-receive or post-receive hook on a repository basis by adding a file to the Bitbucket server. In the Atlassian folder, it is in ApplicationData\Bitbucket\shared\data\repositories\[repository#]\hooks\. Bitbucket keeps track of repos internally using numbers and not names so in the above replace [repository#] with the repo number. That can be found out this way. Put the pre-receive hook in the pre-receive.d folder. Put the post-receive hook in the post-receive.d folder. The names of the hooks/files should begin with a number. That determines what order the hooks are 'activated'. Begin the numbers with at least 21 because the default hook in the folder begins with 20. You want your hook to be activated after the one shipped with Bitbucket server. So a file name for a pre-receive hook could be 21_pre_receive. Don't change the default hooks that are in the folder because they are needed to help Bitbucket work. More information can be found here.
unknown
d13655
train
The snapshot too old error is more or less directly related to the running time of your queries (often a cursor of a FOR loop). So the best solution is to optimize your queries so they run faster. As a short term solution you can try to increase the size of the UNDO log. Update: The UNDO log stores the previous version of a record before it's updated. It is used to rollback transactions and to retrieve older version of a record for consistent data snapshots for long running queries. You'll probably need to dive into Oracle DB administration if you want to solve it via increasing the UNDO log. Basically you do (as SYSDBA): ALTER SYSTEM SET UNDO_RETENTION = 21600; 21600 is 6 hours in seconds. However, Oracle will only keep 6 hours of old data if the UNDO log files are big enough, which depends on the size of the rollback segments and the amount of updates executed on the database. So in addition to changing the undo retention time, you should also make sure that few concurrent updates are executed while your job is running. In particular, updates of the data your job is reading should be minimized. If everything fails, increase the UNDO logs. A: The best explanation of the ORA-01555 snapshot too old error that I've read, is found in this AskTom thread Regards.
unknown
d13656
train
Try to add this in function.php function wpse_registration_redirect() { return home_url().'/my-page' ; } add_filter( 'registration_redirect', 'wpse_registration_redirect' ); or function custom_registration_redirect() { return home_url().'/my-page' ; } add_action('woocommerce_registration_redirect', 'custom_registration_redirect', 2); or After login function admin_default_page() { return home_url().'/my-page' ; } add_filter('login_redirect', 'admin_default_page'); or After WooCommerce login function iconic_login_redirect( $redirect_to) { $redirect_to = 'http://yoursiteshop'; return $redirect_to ; } add_filter( 'woocommerce_login_redirect', 'iconic_login_redirect',1100, 2 );
unknown
d13657
train
The simplest thing that comes to my mind is: * *write a grails controller, instantiate the servlet (once, in the contstructor or in @PostConstruct) and call init()` *map the controller method (via UrlMappings.groovy) to the url that your servlet would be mapped *call servlet.service(request, response). It's a bit of a hack though. Another way is to get ahold of a spring (grails) bean in a filter applied to the servlet, with WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()) and invoke the custom logic there.
unknown
d13658
train
You can set $.ajax 's traditional attribute and set it to true, to send json data as url encoded form. Make sure to set type:'POST'. With this method you can even send arrays and you do not have to use JSON.stringyfy or any changes on server side (e.g. creating custom attributes to sniff header ) I have tried this on ASP.NET MVC3 and jquery 1.7 setup and it's working following is the code snippet. var data = { items: [1, 2, 3], someflag: true}; data.__RequestVerificationToken = $(':input[name="__RequestVerificationToken"]').val(); $.ajax({ url: 'Test/FakeAction' type: 'POST', data: data dataType: 'json', traditional: true, success: function (data, status, jqxhr) { // some code after succes }, error: function () { // alert the error } }); This will match with MVC action with following signature [HttpPost] [Authorize] [ValidateAntiForgeryToken] public ActionResult FakeAction(int[] items, bool someflag) { } A: You don't need the ValidationHttpRequestWrapper solution since MVC 4. According to this link. * *Put the token in the headers. *Create a filter. *Put the attribute on your method. Here is my solution: var token = $('input[name="__RequestVerificationToken"]').val(); var headers = {}; headers['__RequestVerificationToken'] = token; $.ajax({ type: 'POST', url: '/MyTestMethod', contentType: 'application/json; charset=utf-8', headers: headers, data: JSON.stringify({ Test: 'test' }), dataType: "json", success: function () {}, error: function (xhr) {} }); [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } var httpContext = filterContext.HttpContext; var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName]; AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]); } } [HttpPost] [AllowAnonymous] [ValidateJsonAntiForgeryToken] public async Task<JsonResult> MyTestMethod(string Test) { return Json(true); } A: What is wrong is that the controller action that is supposed to handle this request and which is marked with the [ValidateAntiForgeryToken] expects a parameter called __RequestVerificationToken to be POSTed along with the request. There's no such parameter POSTed as you are using JSON.stringify(data) which converts your form to its JSON representation and so the exception is thrown. So I can see two possible solutions here: Number 1: Use x-www-form-urlencoded instead of JSON for sending your request parameters: data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val(); data["fiscalyear"] = fiscalyear; // ... other data if necessary $.ajax({ url: url, type: 'POST', context: document.body, data: data, success: function() { refresh(); } }); Number 2: Separate the request into two parameters: data["fiscalyear"] = fiscalyear; // ... other data if necessary var token = $('[name=__RequestVerificationToken]').val(); $.ajax({ url: url, type: 'POST', context: document.body, data: { __RequestVerificationToken: token, jsonRequest: JSON.stringify(data) }, success: function() { refresh(); } }); So in all cases you need to POST the __RequestVerificationToken value. A: You can't validate an content of type contentType: 'application/json; charset=utf-8' because your date will be uploaded not in the Form property of the request, but in the InputStream property, and you will never have this Request.Form["__RequestVerificationToken"]. This will be always empty and validation will fail. A: You won't ever have to validate an AntiForgeryToken when you receive posted JSON. The reason is that AntiForgeryToken has been created to prevent CSRF. Since you can't post AJAX data to another host and HTML forms can't submit JSON as the request body, you don't have to protect your app against posted JSON. A: I have resolved it globally with RequestHeader. $.ajaxPrefilter(function (options, originalOptions, jqXhr) { if (options.type.toUpperCase() === "POST") { // We need to add the verificationToken to all POSTs if (requestVerificationTokenVariable.length > 0) jqXhr.setRequestHeader("__RequestVerificationToken", requestVerificationTokenVariable); } }); where the requestVerificationTokenVariable is an variable string that contains the token value. Then all ajax call send the token to the server, but the default ValidateAntiForgeryTokenAttribute get the Request.Form value. I have writed and added this globalFilter that copy token from header to request.form, than i can use the default ValidateAntiForgeryTokenAttribute: public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new GlobalAntiForgeryTokenAttribute(false)); } public class GlobalAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter { private readonly bool autoValidateAllPost; public GlobalAntiForgeryTokenAttribute(bool autoValidateAllPost) { this.autoValidateAllPost = autoValidateAllPost; } private const string RequestVerificationTokenKey = "__RequestVerificationToken"; public void OnAuthorization(AuthorizationContext filterContext) { var req = filterContext.HttpContext.Request; if (req.HttpMethod.ToUpperInvariant() == "POST") { //gestione per ValidateAntiForgeryToken che gestisce solo il recupero da Request.Form (non disponibile per le chiamate ajax json) if (req.Form[RequestVerificationTokenKey] == null && req.IsAjaxRequest()) { var token = req.Headers[RequestVerificationTokenKey]; if (!string.IsNullOrEmpty(token)) { req.Form.SetReadOnly(false); req.Form[RequestVerificationTokenKey] = token; req.Form.SetReadOnly(true); } } if (autoValidateAllPost) AntiForgery.Validate(); } } } public static class NameValueCollectionExtensions { private static readonly PropertyInfo NameObjectCollectionBaseIsReadOnly = typeof(NameObjectCollectionBase).GetProperty("IsReadOnly", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance); public static void SetReadOnly(this NameValueCollection source, bool readOnly) { NameObjectCollectionBaseIsReadOnly.SetValue(source, readOnly); } } This work for me :) A: I hold the token in my JSON object and I ended up modifying the ValidateAntiForgeryToken class to check the InputStream of the Request object when the post is json. I've written a blog post about it, hopefully you might find it useful. A: Check out Dixin's Blog for a great post on doing exactly that. Also, why not use $.post instead of $.ajax? Along with the jQuery plugin on that page, you can then do something as simple as: data = $.appendAntiForgeryToken(data,null); $.post(url, data, function() { refresh(); }, "json"); A: AJAX based model posting with AntiForgerytoken can be made bit easier with Newtonsoft.JSON library Below approach worked for me: Keep your AJAX post like this: $.ajax({ dataType: 'JSON', url: url, type: 'POST', context: document.body, data: { '__RequestVerificationToken': token, 'model_json': JSON.stringify(data) };, success: function() { refresh(); } }); Then in your MVC action: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(FormCollection data) { var model = JsonConvert.DeserializeObject < Order > (data["model_json"]); return Json(1); } Hope this helps :) A: I was just implementing this actual problem in my current project. I did it for all Ajax POSTs that needed an authenticated user. First off, I decided to hook my jQuery Ajax calls so I do not to repeat myself too often. This JavaScript snippet ensures all ajax (post) calls will add my request validation token to the request. Note: the name __RequestVerificationToken is used by the .NET framework so I can use the standard Anti-CSRF features as shown below. $(document).ready(function () { securityToken = $('[name=__RequestVerificationToken]').val(); $('body').bind('ajaxSend', function (elm, xhr, s) { if (s.type == 'POST' && typeof securityToken != 'undefined') { if (s.data.length > 0) { s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken); } else { s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken); } } }); }); In your Views where you need the token to be available to the above JavaScript code, just use the common HTML-Helper. You can basically add this code wherever you want. I placed it within a if(Request.IsAuthenticated) statement: @Html.AntiForgeryToken() // You can provide a string as salt when needed which needs to match the one on the controller In your controller simply use the standard ASP.NET MVC anti-CSRF mechanism. I did it like this (though I actually used a salt). [HttpPost] [Authorize] [ValidateAntiForgeryToken] public JsonResult SomeMethod(string param) { // Do something return Json(true); } With Firebug or a similar tool you can easily see how your POST requests now have a __RequestVerificationToken parameter appended. A: I had to be a little shady to validate anti-forgery tokens when posting JSON, but it worked. //If it's not a GET, and the data they're sending is a string (since we already had a separate solution in place for form-encoded data), then add the verification token to the URL, if it's not already there. $.ajaxSetup({ beforeSend: function (xhr, options) { if (options.type && options.type.toLowerCase() !== 'get' && typeof (options.data) === 'string' && options.url.indexOf("?__RequestVerificationToken=") < 0 && options.url.indexOf("&__RequestVerificationToken=") < 0) { if (options.url.indexOf('?') < 0) { options.url += '?'; } else { options.url += '&'; } options.url += "__RequestVerificationToken=" + encodeURIComponent($('input[name=__RequestVerificationToken]').val()); } } }); But, as a few people already mentioned, the validation only checks the form - not JSON, and not the query string. So, we overrode the attribute's behavior. Re-implementing all of the validation would have been terrible (and probably not secure), so I just overrode the Form property to, if the token were passed in the QueryString, have the built-in validation THINK it was in the Form. That's a little tricky because the form is read-only, but doable. if (IsAuth(HttpContext.Current) && !IsGet(HttpContext.Current)) { //if the token is in the params but not the form, we sneak in our own HttpContext/HttpRequest if (HttpContext.Current.Request.Params != null && HttpContext.Current.Request.Form != null && HttpContext.Current.Request.Params["__RequestVerificationToken"] != null && HttpContext.Current.Request.Form["__RequestVerificationToken"] == null) { AntiForgery.Validate(new ValidationHttpContextWrapper(HttpContext.Current), null); } else { AntiForgery.Validate(new HttpContextWrapper(HttpContext.Current), null); } } //don't validate un-authenticated requests; anyone could do it, anyway private static bool IsAuth(HttpContext context) { return context.User != null && context.User.Identity != null && !string.IsNullOrEmpty(context.User.Identity.Name); } //only validate posts because that's what CSRF is for private static bool IsGet(HttpContext context) { return context.Request.HttpMethod.ToUpper() == "GET"; } ... internal class ValidationHttpContextWrapper : HttpContextBase { private HttpContext _context; private ValidationHttpRequestWrapper _request; public ValidationHttpContextWrapper(HttpContext context) : base() { _context = context; _request = new ValidationHttpRequestWrapper(context.Request); } public override HttpRequestBase Request { get { return _request; } } public override IPrincipal User { get { return _context.User; } set { _context.User = value; } } } internal class ValidationHttpRequestWrapper : HttpRequestBase { private HttpRequest _request; private System.Collections.Specialized.NameValueCollection _form; public ValidationHttpRequestWrapper(HttpRequest request) : base() { _request = request; _form = new System.Collections.Specialized.NameValueCollection(request.Form); _form.Add("__RequestVerificationToken", request.Params["__RequestVerificationToken"]); } public override System.Collections.Specialized.NameValueCollection Form { get { return _form; } } public override string ApplicationPath { get { return _request.ApplicationPath; } } public override HttpCookieCollection Cookies { get { return _request.Cookies; } } } There's some other stuff that's different about our solution (specifically, we're using an HttpModule so we don't have to add the attribute to every single POST) that I left out in favor of brevity. I can add it if necessary. A: Unfortunately for me, the other answers rely on some request formatting handled by jquery, and none of them worked when setting the payload directly. (To be fair, putting it in the header would have worked, but I did not want to go that route.) To accomplish this in the beforeSend function, the following works. $.params() transforms the object into the standard form / url-encoded format. I had tried all sorts of variations of stringifying json with the token and none of them worked. $.ajax({ ...other params..., beforeSend: function(jqXHR, settings){ var token = ''; //get token data = { '__RequestVerificationToken' : token, 'otherData': 'value' }; settings.data = $.param(data); } }); ``` A: You should place AntiForgeryToken in a form tag: @using (Html.BeginForm(actionName:"", controllerName:"",routeValues:null, method: FormMethod.Get, htmlAttributes: new { @class="form-validator" })) { @Html.AntiForgeryToken(); } Then in javascript modify the following code to be var DataToSend = []; DataToSend.push(JSON.stringify(data), $('form.form-validator').serialize()); $.ajax({ dataType: 'JSON', contentType: 'application/json; charset=utf-8', url: url, type: 'POST', context: document.body, data: DataToSend, success: function() { refresh(); } }); Then you should be able to validate the request using ActionResult annotations [ValidateAntiForgeryToken] [HttpPost] I hope this helps.
unknown
d13659
train
Not sure about JetS3t API but, the AWS SDK for Java does provide a simple copyObject method A: so i ended up figuring out how to do clone the asset in s3 using JetS3t. it was simpler than i expected. i'll post it up incase anyone ever googles this question. all do is first get the s3 object you want to clone. after you have it, call setKey(filename) on the s3 object. "filename" is the path for where you want the object to be followed by the file name itself i.e. yours3bucketname/products/assets/picture.png after your done with that, just call putObject(bucket_name, s3object), passing the s3object that you called setKey on as the second argument. good luck! happy programming!
unknown
d13660
train
The "fetchval" method in your parent is not referencing your child but the "value" property in your data function. "this" refers to your parent component. Basically, you are trying to call a "getVal" function on a string in your parent. If you want to call a function on your child component, you need a reference to the child and call that function on that reference. You need to add a ref to your child component. If you're not familiar with refs, I suggest starting here: Template Refs
unknown
d13661
train
I see a missing bracket in your output.
unknown
d13662
train
I figured it out. You call the below method to check the default options and the boolean below to true to set the prevent_open. $('#jstree').on('ready.jstree', function (e, data) { data.instance.select_node(['info'], false, true); }); //$('#jstree').jstree().select_node('info', false,true)
unknown
d13663
train
You can get an object describing the current tab the user is looking at using browser.tabs.getCurrent(). This object has a property url, which you can then use to make an XMLHttpRequest. browser.tabs.getCurrent().then(currentTab => { let xhr = new XMLHttpRequest(); xhr.open("GET", currentTab.url); // ... }); Edit: As pointed out by Makyen, tabs.currentTab is not actually what you want. Instead tabs.query with active: true should be used. Something like that should work: browser.tabs.query({active: true, currentWindow: true}).then(tabs => { let currentTab = tabs[0]; let xhr = new XMLHttpRequest(); xhr.open("GET", currentTab.url); // ... }) In order to make cross origin requests, you will need to get permission in your manifest.json file: { ... "permissions": [ "tabs", "<all_urls>" ], ... } <all_urls>for instance will allow you to make http requests to any url. You can read more here.
unknown
d13664
train
9 patch seems the simplest way to achieve what you want. And I believe, it would generate less computations to display your image. 9 patch is not so complicated, even easy. Did you try the android 9 patch tool?
unknown
d13665
train
It is not supported by CAPL. You just have to add the bits and use the obtained number in Hex or Dec format. Alternatively you can create a function to display it in your report as a binary if you really want to
unknown
d13666
train
To get an exact dD-kernel, use a exact number type with CGAL::Cartesian_d, for example: #include <CGAL/Cartesian_d.h> #include <CGAL/Gmpq.h> typedef CGAL::Cartesian_d<CGAL::Gmpq> Exact_kernel_d;
unknown
d13667
train
Yes, this bookkeeping with i is usually a sign there should be something better. I came up with: ar =[ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york" }, { name: "bar1", location: "new york" }, { name: "bar2", location: "new york" }, { name: "bar3", location: "new york" }, { name: "baz1", location: "chicago" }, { name: "baz2", location: "chicago" }, { name: "baz3", location: "chicago" }, { name: "quux1", location: "chicago" }, { name: "quux2", location: "chicago" }, { name: "quux3", location: "chicago" } ] # next line handles unsorted arrays, irrelevant with this data ar = ar.sort_by{|h| h[:location]} num_groups = 3 groups = Array.new(num_groups){[]} wheel = groups.cycle ar.each{|h| wheel.next << h} # done. p groups # => [[{:name=>"baz1", :location=>"chicago"}, {:name=>"quux1", :location=>"chicago"}, {:name=>"foo1", :location=>"new york"}, ...] because I like the cycle method. A: a.each_slice(group_size).to_a.transpose Will work given that your data is accurately portrayed in the example. If it is not please supply accurate data so that we can answer the question more appropriately. e.g. a= [ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york" }, { name: "bar1", location: "new york" }, { name: "bar2", location: "new york" }, { name: "bar3", location: "new york" }, { name: "baz1", location: "chicago" }, { name: "baz2", location: "chicago" }, { name: "baz3", location: "chicago" }, { name: "quux1", location: "chicago" }, { name: "quux2", location: "chicago" }, { name: "quux3", location: "chicago" } ] group_size = 3 a.each_slice(group_size).to_a.transpose #=> [ [ {:name=>"foo1", :location=>"new york"}, {:name=>"bar1", :location=>"new york"}, {:name=>"baz1", :location=>"chicago"}, {:name=>"quux1", :location=>"chicago"} ], [ {:name=>"foo2", :location=>"new york"}, {:name=>"bar2", :location=>"new york"}, {:name=>"baz2", :location=>"chicago"}, {:name=>"quux2", :location=>"chicago"} ], [ {:name=>"foo3", :location=>"new york"}, {:name=>"bar3", :location=>"new york"}, {:name=>"baz3", :location=>"chicago"}, {:name=>"quux3", :location=>"chicago"} ] ] each_slice 3 will turn this into 4 equal groups (numbered 1,2,3) in your example. transpose will then turn these 4 groups into 3 groups of 4. If the locations are not necessarily in order you can add sorting to the front of the method chain a.sort_by { |h| h[:location] }.each_slice(group_size).to_a.transpose Update It was pointed out that an uneven number of arguments for transpose will raise. My first though was to go with @CarySwoveland's approach but since he already posted it I came up with something a little different class Array def indifferent_transpose arr = self.map(&:dup) max = arr.map(&:size).max arr.each {|a| a.push(*([nil] * (max - a.size)))} arr.transpose.map(&:compact) end end then you can still use the same methodology a << {name: "foobar1", location: "taiwan" } a.each_slice(group_size).to_a.indifferent_transpose #=> [[{:name=>"foo1", :location=>"new york"}, {:name=>"bar1", :location=>"new york"}, {:name=>"baz1", :location=>"chicago"}, {:name=>"quux1", :location=>"chicago"}, #note the extras values will be placed in the group arrays in order {:name=>"foobar4", :location=>"taiwan"}], [{:name=>"foo2", :location=>"new york"}, {:name=>"bar2", :location=>"new york"}, {:name=>"baz2", :location=>"chicago"}, {:name=>"quux2", :location=>"chicago"}], [{:name=>"foo3", :location=>"new york"}, {:name=>"bar3", :location=>"new york"}, {:name=>"baz3", :location=>"chicago"}, {:name=>"quux3", :location=>"chicago"}]] A: Here's another way to do it. Code def group_em(a, ngroups) a.each_with_index.with_object(Array.new(ngroups) {[]}) {|(e,i),arr| arr[i%ngroups] << e} end Example a = [ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york" }, { name: "bar1", location: "new york" }, { name: "bar2", location: "new york" }, { name: "bar3", location: "new york" }, { name: "baz1", location: "chicago" }, { name: "baz2", location: "chicago" }, { name: "baz3", location: "chicago" }, { name: "quux1", location: "chicago" }, { name: "quux2", location: "chicago" } ] Note that I've omitted the last element of a from the question in order for a to have an odd number of elements. group_em(a,3) #=> [[{:name=>"foo1", :location=>"new york"}, # {:name=>"bar1", :location=>"new york"}, # {:name=>"baz1", :location=>"chicago" }, # {:name=>"quux1", :location=>"chicago" }], # [{:name=>"foo2", :location=>"new york"}, # {:name=>"bar2", :location=>"new york"}, # {:name=>"baz2", :location=>"chicago" }, # {:name=>"quux2", :location=>"chicago" }], # [{:name=>"foo3", :location=>"new york"}, # {:name=>"bar3", :location=>"new york"}, # {:name=>"baz3", :location=>"chicago" }]]
unknown
d13668
train
For primitive values you can just use == aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR)==year A: Just use: aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH) == month A: If all of the XYZ.getTransDate() returns Calendar, then XYZ.getTransDate().get(SOMETHING) returns primitive int. Primitives do not have comapreTo method, just use == so instead of XYZ.getTransDate().get(MONTH).compareTo(month) == 0 use XYZ.getTransDate().get(MONTH) == month A: This should work: Calendar transDate = aBank.getAccounts().get(i).getTransaction().get(j).getTransDate(); if (transDate.get(Calendar.YEAR) == year && transDate.get(Calendar.MONTH) == month && transDate.get(Calendar.DAY_OF_MONTH) == day) { // do something } Even better if you use something like Apache Commons Lang: if (DateUtils.isSameDay(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate(), Calendar.getInstance().set(year, month, day)) { ... }
unknown
d13669
train
You can use $objectToArray operator to get rid of the dynamic keys. db.getCollection('Test').aggregate([ { $project: {"keys": { "$objectToArray": "$$ROOT.am_data" }} }, { $unwind : "$keys"}, { $project: {"am_name":"$keys.v.am_name", "no_of_mnths":"$keys.v.no_of_mnths" } } ]) Result: [{ "_id" : ObjectId("5de775b53ec85e73da2b6d8a"), "am_name" : "Unmanaged ", "no_of_mnths" : 12 }, { "_id" : ObjectId("5de775b53ec85e73da2b6d8a"), "am_name" : "Daniel Schiralli", "no_of_mnths" : 12 }] A: the key should not change. base on your description you need to adjust the schema, instead of am_data Object it should be an array instead. { "_id": { "$oid": "5de775b53ec85e73da2b6d8a" }, "vpg_id": 2, "year": 2019, "am_data": [ { "id": "822", "am_name": "Unmanaged ", "no_of_mnths": 12, "total_invoice": 14476.15, "total_bv_invoice": 1840, "opp_won_onetime_amt": 0, "one_time_quota": 0, "recurring_quota": 200, "opp_won_rec_amt": 0, "avg_total_invoice": 1206.3458333333333, "avg_total_bv_invoice": 153.33333333333334, "avg_opp_won_onetime_amt": 0, "avg_one_time_quota": 0, "avg_opp_won_rec_amt": 0, "avg_recurring_quota": 16.666666666666668 }, { "id": "2155", "am_name": "Daniel Schiralli", "no_of_mnths": 12, "total_invoice": 396814.66000000003, "total_bv_invoice": 577693.3200000001, "opp_won_onetime_amt": 4792.5, "one_time_quota": 14400, "recurring_quota": 4800, "opp_won_rec_amt": 345, "avg_total_invoice": 33067.888333333336, "avg_total_bv_invoice": 48141.11000000001, "avg_opp_won_onetime_amt": 399.375, "avg_one_time_quota": 1200, "avg_opp_won_rec_amt": 28.75, "avg_recurring_quota": 400 } ] }
unknown
d13670
train
As far as I know, the shortest way is: var myStruct = TheStruct() var address = withUnsafeMutablePointer(&myStruct) {UnsafeMutablePointer<Void>($0)} But, why you need this? If you want pass it as a parameter, you can (and should): func foo(arg:UnsafeMutablePointer<Void>) { //... } var myStruct = TheStruct() foo(&myStruct) A: Most of the method prototypes have been changed as Swift evolved over the years. Here is the syntax for Swift 5: var struct = TheStruct() var unsafeMutablePtrToStruct = withUnsafeMutablePointer(to: &struct) { $0.withMemoryRebound(to: TheStruct.self, capacity: 1) { (unsafePointer: UnsafeMutablePointer<TheStruct>) in unsafePointer } }
unknown
d13671
train
The behavior you observed : The real confusing part is that it doesn't reinitialize it to 0 every time the recursive function calls itself. It's like this whole line of code static int i = 0; is skipped? is exactly what you are asking for with static. A local static variable is initalized the first time its definition (i.e, the line static int i = 0;) is reached. In your case it means it will be set to zero only on the first call ever to this method during the whole runtime of your program. There is no notion of multiple recursive calls to the same function, so it will make no difference if the method is invoked by itself (the multiple recursive call you are referring to) or if you are starting a whole new stack of recursion somewhere else in your client code. Possible solution To go back on your description, it will only work with i being static (for n!=1) because, if your removed static keyword, then i would be initialized to zero each time the method is entered (a different local instance of i for each invocation of the method). Thus in your condition if(++i == n) ++i would always evaluate to 1, independently of the recursion depth. If you want the static i to be reinitialized each time you call your method in your client code (i.e. to start a new stack of recursion), you could write it like : void printNthFromLast(Node* head, int n, bool reinit=true) { static int i = 0; if(reinit) { i=0; } if(head == nullptr) return; printNthFromLast(head->next, n, false); if(++i == n) cout << head->data; } Thread safe with tail call optimization A cleaner solution would be to have i as a mutable parameter to the function, so your function would be thread-safe. And with a better ordering of the operation, you do not need to save the previous invocation frame, thus enjoying tail call optimization offered by most of recent compilers. EDIT : As pointed by Matthieu, my original implementation printed the Nth element instead of the Nth from last element. Fixing while enabling TCO is less elegant, but can be done as follows : /// n==1 means printing the last element here static void printNthFromLastImpl(const Node* currentNode, const Node* offsetNode, const int n, int currentDepth) { // n == 0 will never print in the original example by op, so forbid it assert(n); if(++currentDepth > n) { offsetNode = offsetNode->next; } if(currentNode->next) { currentNode = currentNode->next; } else { if(currentDepth >= n) { cout << offsetNode->data; } return; } return printNthFromLastImpl(currentNode, offsetNode, n, currentDepth); } /// \brief : code to call from client static void printNthFromLast(const Node* head, const int n) { if (head) { printNthFromLastImpl(head, head, n, 0); } } A: When you declare a static local variable the compiler only initializes it once (the first time control flow passes over the variable declaration); thereafter the variable keeps its value across all calls to the function that declares it for the lifetime of the program, much like a global variable. How is this achieved? When the compiler sees something like this: void foo() { static int i = 0; cout << i++; } It produces code equivalent to this: bool foo_i_initialized = false; // global int foo_i; // global void foo() { if (!foo_i_initialized) { foo_i = 0; foo_i_initialized = true; } cout << foo_i++; } The above example is a bit contrived because here foo_i is a primitive initialized with a constant and as such it could have been statically initialized in global scope (removing the need for the boolean flag), but this mechanism also handles more complicated scenarios. A: The initialization is only executed at the first call of the function. Subsequent calls will use the already inititalized value. A: So, as said, static int i = 0; is local to the function. It is initialized the first time flow-control passes through its definition, and skipped ever after. Two special cases are made: * *in case of dynamic initialization (by a function) which throws an exception, initialization will be reattempted the next time flow-control passes through the definition. *in case of calls from multiple threads, the first thread does the initialization and all others are blocked until it is done (or fails with an exception) Now, regarding your code: don't. A local static is a global variable in disguise, your code is equivalent to: int i = 0; void printNthFromLast(Node* head, int n) { if(head == nullptr) return; printNthFromLast(head->next, n); if(++i == n) cout << head->data; } Note: not only is it more difficult to debug, it is also not thread-safe. Instead, you should provide a local variable for this usage: static void printNthFromLastImpl(Node const* const head, int& i, int const n) { if(head == nullptr) return; printNthFromLastImpl(head->next, i, n); if(++i == n) cout << head->data; } // Each call to this function instantiates a new `i` object. void printNthFromLast(Node const* const head, int const n) { int i = 0; printNthFromLastImpl(head, i, n); } EDIT: As remarked by Ad N, since the list is not modified it should be passed by const pointer. Following Ad N latest edit (TCO version), I realized an iterative implementation should work (note, there might be some off by one errors). void printNthFromLast(Node const* const head, int const n) { if (n == 0) { return; } // Set "probe" to point to the nth item. Node const* probe = head; for (int i = 0; i != n; ++i) { if (probe == nullptr) { return; } probe = probe->next; } Node const* current = head; // Move current and probe at the same rhythm; // when probe reaches the end, current is the nth from the end. while (probe) { current = current->next; probe = probe->next; } std::cout << current->data; } A: You've described it very well yourself. A static variable is initialised only once, the first time through the function, and the variable is then shared across calls to the function. A: A variable declared static is initialized only once. So even, when the function is called again, the value of the variable i here in this context is retained from the previous call. The next time the program reaches the static initialize statement to an initialized variable, it skips the statement. Since, static variables are stored in the BSS segment and not on the stack, the previous state of the variable in previous function calls, is not altered. A: Not only shared among multiple recursive calls, shared among all calls. There is actually only a single instance of the variable i, and it's shared among all calls of the function.
unknown
d13672
train
By the amount of information I can collect after seeing that screenshot I can say it is either 1 of the following 2 problems: 1. The parent div of the div with class 'dropdown-menu' do not have "position: relative" property applied to it. 2. Two divs need to be sibling to each other to hide or show one of them behind the other using z-index (they can't have parent child relationship).
unknown
d13673
train
search_index.py: tags = MultiValueField(faceted=True) schema.xml: <field name="tags" type="text" indexed="true" stored="true" multiValued="true" /> <field name="tags_exact" type="string" indexed="true" stored="true" multiValued="true" />
unknown
d13674
train
1st I created a view holding all sales items grouped by product id in the main database: CREATE OR REPLACE VIEW unit_sold_all AS SELECT p.`product-id` AS product_id, ( (SELECT IFNULL(SUM(s0.qty), 0) FROM db_1.sales_item_details s0 WHERE s0.product_id = p.`product-id`) + (SELECT IFNULL(SUM(s1.qty), 0) FROM db_2.sales_item_details s1 WHERE s1.product_id = p.`product-id`) + (SELECT IFNULL(SUM(s2.qty), 0) FROM db_3.sales_item_details s2 WHERE s2.product_id = p.`product-id`) + (SELECT IFNULL(SUM(s3.qty), 0) FROM db_4.sales_item_details s3 WHERE s3.product_id = p.`product-id`) + (SELECT IFNULL(SUM(s4.qty), 0) FROM db_5.sales_item_details s4 WHERE s4.product_id = p.`product-id`) ) as total_unit_sales FROM products p Then in another sql, I selected the sum of the sales. PS: I answered this question myself because this might need by another person in the future.
unknown
d13675
train
You should take a look at llvm-c-kaleidoscope where you can learn by example how to use the llvm-c interface.
unknown
d13676
train
If you write inter1 obj = ... then you will not be able to write obj.method2) unless you cast to inter2 or to a type that implements inter2. For example inter1 obj = quest(); if (obj instanceof class1) ((class1) obj).method2(); or inter1 obj = quest(); if (obj instanceof inter2) ((inter2) obj).method2(); As an aside, when you write in Java you normally give classes and interfaces names that begin the a capital letter, otherwise you confuse people reading your code. A: Using genecics it is possible to declare generic reference implementing more than one type. You can invoke method from each interface it implements without casting. Example below: public class TestTwoTypes{ public static void main(String[] args) { testTwoTypes(); } static <T extends Type1 & Type2> void testTwoTypes(){ T twoTypes = createTwoTypesImplementation(); twoTypes.method1(); twoTypes.method2(); } static <T extends Type1 & Type2> T createTwoTypesImplementation(){ return (T) new Type1AndType2Implementation(); } } interface Type1{ void method1(); } interface Type2{ void method2(); } class Type1AndType2Implementation implements Type1, Type2{ @Override public void method1() { System.out.println("method1"); } @Override public void method2() { System.out.println("method2"); } } The output is: method1 method2 A: If you want to do this in spring, the general idea would be: // Test.java public class Test { private final Interface1 i1; private final Interface2 i2; public Test(Interface1 i1, Interface2 i2) { this.i1 = i1; this.i2 = i2; } } <!-- application-context.xml --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="implementer" class="org.mypackage.Implementer" /> <bean id="test" class="org.mypackage.Test"> <constructor-arg ref="implementer"/> <constructor-arg ref="implementer"/> </bean> </beans> // Main.java public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml"); Test t = (Test) context.getBean("test"); }
unknown
d13677
train
Try to follow all steps on their website including mkdir ./dags ./logs ./plugins echo -e "AIRFLOW_UID=$(id -u)\nAIRFLOW_GID=0" > .env. I don't know but it works then, but still unhealthy, airflow.apache.org/docs/apache-airflow/stable/start/docker.html
unknown
d13678
train
Thanks everyone and especially @AlexK who make search about library. The problem was not the missing of the jasperreports-functions libs but the missing of the joda-time library which is used by jasperreports-functions inside DAYS(), YEARS() and MONTHS() methods. Adding https://github.com/JodaOrg/joda-time/releases/download/v2.9.9/joda-time-2.9.9.jar solved my problem.
unknown
d13679
train
Answer is almost what I thought. In /etc/postfix/transport you need to put the following to deliver to anything other than port 25 domain.com smtp:domain.com:143
unknown
d13680
train
Try this: (Untested) <a href="#" class="dairy">Dairy</a> <a href="#" class="meat">Meat</a> <a href="#" class="vegetable">Vegetable</a> $('a').click(function(e){ var myId = $(this).attr('class'); $('#primary-div div.child:not(.' + myId + ')').hide(); $('#primary-div div.child.' + myId).show(); return false; }); A: $('a').click(function(evt){ var myId = $(this).attr('class'); $('div#primary-div div.child').hide(); $('div#primary-div div.'+myId).show(); }); This should do it. A: Just for kicks, here is an optimized version that utilizes jQuery chaining and the end() method: $('a').click(function(e){ $("div#primary-div > div") .not('.' + this.className).hide().end() .filter('.' + this.className).show(); return false; });
unknown
d13681
train
Turns out the question is wrong. The code above works in NLog - a single string is not treated as a message template and is rendered verbatim. I was tunneling it thru to Serilog per the linked question, and Serilog was doing the collapsing I show the effects of in the question.
unknown
d13682
train
Not at all that familair with webgrid, but would the following be a solution for you? I made the following simple model: public class Foo { public string Name { get; set; } public Lookup Lookup { get; set; } } public class Lookup { public string Name { get; set; } public Description Description { get; set; } } public class Description { public string English { get; set; } public string French { get; set; } } controller action (i don't have a db, so I mocked some data): public ViewResult Index() { //var foos = db.Foos; var foos = new List<Foo>(); foos.Add(new Foo { Name = "Foo1" }); foos.Add(new Foo { Name = "Foo2", Lookup = new Lookup { Name = "Lookup2", Description = new Description { English = "englishFoo2", French = "frenchFoo2" } } }); foos.Add(new Foo { Name = "Foo3", Lookup = new Lookup { Name = "Lookup3", Description = new Description { //English = "englishFoo3", French = "frenchFoo3" } } }); foos.Add(new Foo { Name = "Foo4" }); foos.Add(new Foo { Name = "Foo5", Lookup = new Lookup { Description = new Description { English = "englishFoo5", French = "frenchFoo5" } } }); foos.Add(new Foo { Name = "Foo6", Lookup = new Lookup { Name = "Lookup6" } }); return View(foos); } So, I now have Foos with or without Lookups (with or without Description). The view is as follows: @model IEnumerable<Foo> @{ var grid = new WebGrid(Model, defaultSort: "sortMe", rowsPerPage: 10); grid.GetHtml(htmlAttributes: new { id = "DataTable" }); } @grid.GetHtml( columns: grid.Columns( grid.Column( columnName: "Name", header: "Foo" ), grid.Column( columnName: "Lookup.Name", header: "Lookup", format: @<span>@if (item.Lookup != null) { @item.Lookup.Name } </span> ), grid.Column( columnName: "Lookup.Description.English", header: "Description.English", format: @<span>@if (item.Lookup != null && item.Lookup.Description != null) { @item.Lookup.Description.English } </span> ), grid.Column( columnName: "Lookup.Description.French", header: "Description.French", format: @<span>@if (item.Lookup != null && item.Lookup.Description != null) { @item.Lookup.Description.French } </span> ) ) ) which works just fine for me (Asp.Net MVC 3), it procudes the following html: [snip] <tr> <td>Foo4</td> <td><span></span></td> <td><span></span></td> <td><span></span></td> </tr> <tr> <td>Foo5</td> <td><span></span></td> <td><span>englishFoo5 </span></td> <td><span>frenchFoo5 </span></td> </tr> <tr> <td>Foo6</td> <td><span>Lookup6</span></td> <td><span></span></td> <td><span></span></td> </tr> [/snip]
unknown
d13683
train
It seems you are missing libc++abi. Try adding -lc++abi to your link command.
unknown
d13684
train
This is done by selecting some information regarding the triggering event itself from the stream. on ParentEvent1 as p1 insert into TestEvent select p1, somemoreinformation from MyNamedWindow Instead of selecting the event itself its also fine to select some text: on P1 insert into TestEvent select 'P1' as triggeredBy from ... on P2 insert into TestEvent select 'P2' as triggeredBy from ...
unknown
d13685
train
I solved conversion to grayscale with a commercial component with this post and I also posted there my complete solution, in care anyone will struggle like me. Converting PDF to Grayscale pdf using ABC PDF
unknown
d13686
train
Here is a solution using scikit-learn. * *sklearn.preprocessing.MultiLabelBinarizer to transform each basket into a 0-1 vector with one coordinate per food type; *sklearn.cluster.AgglomerativeClustering to make clusters, with baskets in the same cluster if they differ by at most 8 food types (8 = 2 * 4 = 2 * (10 - 6), so if two baskets have exactly 6 food types in common, then their vectors will differ by 8 coordinates) *AgglomerativeClustering().fit_predict() returns a list of numbers: number x at index i in the list means that the ith basket is in the xth cluster. *itertools.groupby with zip can be used to get the clusters as a list of lists of baskets. import random from sklearn.cluster import AgglomerativeClustering from sklearn.preprocessing import MultiLabelBinarizer from itertools import groupby from operator import itemgetter n_baskets = 10000 n_foodperbasket = 10 n_samefoodpercluster = 6 max_volume = 1000 food = sorted(['apple', 'banana','grapes','orange','potato','kiwi','pomegranate','blueberry', 'strawberry','cantalope','honeydew','papaya','mango','raspberry', 'celery','carrot', 'raddish','lettuce','tomato','garlic','onion','cabbage','corn','shallot', 'peas','squash','broccoli','spinach']) # removed your duplicate 'potato' baskets = [(random.sample(food, n_foodperbasket), random.randint(0,max_volume), i) for i in range(n_baskets)] vectorbaskets = MultiLabelBinarizer(classes=food).fit_transform([b[0] for b in baskets]) clustering = AgglomerativeClustering(n_clusters=None, distance_threshold=2*(n_foodperbasket - n_samefoodpercluster)) clusters = clustering.fit_predict(vectorbaskets) groups = [list(g) for k,g in groupby(sorted(zip(clusters, baskets)), key=itemgetter(0))] print(groups)
unknown
d13687
train
ArrayList<Person> people = new ArrayList<Person>(); public ArrayList<Person> getPeople(){ return people; } public void addPerson(Person p){ people.add(p); }
unknown
d13688
train
Looks like I didn't read api carefully enough var magnificPopup = $.magnificPopup.instance; $('body').on('click', '#photo-prev', function() { magnificPopup.prev(); }); where #photo-prev is id of previous button A: I think it's a better solution https://codepen.io/dimsemenov/pen/JGjHK just make a small change if you want to append it to the counter area. this.content.find('div.mfp-bottom-bar').append(this.arrowLeft.add(this.arrowRight));
unknown
d13689
train
Just a SELECT * FROM table_name will select all the columns and rows. $query = "SELECT * FROM table_name"; $result = mysql_query($query); $num = mysql_num_rows($results); if ($num > 0) { while ($row = mysql_fetch_assoc($result)) { // You have $row['ID'], $row['Category'], $row['Summary'], $row['Text'] } } A: OK, I found my answer with better search terms. I'm still new here, so let me know if this is not a fair way to handle the situation. I upvoted @Indranil since he or she spent so much time trying to help me. Anyway... $content = array(); while($row = mysql_fetch_assoc($result)) { $content[$row['id']] = $row; } Puts my whole entire table into one huge, multidimensional array so that I can use it throughout my code. And it even names the first level of the array by the ID (which is the unique identifier). Thank you to those that tried to help me! Billy A: $pdo = new PDO( 'mysql:host=hostname;dbname=database;charset=utf-8', 'username', 'password' ); $pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false ); $stmt = $pdo->query('SELECT ID, Category, Summary, Text FROM Table'); if ( $stmt !== false ) { $data = $stmt->fetchAll( PDO::FETCH_ASSOC ); } In the case if the SQL query has no conditions, use query() , otherwise, you should be using prepare() ans bind the parameters. Oh .. and please stop using the ancient mysql_* functions, they are in the process of being deprecated and no new code should written with them.
unknown
d13690
train
After creating your JComboBox with your empty Vector, you set the selectedIndex to loginy.capacity (). The problem is that while the capacity of your Vector is 10 (as stated in the JavaDoc for the default constructor), it's actual size is 0. Hence the ArrayOutOfBoundsException. You should check for the size of your Vector before setting the selected index of your JComboBox. A: I suspect the problem is you are trying to set the selected index of your combo box to the capacity of your vector. loginList.setSelectedIndex(loginy.capacity()); From the docs .capacity(): Returns the current capacity of this vector. Returns: the current capacity (the length of its internal data array, kept in the field elementData of this vector) This is not the size i.e. the number of logins in your database. this is the capacity of internal datastructure which will always be >= the number of elements in the vector. Try using Vector#size() but you will still need to subtract one (provided there is actually data in the vector) from this so your code should be: loginList.setSelectedIndex(loginy.size() - 1); And this will set the last login in the comboBox. Which is not required in your case as you are populating the vector after creating the combobox so you could just remove this line from your code until you populate the vector. Edit as per comments All you should need to do to have the logins is reorder the execution order. I.e populate your vector then create your combo box, Change your main method to something like this: public static void main(String[] args) { //First initialise your database (dont do this in the action performed method) // you should only need one and not need to create a new one on each action DATABASE = new DatabaseManagement("pacjent"); // Read logins (I assume this is the method that does it) DATABASE.loginReader(loginy,"uzytkownicy"); // Then create your message window... Message window = new Message(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); }
unknown
d13691
train
The privacy field is actually privacy.{key}. So, the correct code is "form_params" => array( "privacy.embed": "public" "name" => $video_name, "description" => $video_description )
unknown
d13692
train
You can make a context which enables easy access to the alert anywhere in the application. AlertProvider.js import React, { useState, useCallback, useContext, createContext } from 'react' const AlertContext = createContext() export function AlertProvider(props) { const [open, setOpen] = useState(false) const [message, setMessage] = useState() const handleClose = useCallback(() => { setOpen(false) }, [setOpen]) const handleOpen = useCallback(message => { setMessage(message) setOpen(true) }, [setMessage, setOpen]) return ( <AlertContext.Provider value={[handleOpen, handleClose]}> {props.children} <Alert color="info" isOpen={open} toggle={handleClose} > {message} </Alert> </AlertContext.Provider> ) } export function useAlert() { const context = useContext(AlertContext); if (!context) throw new Error('`useAlert()` must be called inside an `AlertProvider` child.') return context } Update your App.js import { Alert } from 'reactstrap'; import { AlertProvider } from './AlertProvider'; function App() { return ( <AlertProvider> <Router> <div className="App"> <nav className="navbar navbar-expand-lg navbar-light fixed-top"> <div className="container"> <Link className="navbar-brand" to={"/add"}> Chicommons </Link> <NavBar /> </div> </nav> <div className="auth-wrapper"> <div className="auth-inner"> <Switch> <Route exact path="/" component={Add} /> <Route path="/add" component={Add} /> <Route path="/edit/:id" component={Edit} /> <Route path="/search" component={Search} /> <Route path="/:coop_id/people" component={AddPerson} /> <Route path="/:coop_id/listpeople" component={ListPeople} /> </Switch> </div> </div> </div> </Router> </AlertProvider> ); } export default App; You can then use this in functional components: import React, { useEffect } from 'react' import { useAlert } from './AlertProvider' function MyComponent() { const [open, close] = useAlert(); useEffect(() => { // when some condition is met open("Hi") // closable with the toggle, or in code via close() }) } This uses an imperative mood to open and close by calling open() and close(). If you want a declarative mood, the context should instead directly return the setMessage and setOpen functions. You can also play around to place the alert component in some other place. A: Just below function App() {. add: const [alertMessage, setAlertMessage] = React.useState("") And change your alert to: <Alert color="info" isOpen={alertMessage!=""} toggle={()=>setAlertMessage("")} > {alertMessage} </Alert> And then I don't know how the rest of your app is laid out, but you want to pass in the setAlertMessage function into handleFormSubmit as a callback, and call it in/near setErrors
unknown
d13693
train
You should be able to change the font in settings * *On Windows: File -> Settings *On Mac: Android Studio -> Preferences IDE Settings -> Editor -> Colors & Fonts -> Font
unknown
d13694
train
When the form is submitted to the server the page is reloaded. Unless you set the submitted values in the textboxes upon loading the page again they are cleared. ASP.NET MVC doesn't use Viewstate like ASP.NET WebForms so unless you manually init the fields they will be empty when pages are reloaded after a form submission. Update: You can also submit the form data via jQuery. In order to do that you would do something like this: * *Add a click handler to the submit button. (If it is declared as you should also change it to a normal button so that the browser wont submit the form automatically. *In the click handler add code to do the ajax submission. See this question for tips on that Submit form using AJAX and jQuery But en the end it might be easier to just put the submitted data in the viewmodel and reinitialize the fields in the view after submission.
unknown
d13695
train
You are not in any event handling or callback context here, so $(this) simply refers to the window object (wrapped in jQuery.) Go through the li in a loop, then $(this) will have the proper context inside the callback function. $("li").each(function() { $(this).text("this ol's index is " + $(this).closest("ol").index()); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <body> <div> <ol><li class="li"></li></ol> <ol><li class="li"></li></ol> <ol><li class="li"></li></ol> </div> </body> </html>
unknown
d13696
train
Yes, of course. In fact you can find a lot of examples: There are some ready implementations like tf.contrib.learn.LinearClassifier in https://www.tensorflow.org/tutorials/wide Or something like this: https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/logistic_regression.py where you use tf.matmul and appropriate activations. There is even something with gradient boosting: https://arogozhnikov.github.io/2016/07/05/gradient_boosting_playground.html
unknown
d13697
train
Draw a block of the desired undercolor on the image, then annotate the image such that the text is over the block. To determine the desired size of the block, use get_type_metrics or get_multiline_type_metrics to get the dimensions of your text, then add in how much padding you want. A: Annotate in ImageMagick does not have any option to pad the undercolor. But you can trick it. The simplest ways is to put spaces on the left and right side of your text using "\ ". But that will only pad on the left and right. In label: you can add newlines, but that does not work in annotate. You could add -interline-spacing, but that will only pad on the bottom. But here is a trick. Create text in the undercolor with a slightly larger pointsize, then write over it with your desired color text. For example: Without padding: convert logo.jpg -gravity center -undercolor pink -pointsize 24 -fill black -annotate +0+0 "This Is Some Text" result1.jpg With padding: convert logo.jpg -gravity center -pointsize 34 -undercolor pink -fill pink -annotate +0+0 "X X" -pointsize 24 -fill black -annotate +0+0 "This Is Some Text" result2.jpg Alternately, you could just draw a pink rectangle in the center of the image of the desired size.
unknown
d13698
train
Based on how my app was set up I ultimately decided to remove the photoURL property altogether since it could be defined elsewhere in the app. After testing, only one of my images worked. This is why I experienced the full profile updates working out sometimes since random images were selected each time a new user signs up. I ended up sticking wth this image as the default image. As @adsy mentioned, my profile updates weren't happening consistently because certain profile images I had exceeded the allowed input body length for this property. The example in the Docs shows a link with 43 characters but no other information. The path to the profile images in the question are much shorter than this so I still need some understanding. After researching a bit, I didn't come across the maximum limit set. It's now something to contact Google Developer's support team about. If anyone has the information for the allowed input body length for this property, feel free to share it on this post. Thanks! const handleSignUp = async (e) => { e.preventDefault(); try { // firebase work! const auth = getAuth(); let { user } = await createUserWithEmailAndPassword( auth, email, password ); console.debug(`User ${user.uid} created`); // updating the user's profile with their first name await updateProfile(user, { displayName: firstName, }); console.debug(`User profile updated`); // navigate to the profile page navigate('/profile'); } catch (e) { if (e.message === 'Firebase: Error (auth/email-already-in-use).') { setError('That email is already in use, please try again.'); } } };
unknown
d13699
train
When the Rectangle has been drawn iterate over the locations and use the method contains() of the Rectangle's bounds to test if the LatLng's are within the bounds of the Rectangle
unknown
d13700
train
// Create the connection (unchanged) Properties connInfo = new Properties(); connInfo.put("user", "Main"); connInfo.put("password", "poiuyt"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ABCNews", connInfo); // Prepare the statement - should only be done once, even if you are looping. String sql = "insert into abcnews_topics VALUES (null, ?)"; PrepatedStatement stmt = connection.prepareStatement(sql); // Bind varaibles stmt.setString (1, text_topic); // Note that indexes are 1-based. // Execute stmt.executeUpdate(); A: You should parameterize your SQL, and call prepareStatement: String sql = "insert into abcnews_topics VALUES (null, ?)"; try (PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, textTopic); statement.execute(); } (The try-with-resources statement will close the PreparedStatement automatically. If you're using Java 6 or earlier, use a try/finally block to do it yourself.) Note that I've changed the text_topic variable to textTopic to follow Java naming conventions, renamed stmt to statement to avoid abbreviation, and also moved the declaration of statement to the assignment. (There's no point in declaring it earlier: try to limit scope where possible.)
unknown