id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23534000
A: We should be able to set the UserEditMode property of RadDataGrid to Inline. The default value of UserEditMode is None that the editing is not allowed. If you want edit only one column of RadDataGrid, you should be able to set CanUserEditfor other column to False. The default value of CanUserEdit is True. For example: <telerikGrid:RadDataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" UserEditMode="Inline"> <telerikGrid:RadDataGrid.Columns > <telerikGrid:DataGridTextColumn PropertyName="Product" Header="Product" CanUserEdit="False"/> <telerikGrid:DataGridBooleanColumn PropertyName="Stock" Header="Stock" CanUserEdit="True" /> </telerikGrid:RadDataGrid.Columns> </telerikGrid:RadDataGrid> Code behind: public sealed partial class MainPage : Page { ObservableCollection<Data> Products; public MainPage() { this.InitializeComponent(); Products = new ObservableCollection<Data>() { new Data { Product = "Milk", Stock = true }, new Data { Product = "Cheese", Stock = false }, new Data { Product = "Bread", Stock = false }, new Data { Product = "Chocolate", Stock = true } }; this.DataContext = Products; } } public class Data { public string Product { get; set; } public bool Stock { get; set; } }
doc_23534001
LOG(INFO) << "totalTranslation: " << m_move.totalTranslation << " tileSize: " << static_cast<double>(tileSize); if(m_move.totalTranslation >= static_cast<double>(tileSize)) { LOG(INFO) << "in!"; } tileSize equals 62 (it's int). In a loop, I increase m_move.totalTranslation value. The problem is that when m_move.totalTranslation equals 62, it doesn't enter if statement. It does, however, if it's larger than 62. Look at the log that was generated: I0118 15:20:11.788576 5644 GameObject.cpp:270] totalTranslation: 61.008 tileSize: 62 I0118 15:20:11.806589 5644 GameObject.cpp:270] totalTranslation: 62 tileSize: 62 I0118 15:20:11.822602 5644 GameObject.cpp:270] totalTranslation: 62.93 tileSize: 62 I0118 15:20:11.822602 5644 GameObject.cpp:272] in! As you can see, in! is only logged when totalTranslation is larger than 62. Why? I thought it might be casting problem, but I cast this tileSize which is of int type to double and still no difference. A: For comparison of equality between floating point numbers, it is preferred to see the closeness of the numbers because of the internal representation of floating point numbers in the computer. You might have to check if the numbers are in epsilon distance of each other.The result of equality comparison depends on the particular compiler/machine. Maybe you could look at this for more details: http://www.parashift.com/c++-faq/floating-point-arith.html A: Double sometime made annoying error... It seem to be 62.0, but in reality it's 61.9999999... but when you print it, it write you 62... Try this : if (62.0 == totalTransaction + 0.01) do something A: When you are checking for equality of two doubles, you are on a right path to spefiy the epsilon, e.g. the acceptable margin. double a = 62; double b = 62.0000000000001; double eps = 1e-10; if (abs(a-b) < eps) { cout << "match!" << endl; }
doc_23534002
build.gradle (app): apply plugin: 'com.android.application' apply plugin: 'me.tatarka.retrolambda' android { compileSdkVersion 25 buildToolsVersion "25.0.1" defaultConfig { applicationId "xsystem.ru.test" minSdkVersion 16 targetSdkVersion 25 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:25.1.0' } build.gradle (Project): // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.3' classpath 'me.tatarka:gradle-retrolambda:3.2.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } Gradle stacktrace: 19:32:51.295 [ERROR] [org.gradle.BuildExceptionReporter] 19:32:51.295 [ERROR] [org.gradle.BuildExceptionReporter] FAILURE: Build failed with an exception. 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] * What went wrong: 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] Execution failed for task ':app:compileRetrolambdaDebug'. 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] > Process 'command 'C:\Program Files\Java\jdk1.8.0_121\bin\java.exe'' finished with non-zero exit value -1073740791 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] * Exception is: 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileRetrolambdaDebug'. 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] Caused by: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_121\bin\java.exe'' finished with non-zero exit value -1073740791 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:367) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.process.internal.DefaultJavaExecAction.execute(DefaultJavaExecAction.java:31) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.file.DefaultFileOperations.javaexec(DefaultFileOperations.java:170) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.project.AbstractProject.javaexec(AbstractProject.java:848) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.project.AbstractProject.javaexec(AbstractProject.java:844) 19:32:51.296 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.Project$javaexec$11.call(Unknown Source) 19:32:51.297 [ERROR] [org.gradle.BuildExceptionReporter] at me.tatarka.RetrolambdaTask.execute(RetrolambdaTask.groovy:69) 19:32:51.297 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75) 19:32:51.297 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:245) 19:32:51.297 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:221) 19:32:51.297 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:232) 19:32:51.297 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:210) 19:32:51.297 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80) 19:32:51.297 [ERROR] [org.gradle.BuildExceptionReporter] at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61) 19:32:51.297 [ERROR] [org.gradle.BuildExceptionReporter] ... 14 more 19:32:51.297 [ERROR] [org.gradle.BuildExceptionReporter] A: Update class path to classpath 'me.tatarka:gradle-retrolambda:3.2.5' then add this to your dependencies retrolambdaConfig 'net.orfjackal.retrolambda:retrolambda:2.3.0' Add following code to application block compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } After this it should work. Update: The latest version of retrolambda till today (September 11 2017) is 3.7.0 A: Add this in app gradle build file before android block (on top) //noinspection GradleCompatible apply plugin: 'com.android.application' apply plugin: 'me.tatarka.retrolambda' tasks.whenTaskAdded { task -> if (task.name.startsWith("lint")) { task.enabled = false } } retrolambda { jvmArgs '-noverify' } and I also changed my class path version from 3.4.0 to 3.2.5 and my issue resolved. Also no need to add retroLambdaConfig A: When I updated the AS project to AS 3.4.1, there were a lot of problems, and I finally got stuck on this error message. There was very little related information on the Internet, let alone the solution. In desperation, I looked at other warnings. The following warning was changed casually: One of the plugins you are using supports Java 8 language features. To try the support built into the Android plugin, remove the following from your build.gradle The solution is to remove the previously dependent lambda library, because after version 3.0, AS itself supports lambda apply plugin: 'me.tatarka.retrolambda' //remove this line dependencies { classpath 'com.android.tools.build:gradle:3.4.1' classpath 'me.tatarka:gradle-retrolambda:3.2.4' //remote this line } After removing this sentence, synchronize it, and miraculously compiled successfully. It seems that this plug-in library does not exist after version 3.0, and it cannot be recognized.
doc_23534003
This isn't working: listHouseParts.Add(new HousePart(content, contentHouseOne[i], newPosition)); But this works: listHouseParts.Add(new HousePart(content, "100x100", newPosition)); EDIT: Here are some code to declare arrays string[] contentHouseOne = new string[] { "ruta100x100Red", "ruta100x100Grey", "ruta100x100Green", "ruta100x100Yellow", "ruta100x100Blue" }; bool[,] occupiedPositions = new bool[500,500]; Here are some code to set all grid positions to false for (int i = 0; i < gridCol; i++) for (int ii = 0; ii < gridRow; ii++) occupiedPositions[i, ii] = false; And finally here are the code that I have the problem int i = 0; do { Vector2 newPosition = NewRandomPosition; if (occupiedPositions[(int)newPosition.X, (int)newPosition.Y] == false) { listHouseParts.Add(new HousePart(content, contentHouseOne[i], newPosition)); occupiedPositions[(int)newPosition.X, (int)newPosition.Y] = true; i++; } } while (i <= 5); A: Your string array includes five elements: string[] contentHouseOne = new string[] { "ruta100x100Red", "ruta100x100Grey", "ruta100x100Green", "ruta100x100Yellow", "ruta100x100Blue" }; But your while loop ends if your running variable i is greater than 5 while (i <= 5); which causes a IndexOutOfBounds exception on contentHouseOne, because the 6th element at index 5 isn't defined. You should change your while condition to (i < 5). A: Try this so atleast you know if its empty or not HousePart housePart = new HousePart(); housePart.Content = content; if (!string.IsNullOrEmpty(contentHouseOne[i])) housePart.ContentHouseOne = contentHouseOne[i]; else housePart.ContentHouseOne = string.Empty; housePart.NewPosition = newPosition; listHouseParts.Add(housePart);
doc_23534004
A: One easy way to get a quick initial glance at what a library exposes is to create a dummy project, add a reference to the DLL and then use the Class explorer to examine the exposed pieces. A: To add to BBlake's answer; to bring up the Class View in Visual Studio 2008, just go to View -> Class View. You can also use the Object Browser, click View -> Object Browser.
doc_23534005
* *Off (default) *On (hover/rollover) *Down (active/click) In both Safari desktop and Safari mobile, when the down state is added (via :active pseudo state) it kills the click event. Why can't these two pieces play nice together? Simple example demoing it here: https://jsfiddle.net/m7hev81t/1/ $('button').on('click',function(e){ $('#log').html('clicked ' + new Date().getTime()); }); button { position:relative; background:transparent; border:none; height:50px; width:200px; cursor:pointer; } button .state { position:absolute; width:100%; height:100%; display:none; top:0; left:0; } .state.off { background:green; display:block; } .state.on { background:orange;} .state.down { background:red; } button:hover .state.off, button:hover .state.down {display:none;} button:hover .state.on {display:block;} button.has-down:active .state.on, button.has-down:active .state.off {display:none;} button.has-down:active .state.down {display:block;} #log { width:100%; border:1px solid grey; min-height:2em; margin-top:2em; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <p> No down/click state. </p> <button> <div class="state off"> off </div> <div class="state on"> on </div> <div class="state down"> down </div> </button> <p> Down/click state. </p> <button class="has-down"> <div class="state off"> off </div> <div class="state on"> on </div> <div class="state down"> down </div> </button> <div id="log"/> A: I think the issue is that the states themselves are catching the click event. Then when the state is hidden, the click doesn't bubble up. Adding this line of CSS makes it work: button.has-down .state { pointer-events:none; } Here's the fiddle: https://jsfiddle.net/m7hev81t/2/ And full example, where the second button now triggers the event. $('button').on('click',function(e){ $('#log').html('clicked ' + new Date().getTime()); }); button { position:relative; background:transparent; border:none; height:50px; width:200px; cursor:pointer; } button .state { position:absolute; width:100%; height:100%; display:none; top:0; left:0; } .state.off { background:green; display:block; } .state.on { background:orange;} .state.down { background:red; } button:hover .state.off, button:hover .state.down {display:none;} button:hover .state.on {display:block;} button.has-down .state { pointer-events:none; } button.has-down:active .state.on, button.has-down:active .state.off {display:none;} button.has-down:active .state.down {display:block;} #log { width:100%; border:1px solid grey; min-height:2em; margin-top:2em; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <p> No down/click state. </p> <button> <div class="state off"> off </div> <div class="state on"> on </div> <div class="state down"> down </div> </button> <p> Down/click state. </p> <button class="has-down"> <div class="state off"> off </div> <div class="state on"> on </div> <div class="state down"> down </div> </button> <div id="log"/> A: MDN On systems with multi-button mice, CSS3 specifies that the :active pseudo-class must only apply to the primary button; on right-handed mice, this is typically the leftmost button. so I guess not everything "click" the element will fire :active, on safari, finger or mouse pointed on element does not count, unless: By default, Safari on iOS does not use the :active state unless there is a touchstart event handler on the relevant element or on the element.
doc_23534006
Here is the code: asp: <columns> <asp:TemplateField > <ItemTemplate> <asp:TextBox ID="txtFruit" runat="server" Visible="true" Text='<%# Bind("txtFruit")%>' /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="HiddentxtFruit" HeaderText ="Fruit" HeaderStyle-Width="0%" HtmlEncode="false" Visible="false" /> </asp:TemplateField> <asp:TemplateField HeaderText="Confirm"> <ItemTemplate> <asp:Button ID="btnSubmit" Text="Confirm" runat="server" CommandName="Submit" /> </ItemTemplate> </asp:TemplateField> </columns> code behind: For intX As Integer = 0 To gridview1.Rows.Count - 1 Dim txtPLACE As TextBox = TryCast(gridview1.Rows(0).Cells(0).FindControl("txtFruit"), TextBox) Next or For intX As Integer = 0 To gridview1.Rows.Count - 1 Dim txtPLACEss As TextBox = DirectCast(gridview1.Rows(intX).FindControl("txtFruit"), TextBox) Next This will only get the first row from the gridview. A: use below code to get index of the row: Dim rowIndex = DirectCast(DirectCast(sender, Control).NamingContainer, GridViewRow).RowIndex And then Dim txtPLACEss As TextBox = DirectCast(gridview1.Rows(rowIndex).FindControl("txtFruit"), TextBox) That will solve your problem UPDATE : <asp:TemplateField > <ItemTemplate><asp:TextBox ID="txtFruit" runat="server" Visible="true" Text='<%# Bind("txtFruit")%>' /></ItemTemplate></asp:TemplateField> <asp:TextBox ID="txtFruitHidden" runat="server" Text='<%# Bind("txtFruit")%>' HeaderStyle-Width="0%" HtmlEncode="false" Visible="false" /> </asp:TemplateField> Then in C# Dim txtPLACEss As TextBox = DirectCast(gridview1.Rows(rowIndex).FindControl("txtFruitHidden"), TextBox) Hope this will resolve your problem ..
doc_23534007
The date range could be a few weeks, days, hours, seconds (even milliseconds). I've looked into moment.js and format.js but I'm hoping there's something better out there. I want to achieve something like highcharts daterange. These charts select appropriate formats for the datetime axis according to the range. Any help would be appreciated. A: Try this below code, it is still rough: var start = new Date(2014,12,22); var end = new Date(2014,12,23); var range = end.getTime() - start.getTime(); // milliseconds var seconds = range/1000; var minutes = seconds/60; var hour = minutes/60; var days = hour/24; var months = days/30; var year = months/12; var maxValue = [9999, 12, 31, 24, 60, 60]; var dateRange = [year, months, days, hour, minutes, seconds]; var dateFormat = ['#yr', '#mt', '#d', '#h', '#min', '#sec']; var specifiedIndex = 0; // default format for (var index = 0; index < maxValue.length; index ++) { if ((dateRange[index] < maxValue[index]) && (dateRange[index] >= 1)) { specifiedIndex = index; index = maxValue.length; } } alert("format date = " + dateFormat[specifiedIndex]); Thank you, A: First, we need to check if the CLDR (http://cldr.unicode.org/) data exists for this use-case, then you can open an issue here https://github.com/tc39/ecma402, and we can start looking for solution in javascript to display date ranges in relative form.
doc_23534008
public void onCreate(Bundle savedInstanceState) { ......................... .......................... btnUpdateNow.setOnClickListener(new OnClickListener() { public void onClick(View v) { Thread updateThread = new Thread() { Handler uiHandle; @Override public void run() { GetDetailsUpdate getDetailsUpdate = new GetDetailsUpdate( strUserId, strPassword, strUDID, getApplicationContext()); uiHandle.sendEmptyMessage(0); } }; updateThread.start(); Handler uiHandler = new Handler(){ @Override public void handleMessage (Message msg){ loader.setVisibility(View.INVISIBLE); } }; } } } But it is giving following error. 05-27 17:35:11.580: ERROR/AndroidRuntime(4555): Uncaught handler: thread Thread-11 exiting due to uncaught exception 05-27 17:35:11.580: ERROR/AndroidRuntime(4555): java.lang.NullPointerException What is the problem in my code? A: You have defined your Handler twice: in the thread class, and in the onClickListener. So, you initialize not the variable you're using. Follow the next steps: Firstly, remove the declaration from here: Thread updateThread = new Thread() { Handler uiHandle; Secondly, define your handler in the activity class, not in the onClickListener. A: Your updateThread is using the uiHandle: uiHandle.sendEmptyMessage(0); But in your whole Thread implementation this field variable is never set to anything so it is null.
doc_23534009
script: element(by.id('address_permanentAddress_personal_details')).sendKeys('LocationAddress'); browser.actions().click(element(by.css('.pac-container.pac-logo.hdpi .pac-item:first-child'))).perform() browser.sleep(1000); element(by.id('address_permanentAddress_personal_details')).sendKeys(protractor.Key.TAB); Google API Javascript NOV 25 screenshot timeout error myscript A: You don't need to use actions class to select the location dropdown value. Try the below option element(by.id('address_permanentAddress_personal_details')).sendKeys('LocationAddress'); var dropEle = element(by.css('.pac-container.pac-logo.hdpi .pac-item:first-child')); await browser.wait(ExpectedConditions.elementToBeClickable(dropEle),5000,'Wait for first drop value'); await dropEle.click(); Hope it helps you
doc_23534010
body { overflow-x: hidden; } .navbar { background-color: #ffffff; border-bottom: 2px solid #000000; margin: 0px -2000px; padding: 0px 2000px; } .cent { text-align: center; } .navbar a { display: block; color: #000000; padding: 14px; text-decoration: none; } <html> <head> <title>entertainment</title> <link rel="stylesheet" href="entertainment.css"> <script src="entertainment.js"></script> </head> <body> <div class="navbar"> <div class="cent"> <a href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> </div> </div> </body> </html> A: You currently have .navbar a set to display: block. This causes elements to be positioned underneath eachother. To keep the elements' block propperties but still display them next to each other, replace block with inline-block. Here is the working code snippet: body { overflow-x: hidden; } .navbar { background-color: #ffffff; border-bottom: 2px solid #000000; margin: 0px -2000px; padding: 0px 2000px; } .cent { text-align: center; } .navbar a { /* This is what changed */ display: inline-block; color: #000000; padding: 14px; text-decoration: none; } <html> <head> <title>entertainment</title> <link rel="stylesheet" href="entertainment.css"> <script src="entertainment.js"></script> </head> <body> <div class="navbar"> <div class="cent"> <a href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> </div> </div> </body> </html> A: Use flex with justify-content: center and get rid of the double div that wrapping your nav bar elements body { overflow-x: hidden; } .navbar { background-color: #ffffff; border-bottom: 2px solid #000000; margin: auto 0; display: flex; justify-content: center; } .cent { text-align: center; } .navbar a { display: block; color: #000000; padding: 14px; text-decoration: none; } <div class="navbar"> <a href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> </div> A: Change display rule for .navbar a to inline-block; .navbar a { display: inline-block; } body { overflow-x: hidden; } .navbar { background-color: #ffffff; border-bottom: 2px solid #000000; margin: 0px -2000px; padding: 0px 2000px; } .cent { text-align: center; } .navbar a { display: inline-block; color: #000000; padding: 14px; text-decoration: none; } <html> <head> <title>entertainment</title> <link rel="stylesheet" href="entertainment.css"> <script src="entertainment.js"></script> </head> <body> <div class="navbar"> <div class="cent"> <a href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> </div> </div> </body> </html> A: You can use the display: inline-block to make everything inline. There are some examples here - https://www.w3schools.com/css/css_display_visibility.asp body { overflow-x: hidden; } .navbar { background-color: #ffffff; border-bottom: 2px solid #000000; margin: 0px -2000px; padding: 0px 2000px; } .cent { text-align: center; } .navbar a { display: inline-block; color: #000000; padding: 14px; text-decoration: none; } <html> <head> <title>entertainment</title> <link rel="stylesheet" href="entertainment.css"> <script src="entertainment.js"></script> </head> <body> <div class="navbar"> <div class="cent"> <a href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> </div> </div> </body> </html>
doc_23534011
I am running ember-cli 0.2.2. I generated an helper from an addon project with: ember g helper display-helper The generator placed the file in app/helpers which seemed wrong to me, I would have thought that it should have been placed in addon helpers. I moved the file to addon/helpers and it looks like this: export default Ember.Handlebars.registerBoundHelper('displayHelper', function displayHelper(searchPath) { return new Ember.Handlebars.SafeString(get(this, searchPath)); }); When I ran ember test I get the following output: ✘ Error: Assertion Failed: A helper named 'displayHelper' could not be found The only way I get this helper to be found by the resolver is to add an import that references the helper in a component that is using it like this: import displayHelper from '../helpers/display-helper'; This does not seem correct, I would have thought the resolver would have found this automatically? Also even if I have the reference, the following code ends up with the same error message as above: import Ember from 'ember'; var get = Ember.get; function displayHelper(context, searchPath) { return new Ember.Handlebars.SafeString(get(context, searchPath)); } export default Ember.Handlebars.makeBoundHelper(displayHelper); So to sum up, I have to have this line in the component whose template uses the helper: import displayHelper from '../helpers/display-helper'; And I have to use registerBoundHelper and not makeBoundHelper like the docs say or the helper cannot be found. A: If you move your helper from app/helpers to addon/helpers, it is not available in your app namespace. To fix this, add the following file: // app/helpers/display-helper.js import displayHelper from 'your-addon-name/helpers/display-helper"; export default displayHelper; (Do not copy your-addon-name literally, use the name of your addon, which is also your addon's namespace.) This is based on the instructions here: http://www.ember-cli.com/#addon-components Just like the example component there, you can put your real helper code in addons/helpers/display-helper, but you need to import and reexport it to your app for your resolver to find it.
doc_23534012
has anyone seen this problem and do you know a solution? Only workaround is to remove the Generate Versioning Source Filename, but I still get a build error when I do this.
doc_23534013
static LinqMPISMPPCalenderDataContext DBCalender; DBCalender = new LinqMPISMPPCalenderDataContext(connectionString); var ExceptionPeriod= DBCalender.Table_ExceptionPeriods .Where(table=>Table.StartDate<= Date && table.FinishDate >= Date && table.CalenderID==CalenderID).Single(); Table_ExceptionPeriod TblException =null; TblException = ExceptionPeriod; TblException.StartDate = ExceptionPeriod.StartDate.AddDays(1); DBCalender.SubmitChanges(); A: Once you've got your object from the DB via your .Single() call you should be able to just set properties on it and call SubmitChanges(). There's no need for the TblException stuff. So ... static LinqMPISMPPCalenderDataContext DBCalender; DBCalender = new LinqMPISMPPCalenderDataContext(connectionString); var ExceptionPeriod = DBCalender.Table_ExceptionPeriods .Where(table=>Table.StartDate<= Date && table.FinishDate >= Date && table.CalenderID==CalenderID).Single(); ExceptionPeriod.StartDate = ExceptionPeriod.StartDate.AddDays(1); DBCalender.SubmitChanges(); A: There doesn't seem to be anything logically wrong with the code, as Antony says you could reduce the number of lines. I'd probably step through the code line by line, before the submit line check if the StartDate has actually changed. Only things I can imagine that could be going wrong are some kind of transaction roll back in the database or you're not looking at the record you think you are.
doc_23534014
I have tried it using array.splice in for loop but as item is being removed in each iteration, indexes of other items are being changed. JavaScript: var array = [10, 11, 12, 13, 14, 15]; var indexes = [0, 1, 2, 3, 4, 5]; indexes.forEach(function(item) { array.splice(item, 1); }); console.log(array); A: You can utilize Array.prototype.filter and do the following: var array = [10, 11, 12, 13, 14, 15]; var indexes = [0, 1, 2, 3, 4, 5]; array = array.filter(function(x, i) { return indexes.indexOf(i) === -1; }); console.log(array); A: Here you are using forEach loop which give you the item as first argument and the index on second one, so as per my understanding what you want to do can achieve by this, try this hope this solve your problem :) indexes.forEach(function(item, index) { array.splice(index, 1); }); A: Sort the indexes array from high to low, then spice will only change the index of the numbers you have already removed
doc_23534015
So I created two Pod security policies: One allowing running privileged containers and one for restricting privileged containers. [root@master01 vagrant]# kubectl get psp NAME PRIV CAPS SELINUX RUNASUSER FSGROUP SUPGROUP READONLYROOTFS VOLUMES privileged true RunAsAny RunAsAny RunAsAny RunAsAny false * restricted false RunAsAny RunAsAny RunAsAny RunAsAny false * Created the Cluster role that can use the pod security policy "restricted" and binded that role to all the serviceaccounts in the cluster apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: psp-restricted rules: - apiGroups: ['policy'] resources: ['podsecuritypolicies'] verbs: ['use'] resourceNames: - restricted --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: psp-restricted roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: psp-restricted subjects: - kind: Group name: system:serviceaccounts apiGroup: rbac.authorization.k8s.io Now I deploying a pod with "privileged" mode. But it is getting deployed. The created pod annotation indicating that the psp "privileged" was validated during the pod creation time. Why is that ? the restricted PSP should be validated right ? apiVersion: v1 kind: Pod metadata: name: psp-test-pod namespace: default spec: serviceAccountName: default containers: - name: pause image: k8s.gcr.io/pause securityContext: privileged: true [root@master01 vagrant]# kubectl create -f pod.yaml pod/psp-test-pod created [root@master01 vagrant]# kubectl get pod psp-test-pod -o yaml |grep kubernetes.io/psp kubernetes.io/psp: privileged Kubernetes version: v1.14.5 Am i missing something here ? Any help is appreciated. A: Posting the answer to my own question. Hope it will help someone All my PodSecurityPolicy configurations are correct. The issue was, I tried to deploy a pod by its own not via any controller manager like Deployment/Replicaset/Daemonset etc.. Most Kubernetes pods are not created directly by users. Instead, they are typically created indirectly as part of a Deployment, ReplicaSet or other templated controller via the controller manager. In the case of a pod deployed by its own, pod is created by kubectl not by controller manager. In Kubernetes there is one superuser role named "cluster-admin". In my case, kubectl is running with superuser role "cluster-admin". This "cluster-admin" role has access to all the pod security policies. Because, to associate a pod security policy to a role, we need to use 'use' verbs and set 'resources' to 'podsecuritypolicy' in 'apiGroups' In the cluster-admin role 'resources' * include 'podsecuritypolicies' and 'verbs' * include 'use'. So all policies will also enforce on the cluster-admin role as well. [root@master01 vagrant]# kubectl get clusterrole cluster-admin -o yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: annotations: rbac.authorization.kubernetes.io/autoupdate: "true" labels: kubernetes.io/bootstrapping: rbac-defaults name: cluster-admin rules: - apiGroups: - '*' resources: - '*' verbs: - '*' - nonResourceURLs: - '*' verbs: - '*' pod.yaml apiVersion: v1 kind: Pod metadata: name: psp-test-pod namespace: default spec: serviceAccountName: default containers: - name: pause image: k8s.gcr.io/pause securityContext: privileged: true I deployed the above pod.yaml using the command kubectl create -f pod.yaml Since I had created two pod security policies one for restriction and one for privileges, cluster-admin role has access to both policies. So the above pod will launch fine with kubectl because cluster-admin role has access to the privileged policy( privileged: false also works because admin role has access to restriction policy as well). This situation happens only if either a pod created directly by kubectl not by kube control managers or a pod has access to the "cluster-admin" role via serviceaccount In the case of a pod created by Deployment/Replicaset etc..first kubectl pass the control to the controller manager, then the controller will try to deploy the pod after validating the permissions(serviceaccount, podsecuritypolicies) In the below Deployment file, pod is trying to run with privileged mode. In my case, this deployment will fail because I already set the "restricted" policy as the default policy for all the serviceaccounts in the cluster. So no pod will able to run with privileged mode. If a pod needs to run with privileged mode, allow the serviceaccount of that pod to use the "privileged" policy apiVersion: apps/v1 kind: Deployment metadata: name: pause-deploy-privileged namespace: kube-system labels: app: pause spec: replicas: 1 selector: matchLabels: app: pause template: metadata: labels: app: pause spec: serviceAccountName: default containers: - name: pause image: k8s.gcr.io/pause securityContext: privileged: true
doc_23534016
In Windows 7 Enterprise, how can I disable the ability for the user to change the user account picture? I do not want an empty frame on the Start menu or on the log-on screen. I want our company logo to display, and I don't want it to be able to be changed. A: 'Apply the default user logon picture to all users' in the group policy is stated right in the description of it that it is supposed to do what I want, but it does not perform as advertised. This link indicates that this is a known bug in Vista, and I cannot find any evidence yet that the bug has been fixed in Windows 7. My research seems to indicate that what I want to do is not possible without quite a lot of fooling around. A: In the documentation I found Apply the default user logon picture to all users Here is a detailed description.
doc_23534017
var array = ko.observableArray(null) console.log(array()) It would return me null. The same thing on knockout 3.2.0 doesn't happen because the observable array instead of null is create as an empty array. This is my case: <div> <div class="spinner" data-bind="visible: comments() == null"> <!-- ko foreach: comments --> ... <!-- /ko --> </div> I'd like to start showing in the comments div a spinner, and when the comments are populated, i'll hide the spinner and show the comments. I can't do data-bind="visible: comments().length == 0" because if the post has no comments, the comments array will have 0 length and the spinner will be shown forever. How can I make this work? A: This would work. self.comments = ko.observableArray([]); <!-- ko if: comments().length > 0 --> Greater than zero // Show spinner <!-- /ko --> <!-- ko ifnot: comments().length > 0 --> No greater than zero // No spinner needed <!-- /ko --> Let me know what you think.
doc_23534018
I am trying to use the RetryCount property, but it doesn't seem to work. Is there any other way to try to reconnect to the redistribution server through ErrorHandler? A: I suppose, I don't know Spanish, neither I use Redis, reading only the documentation ServiceStack RedisMqServer this is the initialization, where you set the retryCount . var redisFactory = new PooledRedisClientManager("localhost:6379"); var mqHost = new RedisMqServer(redisFactory, retryCount:2); but the RetryCount, is protected (set) public int RetryCount { get; protected set; } So I think it is not possible to reset it. I don't know about another way to "re-attempt to connect to the server via ErrorHandler " I gave it a try BTW I cannot find the source in github for RedisMqServer in ServiceStack v3. During the last changes, it seems the link is broken.
doc_23534019
I have followed the standard procedure from Realm docs * *npm install --save realm *react-native link realm but when i add const Realm = require('realm'); or import Realm from 'realm'; I get the error You can see my code and project on github with the error throwing when I add the code to RNExpo/screens/SettingsScreen.js What is causing this error? Am i meant to import Realm on other files apart from the file i am using realm in? A: I managed to get in touch with Nikhilesh at Expo who told me that I was unable to use Expo with Realm because using Realm involves adding native code [and] to do something like that on expo you need to 'detach' which goes like this https://docs.expo.io/versions/v15.0.0/index.html He told me they Expo were interested in adding Realm support in the future, but for now it is not possible to use these services in unison.
doc_23534020
The method I am working on really needs to accept two arguments. * *The type of event *Some arguments The "some arguments" is a number of key/value pairs. The web service is going to be called from other languages - not just .NET languages. What should my method signature look like... public bool Notify(string eventType, IEnumerable<KeyValuePair<string, string> arguments) Or... public bool Notify(string eventType, IDictionary<string, string> arguments) Or something else. A: I would stay away from interfaces when defining data contracts. Maybe something like this: public bool Notify(string eventType, KeyValuePair<string, string>[] arguments) { } Or define a custom class: public class Argument { public string Name { get; set; } public string Value { get; set; } } and then: public bool Notify(string eventType, Argument[] arguments) { }
doc_23534021
A: You don't need that many annotations on your objects for JAXB (mostly @XmlRootElement) if your objects are neat and clean. If you want absolutely no annotations EclipseLink MOXy is one JAXB implementation which can use XML files to define the mapping instead. A: Apache xml-beans, can solve your requirement. It uses an xml mapping file, and does not require any annotations.
doc_23534022
Here is a sample script: use strict; use warnings; use feature 'say'; use Mojo::JSON qw(decode_json); use Mojo::UserAgent; sub _get_new_proxy { my $cmd = `docker run -it nrdhm/proxybroker proxybroker find --types HTTP -l 1 -f json`; my $res = decode_json $cmd; my $obj = $res->[0]; return $obj; } sub _new_proxy_socket_str { my $hash = _get_new_proxy(); return ( lc $hash->{types}[0]{type} ) . '://' . $hash->{host} . ':' . $hash->{port}; } my $ua = Mojo::UserAgent->new(); my $ip_check_url = 'https://api.ipify.org'; say "Current ip: " . $ua->get($ip_check_url)->res->text; my $proxy_socket = _new_proxy_socket_str(); $ua->proxy->http($proxy_socket)->https($proxy_socket); say "Set proxy:" . $proxy_socket; say "Current ip: " . $ua->get($ip_check_url)->res->text; Same feature works fine in LWP::UserAgent: use strict; use warnings; use LWP::UserAgent (); use JSON::MaybeXS; use feature 'say'; sub _get_new_proxy { my $cmd = `docker run -it nrdhm/proxybroker proxybroker find --types HTTP -l 1 -f json`; my $res = decode_json $cmd; my $obj = $res->[0]; return $obj; } sub _new_proxy_socket_str { my $hash = _get_new_proxy(); return ( lc $hash->{types}[0]{type} ) . '://' . $hash->{host} . ':' . $hash->{port}; } my $ua = LWP::UserAgent->new( timeout => 10 ); my $ip_check_url = 'https://api.ipify.org'; say "Current ip: " . $ua->get($ip_check_url)->decoded_content; my $proxy_socket = _new_proxy_socket_str(); $ua->proxy( [ 'http', 'https' ], $proxy_socket ); say "Set proxy: " . $proxy_socket; say "Current ip: " . $ua->get($ip_check_url)->decoded_content; Please help me to figure out what is the problem UPD: Seems like problem is only with HTTPS requests. If I use http://api.ipify.org instead https://api.ipify.org Mojo::UserAgent works fine
doc_23534023
EDIT: This data would only need to be used inside my hub class, I would not need to access it elsewhere in my asp.net application. It would definitely need to be user specific though. A: If you're only looking for the equivalent capabilities of the built in ASP.NET cache then you can simply spin up a static instance of System.Runtime.Caching.MemoryCache class. Then just access the static instance in your various hub methods. Keep in mind this is a single server, in-memory solution. For more advanced, out of process, distributed caching solutions I would look to AppFabric (Azure or on-premises) or Memcached.
doc_23534024
I define a func getGatewayInfo() to get the Gateway IP Address and return it to the caller. But when I call this func print(NetworkUtility().getGatewayInfo()) from other VC's viewDidLoad, it returns nil. From the log, I could see gatewayIPAddress has got the value from NWEndpoint, which is 192.168.1.1. However, it returns nil and print out "Gateway IP address is not found!". Could u give me some hint where I did wrong? Gateway IP address is not found! Gateway: 192.168.1.1 import UIKit import Network class NetworkUtility { var gatewayIPAddress: String? func getGatewayInfo() -> String { let monitor = NWPathMonitor(requiredInterfaceType: .wifi) monitor.pathUpdateHandler = { path in let endpoint = path.gateways[0] switch endpoint { case .hostPort(let host, _): self.gatewayIPAddress = host.debugDescription print("Gateway: \(self.gatewayIPAddress!)") default: break } } monitor.start(queue: DispatchQueue(label: "nwpathmonitor.queue")) if let gatewayIPAddress = gatewayIPAddress { return gatewayIPAddress } else { return "Gateway IP address is not found!" } } } A: The problem here is the handler code (closure) in monitor.pathUpdateHandler path in is asynchronous executed, so the return statement in the previous code will be executed before it. Eventually, the returned parameter is nil. And since we don't know when the code in closure will be finished like some networking request. So we cannot using return method in this function. Instead, we should use another completion handler to return the param value, which is callback. Like what we do in some JSON request functions. Code to involve the another completionHandler in case to return the string parameter: func getGatewayInfo(completionHandler: @escaping (String) -> ()) { let monitor = NWPathMonitor(requiredInterfaceType: .wifi) monitor.pathUpdateHandler = { path in if let endpoint = path.gateways.first { switch endpoint { case .hostPort(let host, _): let remoteHost = host.debugDescription print("Gateway: \(remoteHost)") // Use callback here to return the ip address to the caller completionHandler(remoteHost) default: break } } else { print("Wifi connection may be dropped.") } } monitor.start(queue: DispatchQueue(label: "nwpathmonitor.queue")) } The caller: override func viewDidLoad() { super.viewDidLoad() title = pageTitle // Receive remoteHost from callback parameter(aka. gateway ip address) NetworkUtility().getGatewayInfo { (remoteHost) in print("remote: \(remoteHost)") DispatchQueue.main.async { self.gwIPAddress.text = remoteHost } } }
doc_23534025
my setup is every time I create a Tenant the gem automatically creates a specific schema for the new tenant. every time I run the rails sunspot:reindex the record will not appear in the search level. but in ActiveRecord(ex.Client.all) the record is there. my theory is the tenant I created is not reindexing. is there a way to reindex specific schema? or I'm missing something?
doc_23534026
Say I have services A, B, C, D. Service D needs to consume events from A and B, publish commands to C. My solution - Every Service declares its exchange. ExchangeA, ExchangeB, ExchangeC, ExchangeD. Clients can publish commands to that exchange and consume events from those exchanges. These are topic exchanges, so for command, the routing key would be ServiceA.Command.Command1, for event ServiceA.Event.Event1. For the example I've shared: ServiceD binds queue (with name ServiceD.ServiceA.Event.Queue) to ExchangeA with routing key: ServiceA.Event.# ServiceD binds queue (with name ServiceD.ServiceB.Event.Queue) to ExchangeB with routing key: ServiceB.Event.# ServiceD produces command to the exchange ServiceC with routing key ServiceC.Command.Command1 Is this the right approach? Are there some good examples I could take a look? A: Microsoft example micro service project here: https://github.com/dotnet-architecture/eShopOnContainers usually one Exchange and N queues are used. exchange image queues image A: Your Exchange should not be service based but should be associated to the transaction which requires async processing of the messages. Create the Exchanges for those transactions and create and map your publishers to those exchanges. Create consumer queues and bind the queues to the exchange. This would be the queue from where your other service will pull the message for processing. You one service can have 1:N exchanges. A: You may have only one exchange and each services consumes from their own queues (1 queue per topic-service). All services publish to the same exchange. Following your example: * *ServiceD binds queue (with name ServiceD.ServiceA.Event.Queue) to Exchange1 with routing key: ServiceA.Event.# *ServiceD binds queue (with name ServiceD.ServiceB.Event.Queue) to Exchange1 with routing key: ServiceB.Event.# *ServiceD produces command to the exchange Exchange1 with routing key ServiceC.Command.Command1 *ServiceC binds queue (with name ServiceC.Commands.Queue) to Exchange1 with routing key: ServiceC.Command.# *etc. You may also have multiple exchanges, 1 exchange per object type (e.g. one exchange with the customer object events and commands, and another exchange with the order events and commands).
doc_23534027
I tried running all 3 apps from the package.json of the electron app like below; "name": "my-electron-app", "version": "1.0.0", "description": "Hello World!", "main": "./LauncherApp/Backend/main.js", "author": "my name", "license": "", "scripts": { "start": "start electron-forge start && cd Browserapp/api && npm start && cd ../ui && npm start", "package": "electron-forge package", "make": "electron-forge make", "build-installer": "electron-builder" }, Second approach I tried is to start both the API and UI apps in the main.js of the electron app like below; async function api() { await exec("cd " + path.join(__dirname, '../../', 'BrowserApp/api') + " && npm run start", async function(err, stdout, stderr) { return; }); } async function ui() { await exec("cd " + path.join(__dirname, '../../', 'BrowserApp/ui') + " && npm run start", function(err, stdout, stderr) { return; }); } With both approaches, I can successfully start both API and UI apps while testing in debug mode, however when I pack the whole repo into a distributable via electron-builder, only the electron app gets launched but not the UI and API. What I observed is that the electron app cannot find the API and UI applications' paths while running from the distributable. When I run the app in debug mode the paths in the second approach is as below; C:\Users{username}\source\repos\my-electron-app\BrowserApp\api When I run the app after installing the distributable the path in the second approach comes as below; C:\Users{username}\AppData\Local\Programs\my-electron-app\resources\app.asar\BrowserApp\ui How can I achieve to launch all 3 apps after installing the monorepo.
doc_23534028
First, I have a class of Enum, then after that I define another static(I thought this will run one time when the object is initalized?), in this static, I will create dictionary for each of the enum. Enum class: public enum myEnumValues{ testingFile1, testingFile2; // this part I thought it will automatically make the dictionary based on the put I have specified? Here I use 2 put with values "check1" and "check2" public static final Map<myEnumValues, String> var; static{ Map<myEnumValues, String> putting = new EnumMap<>(myEnumValues.class); putting.put(myEnumValues.testingFile1, "check1"); putting.put(myEnumValues.testingFile2, "check2"); var = Collections.unmodifiable(putting); } } My Test class: //Is there a way to print the dictionary value for both keys "testingFile1" and "testingFile2"? I think I understand it very wrong with my method. I am still learning Java. import folder.data.myEnumValues; @Test public void CheckTestForMyEnumValues(){ Map<myEnumValues, String> putting = new EnumMap<>(myEnumValues.class); System.out.println(putting.get(myEnumValues.testingFile1)); System.out.println(putting.get(myEnumValues.testingFile2)); } My expected result should be: check1 check2 My goal of creating this enum dictionary class: 1) I will create another class that will have a variable a. It will then compare if (x == myEnumValues.testingFile1){ var a == myEnumValues.get(); // store the a with value for key "testingFile1". }else{ var a == null; } My test class is mainly for me to get the value for the key and then I will add more codes but the thing is now I could not even make a dictionary with enum and also I could not even know whether the dictionary is made and call the value of each enum. That is why I created this question. A: Use the map that you've created in the static block for accessing the values. Don't create a new map because the new map contains nothing. @Test public void CheckTestForMyEnumValues(){ System.out.println(var.get(myEnumValues.testingFile1)); System.out.println(var.get(myEnumValues.testingFile2)); } A: You can print both keys and values for all entries within a map with following single line (Java 8) putting.forEach((k, v) -> System.out.println(String.format("Key: %s, value: %s", k, v)));
doc_23534029
Uri gmmIntentUri = Uri.parse("geo:0,0?q=50.123,-50.456(label)"); Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); startActivity(mapIntent); Google Maps says it's not able to find the address. When I omit the "(label)", it simply finds the lat long point. Is there a way to display whatever label name I want together with the lat long I specify?
doc_23534030
Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/queues.py", line 242, in _feed send(obj) RuntimeError: dictionary changed size during iteration So I tried changing the dictionary to an immutable dictionary to see where it was getting altered. Here's the traceback I got: Traceback (most recent call last): File "/home/jason/src/interface_dev/jiva_interface/jiva_interface/delta.py", line 54, in main msg = self.recv() File "/home/jason/src/interface_dev/jiva_interface/jiva_interface/process/__init__.py", line 65, in recv return self.inqueue.get(timeout=timeout) File "/usr/lib/python2.6/multiprocessing/queues.py", line 91, in get res = self._recv() File "build/bdist.linux-i686/egg/pysistence/persistent_dict.py", line 22, in not_implemented_method raise NotImplementedError, 'Cannot set values in a PDict' NotImplementedError: Cannot set values in a PDict This is a bit odd, because as far as I can tell, I'm not doing anything other than getting it from the queue. Could someone shed some light on what's happening here? A: There was a bug fixed quite recently where a garbage collection could change the size of a dictionary that contained weak references and that could trigger the "dictionary changed size during iteration" error. I don't know if that is your problem but the multiprocessing package does use weak references. See http://bugs.python.org/issue7105
doc_23534031
Here is my code for the user generated editText field's and saving them to Firebase. public class AddMenuActivity extends AppCompatActivity { private EditText menu_added; private LinearLayout lnrDynamicEditTextHolder; private EditText edtNoCreate; private Button btnCreate, btnSave; private FirebaseAuth auth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_menu); lnrDynamicEditTextHolder = (LinearLayout) findViewById(R.id.lnrDynamicEditTextHolder); edtNoCreate = (EditText) findViewById(R.id.edtNoCreate); btnCreate = (Button) findViewById(R.id.btnCreate); btnSave = (Button) findViewById(R.id.btnSave); auth = FirebaseAuth.getInstance(); btnCreate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(edtNoCreate.getText().toString().length()>0) { try { lnrDynamicEditTextHolder.removeAllViews(); } catch (Throwable e) { e.printStackTrace(); } final int length = Integer.parseInt(edtNoCreate.getText().toString()); for (int i=0;i<length;i++){ final EditText editText = new EditText(AddMenuActivity.this); editText.setId(i+1); editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); editText.setHint("EditText "+(i+1)); lnrDynamicEditTextHolder.addView(editText); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { for (int a=0;a<length;a++){ final String menu_add = editText.getText().toString().trim(); Query menuQuery = FirebaseDatabase.getInstance().getReference().child("Establishment").orderByChild("Estabname").equalTo(menu_add); menuQuery.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.getChildrenCount()>0){ Toast.makeText(AddMenuActivity.this,"This Name has been taken", Toast.LENGTH_SHORT).show(); } else{ if (TextUtils.isEmpty(menu_add)) { Toast.makeText(getApplicationContext(), "Enter an Item!", Toast.LENGTH_SHORT).show(); return; } String menu_id = auth.getCurrentUser().getUid(); DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Menu"); DatabaseReference pushedPostRef = current_user_db.push(); String postId = pushedPostRef.getKey(); DatabaseReference current_user_db2 = FirebaseDatabase.getInstance().getReference().child("Menu").child(postId); Map newPost = new HashMap(); newPost.put("Mfood_Name", menu_add); current_user_db2.setValue(newPost); startActivity(new Intent(AddMenuActivity.this, ManageEstablishmentActivity.class)); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } }); } } } }); } Here is the XML File <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/edtNoCreate" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="Number Of Food's" android:inputType="number" /> <Button android:id="@+id/btnCreate" android:layout_width="76dp" android:layout_height="match_parent" android:background="@drawable/rounded_button" android:layout_margin="6dp" android:text="Create" /> <Button android:id="@+id/btnSave" android:layout_width="76dp" android:layout_height="match_parent" android:background="@drawable/rounded_button" android:layout_margin="6dp" android:text="Save" /> </LinearLayout> <ScrollView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:layout_marginTop="5dp"> <LinearLayout android:id="@+id/lnrDynamicEditTextHolder" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> </LinearLayout> </ScrollView> </LinearLayout> A: Do like this - Map newPost = new HashMap(); newPost.put("Mfood_Name", menu_add); newPost.put("mfood_Quantity", itemQuantity); current_user_db2.setValue(newPost); A: In Firebase Realtime Database / Firestore, you can store array and list in the form of Hashmap (Realtime / Firestore). Example code snippet for Cloud Firestore: public class MapPost { String title; Map<String,Boolean> categories; public MapPost(String title, Map<String,Boolean> categories) { this.title = title; this.categories = categories; } } Map<String, Boolean> categories = new HashMap<>(); categories.put("technology", true); categories.put("opinion", true); categories.put("cats", true); MapPost myMapPost = new MapPost("My great post", categories);
doc_23534032
* *might be missing some numbers and *might have some unexpected numbers thrown in, how would you build an algorithm to remove all the outliers from the array? Examples of possible arrays: 1,2,3,4,1,1,1,100,5,6,7 1,2,4,100,5,6,7 1,2,4,100,101,5,6,7,300 2,3,4,5,6,7,300 In all of the examples above, you should be able to know that the array is supposed to be either 1-7 or 2-7. Some real-life example arrays: 1, 2, 295, 296, 297, 4, 5, 6, 8, 9, 10, 11, 12, 13, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 6, 6, 6, 6, 5, 5, 6, 6, 6, 6, 6, 4, 6, 6, 3, 4, 6, 6, 6, 5, 6, 6, 6, 4, 5, 6, 3, 6, 6, 6, 6, 6, 6, 6, 5, 6, 6, 6, 6, 6, 4, 6, 3, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 4, 6, 6, 6, 6, 6, 6, 5, 6, 6, 6, 3, 3, 6, 6, 6, 3, 6, 6, 4, 4, 6, 6, 6, 6, 6, 3, 6, 6, 6, 3, 6, 4, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 6, 6, 3, 6, 6, 6, 6, 6, 6, 5, 6, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 6, 6, 6, 6, 6, 6, 15, 18, 20, 21, 22, 23, 24, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 26, 712, 383, 114, 118, 225, 304, 323, 349, 357, 550, 556, 590, 649, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 51 One solution that I came up with is to filter out all values that are more than N (=5?) greater than the previous valid value, as well as all values that are less than the previous valid value. const filterOutliers = (someArray) => { let previousValidValue = null; return someArray.filter((x, index) => { //Assume the first value is valid - although this assumption might not always be true. if(!previousValidValue) { previousValidValue = x; return true; } // if the number is less than the previous valid value, remove it if(x < previousValidValue) { return false; } // if the number is more than 5 greater than the last valid value, remove it if(x > previousValidValue + 5) { return false; } previousValidValue = x; return true; }) } Potentially relevant link: Javascript: remove outlier from an array? A: It seems that your inlier data values do have a constant increment. So compute the increments, take the mode and keep the sequences of values that follow this increment (to a suitable tolerance).
doc_23534033
What tactic should be used in this case? Where did I go wrong with this one? Should I start differently? From Coq Require Import Strings.String Arith.PeanoNat Arith.Plus. Definition Ident : Type := string. Inductive AExp : Type := | ALit (n : nat) | AVar (s : Ident) | APlus (a1 a2 : AExp) | ADup (n : AExp) . Definition State := Ident -> nat. Definition empty : State := fun x => 0. Definition aState : State := fun x => match x with | "X"%string => 1 | "Y"%string => 2 | "Z"%string => 42 | _ => 0 end . Definition X:Ident := "X"%string. Definition Y:Ident := "Y"%string. Definition Z:Ident := "Z"%string. Fixpoint val (a : AExp) (s : State) : nat := match a with | ALit n => n | AVar x => s x | APlus a1 a2 => val a1 s + val a2 s | ADup a => val a s + val a s end. Fixpoint aqb (a1 a2 : AExp) : bool := match a1, a2 with | ALit n, ALit m => Nat.eqb n m | AVar s, AVar x => String.eqb s x | APlus a1 a2, APlus a1' a2' => aqb a1 a1' && aqb a2 a2' | ADup a1, ADup a1' => aqb a1 a1' | _, _ => false end. Fixpoint optmal (a : AExp) : AExp := match a with | APlus a1 a2 => if aqb a1 a2 then ADup (optmal a1) else APlus (optmal a1) (optmal a2) | ADup a0 => ADup (optmal a0) | _ => a end. Theorem optmald : forall a s, val a s = val (optmal a) s. Proof. intros. unfold val. induction a. * simpl. reflexivity. * simpl. reflexivity. * A: First, instead of unfold val, it's better to rely on simpl after induction to simplify things, as that generally leads to goals that are easier to read. Theorem optmald : forall a s, val a s = val (optmal a) s. Proof. intros. induction a; simpl. * reflexivity. * reflexivity. * Now the goal looks like val a1 s + val a2 s = val (if aqb a1 a2 then ADup (optmal a1) else APlus (optmal a1) (optmal a2)) s When there is an if (or a match) in the goal, one often good step is to destruct the scrutinee: destruct (aqb a1 a2) eqn:Ea. A: The theorem follows by induction on a. However, it is useful to first prove the lemma aeq_val first. It follows by induction on a1 and considering the cases of a2 and whether or not the branches of a1 and a2 are equal. All of the rewriteing can be handled automatically by congruence which is a tactic that can solve many goals that only require reasoning about equalities and reflexivity. Lemma aeq_val : forall a1 a2 s, aqb a1 a2 = true -> val (optmal a2) s = val (optmal a1) s. induction a1; destruct a2; simpl; try congruence; intros ? H. - apply eq_sym, EqNat.beq_nat_eq, eq_sym, H. - apply eq_sym, f_equal, String.eqb_eq, H. - destruct (andb_prop _ _ H) as [H1 H2]. apply aqb_eq in H1; apply aqb_eq in H2. destruct (aqb a2_1 a2_2) eqn:Hx; destruct (aqb a1_1 a1_2) eqn:Hy; congruence. - apply aqb_eq in H; congruence. Qed. Theorem optmald : forall a s, val a s = val (optmal a) s. Proof. induction a; intros ?; simpl; auto. destruct (aqb a1 a2) eqn:H; rewrite IHa1, IHa2; auto; clear IHa1 IHa2. simpl; apply f_equal, aeq_val; auto. Qed.
doc_23534034
When adding the script into the normal webpage in wordpress, (what should be the insides of the section), it auto removes the script tags, and just puts in the code. When adding the script as a text widget to the page, it does the same thing as above...removes the script tags when I save the widget, while this may work, I would like to have some reassurance that it does, or a better method that doesn't seem as much of a work around. If I am unclear, please let me know and I can clarify more, hopefully someone has an answer.
doc_23534035
func (db *DB) Query(query string, args ...interface{}) (*Rows, error) and the func (db *DB) QueryRow(query string, args ...interface{}) *Row in the "database/sql" package even if you have LIMIT 1; at the end of your query? A: The difference is the overhead of a function call (i.e., almost nothing, compared to sending a query to your database). QueryRow calls Query, and then wraps the results in an sql.Row.
doc_23534036
Any ideas? I know there are other questions like this on stackoverflow, I've seen them, but none of them seem to have a proper, working answer. A: Since include() returns false when fails, just check if it returns true and then do something like die() or show an error. if (!include('page.php')) die('Error.'); A: You can check the return value of include to see if it failed or not: if((@include $filename) === false) { // handle error } You'll note I included the error suppression operator (@ ) to hide the standard error messages from being displayed.
doc_23534037
A: Basically, yes. Most of C++11 has been implemented in VS2015. Most of C++14 has been implemented in VS2017. Completely? No. There are still various missing features (expression SFINAE) and bugs in the Microsoft compiler implementations of C++. If and when you run into these limitations depends on the style of code you write. A: You can check that on MSDN or cppreference A screenshot from MSDN:
doc_23534038
I've been looking for this solution for two days, but can't get the required result. Logs Table is as under (checkin_out_log) ╔════════╦═══════╦═════════════════════════╦════════════╗ ║ emp_id ║ shift ║ check_time ║ check_type ║ ╠════════╬═══════╬═════════════════════════╬════════════╣ ║ 2 ║ 1 ║ 2018-02-22 07:00:44.000 ║ C-IN ║ ║ 2 ║ 1 ║ 2018-02-22 13:00:35.000 ║ B-OUT ║ ║ 2 ║ 1 ║ 2018-02-22 13:30:46.000 ║ B-IN ║ ║ 2 ║ 5 ║ 2018-02-22 16:00:55.000 ║ C-OUT ║ ╚════════╩═══════╩═════════════════════════╩════════════╝ Desired OUTPUT is : ╔════════╦══════════╦═════════════════════════╦════════════╗ ║ emp_id ║ IN Hrs ║ Date ║ OUT HRS ║ ╠════════╬══════════╬═════════════════════════╬════════════╣ ║ 2 ║ 08:30 ║ 2018-01-22 ║ 00:30 ║ ╚════════╩══════════╩═════════════════════════╩════════════╝ Here is the data in query Here is what I get in results with data shown in screenshot with your query, please guide whats wrong A: Assuming the IN and OUT are always in pair. You can make use of LEAD() window function to get next check_time. And use CASE WHEN condition to determine it is IN or OUT time select emp_id, in_hrs = sum(in_mins) / 60.0, check_date = convert(date, check_time), out_hrs = sum(out_mins) / 60.0 from ( select *, in_mins = CASE WHEN check_type in ('C-IN', 'B-IN') AND LEAD(check_type) OVER (PARTITION BY emp_id ORDER BY check_time) in ('C-OUT', 'B-OUT') THEN DATEDIFF(MINUTE, check_time, LEAD(check_time) OVER (PARTITION BY emp_id ORDER BY check_time)) ELSE 0 END, out_mins= CASE WHEN check_type in ('C-OUT', 'B-OUT') AND LEAD(check_type) OVER (PARTITION BY emp_id ORDER BY check_time) in ('B-IN') THEN DATEDIFF(MINUTE, check_time, LEAD(check_time) OVER (PARTITION BY emp_id ORDER BY check_time)) ELSE 0 END from checkin_out_log ) d group by emp_id, convert(date, check_time) Edit : added condition to validate cases where IN without OUT or vice-versa. The in/out will be ignore and no calculation. The added condition are LEAD(check_type) OVER (PARTITION BY emp_id ORDER BY check_time) in ('C-OUT', 'B-OUT')
doc_23534039
which concatenate in path of next existed node in xml. But when i try to select valu from it, it results in paste of value of this variable, not the value of node. I can`t find how i can convert string to node set for proper selection. Please, help. <xsl:for-each select="result/node()"> <xsl:copy> <xsl:for-each select="./node()"> <xsl:copy> <xsl:attribute name="rating"> <xsl:text>0</xsl:text> </xsl:attribute> <xsl:choose> <xsl:when test="translate( substring(.,1,3), $upCase, $lowCase ) = 'id_'"> <xsl:value-of select="."/> </xsl:when> <xsl:otherwise> <xsl:variable name="cval" select="concat( '/survey/checkbox_value/', local-name(), '/.' )" /> <xsl:value-of select="$cval" /> </xsl:otherwise> </xsl:choose> </xsl:copy> </xsl:for-each> </xsl:copy> </xsl:for-each> A: You don't need to convert anything. It could be done with plain xpath. <xsl:variable name="local_name" select="local-name()"/> <xsl:value-of select="/survey/checkbox_value/node()[ local-name() = $local_name ]"/>
doc_23534040
A: From this article: Garbage Collection Part 2: Automatic Memory Management in the Microsoft .NET Framework by Jeffrey Richter Synchronization-free Allocations On a multiprocessor system, generation 0 of the managed heap is split into multiple memory arenas using one arena per thread. This allows multiple threads to make allocations simultaneously so that exclusive access to the heap is not required. Scalable Collections On a multiprocessor system running the server version of the execution engine (MSCorSvr.dll), the managed heap is split into several sections, one per CPU. When a collection is initiated, the collector has one thread per CPU; all threads collect their own sections simultaneously. The workstation version of the execution engine (MSCorWks.dll) doesn't support this feature. There is a lot other things going on, look for the "Performance for Multithreaded Applications" headline.
doc_23534041
StackExchange.Redis.StrongName.Core: version 1.2.6, published 2017, 16.3M downloads StackExchange.Redis.StrongName: version 1.1.605, published 2016, 56.1M downloads I cannot find better descritpion for StackExchange.Redis.StrongName.Core than in Nuget. They both seems to be the same. Both are compatible from net standard 1.5. A: The Nuget page for StackExchange.Redis.StrongName.Core suggests that it was a separate package developed when .NET Core was new. https://www.nuget.org/packages/StackExchange.Redis.StrongName.Core/ Alpha for .NET Core RTM; if you aren't doing .NET Core, you probably don't want this So if you're working on a .NET Core project now, you will most likely want the StackExchange.Redis.StrongName package which seems to be the 'productionised' version and supports .NET Core.
doc_23534042
How to do it for a list of tuples? If these are the tuple values t = [('2010-09-11', 'somedata', somedata), ('2010-06-11', 'somedata', somedata), ('2010-09-12', 'somedata', somedata)] tuples should be sorted based on dates in the first field. A: Usually, just sorted(t) works, as tuples are sorted by lexicographical order. If you really want to ignore everything after the first item (instead of sorting tuples with the same first element by the following elements), you can supply a key that picks out the first element. The simplest way would be operator.itemgetter: import operator ... for item in sorted(t, key=operator.itemgetter(0)): ... Of course if you want to sort the list in-place, you can use t.sort(key=operator.itemgetter(0)) instead. A: Or you can use something like this to be sure that list of tuples sorted by dates: from datetime import datetime initData = [('2010-09-11','somedata',1), ('2010-06-11','somedata',2), ('2010-09-12','somedata',3)] outData = sorted(initData , key=lambda x: datetime.strptime(x[0],"%Y-%m-%d")) A: If '2010-09-11' is year-month-day , you do: somedata = 'jyhghg' t = [('2010-09-11','somedata',somedata), ('2010-06-11','somedata',somedata), ('2010-09-12','somedata',somedata), ('2010-08-12','somedata',somedata)] from operator import itemgetter t.sort(key = itemgetter(0)) print t result [('2010-06-11', 'somedata', 'jyhghg'), ('2010-08-12', 'somedata', 'jyhghg'), ('2010-09-11', 'somedata', 'jyhghg'), ('2010-09-12', 'somedata', 'jyhghg')] . If '2010-09-11' is year-day-month, you do: from time import strptime,strftime somedata = 'jyhghg' t = [('2010-09-11','somedata',somedata), ('2010-06-11','somedata',somedata), ('2010-09-12','somedata',somedata), ('2010-08-12','somedata',somedata)] t.sort(key = lambda x: strftime('%Y%m%d',strptime(x[0],'%Y-%d-%m'))) print t result [('2010-06-11', 'somedata', 'jyhghg'), ('2010-09-11', 'somedata', 'jyhghg'), ('2010-08-12', 'somedata', 'jyhghg'), ('2010-09-12', 'somedata', 'jyhghg')] . Edit 1 Reading the answer of Artsiom Rudzenka in which he uses strptime() alone, I realized that strptime() produces a struct_time object that is sorted by nature . Such an object has attributes tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst that are accessible through common dot-notation access (toto.tm_mon for exemple), but also through index-notation access (toto[1] for exemple) , because the attributes of a struc_time object are registered in this order tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst . The struct_time data type has a named tuple's interface . Since a struct_time object is ordered by nature, it isn't necessary to apply strftime() to obtain a date string having year-month-day in this order: this order is already present in the struct_time object. Then , I correct my code for the case in which 11 in '2010-06-11' is the month : I eliminate strftime() from time import strptime somedata = 'jyhghg' t = [('2010-09-11','somedata',somedata), ('2010-06-11','somedata',somedata), ('2010-09-12','somedata',somedata), ('2010-08-12','somedata',somedata)] t.sort(key = lambda x: strptime(x[0],'%Y-%d-%m')) print t Edit 2 Taking Kirk Strauser's info in consideration: import re regx = re.compile('(\d{4})-(\d\d)-(\d\d)') somedata = 'jyhghg' t = [('2010-09-11','somedata',somedata), ('2010-06-11','somedata',somedata), ('2010-09-12','somedata',somedata), ('2010-08-12','somedata',somedata)] t.sort(key = lambda x: regx.match(x[0]).group(1,3,2)) print t A: You can use the very simple t.sort() see: How does Python sort a list of tuples?
doc_23534043
let wait = SKAction.waitForDuration(0.2, withRange: 0.19) let spawn = SKAction.runBlock { self.addTears() } let sequence = SKAction.sequence([wait, spawn]) self.runAction(SKAction.repeatActionForever(sequence)) Before these nodes spawn, I want to wait for a duration of 1 second, but only when the game starts. I tried to add a waitForDuration before I run the sequence but it didn't work. A: Try: let otherWait = SKAction.waitForDuration(1) let otherSequence = SKAction.sequence([otherWait, SKAction.repeatActionForever(sequence)]) runAction(otherSequence)
doc_23534044
I know I can add the cooldown by adding a decorator in the command function @commands.command() @commands.cooldown(1, 5, commands.BucketType.user) async def ping(self, ctx): await ctx.send('Pong!') but I don't want to add this decorator to all my functions manually because I have too many functions. is there any way to add a cooldown to all these functions at once? maybe using something like the cog_before_invoke function? I've even tried to create my own decorator for this, but I didn't manage to add it to the cog_before_invoke function or any other way to do this to multiple commands without add the code manually to each command def my_cooldown(rate, per, type=commands.BucketType.default): def decorator(func): if isinstance(func, commands.Command): func._buckets = commands.CooldownMapping(commands.Cooldown(rate, per, type)) else: func.__commands_cooldown__ = commands.Cooldown(rate, per, type) return func return decorator A: You can use the sleep() method of the built-in time module. import time # The regular stuff @commands.command() async def your_func(self, ctx): # The code time.sleep(5) This will pause the execution of your code completely so no other command can be called either.
doc_23534045
dotnet new blazorwasm -f net6.0 I am running the project with: dotnet watch run Whenever I save something which should trigger a rebuild, the change is recognised but nothing happens. I just get the following information and nothing more: watch : File changed: /Path/to/File.example. It was working fine for a while before stopping unexpectedly. Full output: watch : Project supports hot reload and was configured to run with the default run-command. Watching with hot-reload watch : Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload. Press "Ctrl + R" to restart. watch : Building... watch : Started '/usr/local/share/dotnet/dotnet' '' with process id 3155 Determining projects to restore... All projects are up-to-date for restore. waveshape -> /Users/example/Projects/waveshape/bin/Debug/net6.0/waveshape.dll waveshape (Blazor output) -> /Users/example/Projects/waveshape/bin/Debug/net6.0/wwwroot watch : Process id 3155 ran for 3605ms watch : Running MSBuild target 'GenerateWatchList' on '/Users/example/Projects/waveshape/waveshape.csproj' watch : Started '/usr/local/share/dotnet/dotnet' '' with process id 3164 watch : Process id 3164 ran for 557ms watch : Watching 28 file(s) for changes watch : dotnet-watch is configured to launch a browser on ASP.NET Core application startup. watch : Configuring the app to use browser-refresh middleware. watch : Refresh server running at wss://localhost:61209,ws://localhost:61210. watch : HotReloadProfile: BlazorWebAssembly. watch : Started 'dotnet' '"/Users/example/.nuget/packages/microsoft.aspnetcore.components.webassembly.devserver/6.0.1/build/../tools/blazor-devserver.dll" --applicationpath "/Users/example/Projects/waveshape/bin/Debug/net6.0/waveshape.dll"' with process id 3173 watch : Running dotnet with the following arguments: run watch : Started watch : Waiting for a browser to connect info: Microsoft.Hosting.Lifetime[14] Now listening on: https://localhost:7081 watch : Launching browser. info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5236 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Development info: Microsoft.Hosting.Lifetime[0] Content root path: /Users/example/Projects/waveshape watch : File changed: /Users/example/Projects/waveshape/Pages/Index.razor. A: I had this problem and can reproduce when the http port is "wrong". I don't know why it's "wrong", but port 5220 I had exact same problem, but when I changed to 5180 it works. The port change has to be done in launchSettings.json file. Someone created and issue but got no response yet. A: Try with * *dotnet watch --project .\ProjectName.csproj -v *dotnet watch --project . -v If you see watch : Hot reload capabilities: Baseline. it should work correctly. This is a workaround because there are problems with the hot reload. Other people are having problems as well - https://github.com/dotnet/aspnetcore/issues/38036
doc_23534046
My code will create sub menu "run". I would like to make "run" menu appear in menu "Export Event Google calendar". What should I do? I use onOpen() cause I think it will automatic appear menu when install add-on but only work with my own sheet. After Publicing add-on my menu it dose not show my function. It only shows in test when I paste all my code into a new sheet. and it show my function "run" as a sub-menu unber "Untitled project" . enter image description here Here is a part of code: function onOpen(e) { SpreadsheetApp.getUi().createAddonMenu() .addItem("Run", "My Function") .addSeparator() .addToUi(); }
doc_23534047
docker exec -d <container> /bin/sh -c 'echo user:$1 | chpasswd' sees that variable as empty. I've tried setting it to an environment variable for /bin/sh to access but no luck.
doc_23534048
Table A of customer data ID - Name - Age 1 - Joe - 24 2 - Bloggs - 46 Table B is a temp table of random numbers ID - RandomNumber 1 - 68 2 - 46 3 - 49 4 - 24 I need to select from table A SELECT * FROM tableA a WHERE a.age = [randomNumber from tableB] The where clause needs to look into tableB. Looks at first random number - 68, does this exist in Age column of tableA, no, so move to next random number. does 46 exist in tableB, yes, it then returns 2 - Bloggs - 46, and inserts that row into another table. the process starts again but from where is left off - does 49 exist in tableA, no, so next, does 24 exist in tableA, yes, copy that row into other table. I have a list of 150 students, and want to randomly select 30 by age. I could use RAND() function, but number will change every time, so id rather place random numbers in a table first, and then look up. Any help is much appreciated. A: If you want to randomly order the output rows, ORDER BY RAND() is your friend: SELECT sub.* FROM ( SELECT ta.ID, ta.Name, ta.Age, ROWNUM num FROM TABLEA ta JOIN TABLEB tb ON ta.Age = tb.RandomNumber ORDER BY RAND() ) sub WHERE sub.num <=30 This will retrieve maximum 30 randomly selected names from your table A Note: if you are using a DBMS where LIMIT is implemented, you can simplify the query and simply use SELECT ta.ID, ta.Name, ta.Age FROM TABLEA ta JOIN TABLEB tb ON ta.Age = tb.RandomNumber ORDER BY RAND() LIMIT 30 A: You can try SELECT tableA.name FROM tableA, tableB WHERE tableA.age IN (SELECT RandomNumber FROM tableB) If you need only 30 students, you should also add LIMIT 30 A: Here you can find an example for your request. select top 30 * from TableA where Age in (select RandomNumber from TableB)
doc_23534049
"1w 3d 5h 3m" and "32d 5h 3m" I'm using the following regex at the moment: /\d+[wdhm]\z/ but this is not working if a string contains a letter that I don't want, for example: "3pp 2h 35m" and "2d 5qq 3m" The only allowed letters in the string can be "w", "d", "h" and "m" and must be in that order if once is present, for example "2d 35m" is acceptable but "3h 1w" is not because it's in the wrong order. A: You may use this regex with multiple optional matches and a lookahead: ^(?=\d)(?:\d+w\h*)?(?:\d+d\h*)?(?:\d+h\h*)?(?:\d+m)?$ RegEx Demo RegEx Details: * *^: Start *(?=\d): Lookahead to assert presence of a digit to disallow empty matches *(?:\d+w\h*)?: Match 1+ digits followed by w and 0+ whitespaces *(?:\d+d\h*)?: Match 1+ digits followed by d and 0+ whitespaces *(?:\d+h\h*)?: Match 1+ digits followed by h and 0+ whitespaces *(?:\d+m)?: Match 1+ digits followed by m *$: End If you don't want to allow zero spacing between components then use: ^(?=\d)(?:\d+w\h*)?(?:\b\d+d\h*)?(?:\b\d+h\h*)?(?:\b\d+m)?$ RegEx Demo 2 If you want to allow only single spacing then use: ^(?=\d)(?:\d+w\h)?(?:\b\d+d\h)?(?:\b\d+h\h)?(?:\b\d+m)?$ RegEx Demo 3
doc_23534050
P.S. I'm using basic Java, with no frameworks or libraries. Pseudo-code that demonstrates what I'm looking for if Entity[ALL-MEMBERS].isAlive { gameOver = true; } A: Java 6, 7, and 8: public boolean areAllAlive(Entity[] entities) { if(entities == null || entities.length == 0) { return false; //? } for(Entity e : entities) { if(!e.isAlive()) { return false; } } return true; } Java 8, using streams/functions: public boolean areAllAlive(Entity[] entities) { if(entities == null || entities.length == 0) { return false; //? } return Arrays.stream(entities).allMatch(e -> e.isAlive()); } A: First, since you probably don't know the number of Entities you are going to use before hand an ArrayList is probably a better choice. Then yes, you should use an enhanced for loop: List<Entity> list = new ArrayList<>(); public void addEntities(){ //add Entities here } public boolean ifAlive(){ for (Entity e: list){ if (!e.isAlive()){ return false; } } return true; } or something like that. A: Assuming array is your entity's array, try this.: for (int i = 0; i < array.length; i++) { Entity entity = array[i]; if (entity.isAlive) { gameOver = true; //your code here } }
doc_23534051
When I use this example to try to sync multiple charts https://www.highcharts.com/demo/synchronized-charts I'm failing because my charts do NOT live in the same div. Their example however does only work if the charts are below each other, not if they are placed next to each other or anywhere at the page. Ideally, I would just sync the value of the hovered x Axis point as this value (timestamp) is the same for all charts available on this page. Anybody knows a non hacky way how to do it? Thanks A: In broad strokes the way I have solved this in the past would be to use the mouseOver event for a point to capture that points xAxis value. See this example. In addition to getting the value, I would call a custom function that goes through all charts and highlight the same xAxis value there (if it exists). To make this easier I would make some global array or similar that has a reference to all charts on the page. This way you don't need to explicitly reference each chart from other charts. To make this look nice and be practical, all charts need to be able to call the same custom function to highlight a value, and have a similar function that removes the highlight on the mouseOut event. This is just one possible solution, there are many ways to achieve what you are after. Here is a very basic implementation of what I wrote above function sharedMouseOver() { let currentX = this.x charts = Highcharts.charts; charts.forEach(function(chart, index) { chart.series.forEach(function(series, seriesIndex) { series.points.forEach(function(point, pointsIndex) { if (point.x == currentX) { point.setState('hover') } }) }); }); } function sharedMouseOut() { charts = Highcharts.charts; charts.forEach(function(chart, index) { chart.series.forEach(function(series, seriesIndex) { series.points.forEach(function(point, pointsIndex) { point.setState('') }); }); }); } And in each chart you can find this: plotOptions: { series: { point: { events: { mouseOver: sharedMouseOver, mouseOut: sharedMouseOut } }, ... } Working example: https://jsfiddle.net/ewolden/tvgL8pnh/17/ function sharedMouseOver() { let currentX = this.x charts = Highcharts.charts; charts.forEach(function(chart, index) { chart.series.forEach(function(series, seriesIndex) { series.points.forEach(function(point, pointsIndex) { if (point.x == currentX) { point.setState('hover') } }) }); }); } function sharedMouseOut() { charts = Highcharts.charts; charts.forEach(function(chart, index) { //if (chart.renderTo.id === chartsId) { // chosenChart = chart; //} chart.series.forEach(function(series, seriesIndex) { series.points.forEach(function(point, pointsIndex) { point.setState('') }); }); }); } Highcharts.chart('container', { legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, plotOptions: { series: { point: { events: { mouseOver: sharedMouseOver, mouseOut: sharedMouseOut } }, pointStart: 2010 } }, series: [{ name: 'Installation', data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175] }, { name: 'Other', data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111] }], }); Highcharts.chart('container2', { legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, plotOptions: { series: { point: { events: { mouseOver: sharedMouseOver, mouseOut: sharedMouseOut } }, pointStart: 2010 } }, series: [{ name: 'Manufacturing', data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434] }], }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://code.highcharts.com/highcharts.js"></script> <div id="container"></div> <div id="container2"></div>
doc_23534052
var p = 'post/'+permalink console.log(p); var fs = require('fs'); var gm = require('gm').subClass({ imageMagick: true }); gm('images/black-yellow-simple-lady-woman.jpg') .resize(234, 567) .autoOrient() .write(p, function (err) { if (err) console.log(' noooo! '+err); }); Error: Command failed: convert: unable to open image `images/black-yellow-simple-lady-woman.jpg': No such file or directory @ error/blob.c/OpenBlob/2643. convert: no images defined `post/ribs_52977588145822' @ error/convert.c/ConvertImageCommand/3127. A: Please change your relative path gm('images/black-yellow-simple-lady-woman.jpg') to absolute '/home/user/meteorproject/public/images/black-yellow-simple-lady-woman.jpg'
doc_23534053
<nav class="navbar navbar-toggleable-md navbar-light bg-faded"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a> <a class="nav-item nav-link" href="#">Features</a> <a class="nav-item nav-link" href="#">Pricing</a> <a class="nav-item nav-link disabled" href="#">Disabled</a> </div> </div> </nav> Now I want to center the div "navbar-nav" according to browser width. One thing that I have tried is giving it mr-auto and ml-auto which does seem to center it but not exactly. What it actually does it centers it according to the width "browser window width - logo width" . I want it centered exactly in the middle of the screen. I have tried changing position to absolute as well but again that kind of messes up layout in collapsed mode as well. A: Use the flexbox and margin utils responsively... Bootstrap 4 alpha 6 http://codeply.com/go/YvzHvQQRAs (center brand & links) <nav class="navbar navbar-toggleable-md navbar-light bg-faded"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="d-md-flex d-block flex-row mx-md-auto mx-0"> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse mr-auto" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a> <a class="nav-item nav-link" href="#">Features</a> <a class="nav-item nav-link" href="#">Pricing</a> <a class="nav-item nav-link disabled" href="#">Disabled</a> </div> </div> </div> </nav> Bootstrap 4.1 https://www.codeply.com/go/sTJUthyswN (center brand, align left on mobile) EDIT.. The answer is still basically the same. Use mx-auto to center. http://codeply.com/go/mycC5z8lpJ (center links, brand left) <nav class="navbar navbar-toggleable-md navbar-light bg-faded"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav mx-auto"> <a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a> <a class="nav-link" href="#">Features</a> <a class="nav-link" href="#">Pricing</a> <a class="nav-link disabled" href="#">Disabled</a> </div> </div> </nav> If you want the links exactly centered in the viewport, see the 2nd example here: http://www.codeply.com/go/RCBftzZCD8 Other Bootstrap 4 Navbar alignment examples Also see... Center an element in Bootstrap 4 Navbar Center Navbar links without brand pushing it to the right in Bootstrap 4? How to center navbar in Bootstrap 4 using Flexbox How to position navbar contents in Bootstrap 4 Bootstrap 4 Navbar align logo center and toggle icon on the left A: .navbar-nav .nav-link, .navbar-brand { text-align: center; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script> <nav class="navbar navbar-toggleable-md navbar-light bg-faded"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a> <a class="nav-item nav-link" href="#">Features</a> <a class="nav-item nav-link" href="#">Pricing</a> <a class="nav-item nav-link disabled" href="#">Disabled</a> </div> </div> </nav> A: You can use this CSS: #navbarNavAltMarkup { position: absolute; text-align: center; } #navbarNavAltMarkup > div { display: inline-block; width: 100%; } #navbarNavAltMarkup > div > a { display: inline; } It makes the container of the menu independent from its parent, gives it full width and aligns the elements inside it in the center. https://codepen.io/anon/pen/XRggYY
doc_23534054
* *User 1: Clicked button 1, redirected to page 2 *User 1: Clicked button 2, redirected to page 3 *User 1: Clicked button 18, redirected to page 100 *User 1: Clicked button 1, redirected to page 2 *User 1: Clicked button 2, redirected to page 3 then I would see the pattern ((button 1, page 2) => (button 2, page 3)) counted as two occurances. Is this possible, and if so, how? A: It's a very good question and has a fairly simple solution. Use GROUP BY and HAVING to find out which user shows what sort of repeated behavior. Please see the fiddle example here which discusses the DDL and the query I have used to get the desired result. From your description I recommend you create a table for storing user events as follows: CREATE TABLE t_clickevent ( clickevent_id INTEGER, user_id INTEGER, clicked_button_id INTEGER, redirected_url_id INTEGER); Add any more columns as and when you require. This is just a minimal structure. Use the query as follows: SELECT user_id, clicked_button_id, redirected_url_id FROM t_clickevent GROUP BY user_id, clicked_button_id, redirected_url_id HAVING count(*) > 1; Output: USER_ID CLICKED_BUTTON_ID REDIRECTED_URL_ID ----------- --------------------- ----------------- 1 1 2 1 2 3 Cheers!
doc_23534055
The problem arises however when I attempt to run the docker-ized variation of the application. The first DB runs just as it does before but the second DB no longer works. When inside the container, I can ping the second DB and it works, but whenever I try to access it via the code hosted on the server, it doesn't return data within any of the functions that utilize it. I noticed that the container has a separate IP, and may be causing issues since that docker container's IP would not have been whitelisted and may be where the problem begins. I am fairly new to Docker, so any documentation links that would assist me would be extremely helpful. A: So for anyone who is dealing with this situation in the future, I added the line network_mode: "host" to my docker.compose.yaml file. Here is some docs related to this: https://docs.docker.com/network/host/ Essentially what was happening is that the container could not be recognized by the whitelist and was not being allowed access to the second DB. With this change, it allowed the container to share the same network as the server it was being hosted on, and since that server has been whitelisted prior, it all worked out of the gate. If you are using docker, then use --net=host within your run command. Here is a SO link about what this addition does: What does --net=host option in Docker command really do?
doc_23534056
apiVersion: v1 kind: ConfigMap metadata: name: nginx-config namespace: nginx-ingress data: location-snippets: " auth_request /auth; server-snippets: " location = /auth { if ($request_method = 'OPTIONS') { return 204; } if ($request_uri !~ '/api/v') { return 200; } # All none api requests set $method POST; set $backend_path verify; if ($arg_token) { set $method GET; set $backend_path tokens/$arg_token/verify; } internal; resolver kube-dns.kube-system.svc.cluster.local valid=5s; proxy_method $method; proxy_pass http://auth.default.svc.cluster.local:3000/api/v1/users/$backend_path; proxy_pass_request_body off; proxy_set_header Content-Length ''; proxy_set_header X-Original-URI $request_uri; }" A sample client request may look like: GET: /api/v1/apples?token=123 What could I be getting wrong and how can I fix it?
doc_23534057
Intent intent = new Intent(ProgramToProgram.this, com.example.newapp.ProgramToProgram1.class); intent.putExtra("fids", arrayList1); startActivity(intent); I recieve it in the other activity like this: arraylist3 = (ArrayList<String>)getIntent().getSerializableExtra("fids"); Now I have another array list in this activty where I am storing another set of items: listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { pid = docIds.get(position); fgboys1.whereEqualTo("pid", pid) .get() .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) { String fid = documentSnapshot.get("fid").toString(); arrayList1.add(fid); arrayAdapter1.notifyDataSetChanged(); } Toast.makeText(ProgramToProgram1.this, "FIND OUT REGISTERED OR NOT REGISTERED", Toast.LENGTH_SHORT).show(); } }); } }); Now I want to compare the items of arraylist3 and arraylist1 and return the number of items and the similar items. How do I do it? This is what I have tried, but the app crashes each time: registered.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int i; arraylist3 = (ArrayList<String>)getIntent().getSerializableExtra("fids"); for (i = 0; i <arraylist3.size(); i++) { if (arraylist3.contains(arrayList1.get(i))) { i++; } } tv_reg.setText(i); } }); this is the error shown in log : 2020-02-12 11:50:19.014 16489-16489/com.example.newapp E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.newapp, PID: 16489 android.content.res.Resources$NotFoundException: String resource ID #0x0 at android.content.res.Resources.getText(Resources.java:338) at android.widget.TextView.setText(TextView.java:5494) at com.example.newapp.ProgramToProgram1$4.onClick(ProgramToProgram1.java:215) at android.view.View.performClick(View.java:6256) at android.view.View$PerformClick.run(View.java:24701) at android.os.Handler.handleCallback(Handler.java:789) at android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) A: There are some clear bugs in this code: public void onClick(View v) { int i; arraylist3 = (ArrayList<String>)getIntent().getSerializableExtra("fids"); for (i = 0; i <arraylist3.size(); i++) { if (arraylist3.contains(arrayList1.get(i))) { i++; } } tv_reg.setText(i); } Problem #1: you are using i for two (conflicting) purposes: as a counter, and as a loop variable. That won't work. Problem #2: you are appear to be using the wrong arrayList size in: for (i = 0; i <arraylist3.size(); i++) { versus arrayList1.get(i) If the two lists are not guaranteed to always have the same size, that is liable to either skip counting some elements, or give an index out of bounds exception (when i >= arrayList1.size()). There are also some design problems; * *Your variable names are uninformative: arrayList1 and arrayList3 say nothing about the meaning of the lists *The arrayList3 variable looks like it could / should be a local variable not a field.
doc_23534058
If I set the image.src to that large image within the code, it loads in seconds. But for some reason it keeps crashing when the user tries to load it. If anyone can help with this that would be great. Or if there are any suggestions on how to load a large image to a canvas other than this that would also be great. Thanks function handleImage(e){ //clearAnnotations(); //annoRedraw(); //redraw(); var reader = new FileReader(); reader.onload = function(event){ image.src = event.target.result; redraw(); } imageName = e.target.files[0].name; reader.readAsDataURL(e.target.files[0]); imageLoadedCheck(); } and handleImage function is called by this listener imageLoader.addEventListener('change', handleImage, false);
doc_23534059
From my CI project, on index.php, I put this: chdir('/Path/to/vBulletin/Project/www'); require_once('./global.php'); where the global.php is. For what I read, this should read the session. I print the $vBulletin->userinfo object, but I always get the userid = NULL, and the username "Unregistered". Thanks
doc_23534060
What is the correct name? A: _history. I overlooked the bottom section - it will be updated shortly. Sorry
doc_23534061
And I have an average value present in some cell.I would want the excel formula to identify if there is text in another column to average the columns So now if I insert another row, I have to manually update the average formula. Is there a way to have a formula which check if column A is not empty, it should consider the data in column G for the average A: There's a lot of approaches to this. My current favourite is a CELL:INDEX(...) expression. For instance, to find the last populated cell in the first continuously populated range between B1 and B5000, I would use (probably as a named range) $B$1:INDEX($B$1:$B$500,MATCH(TRUE, $B$1:$B$500="", 0)-1). This approach is great because it's non volatile, so it shouldn't bog your worksheet down. It might be vulnerable to $B$500 gradually shrinking if you're only ever deleting rows, though. Alternatives are referencing the whole column ($C:$C), but that's usually dog slow in modern excel, or using OFFSET which never shrinks, but is volatile.
doc_23534062
python testdevice.py <device ip> Que: How to make this script run on multiple devices in parallel? A: Would this not work? python testdevice.py <device ip> & python testdevice.py <device ip> # keep repeating for however many devices you have You would give a different device IP to each call. A: I think that the best way to automate while dealing with multiple computers is to use one of the IT-Automation Tools such as ansible. That gives a general solution and not restricted to python. To do what you need to: - define your hosts ips in your inventory file. - write a playbook to execute a command on the remote nodes, which is explained in here, for example: - command: ./my-script.py args: chdir: somedir/ creates: /path/to/database
doc_23534063
const char* currentLoadedFile = "D:\files\file.lua"; char fileName[256]; if (sscanf(currentLoadedFile, "%*[^\\]\\%[^.].lua", fileName)) { return (const char*)fileName; // WILL RETURN "D:\files\file!! } The issue is that "D:\files\file" will be returned and not the wanted "file"(note: without ".lua") A: You can do this portably and easily using the new filesystem library in C++17. #include <cstdint> #include <cstdio> #include <filesystem> int main() { std::filesystem::path my_path("D:/files/file.lua"); std::printf("filename: %s\n", my_path.filename().u8string().c_str()); std::printf("stem: %s\n", my_path.stem().u8string().c_str()); std::printf("extension: %s\n", my_path.extension().u8string().c_str()); } Output: filename: file.lua stem: file extension: .lua Do note that for the time being you may need to use #include <experimental/fileystem> along with std::experimental::filesystem instead until standard libraries are fully conforming. For more documentation on std::filesystem check out the filesystem library reference. A: Just use boost::filesystem. #include <boost/filesystem.hpp> std::string filename_noext; filename_noext = boost::filesystem::path("D:\\files\\file.lua").stem().string(). const char* result_as_const_char = filename_noext.c_str(); or alternatively, if you want to introduce bugs yourself : // have fun defining that to the separator of the target OS. #define PLATFORM_DIRECTORY_SEPARATOR '\\' // the following code is guaranteed to have bugs. std::string input = "D:\\files\\file.lua"; std::string::size_type filename_begin = input.find_last_of(PLATFORM_DIRECTORY_SEPERATOR); if (filename_begin == std::string::npos) filename_begin = 0; else filename_begin++; std::string::size_type filename_length = input.find_last_of('.'); if (filename_length != std::string::npos) filename_length = filename_length - filename_begin; std::string result = input.substr(filename_begin, filename_length); const char* bugy_result_as_const_char = result.c_str(); A: What about using std::string? e.g. std::string path("d:\\dir\\subdir\\file.ext"); std::string filename; size_t pos = path.find_last_of("\\"); if(pos != std::string::npos) filename.assign(path.begin() + pos + 1, path.end()); else filename = path; A: You can easily extract the file: int main() { char pscL_Dir[]="/home/srfuser/kush/folder/kushvendra.txt"; char pscL_FileName[50]; char pscL_FilePath[100]; char *pscL; pscL=strrchr(pscL_Dir,'/'); if(pscL==NULL) printf("\n ERROR :INvalid DIr"); else { strncpy(pscL_FilePath,pscL_Dir,(pscL-pscL_Dir)); strcpy(pscL_FileName,pscL+1); printf("LENTH [%d}\n pscL_FilePath[%s]\n pscL_FileName[%s]",(pscL-pscL_Dir),pscL_FilePath,pscL_FileName); } return 0; } output: LENTH [25} pscL_FilePath[/home/srfuser/kush/folder] pscL_FileName[kushvendra.txt A: Here you can find an example. I'm not saying it's the best and I'm sure you could improve on that but it uses only standard C++ (anyway at least what's now considered standard). Of course you won't have the features of the boost::filesystem (those functions in the example play along with plain strings and do not guarantee/check you'll actually working with a real filesystem path). A: // Set short name: char *Filename; Filename = strrchr(svFilename, '\\'); if ( Filename == NULL ) Filename = svFilename; if ( Filename[0] == '\\') ++Filename; if ( !lstrlen(Filename) ) { Filename = svFilename; } fprintf( m_FileOutput, ";\n; %s\n;\n", Filename ); A: You could use the _splitpath_s function to break a path name into its components. I don't know if this is standard C or is Windows specific. Anyway this is the function: #include <stdlib.h> #include <string> using std::string; bool splitPath(string const &path, string &drive, string &directory, string &filename, string &extension) { // validate path drive.resize(_MAX_DRIVE); directory.resize(_MAX_DIR); filename.resize(_MAX_FNAME); extension.resize(_MAX_EXT); errno_t result; result = _splitpath_s(path.c_str(), &drive[0], drive.size(), &directory[0], directory.size(), &filename[0], filename.size(), &extension[0], extension.size()); //_splitpath(path.c_str(), &drive[0], &directory[0], &filename[0], &extension[0]); //WindowsXp compatibility _get_errno(&result); if (result != 0) { return false; } else { //delete the blank spaces at the end drive = drive.c_str(); directory = directory.c_str(); filename = filename.c_str(); extension = extension.c_str(); return true; } } It is a lot easier and safe to use std::string but you could modify this to use TCHAR* (wchar, char)... For your specific case: int main(int argc, char *argv[]) { string path = argv[0]; string drive, directory, filename, extension; splitPath(path, drive, directory, filename, extension); printf("FILE = %s%s", filename.c_str(), extension.c_str()); return 0; } A: If you are going to display a filename to the user on Windows you should respect their shell settings (show/hide extension etc). You can get a filename in the correct format by calling SHGetFileInfo with the SHGFI_DISPLAYNAME flag.
doc_23534064
I have an Index view which list courses (ex. history, maths..). When the course is chosen it takes it to the create new view. I want to modify the view so that user fill the application for a specific course. @Html.ActionLink("Choose", "ChooseCorse", "FillCourse", new { id = item.idCourse }, null) Now I'm using an ActionLink to link the user to the create new view and take the id of the course, but it's where I get stuck. How do I display the course chosen and make sure it's saved in the database? [HttpGet] public ActionResult ChooseCourse(int? id) { //For the dropdow list ViewBag.idCourse = new SelectList(db.tbCourses,"idCourse","Name",fillCourse.idCourse); return View(); } [HttpPost] public ActionResult ChooseCourse (tbFillCourse fillCourse) { if(!ModelState.IsValid) { return View(); } else { db.tbFillCourses.Add(fillCourse); db.SaveChanges(); return RedirectToAction("Index"); } } This is my first time using the site so if I need to provide more or have done something wrong please correct me. A: Does this work? [HttpGet] public ActionResult ChooseCourse(int? id) { //For the dropdown list ViewBag.idCourse = new SelectList(db.tbCourses,"idCourse","Name",id); return View(); } I don't know what the parameter tbFillCourse fillCourse is meant to be doing, but; * *You aren't passing anything to it, so it should actually fail because it's not an optional parameter as far as I can tell *You're using it as the default value when populating the drop down It seems like all the HttpGet does is populates a drop down - it doesn't return a view at all. I suggest you use a breakpoint to step through and inspect the parameter values
doc_23534065
A: The question hasn't given many details, but in principle you can recover the position of the window using code like the: tell application "System Events" tell process "App Name" set windowPos to position of first window end tell end tell ... and then compare that to the frame of each desktop to discover which display the window is in. If you need to determine the frame of each desktop programmatically (instead of hand-coding them in), that will take some extra work: either digging the values out of a system plist file or using AppleScriptObjC to get the frame dimensions from NSScreen. Let me know if you need that, and I'll update when I get a chance.
doc_23534066
doc_23534067
My question is the following: where it is easier to combine all these components, in MS Visual tudio Main part is CUDA + OpenCL + OpenGL, it will be the core of the project. P.S. This question is not to star holy-war betwen Qt and MS Visual studio. A: OpenCL is not limited to GPUs, it can be used for parallel programming in clusters as well. Intel for example provides a OpenCL implementation, that is aimed at multicore CPU and clusters. So my recommendation is to use OpenCL for both GPU computing and clustering. MPI (Message Passing Interface) is mainly a way to communicate between tasks running on separate cluster nodes. It's not so much of a clustering framework by itself.
doc_23534068
Both calls from application constructor and from start method return empty string. public class MyApplication extends Application { private HostServices hostService; private MyController controller ; private Parent root; private HostServices hostService; public MyApplication() throws IOException { hostService = getHostServices(); System.out.println("Codebase : "+hostService.getCodeBase() ); // return empty string } @Override public void start(Stage primaryStage) { this.primaryStage = primaryStage; try { FXMLLoader fxmlLoader = new FXMLLoader(this.getClass().getResource("/mypackage/my.fxml") ); controller = new MyController(); fxmlLoader.setController(controller); fxmlLoader.load(); root = fxmlLoader.getRoot(); Scene scene = new Scene(root,1200,1000); primaryStage.setScene(scene); primaryStage.show(); System.out.println("Codebase : "+getHostServices().getCodeBase() ); // return empty string } catch(Exception e) { e.printStackTrace(); } } This is very strange situation since the application deployed to the web it is important to get the codebase. A: From the hostServices.getCodeBase() javadoc: If the application is not packaged in a jar file, this method returns the empty string. Additionally: If the application was launched via a JNLP file, this method returns the codebase parameter specified in the JNLP file. For hostServices.getCodeBase() to return an expected value, you have to appropriately package your application according to the above guidelines. The way in which you package your application will vary according to the packaging tools you use, so refer to your tool vendor's documentation for information on packaging an application using your chosen development environment.
doc_23534069
I created an example word document using the Insert Chart feature in Word, and made a bar chart with various times (around 1 hour each, formatted as, for example, 01:04:04. (using this code as a template). I looked in the Open XML SDK 2.0 Productivity Tool and noticed that it was generated in the reflected code as (for the example above): numericValue9.Text = "4.449074074074074E-2"; //01:04:04 If I want to automatically generate this using my List<TimeSpan>, how do I convert my TimeSpans to this small numerical value? Is that TimeSpan.TotalDays? Also, looking at the Word Document (right clicking the chart and selecting Edit Data), I noticed that "AM" is appended to the end of my TimeSpan. Does excel convert my timespan into a datetime? A: The reason this is happening, as DJ KRAZE mentioned, is due to the cell's format. Open XML assumes DataType = CellValues.String but it will return something that doesn't look right (your "small number") if it isn't actually type string. The way to correct this issue is simply to format the cell as text. You can do this by using a formula like so: // A1 being what ever cell your original data is in =TEXT(A1, "h:mm:ss") The result:
doc_23534070
I am using the Drupal .htaccess rewrite rule for removing the www: RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301] What do you recommend? Adapt this rule to remove the international .br or add another rule on top of this to remove the .br? How would be the final mod_rewrite condition for both removing www and .br from my URLs? A: This should work. <IfModule mod_rewrite.c> # Enable rewrite RewriteEngine On RewriteBase / # Rewrite .br to international domain RewriteCond %{HTTP_HOST} ^www.domain.com.br [NC] RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301] # Rewrite non www. .br to international domain RewriteCond %{HTTP_HOST} ^domain.com.br [NC] RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301] # Rewrite www. to non www. RewriteCond %{HTTP_HOST} ^www.domain.com [NC] RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301] </IfModule>
doc_23534071
Most of the literature I've seen deals with sequences of bit errors in a stream of data, so that wouldn't seem to apply. A simple approach is to take N blocks at a time, then store a block containing the XOR of the N blocks. If one of the N blocks is missing but the check block is not, then the missing block can be reconstructed. Are there error-correcting schemes which are well suited to this problem? Links to literature or code are appreciated. A: Look into Reed-Solomon codes: http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction A: Your best place to begin your search is parchive Parity Volume Set spec. The biggest issue you will have is the overhead metadata needed in each block. Plus that spec is oriented toward compressed archive files. Another good link is the parchive docs on the 2.0 format (based on but more block oriented than parchive 1.0). See QuickPar for a good breakdown on how 2.0 improved on PAR 1.0. A: Check out Raptor codes (https://en.wikipedia.org/wiki/Raptor_code) they're the most advanced fountain codes out there at the moment
doc_23534072
One thread is generating bytes and writing them; the other is consuming them. I want to make sure that I don't generate bytes significantly faster than I can consume them. When does PipedOutputStream block? Is there a fixed size to its buffer? Or do I need to call flush() everytime after I write()? A: That's how it already behaves. The pipes share a rather small buffer, 1k according to the comments below, and if it fills up the writer blocks.
doc_23534073
I initially had an O(n) algorithm, but then, I decided to research big O notation. Apparently (I could be wrong), O(n) algorithms and O(2n) algorithms basically have the same running time. So do O(n) and O(4n) algorithms. In fact, O(n) and O(cn) algorithms (where c is an integer) essentially have the same running time. So now, I have an O(8n) algorithm, but it isn't quick enough for 77-bit numbers. What sort of time complexity would be required to factorise the first few RSA numbers (in under 5-ish minutes)? My O(8n) algorithm: import math num = int(input()) sq = math.sqrt(num) if num % 2 == 0: print(2, int(num / 2)) elif sq % 1 == sq: print(int(sq), int(sq)) else: sq = round(sq) a = 3 b = sq + (1 - (sq % 2)) c = ((b + 1) / 2) d = ((b + 1) / 2) c -= (1 - (c % 2)) d += (1 - (d % 2)) e = ((c + 1) / 2) f = ((c + 1) / 2) e -= (1 - (e % 2)) f += (1 - (f % 2)) g = ((d + 1) / 2) + d h = ((d + 1) / 2) + d g -= (1 - (g % 2)) h += (1 - (h % 2)) while a <= sq and num % a != 0 and b > 2 and num % b != 0 and c <= sq and num % c != 0 and d > 2 and num % d != 0 and e <= sq and num % e != 0 and f > 2 and num % f != 0 and g <= sq and num % g != 0 and h > 2 and num % h != 0: a += 2 b -= 2 c += 2 d -= 2 e += 2 f -= 2 g += 2 h -= 2 if num % a == 0: print(a, int(num / a)) elif num % b == 0: print(b, int(num / b)) elif num % c == 0: print(c, int(num / c)) elif num % d == 0: print(d, int(num / d)) elif num % e == 0: print(e, int(num / e)) elif num % f == 0: print(f, int(num / f)) elif num % g == 0: print(g, int(num / g)) elif num % h == 0: print(h, int(num / h)) A: Your algorithm is poorly-implemented trial division. Throw it away. Here is my basic prime-number library, using the Sieve of Eratosthenes to enumerate prime numbers, the Miller-Rabin algorithm to recognize primes, and wheel factorization followed by Pollard's rho algorithm to factor composites, which I leave to you to translate to Python: function primes(n) i, p, ps, m := 0, 3, [2], n // 2 sieve := makeArray(0..m-1, True) while i < m if sieve[i] ps := p :: ps # insert at head of list for j from (p*p-3)/2 to m step p sieve[i] := False i, p := i+1, p+2 return reverse(ps) function isPrime(n, k=5) if n < 2 then return False for p in [2,3,5,7,11,13,17,19,23,29] if n % p == 0 then return n == p s, d = 0, n-1 while d % 2 == 0 s, d = s+1, d/2 for i from 0 to k x = powerMod(randint(2, n-1), d, n) if x == 1 or x == n-1 then next i for r from 1 to s x = (x * x) % n if x == 1 then return False if x == n-1 then next i return False return True function factors(n, limit=10000) wheel := [1,2,2,4,2,4,2,4,6,2,6] w, f, fs := 0, 2, [] while f*f <= n and f < limit while n % f == 0 fs, n := f :: fs, n / f f, w := f + wheel[w], w+1 if w = 11 then w = 3 if n == 1 return fs h, t, g, c := 1, 1, 1, 1 while not isPrime(n) repeat h := (h*h+c) % n # the hare runs h := (h*h+c) % n # twice as fast t := (t*t+c) % n # as the tortoise g := gcd(t-h, n) while g == 1 if isPrime(g) while n % g == 0 fs, n := g :: fs, n / g h, t, g, c := 1, 1, 1, c+1 return sort(n :: fs) function powerMod(b, e, m) x := 1 while e > 0 if e%2 == 1 x, e := (x*b)%m, e-1 else b, e := (b*b)%m, e//2 return x function gcd(a, b) if b == 0 then return a return gcd(b, a % b) Properly implemented, that algorithm should factor your 79-bit number nearly instantly. To factor larger numbers, you will have to work harder. Look up "elliptic curve factorization" and "self-initializing quadratic sieve" to find factoring algorithms that you can implement yourself.
doc_23534074
Genre : Action,Sport,Fighting,Platform NA : 10, 13, 3, 5 EU : 7, 11, 1, 3 JP : 8, 10, 2, 9 A: library(tidyverse) tribble( ~Region, ~Action, ~Sport, ~Fighting, ~Platform, NA, 10L, 13L, 3L, 5L, "EU", 7L, 11L, 1L, 3L, "JP", 8L, 10L, 2L, 9L ) %>% pivot_longer(-Region) %>% ggplot(aes(name, value, fill = Region)) + geom_col(position = "dodge")
doc_23534075
A: I found the problem and solution. In tiapp.xml, in the tag manifest, there were parameter android:anyDensity with value to "false". When I changed to "true", the scroll of webviews became very quick. In other hand, I needed to change all app's interface because this change caused change of all UI reference. But, after many hours of adjusts, finally the app is OK. Thanks.
doc_23534076
RewriteEngine On<br/> RewriteBase /<br/> RewriteRule ^index\.php$ - [L]<br/> RewriteCond %{REQUEST_FILENAME} !-f<br> RewriteCond %{REQUEST_FILENAME} !-d<br> RewriteRule . /index.php [L] But the website is visible, when I'm trying hit https://tumree.com/index.php In SEO perpective, there shouldn't be duplicate in URL. The two URLs are indexing and its not good. Please help me to fix the issue...
doc_23534077
@OneToMany(mappedBy = "department") private List<Employee> employees; in controller.java @RequestMapping(value = "/indexDep") public @ResponseBody void doPostListDep(HttpServletResponse response) throws JSONException, IOException { departmentService.listDepartment(response); } in departmentService.java public List<Department> listDepartment() { return departmentDao.listDepartment(); } public void listDepartment(HttpServletResponse response) throws IOException, JSONException { PrintWriter out = response.getWriter(); JSONObject obj = new JSONObject(); List lst = new ArrayList(); //here listDepartment() returns an list of departments and in each //department returns arraylist of employees ... i want to put this //in json object to be sent .. so how to make this ?? obj.put("MyListDep", lst); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); out.write(obj.toString()); out.close(); } A: The following code will create an JSONArray with all employees in it: JSONArray array = new JSONArray(); for (Department d : listDepartments()) { JSONObject obj = new JSONObject(); for (Employee e : d.getEmployees()) { obj.put("EMPID", e.getEmpId()); obj.put("EMPAGE", e.getEmpAge()); obj.put("ADDRESS", e.getAddress()); [...] } array.put(obj); } Then you have to send the JSONArray through the PrintWriter like: out.write(array.toString()); A: I recommend you to make a response object representing the structure of wanted json output and replace list with an array which would be serialized without any effort
doc_23534078
Normally I retrieve data by using this code $this->model->find('list', array('fields' => array('Area.id', 'Area.name'), 'recursive' => -1)); and my output is array( '1' => 'Dhaka' '2' => 'New Yourk' '3' => 'Japan' ) But I want to get output like this array( '1' => 'dhaka' '2' => 'new yourk' '3' => 'japan' ) to get this output I try this code $this->model->find('list', array('fields' => array('Area.id', 'LOWER(Area.name)'), 'recursive' => -1)); But it gives me an array. array( '1' => '2' => '3' => ) I know I can do this job with a loop. But I don't want to use loop here. any solutions without loop? A: You need to set a $virtualFields variable in Model. Set it like as below: public $virtualFields = array( 'title' => "LOWER(Area.name)" ); And In your find query in controller. PLease change $this->Area->find("all", array("fields" => array("Area.id", "Area.title"))); It will work..
doc_23534079
MainViewController.m MainViewController.h Myapp.m Myapp.h i want use a method "restanswer" declared in Myapp.m in MainViewController.m, this is the code: //MyApp.h @class MainViewController; @interface MyApp : DEFINE_SUPERCLASS // << @todo note to OP: define your superclass. you rarely need to create a root class in objc. { NSMutableArray * answer; } @property (nonatomic, retain) NSMutableArray *answer; - (NSMutableArray *) restarray; @end //MyApp.m #import "MainViewController.h" @implementation Myapp @synthesize answer; NSMutableArray * answer = nil; - (NSMutableArray *)restarray { answer = [[NSMutableArray alloc] initWithObjects:@"1", @"2",@"3", nil]; return answer; } //MainViewController.m #import "MyApp.h" @implementation MainViewController @synthesize answer; static Myapp * risposte; -(void).......{ NSMutableArray * prova = [risposte restarray]; int numbertest = [prova count]; NSLog(@"the value is: %d", numbertest); } i have no error, but the value of numbertest is: 0, why? my array have 3 object, please help me...sorry for format code i try but don't work... A: ... + (MyApp *)sharedRiposte { // ok -- your OP is lacking (requested) detail // i have to infer some things: // 1) MyApp is an NSApplication or UIApplication subclass // 2) your program actually has designated MyApp as the app's type --- if OS X --- MyApp * app = (MyApp*)[NSApplication sharedApplication]; if (![app isKindOfClass:[MyApp class]]) { assert(0 && "oops, the app type is not defined correctly"); return nil; } else { return app; } --- if iOS --- MyApp * app = (MyApp*)[UIApplication sharedApplication]; if (![app isKindOfClass:[MyApp class]]) { assert(0 && "oops, the app type is not defined correctly"); return nil; } else { return app; } } -(void).......{ MyApp * riposte = [[self class] sharedRiposte]; assert(risposte && "oops, app is not configured properly (assuming MyApp is an NS/UI-Application subclass)"); NSMutableArray * prova = [risposte restarray]; assert(prova && "oops, risposte could not create the restarray"); int numbertest = [prova count]; // we know the answer to this based on the *current* implementation of restarray assert(3 == numbertest && "oops, the array is not what we expect"); NSLog(@"the value is: %d\nthe array is: %@", numbertest, prova); }
doc_23534080
var re = /^\d{1,5}\.\d{1}$/; But it currently checks value which have only decimal and not allowing interger, can i modify this expression tho accept both integer and float Currently accepting 100.0 I want to enter both 100 and 100.0 so that i want to change thisregular expression Some input wilbe a valuable for me A: Try this: /^\d{1,5}(\.\d{1})?$/;
doc_23534081
A: is that possible??? No, sorry. Without the system bar, the user cannot exit your app.
doc_23534082
* *utils Current channels: * *https://conda.anaconda.org/conda-forge/osx-arm64 *https://conda.anaconda.org/conda-forge/noarch To search for alternate channels that may provide the conda package you're looking for, navigate to https://anaconda.org and use the search bar at the top of the page.
doc_23534083
@ParametrizedTest @ValueSource //here it seems only one parameter is supported public void myTest(String parameter, String expectedOutput) I know I could use @MethodSource but I was wondering if in my case I just need to understand better @ValueSource. A: The documentation says: @ValueSource is one of the simplest possible sources. It lets you specify a single array of literal values and can only be used for providing a single argument per parameterized test invocation. Indeed you need to use @MethodSource for multiple arguments, or implement the ArgumentsProvider interface. A: You need jUnit Pioneer and the @CartesianProductTest * *https://github.com/junit-pioneer/junit-pioneer *https://junit-pioneer.org/docs/cartesian-product/ POM: <dependency> <groupId>org.junit-pioneer</groupId> <artifactId>junit-pioneer</artifactId> <version>1.3.0</version> <scope>test</scope> </dependency> Java: import org.junitpioneer.jupiter.CartesianProductTest; import org.junitpioneer.jupiter.CartesianValueSource; @CartesianProductTest @CartesianValueSource(ints = { 1, 2 }) @CartesianValueSource(ints = { 3, 4 }) void myCartesianTestMethod(int x, int y) { // passing test code } A: Another approach is to use @CsvSource, which is a bit of a hack, but can autocast stringified values to primitives. If you need array data, then you can implement your own separator and manually split inside the function. import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static com.google.common.truth.Truth.assertThat; @ParameterizedTest @CsvSource({ "1, a", "2, a;b", "3, a;b;c" }) void castTermVectorsResponse(Integer size, String encodedList) { String[] list = encodedList.split(";"); assertThat(size).isEqualTo(list.length); }
doc_23534084
document.addEventListener('DOMContentLoaded', () => { ms(); }); function ms() { var btns = document.getElementsByClassName("pas"); for (var j = 0; j < btns.length; j++) { document.addEventListener('play', function(e) { var songs = document.getElementsByClassName("pas"); for (var i = 0; i < songs.length; i++) { if (songs[i] != e.target) { songs[i].pause(); } } }, true); } } <audio class="pas" controls loop autoplay> <source src="https://www.mboxdrive.com/Drake_-_One_Dance_(Lyrics)_ft._Wizkid_&_Kyla(128k).m4a" type="audio/mp3"> Your browser dose not Support the audio Tag </audio> <audio class="pas" controls loop autoplay> <source src="https://www.mboxdrive.com/Coobie_-_Miss_You_(Official_Lyric_Video)(256k).mp3" type="audio/mp3"> Your browser dose not Support the audio Tag </audio> The above js is to allow only one audio to be played once. Anyway possible way to add any function to play another audio if the first one is finished? You can try code demo here https://jsfiddle.net/mt1koznd/2/ A: Use the timeupdate event, and the .duration and .currentTime properties. If you intend to switch players, you need to remove the loop attribute and remove the autoplay attribute on all but one or all players will play at the same time. The example will work for an unlimited amount of players and will loop back to the starting player if the current player is the last one. Details are commented in example <!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <style></style> </head> <body> <audio class="song" controls> <source src="https://www.mboxdrive.com/Drake_-_One_Dance_(Lyrics)_ft._Wizkid_&_Kyla(128k).m4a" type="audio/mp3"> </audio> <audio class="song" controls> <source src="https://www.mboxdrive.com/Coobie_-_Miss_You_(Official_Lyric_Video)(256k).mp3" type="audio/mp3"> </audio> <script> // Collect all .song into a NodeList then convert it into a real array const songs = [...document.querySelectorAll('.song')]; // Bind the timeupdate event to each .song songs.forEach(song => song.ontimeupdate = nextSong); // Event handler function nextSong(e) { // Get player's full duration in seconds const end = this.duration; // Get the current time spent playing in seconds let now = this.currentTime; // If the time playing reaches the duration... if (end <= now) { // Get the index position of player const position = songs.indexOf(this); // If the player is the last one start play on the first player if (position === songs.length - 1) { songs[0].play(); // Otherwise start ply on the next player } else { songs[position + 1].play(); } } } </script> </body> </html>
doc_23534085
A: Possible duplicate: How can I expose more than 1 port with Docker? docker run -p <host_port1>:<container_port1> -p <host_port2>:<container_port2>
doc_23534086
All of the data needed to control the processes are stored in a text file. The file might look like this: PID=4390 IDLE=0.000000 BUSY=2.000000 USER=2.000000 PID=4397 IDLE=3.000000 BUSY=1.500000 USER=4.000000 PID=4405 IDLE=0.000000 BUSY=2.000000 USER=2.000000 PID=4412 IDLE=0.000000 BUSY=2.000000 USER=2.000000 PID=4420 IDLE=3.000000 BUSY=1.500000 USER=4.000000 This is a university assignment, however parsing the text file isn't supposed to be a big part of it, which means I can use whatever way is the quickest for me to implement. Entries in this file will be added and removed as processes finish or are added under control. Any ideas on how to parse this? Thanks. A: As far as just parsing is concerned, something like this in a loop: int pid; float idle, busy, user; if(fscanf(inputStream, "PID=%d IDLE=%f BUSY=%f USER=%f", %pid, &idle, &busy, &user)!=4) { /* handle the error */ } But as @Blrfl pointed out, the big problem is to avoid mixups when your application is reading the file and the others are writing to it. To solve this problem you should use a lock or something like that; see e.g. the flock syscall. A: Here is a code that will parse your file, and also account for the fact that your file might be unavailable (that is, fopen might fail), or being written while you read it (that is, fscanf might fail). Note that infinite loop, which you might not want to use (that's more pseudo-code than actual code to be copy-pasted in your project, I didn't try to run it). Note also that it might be quite slow given the duration of the sleep there: you might want to use a more advanced approach, that's more sort of a hack. int pid; float idle, busy, user; FILE* fid; fpos_t pos; int pos_init = 0; while (1) { // try to open the file if ((fid = fopen("myfile.txt","rw+")) == NULL) { sleep(1); // sleep for a little while, and try again continue; } // reset position in file (if initialized) if (pos_init) fsetpos (pFile,&pos); // read as many line as you can while (!feof(fid)) { if (fscanf(fid,"PID=%d IDLE=%f BUSY=%f USER=%f",&pid, &idle, &busy, &user)) { // found a line that does match this pattern: try again later, the file might be currently written break; } // add here your code processing data fgetpos (pFile,&pos); // remember current position pos_init = 1; // position has been initialized } fclose(fid); } A: Use fscanf in a loop. Here's a GNU C tutorial on using fscanf. /* fscanf example */ #include <stdio.h> typedef struct lbCfgData { int pid; double idle; double busy; double user; } lbCfgData_t ; int main () { // PID=4390 IDLE=0.000000 BUSY=2.000000 USER=2.000000 lbCfgData_t cfgData[128]; FILE *f; f = fopen ("myfile.txt","rw+"); for ( int i = 0; i != 128 // Make sure we don't overflow the array && fscanf(f, "PID=%u IDLE=%f BUSY=%f USER=%f", &cfgData[i].pid, &cfgData[i].idle, &cfgData[i].busy, cfgData[i].user ) != EOF; i++ ); fclose (f); return 0; }
doc_23534087
I'm really appreciate if anyone could help thank you! below are my code import React, {useState} from 'react' import { useSelector } from 'react-redux' import { Link } from 'react-router-dom' export const PostsList = () => { const posts = useSelector(state => state.posts) const renderedPosts = posts.map(posts => ( <article className="post-excerpt" key={posts.id}> <h3>{posts.title}</h3> <p className="post-content">{posts.content.substring(0, 100)}</p> <Link to={`/posts/${posts.id}`} className="button muted-button"> View Post </Link> </article> )) return ( <section className="posts-list"> <h2>Posts</h2> {renderedPosts} </section> ) } A: I think you are not getting any value from useSelector. I mean posts variable is initialed to undefined. That is why you are getting an error Cannot read properties of undefined (reading 'map'). Because map can not work on undefined.
doc_23534088
SELECT name FROM Table1 WHERE EXISTS (select .... from table2 Where param = @param AND ... AND ...) AND ... AND ... I would like the EXISTS statement (the part in bold) to be used only when @param has a value otherwise ignore it. I don't want to use dynamic SQL or temporary tables if possible. I am trying to use a CASE statement to work with the EXISTS statement but with not much luck. A: Using the OR in the WHERE clause will most likely by horrendously slow, especially if EXISTS. Other options... Union: only one will return rows SELECT name FROM Table1 WHERE EXISTS (select .... from table2 Where param = @param AND ... AND ...) AND ... AND ... UNION ALL SELECT name FROM Table1 WHERE @param IS NULL AND ... AND ... Conditional branch: IF @param2 IS NULL SELECT name FROM Table1 WHERE ... AND ... ELSE SELECT name FROM Table1 WHERE EXISTS (select .... from table2 Where param = @param AND ... AND ...) AND ... AND ... A: WHERE (@Param IS NULL OR EXISTS (SELECT .... )) Note that this isn't a guarantee - the query optimizer will do what it wants. But is should be smart enough to optimize the exists clause away.
doc_23534089
I recently restarted work on a Titanium Appcelerator App that had not been touched for 18 months or so. (I develop on Mac OS X Yosemite 10.10.15) After jumping through a few hoops i.e. installing latest Appcelerator Studio, latest Titanium SDK 5.1.0v20150929231927, iOS and Android SDK's, updating XCode version, importing the project to a new Workspace (as previous workspace wouldn't recognise the iOS SDK's). I can now build my app and run it in in the iOS Simulator... however none of the PNG's render (or JPG), and show the "missing image icon" instead. (Even though no app code has changed -- so environment or appcelerator issue). (see sample code below where I attempt to render some ImageView and Button controls) The only thing I can do to render an image is to use a GIF. However, this is not a solution as the images we use are not suitable to be converted to GIF due to quality. I have tried the following none of which allow me to render the PNG: Moving images to different folders (Images live in /resources/images/) Trying to use different PNG's Created a brand new test project that has the 2 test windows, this even comes with 2 PNG's for menu tab buttons, even they don't render. Attempt to render other images. Only GIF's will show, even the GIF's live in same folder as the PNG's that do not render. Ensure path's and files are referenced with the correct case. This all means my client cannot get a crucial update to their App. Anybody with a similar issue or resolution as my Mac is ready to be thrown out the window! Some sample code for a hello world test app can be found in this Attached is a sample code from a Hello World test app, PNG that I am trying to render and screenshot of the output from the sample code (to show the 2 x gif's showing but none else). // SAMPLE TEST CODE: Titanium.UI.setBackgroundColor("#000"); var tabGroup = Titanium.UI.createTabGroup(), win1 = Titanium.UI.createWindow({ title: "Tab 1", backgroundColor: "#000" }), tab1 = Titanium.UI.createTab({ icon: "KS_nav_views.png", title: "Tab 1", window: win1 }), label1 = Titanium.UI.createLabel({ color: "#999", text: "I am Window 1", font: { fontSize: 20, fontFamily: "Helvetica Neue" }, textAlign: "center", width: "auto" }), image1 = Titanium.UI.createImageView({ top: 50, left: 50, image: "KS_nav_ui.png" }), image2 = Titanium.UI.createImageView({ top: 100, left: 50, image: "/images/iconjpg.jpg" }), image3 = Titanium.UI.createImageView({ top: 150, left: 50, image: "/iphone/iconjpg.jpg" }), image4 = Titanium.UI.createImageView({ top: 200, left: 50, image: "/iconjpg.jpg" }), image5 = Titanium.UI.createImageView({ top: 250, left: 50, image: "/images/btn-meetings.gif" }), image6 = Titanium.UI.createImageView({ top: 300, left: 50, image: "/images/btn-meetings.png" }), testButton = Ti.UI.createButton({ backgroundImage: "/images/btn-meetings.png", height: 76, width: 150, top: 350, left: 50 }), testButton2 = Ti.UI.createButton({ backgroundImage: "/images/icongif.gif", height: 76, width: 150, top: 400, left: 50 }); win1.add(image1), win1.add(image2), win1.add(image3), win1.add(image4), win1.add(image5), win1.add(image6), win1.add(testButton), win1.add(testButton2), win1.add(label1); var win2 = Titanium.UI.createWindow({ title: "Tab 2", backgroundColor: "#fff" }), tab2 = Titanium.UI.createTab({ icon: "KS_nav_ui.png", title: "Tab 2", window: win2 }), label2 = Titanium.UI.createLabel({ color: "#999", text: "I am Window 2", font: { fontSize: 20, fontFamily: "Helvetica Neue" }, textAlign: "center", width: "auto" }); win2.add(label2), tabGroup.addTab(tab1), tabGroup.addTab(tab2), tabGroup.open(), function() { var e = require("ti.cloud"), i = "production" === Ti.App.deployType.toLowerCase() ? "production" : "development", t = Ti.App.Properties.getString("acs-username-" + i), a = Ti.App.Properties.getString("acs-password-" + i); i && t && a && e.Users.login({ login: t, password: a }, function(e) { "development" === i && (Ti.API.info("ACS Login Results for environment `" + i + "`:"), Ti.API.info(e)), e && e.success && e.users && e.users.length ? Ti.App.fireEvent("login.success", e.users[0], i) : Ti.App.fireEvent("login.failed", e, i) }) }(); Sample png that will not render in app Rendered output from sample code snippet, images shown are only the gifs, jpg and pngs are rendering with the missing icon A: I just ran the following using 5.1.1.GA with your image.. var win = Ti.UI.createWindow({ backgroundColor: 'white' }); win.add(Ti.UI.createImageView({ image: '/images/Jldsg.png' })); win.open(); And that worked fine for me: I have no idea why it wouldn't for you other than there's a lot of linting errors in your code: JSLint was unable to finish. line 68 column 17 Expected ';' and instead saw ','. win1.add(image1), win1.add(image2), win1.add(image3), win1.add(image4), win1.add(image5), win1.add(image6), win1.add(testButton), win1.add(testButton2), win1.add(label1); line 68 column 17 Unexpected ','. win1.add(image1), win1.add(image2), win1.add(image3), win1.add(image4), win1.add(image5), win1.add(image6), win1.add(testButton), win1.add(testButton2), win1.add(label1); A: I experienced a similar problem today, specifically with PNGs I used for tab icons too, which led me to this question. I left my computer for a while and in that time Node crashed. Appcelerator Studio was still running but I know that the build process involves Node scripts, so I quit Appcelerator Studio (and the iOS simulator) and restarted it — and the problem had disappeared. Like David, I could barely contain my frustration when correct code was not working. At least in my case, though, I was able to identify the culprit as something corrupted in the surrounding environment. A: I was having the same issue, with PNGs not rendering. Removing the <use-app-thinning>true</use-app-thinning> tag from my tiapp.xml file worked. They came right back. I am using TiSDK v5.4, OSX Yosemite with xCode 7.2.
doc_23534090
The question is: Is there any way I can easily share these saved Search Phrase and Scene Actions to anyone? If not, do I have to upgrade to neo4j Professional?
doc_23534091
console.log("hello"); return 10; }; var fun = new Function("fnOriginal()"); console.log(fun()); // prints undefined. console.log(fnOriginal()); // prints 10 How would I make fun() return and print 10 like fnOriginal()? A: Obviously, var fun = new Function("return fnOriginal()"); new Function("code") is the same as function() { code }. If the code's missing a return statement, the function won't return anything. A: Use following fnOriginal = function(){ console.log("hello"); return 10; }; var fun = new Function("return fnOriginal();"); alert(fun()); It will return 10.
doc_23534092
Here is my Model class in Model Folder: Model Class IMAGE-01 and here is my Validation Class (cs) in ViewModel Folder Validation Class IMAGE-02 When we run the project , validation not working. A: The namespace of your partial classes for Tbl_Users are in different namespaces (InventoryLogin.Models and InventoryLogin.ViewModel). These partial classes need to be in the same namespace for the data validation rules to be applied correctly to the class. A: Create Tbl_Users class in a separate file and change the namespace like this namespace InventoryLogin.Models { [MetadataType(typeof(InventoryLogin.ViewModel.LoginValidation))] public partial class Tbl_Users{} }
doc_23534093
repository.GetById[[IMyInterface]](id); What do I need to tell CommonDomain or EventStore to accomplish this? I believe my IConstructAggregates receives the Implementation Type of the aggregate that stored the events. Do i need to just keep my own map of ids. For example, say I have these agg roots : class AggRoot1 : IInterface1, IInterface2 {} class AggRoot2 : IInterface1, IInterface2 {} I already saved an aggregate1 instance having 'idFromAggRoot1'. Now I want to fetch like so: repository.GetById<IInterface1>(idFromAggRoot1); How can I know what I should create later since there are two implementors of IInterface1? AggRoot1? AggRoot2? IInterface1? Activator would bomb here so I know I need to implement IConstructAggregates but wonder if there is some other descriptor to tell me what the original commit agg root type was. A: The IConstructAggregates.Build() method can be implemented to return whatever type you need. In Common.AggregateFactory the default implementation creates an instance of the Aggregate via Activator.CreateInstance(type) as IAggregate. An own implementation might look like this: public class MyAggregateFactory : IConstructAggregates { public IAggregate Build(Type type, Guid id, IMemento snapshot) { if (type == typeof(IMyInterface)) return new MyAggregate(); else return Activator.CreateInstance(type) as IAggregate; } } Edit: The aggregate type is being stored in the event message's header as EventMessage.Header[EventStoreRepository.AggregateTypeHeader]
doc_23534094
Error LNK2019 unresolved external symbol "public: void __thiscall Strings::getType(class std::basic_string,class std::allocator >)" (?getType@Strings@@QAEXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function _main Project12 c:\Users\dan revie\documents\visual studio 2015\Projects\Project12\main.obj Strings.h #ifndef STRINGS_H #define STRINGS_H #include <vector> #include <string> using namespace std; //enum stringType { NONE = 0, SINGLEWORD = 1, PALINDROME, WITHDIGITS, OTHERS }; // 1.1 class Strings { public: // public members void getType(string phrase); // 1.4 int getSize(string phrase); // 1.4 //void checkValid(); private: // private members string phrase; // 1.2 int stringSize; // 1.3 vector<Strings> String_records; //2.1 }; #endif Strings.cpp #include "Strings.h" #include <iostream> void Strings::getType(string phrase) { cout << "Hello"; vector <char> palin1; vector <char> palin2; bool palinSwitch = true; // Palindrone Test // forward for (unsigned int i = 0; i < phrase.size(); ++i) { palin1.push_back(phrase[i]); } // backward for (unsigned int i = phrase.size(); i >= 0; --i) { palin2.push_back(phrase[i]); } // Comparison for palindrone for (unsigned int i = 0; i < phrase.size(); ++i) { if (palin1[i] != palin2[i]) { cout << "This is not a palindrone" << endl; palinSwitch = false; } } if (palinSwitch == false) { bool phraseSwitch = false; for (unsigned int i = 0; i < phrase.size(); ++i) { // PHRASE CASE----------------------------------------------------- if (isspace(phrase[i])) { // it is a phrase for (unsigned int i = 0; i < phrase.size(); ++i) { if (isdigit(phrase[i])) { phraseSwitch = true; } } if (phraseSwitch == true) { cout << "This is a phrase with digits" << endl; } else if (phraseSwitch == false) { cout << "This is a phrase without digits" << endl; } } // SINGLE WORD CASE------------------------------------------------ else // it is a single word { for (unsigned int i = 0; i < phrase.size(); ++i) { if (isdigit(phrase[i])) phraseSwitch = true; } if (phraseSwitch == true) { cout << "This is one word with digits" << endl; } else if (phraseSwitch == false) { cout << "This is one word without digits" << endl; } } } } } int Strings::getSize(string phrase) { int count = 0; for (unsigned int i = 0; i < phrase.size(); ++i) { if (!isspace(phrase[i])) ++count; } return count; } main.cpp #include "Strings.h" #include <iostream> int main() { string phrase; Strings s; cout << "Please enter a string to be analyzed: "; cin >> phrase; s.getType(phrase); //s.getSize(phrase); return 0; } If anyone could shed light on this it would be appreciated.
doc_23534095
What can I do to make this endeavour more energy-saving? A: Here is one approach for a right-to-left scrolling display. * *Create a custom view that can draw a 5x8 cell with its drawRect function. *Use 11 of these views to represent your display. Add them as subviews to an appropriately size view. *Every 1/25 of a second, move the 11 views and if the leftmost one has scrolled off the end, move it to the right side and update it with new letter data.
doc_23534096
import subprocess for file in ('folder_with_all_files'): a= subprocess.Popen(['my_exe_file.exe',file,'command'],shell=True, stderr=subprocess.STDOUT,stdout=subprocess.PIPE)\ communicate()[0] Normally in .py script all goes fine. but when i am trying to put those lines in tkinter, nothing happens. Part of Tkinter code: def Run(): for file in ('folder_with_all_files'): a= subprocess.Popen(['my_exe_file.exe',file,'command'],shell=True, stderr=subprocess.STDOUT,stdout=subprocess.PIPE)\ communicate()[0] button.configure(command=RUN) What i am doing wrong? and how to choose only specific extension of files that i want to use, example : .dat only Thanks EDIT: i have also tried: def Run(): filenames=os.listdir('folder_with_all_files') for file in filenames: a= subprocess.Popen(['my_exe_file.exe',file,'command'],shell=True, stderr=subprocess.STDOUT,stdout=subprocess.PIPE)\ communicate()[0] even when i am adding direct path to file doesnt work a= subprocess.Popen(['my_exe_file.exe','direct path/file','command'] but still doesnt work A: Problem was connected with files, i was showing only the path to the folder, and program didnt know which files should use. this line of code helped me to solve the problem, and get specific extension of the files: filenames= glob.glob(os.path.join('path',"*.xxx")) Cheers
doc_23534097
Is it possible to hide an action from "global action search"? A: No, what is the use case to hide is specifically there?
doc_23534098
I have a T4 template that I run in the debugging solution of a Domain Specific Language (DSL) that I'm building (let's assume it's called MyDsl :P). I have this as the template header: <#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" #> <#@ output extension=".txt" #> <#@ MyDsl processor="MyDslDirectiveProcessor" requires="fileName='Sample.mydsl'" #> The issue is caused by the custom directive, which prevents template generation because it "Failed to resolve type for directive processor MyDslDirectiveProcessor." When I remove the custom directive to try to see if the error depends on something else, I get an error in the first (template) directive, that ModelingTextTransformation does not exist in the namespace Microsoft.VisualStudio.TextTemplating.VSHost. This also happens with the automatically-added templates in this debugging solution, since they contain these same code lines. Help is appreciated :) P.S: I use Visual Studio 2012. Also, possible similar question here. A: So apparently I accidentally renamed my project name in DSL Explorer...I was probably naming something else and my computer went stupid on me without me realizing it.
doc_23534099
dataDIR P1 p1_file.mat P2 p2_file.mat I would like to recover a list of all the *.file These following lines work fine : dir([dataDIR 'P*/']) dir([dataDIR '*.mat']) dir([dataDIR '*myfile*.mat']) Then when I want multiple wildcard *, one at the subfolder and one at the file name, it does not find anything. dir([dataDIR 'P*/*.mat']) I would like to search directly in the folders and subfolders without having to use a loop. I am using Matlab R2015b and windows 7.