_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d14101
val
In stead of converting array of points into LineSegment collection, you can simply use PolyLineSegment. If the Binding just need to work intially (turn array of points to PointCollection of the PolyLineSegment intially, after that every changes made on the array of points won't trigger updating to the PolyLineSegment), you can do something like this: public MainWindow(){ InitializeComponent(); //set DataContext //Initialize your Points here ... //... DataContext = this; } public Point[] Points {get;private set;} Here is the converter used to convert the array of points to PointCollection: public class PointArrayToPointCollection : IValueConverter { object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { var points = value as IEnumerable<Point>; if(points != null) return new PointCollection(points); return Binding.DoNothing; } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } Then in XAML code: <Window x:Class="yourNameSpace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:yourNameSpace"/> <Window.Resources> <local:PointArrayToPointCollection x:Key="pointsToPointCollection"/> </Window.Resources> <Image> <Image.Source> <DrawingImage> <DrawingImage.Drawing> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Brush="Red" Thickness="1"></Pen> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <PathGeometry> <PathFigure> <PolyLineSegment Points="{Binding Points, Converter={StaticResource pointsToPointCollection}}"/> </PathFigure> </PathGeometry> </GeometryDrawing.Geometry> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> </Window> This answer may not exactly solve your problem but the idea of using PolyLineSegment should point you to the right direction. Update: Well I just thought you need some actual code run in real application. If you need just XAML code to test (or play with) right in KXAML editor, there is no reason for you to use XML data here. Because we need exactly a PointCollection for the Points property of a PolyLineSegment, so using any other kind of data will require some conversion (which can be done only via code behind). So we can just need to specify the PointCollection as an instance right in XAML code, it can be like this: <Page.Resources> <PointCollection x:Key="points"> <Point>0,30</Point> <Point>20,50</Point> <Point>40,10</Point> </PointCollection> </Page.Resources> <Grid> <Grid.Background> <DrawingBrush> <DrawingBrush.Drawing> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Brush="Red" Thickness="1"></Pen> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <PathGeometry> <PathFigure> <PolyLineSegment Points="{StaticResource points}"></PolyLineSegment> </PathFigure> </PathGeometry> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> </Grid.Background> </Grid> I understand that you may have a collection of more continuous points (which can shape a nearly curvy line). If you want some perfect curve, you can try playing with BezierSegment, PolyBezierSegment, QuadraticBezierSegment, PolyQuadraticBezierSegment like this: <Grid> <Grid.Background> <DrawingBrush Stretch="None" Viewport="0.2,0.2,0.6,0.6"> <DrawingBrush.Drawing> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Brush="Red" Thickness="1"></Pen> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <PathGeometry> <PathFigure> <PolyBezierSegment Points="10,10 200,150 300,30 320,10 330,-100 20,30"> </PolyBezierSegment> </PathFigure> </PathGeometry> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> </Grid.Background> </Grid> Or you can even try using the so-called mini Path language to define the PathGeometry like this: <Grid> <Grid.Background> <DrawingBrush Stretch="None" Viewport="0.2,0.2,0.6,0.6"> <DrawingBrush.Drawing> <GeometryDrawing Geometry="M0,0 C10,10 200,150 300,30 320,10 330,-100 20,30"> <GeometryDrawing.Pen> <Pen Brush="Red" Thickness="1"></Pen> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> </Grid.Background> </Grid> The mini path language works due to the implicit GeometryConverter. You can use this mini language for PathFigureCollection (converted by PathFigureCollectionConverter) and the Data property of a Path shape.
unknown
d14102
val
The trick is you are adding the traversed class upon the user action... after you have attached the event handler to all matches with jQuery (thus the new element isn't caught) I'd recommend a change of approach. Keep a class on the elements that can be toggled, and just slide up/down as needed using .toggle(); e.g. $('.collapsible').toggle(function(){ $(this).next('p.traversing').slideUp(); }, function(){ $(this).next('p.traversing').slideDown(); } ); Here's a demo: http://jsfiddle.net/7aVkx/1/ A: dont attach click handler multiple times instead use slideToggle() $(".traverse").click(function(){ $(this).next("p.traversing").slideToggle(); $(this).removeClass('traverse'); $(this).addClass('traversed'); }); A: you could do a live click bind. as you are adding this class to the paragraph after the load, it wont find a reference to it. $(".traversed").live("click",function(){}); Is there a reason why you want to change the class? An aternative might be to use slideToggle() and leave the class alone. A: You would have to use .live for this since you (in your click handlers) constantly adding/removing classes that are used to select elements to handle. Doing just: $(".traverse").click(....) Doesn't "track" future elements that may have "traverse" class. It should work fine if you will use: $(".traverse").live("click", ....) A: $('p.traversing').slideUp(); $(".traverse").click(function() { $(this).removeClass('traverse').addClass('traversed'); $(this).next("p.traversing").slideToggle(); }); $(".traversed").click(function() { $(this).next("p.traversing").slideToggle(); $(this).removeClass('traversed').addClass('traverse'); }); A: You're setting the handler on all elements of class .traversed, but at that time your desired elements don't have that class. Use .live instead:* $(".traverse").live('click', function(){ $(this).next("p.traversing").slideDown(); $(this).removeClass('traverse'); $(this).addClass('traversed'); }); $(".traversed").live('click', function(){ $(this).next("p.traversing").slideUp(); $(this).removeClass('traversed'); $(this).addClass('traverse'); }); Live demo. * "Description: Attach a handler to the event for all elements which match the current selector, now and in the future."
unknown
d14103
val
It would be better to do this on the client side using JavaScript. You can use something like this: http://code.google.com/p/ie6-upgrade-warning/ You can tweak it to whatever you want. If your goal is simply to make sure the user is not in compatibility mode, then you can use either the meta tag or http header version of X-UA-COMPATIBLE: <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" > </head> <body> <p>Content goes here.</p> </body> </html>
unknown
d14104
val
BufferedImage bufferedImage; //assumed that you have created it already ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage,"jpg", byteStream); byte[] byteArray = byteStream.toByteArray();
unknown
d14105
val
From the jQuery UI documentation, you can use the position option but it defaults to center (as shown in your example). Default: { my: "center", at: "center", of: window } Specifies where the dialog should be displayed when opened. The dialog will handle collisions such that as much of the dialog is visible as possible. The following code should suffice by positioning it to the right bottom with an offset for your editButton height, add this to your options: draggable: false, position: { my: "right bottom", at: "right bottom-44" }, See this updated fiddle. A: What's the purpose of the jQuery UI dialog? If you strip it out and use plain HTML/CSS the whole thing becomes a lot easier to manage. If that chat button has to move for some reason, or becomes scrollable, you're back to "stuck wrestling with this thing that's generally meant to take over the page and sit in the center"! Here's a sample of another way. You probably want to run it in "Full Page" so the dialog doesn't get truncated. /* JS only to toggle a class on the container */ $(document).on("click", ".editButton, .chat-cancel", toggleChat); function toggleChat(){ var $chatWindow = $('.chat-area'); $('#comment').val(''); $chatWindow.toggleClass('visible'); } /* Terrible CSS but hopefully you'll get the idea. 1), 2) and 3) are the main bits to take away. The rest is me faffing around. */ /* 1) By default, #dialogContent is hidden. */ #dialogContent { height: 0px; margin-bottom: 30px; overflow: hidden; position: relative; /* use CSS transitions to show it */ transition: height 0.5s ease-in-out; } /* 2) When someone clicks "chat" we add the class 'visible' to it*/ .visible #dialogContent { display: block; height: 270px; } .chat-area, .chat-area * { box-sizing: border-box; } /* 3) Fix the entire container to the bottom right and then position the needed elements within it */ .chat-area { bottom: 0; right: 10px; position: fixed; width: 200px; font-family: helvetica, arial, sans-serif; padding: 10px; background-color: green; } #comment { font-family: helvetica, sans-serif; font-size: 12px; margin-bottom: 4px; padding: 4px; } .editButton { background: green; bottom: 0; color: white; cursor: pointer; height: 30px; right: 0; padding: 0 10px 7px 10px; position: absolute; width: 100%; } .visible .editButton:before { content: "Close "; width: auto; } .chat-area h2 { color: #fff; display: inline-block; font-size: 15px; margin: 0 0 4px 0; } header .chat-cancel { color: #fff; display: inline-block; float: right; cursor: pointer; } button { background: #3498db; background-image: linear-gradient(to bottom, #999999, #7a7a7a); border: 0 none; border-radius: 5px; color: #ffffff; cursor: pointer; font-family: Arial; font-size: 15px; padding: 5px 10px; text-decoration: none; } button:hover { background: #3cb0fd; background-image: linear-gradient(to bottom, #555555, #444444); text-decoration: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="chat-area"> <div id="dialogContent" title="This is a dialog box"> <header> <h2> Chat Dialog Header</h2> <span class="chat-cancel">X</span> </header> <textarea rows="14" cols="40" name="comment" id="comment"></textarea> <button class="chat-cancel"> Cancel </button> <button class="chat-save" type="submit"> Save </button> </div> <div class="editButton">Chat</div> </div>
unknown
d14106
val
RequestDispatcher is an interface and we can't create an object obviously with that. So, it is an object of the class that implements RequestDispatcher that you get when the calling getRequestDispatcher(). You need to have the source code of the Servlet implementation(this depends on the container that you are using) to see the class that is providing the implementation. A: You are right, RequestDispatcher is an interface you we can not create an object of this. Now see: request.getRequestDispatcher('somePage'); This method returns a class which implements RequestDispatcher and that class is totally depends upon the server which you are using. For Ex. In case of Glass Fish server, it returns org.apache.catalina.core.ApplicationDispatcher object and it has already told by @Pshemo.
unknown
d14107
val
Something like: [p,f,e] = fileparts ( ALLEEG(data_set).filename ); newFilename = sprintf ( '%s_pre.%s', f, e ) pre = ALLEEG(data_set).pre; save ( newFilename, 'pre' ); newFilename = sprintf ( '%s_post.%s', f, e ) post = ALLEEG(data_set).post; save ( newFilename, 'post' );
unknown
d14108
val
The trick that solves 90% of the issues since Visual Studio 2002 ;-) manually delete all bin and obj folders in your solution. A: Can you post your project file (.csproj)? You need to have the correct attributes in all your project files. The nulls below are not required and neither is C# 8. But 3.1 must be specified in the project files. This is the setup I use on my current core 3.1 projects: <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <LangVersion>8.0</LangVersion> <Nullable>enable</Nullable> <NullableContextOptions>enable</NullableContextOptions> </PropertyGroup>
unknown
d14109
val
The Windows version has been released by ApacheHaus recently. They have this module for both Apache 2.2 and 2.4 (x86 and x64 both). here is the link https://www.apachehaus.net/modules/mod_auth_token/
unknown
d14110
val
I'm looking for this tools too but I don't found any good. I try logger and there're fine for me. scala-logger: Simple Scala friendly logging interface. Logback Project for backend
unknown
d14111
val
If Region and Department fields have mapping in data set, then use Filters instead of a parameter. For Department Filter check the option "Only Relevant Values" in filter settings. Hope this works!
unknown
d14112
val
Unfortunately, there is no way to enforce that an array contains a specific number of something. The closest you can do is to enforce that something exists (1 to n) in an array. If "customItem1" is always the first item, it can be done. { "type": "array", "anyOf": [ { "items": [ { "$ref": "#/definitions/customItem1" } ], "additionalItems": { "$ref": "#/definitions/customItem2" }, }, { "items": { "$ref": "#/definitions/customItem2" } } ], "definitions": { "customItem1": { "type": "string" }, "customItem2": { "type": "boolean" } } }
unknown
d14113
val
Use a cell instead of an array. fileNames = {'fileName1.mat', ..., 'fileName_n.mat'}; Your code is in principle a string cat, giving you just one string (since strings are arrays of characters). for i=1:n load(fileNames{i}) ... end Use { and } instead of parentheses.
unknown
d14114
val
You are specifically picking numbers where there are a reminder. You can just loop while there is a reminder instead: } while (num1 % num2 != 0); However, you won't need to loop at all. If you pick the second operand and the answer, you can calculate the first operand: num2 = (int) (Math.random() *10); compAnswer = (int) (Math.random() * 10); num1 = num2 * compAnswer;
unknown
d14115
val
The CheckBox column of the DataGridView control is implemented by the DataGridViewCheckBoxCell class, and this class has a delay function, that is, when the user selects a CheckBox in the DataGridView, it will delay updating it to the data source for a period of time. You just need to add an event about CurrentCellDirtyStateChanged to get the state immediately private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e) { if (this.dataGridView1.IsCurrentCellDirty) { this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); } } Best used with CellValueChanged: private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { int total = 0; for (int i = 0; i <= dataGridView1.RowCount - 1; i++) { Boolean chek = Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value); if (chek) { total += 1; } } total *= 50; textBox1.Text = total.ToString(); }
unknown
d14116
val
Option 1 Use blockingFirst() to get data via a blocking call: val allPosts = postsRemoteDataSource.getAllPosts().blockingFirst() assertEquals(10, allPosts.size) Note that making blocking calls on a Flowable is usually considered bad practice in production code, but it's safe to do in tests since your object under test is backed by a mock. Option 2 Obtain a TestSubscriber by calling test() and assert on it: val subscriber = postsRemoteDataSource.getAllPosts().test() subscriber.assertValueCount(10)
unknown
d14117
val
I had to use CASE, along with some modifications to make it run on heroku's postgres server. start_date = (Time.now - 10.days) end_date = Time.now joins("left join impressions on impressions.impressionable_id = items.id and impressions.impressionable_type = 'Item'") .select("count(distinct(case when (impressions.created_at BETWEEN '#{start_date}' AND '#{end_date}') then ip_address end)) as counter, impressionable_id, items.gender, items.title, items.id, items.image") .group('items.id', 'impressions.impressionable_id') .order("counter desc")
unknown
d14118
val
I believe the collection is immutable. You can create a copy of the collection. When you find the elements you want, add them to the collection you have deep cloned. See if you can ToList() the collection to create a copy of your target collection. Also as the code is not in your question, have you considered using InsertAfter() on the parent node or AppendChild() once you have created your elements?
unknown
d14119
val
Did you try to * *set display only item's template to "optional" (instead of e.g. "optional - floating"), and then *set its "custom attributes" property (which is in the "Advanced" set of properties) to e.g. style="width:300px" Illustration:
unknown
d14120
val
Well, I decided to use only 4 values in buffer structure, it seems it works well. In the end of the code there is a dataBuffer check. Now I need to write a printBuffer function just to show values in dataBuffer from HEAD to TAIL but I noticed a problem: everytime I write a values in the buffer, the difference between HEAD and TAIL is always 1 (as I understood when buffer is empty, size = 8 and there are only 6 values in data[], it has to be shown like bufferData[0] = 1 ... bufferData[5] = 6 but as result in works incorrectly.Could you explain me please how to bring the function printBuffer to acceptable form? Thanks. Here is my code (it works and there are checking everywhere): #include <stdio.h> #include <stdlib.h> #include <string.h> struct ringBuffer { int *bufferData; int head; int tail; int size; }; void bufferFree(struct ringBuffer *buffer) { free(buffer->bufferData); } void bufferInitialization(struct ringBuffer *buffer, int size) { buffer->size = size; buffer->head = 0; buffer->tail = 0; buffer->bufferData = (int*)malloc(sizeof(int) * size); } void printBuffer(struct ringBuffer *buffer, int i, int size) { printf("Values from HEAD to TAIL: "); if (buffer->head == buffer->tail) { printf("Head and tail are equals\n"); } else { printf("bufferData[%d] = %d\n", i, buffer->bufferData); } } int pushBack(struct ringBuffer *buffer, int data) { buffer->bufferData[buffer->tail++] = data; if (buffer->tail == buffer->size) { buffer->tail = 0; } return 0; } int popFront(struct ringBuffer *buffer) { if (buffer->head != buffer->tail) { buffer->head++; if (buffer->head == buffer->size) { buffer->head = 0; } } return 0; } int main(int argc, char* argv[]) { struct ringBuffer buffer; int size = 8; int data[] = { 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30 }; // 20 values int dataSize = sizeof(data)/sizeof(data[0]); /* Test implimention with 1 element in dataBuffer */ bufferInitialization(&buffer, size); printf("Head : %d - Tail: %d\n", buffer.head, buffer.tail); pushBack(&buffer, 5); printf("Head : %d - Tail: %d\n", buffer.head, buffer.tail); popFront(&buffer); printf("Head : %d - Tail: %d\n", buffer.head, buffer.tail); printf("\nnumElements in data = %d : bufferSize = %d\n\n", dataSize, size); bufferFree(&buffer); /* Implimention with dada[] */ printf("INITIALIZATION\n"); bufferInitialization(&buffer, size); printf("Head : %d - Tail: %d\n", buffer.head, buffer.tail); /* pushBack call */ printf("\nPUSHBACK\n\n"); for (int i = 0; i < dataSize; i++) { pushBack(&buffer, data[i]); printf("Head : %d - Tail : %d :: Data = %d (data[%d]) \n", buffer.head, buffer.tail, data[i], i); /*for (int k = buffer.head; k<=buffer.tail; k++) { // Print methode from head to tail printBuffer((ringBuffer*)buffer.bufferData, i, size); }*/ popFront(&buffer); } popFront(&buffer); printf("Head : %d - Tail : %d :: (popFront)\n", buffer.head, buffer.tail); /* bufferData check */ printf("\nbufferData check:\n"); for (int i = 0; i < size; i++) { printf("[%d] = %d ", i, buffer.bufferData[i]); } printf("\nHead : %d - Tail : %d\n", buffer.head, buffer.tail); bufferFree(&buffer); system("pause"); return 0; } A: #include <stdio.h> #include <stdlib.h> #include <string.h> struct ringBuffer { char *bufferData; void *bufferEnd; int head; int tail; int size; int used; int capacity; // "Π²ΠΌΠ΅ΡΡ‚ΠΈΠΌΠΎΡΡ‚ΡŒ" }; void bufferInitialization(struct ringBuffer *buffer, int capacity, int size) { buffer->bufferData = (char*)malloc(capacity * size); if (buffer->bufferData == 0) { buffer->bufferEnd = (char *)buffer->bufferData + capacity * size; } buffer->capacity = capacity; buffer->used = 0; buffer->size = size; buffer->head = *buffer->bufferData; buffer->tail = *buffer->bufferData; } void bufferFree(struct ringBuffer *buffer) { free(buffer->bufferData); } int pushBack(struct ringBuffer *buffer, char *data) { if (buffer->used == buffer->capacity) { printf("Capacity error\n"); buffer->bufferData = 0; //?? } memcpy((ringBuffer*)buffer->head, data, buffer->size); buffer->head = buffer->head + buffer->size; if (buffer->head == (char)buffer->bufferEnd) { buffer->head = (char)buffer->bufferData; } buffer->used++; return 0; } int popFront(struct ringBuffer *buffer, char *data) { if (buffer->used == 0) { printf("Buffer is clear\n"); } memcpy(data, (ringBuffer*)buffer->tail, buffer->size); buffer->tail = (char)buffer->tail + buffer->size; if (buffer->tail == (char)buffer->bufferEnd) { buffer->tail = (char)buffer->bufferData; } buffer->used--; return 0; } int main() { struct ringBuffer buffer; int size = 6; int capacity = 10; bufferInitialization(&buffer, capacity, size); char *data[] = { "1" , "2", "3", "4" , "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" }; for (int i = 0; i < size; i++) { printf("Push: data[%d] = %d\n", i, *data[i]); pushBack(&buffer, (char*)data[i]); } printf("\n"); for (int i = 0; i < size; i++) { printf("PushBack: queue[%d] = %s\n", i, (ringBuffer*)popFront(&buffer, (char*)data[i])); // !!! } printf("\n"); for (int i = 0; i < size; i++) { printf("PopFront: data[%d] = %s : %s\n", i, *data[i]); pushBack(&buffer, (char*)data[i]); } printf("\n"); system("pause"); return 0; } A: This is a sample without memcpy. So you cann see the problem with the buffer end while copying. It's not tested but shows how you can go on. It's a char ringbuffer, so you have to write chars. There is no check for \0, so your size must include them if you read and write "strings". #include <stdio.h> #include <stdlib.h> #include <string.h> struct ringBuffer { char *bufferData; char *head; char *tail; char *end; int size; int free; }; void bufferInitialization(struct ringBuffer *buffer, int size) { buffer->size = size; buffer->used = 0; buffer->head = buffer->tail = buffer->bufferData = malloc(size); buffer->end = buffer->bufferData + size; } int pushBack(struct ringBuffer *buffer, char *data, int size) { if(size > buffer->size - buffer->used) return -1; for( ; size>0 && buffer->used < buffer->size; buffer->used++, size--) { *buffer->head = *data; buffer->head++; data++; if(buffer->head == buffer->end) buffer->head = buffer->bufferData; } return 0; } int popFront(struct ringBuffer *buffer, char *data, int size) { if(size > buffer->used) return -1; for( ; size>0 && buffer->used > 0; buffer->used--, size--) { *data = *buffer->tail; buffer->tail++; data++; if(buffer->tail == buffer->end) buffer->tail = buffer->bufferData; } return 0; }
unknown
d14121
val
Instead of copying the range you'll need to create a value array that matches the target structure. In lieu of sample data I'll play with the following toy example: Sheet "Source": A B C 1 1 2 Sheet "Target": _ A B C D 1 2 3 4 5 6 7 8 B E C A function copyOver() { const source = SpreadsheetApp .getActiveSpreadsheet() .getSheetByName("Source") .getDataRange() .getValues(); const target = SpreadsheetApp .getActiveSpreadsheet() .getSheetByName("Target"); const headerRow = 8; const targetHeaders = target.getDataRange().getValues()[headerRow - 1]; const sourceHeaders = source[0]; const sourceValues = source.slice(1); const columnLookup = targetHeaders.map(h => sourceHeaders.indexOf(h)); function buildRow(row) { return columnLookup.map(c => c == -1 ? "" : row[c]); } const output = sourceValues.map(buildRow); if (output.length > 0) { target .getRange(headerRow + 1, 1, output.length, output[0].length) .setValues(output); } } A: First of all try yelling at users and making them understand that they may not mess with sheets with active programming (This is successful 75% of the time). Otherwise, you'll want to check your columns before you copy. function OPupdates() { var sheetfrom2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Helper Sheet'); //this contains source info var sheetto2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Plan');//sheet into which the new source data is copied var statuscolumn = -1; var headerWewant = "STATUS";//modify for the correct column name var targetSheetHeader = sheetto2.getRange(1,1,1,sheetto2.getLastColumn().getValues(); for (var j=0; i<targetSheetHeader[0].length;i++) { if (data[0][j] == headerWeWant) statuscolumn = j+1; } if (statuscolumn == -1) {console.error("Couldn't find the status column"; return;} sheetfrom2.getRange(2, 2, sheetfrom2.getLastRow(), 1).copyTo(sheetto2.getRange(8,statuscolumn, sheetfrom2.getLastRow()-2, 1), { contentsOnly: true }); } But training the users to go in fear of your wroth is a better long term strategy ;).
unknown
d14122
val
I feel the approach taken by you can be made better. You can at all not use a tablelayout, and still get the feel of using a table layout. A simple approach, your tablerow is nothing but a simple row, and similar rows make a layout, ultimately giving you the look n feel of a tablelayout. Why not creating a custom linearlayout with two or three textviews inside it with divider views added. You can inflate this layout in a customadapter class extending BaseAdapter, and in the getView method simply inflate the layout and using a viewholder class you can populate the adapter.
unknown
d14123
val
error[E0161]: cannot move a value of type `dyn Element<T>` --> src/lib.rs:12:35 | 12 | self.successor = Box::new(self.successor.append_item(item)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the size of `dyn Element<T>` cannot be statically determined The issue here is that fn append_item(self, item: T) takes self by value, but in this case self has type dyn Element<T>, which is unsized and can therefore never be passed by value. The easiest solution here is to just take self: Box<Self> instead. This means that this method is defined on a Box<E> instead of directlThis will work perfectly fine with trait objects like dyn Element<T>, and it does not require the type to be sized. (Additionally, in the updated code below, I've changed the return type to Box<Node<T>> for convenience, but this is not required per se, just a bit more convenient.) trait Element<T> { fn append_item(self: Box<Self>, item: T) -> Box<Node<T>>; } impl<T> Element<T> for Node<T> { fn append_item(mut self: Box<Self>, item: T) -> Box<Node<T>> { self.successor = self.successor.append_item(item); self } } impl<T> Element<T> for End { fn append_item(self: Box<Self>, item: T) -> Box<Node<T>> { Box::new(Node { data: item, successor: self }) } } [Playground link] error[E0310]: the parameter type `T` may not live long enough --> src/lib.rs:12:26 | 12 | self.successor = Box::new(self.successor.append_item(item)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds | The issue here is that dyn Trait has an implicit lifetime. In reality, it's dyn '_ + Trait. What exactly that lifetime is depends on the context, and you can read the exact rules in the Rust reference, but if neither the containing type nor the trait itself has any references, then the lifetime will always be 'static. This is the case with Box<dyn Element<T>>, which really is Box<dyn 'static + Element<T>>. In other words, whatever type is contained by the Box must have a 'static lifetime. For this to be the case for Node<T>, it must also be that T has a 'static lifetime. This is easy to fix, though: just follow the compiler's suggestion to add a T: 'static bound: impl<T: 'static> Element<T> for Node<T> { // ^^^^^^^^^ // ... } [Playground link) A: Frxstrem already elaborated how to get around the need to move by using Box<Self> as receiver. If you need more flexibility in the parameter type (i.e. be able to hold on to references as well as owned types) instead of requiring T: 'static you can introduce a named lifetime: trait Element<'a, T: 'a> { fn append_item(self: Box<Self>, item: T) -> Node<'a, T>; } struct Node<'a, T: 'a> { data: T, successor: Box<dyn Element<'a, T> + 'a>, } impl<'a, T: 'a> Element<'a, T> for Node<'a, T> { fn append_item(self: Box<Self>, new_data: T) -> Node<'a, T> { Node { successor: Box::new(self.successor.append_item(new_data)), ..*self } } } struct End; impl<'a, T: 'a> Element<'a, T> for End { fn append_item(self: Box<Self>, data: T) -> Node<'a, T> { Node { data, successor: self, } } }
unknown
d14124
val
In the access_control of your security add: - { path: ^/js/, role: IS_AUTHENTICATED_ANONYMOUSLY }
unknown
d14125
val
You probably can't do it. Web browsers explicitly block this behavior because users don't expect it and find it annoying. See Google's Chrome blog post, Mozilla's Firefox documentation, and Apple's WebKit/Safari blog post about these rules. If you will be deploying your app in a corporate environment where you have control over the web browsers, you can probably configure the browsers on the computers to allow autoplay for your site. See the links above for details.
unknown
d14126
val
Assuming there will be a lot of products, it will be too much to download to the client in order to filter using Angular. It doesn't scale very well. As the list of products gets bigger and bigger, it will be less and less performant. The better way would, generally, be to let MongoDB do the filtering for you. It's very fast. But, you can control the filtering from Angular by posting to the server the filtering term you want on the endpoint used for that method of filtering, for example, using the http module http.post('/api/filter/' + methodOfFiltering, { 'term': termtoFilterBy }, function(dataReturned) { // use dataReturned to do something with the data }); Put this in an angular service method, so you can inject it into any of your controllers/components. Create an endpoint that will use the method and the keyword in the mongoose query. I'm assuming that you're using Express for your server routes. app.post('/api/filter/:method', function(req, res) { var method = req.params.method; var termToFilterBy = req.body.term; productSchema.find({method: termToFilterBy}, function(err, products) { res.send(products); }); }); Let me know if this helps.
unknown
d14127
val
You may use a negative lookahead to exclude specific matches: \$\{(?!pageContext\.).*?\} ^^^^^^^^^^^^^^^^ The (?!pageContext\.) lookahead will fail all matches where { is followed with pageContext.. Also, you can use [^{}]* instead of .*?. See the regex demo Pattern details: * *\$ - a literal $ *\{ - a literal { *(?!pageContext\.) - fail the match if a pageContext. follows the { immediately *.*? - any 0+ characters other than a newline (or [^{}]* - zero or more characters other than { and }) *\} - a literal }. NOTE: If you need to avoid matching any ${...} substring with pageContext. anywhere inside it, use \$\{(?![^{}]*pageContext\.)[^{}]*\} ^^^^^^^^^ Here, the [^{}]* inside the lookahead will look for pageContext. after any 0+ chars other than { and }. A: Look aheads or look behinds are expensive. You should prefer the optional match trick: \$\{(?:.*pageContext.*|(.*))\} Live Example To avoid confusion let me specify that this will match any string with a "${" prefix and a "}" suffix, but if that string contained "pageContext" the 1st capture will be empty. If the 1st capture is non-empty you have a string matching your criteria.
unknown
d14128
val
Use Xpath-contains instead of string-contains * *Shorten your xpath by using //tag[contains(@attr, 'string')] for example //spans[contains(@class, 'MuiCheckbox-checked')] Code Solution(Level-by-Level) * *First, select high-level elements *Then, find your second-level elements(i.e. Button)
unknown
d14129
val
I think you have cited the encoding in too many different ways. You should only need to set it once. Try this: var wordApp = new Word.Application(); var doc = wordApp.Documents.Open("input.doc"); doc.Fields.Update(); // ** this is the new line of code. Console.WriteLine(doc.TextEncoding); // msoEncodingWestern doc.WebOptions.Encoding = MsoEncoding.msoEncodingUTF8; doc.SaveAs2("output.htm", WdSaveFormat.wdFormatFilteredHTML); doc.Close(); wordApp.Quit(); A: I solved the problem with the following: var from = ((char)0xF0AE).ToString(); var to = ((char)0x2192).ToString(); doc.Content.Find.Execute(from, ReplaceWith: to, Replace: WdReplace.wdReplaceAll); It's not a generalized solution, i.e. this method only handles a right arrow case and another method needs to be defined if a left arrow is an issue.
unknown
d14130
val
You can't directly get the size of the uncompressed file, but you can use seek for it. Create an object from the file and try to seek to the first byte. If you can seek, then your file is at least 1 byte in size, otherwise it is empty. #!/usr/bin/env perl use strict; use warnings; use IO::Uncompress::Gunzip; use Fcntl qw(:seek); my $u = IO::Uncompress::Gunzip->new('readme.gz'); if ( $u->seek(1, SEEK_CUR) ) { print "Can seek, file greather than zero\n"; } else { print "Cannot seek, file is zero\n"; } A: You could use IO::Compress::Gzip which comes with Perl 5.10 and above (or download it via CPAN). And use that to read the file. However, you could just do a stat on the file and simply see if it contains only 26 bytes since an empty file will consist of just a 26 byte header. I guess it simply depends what you're attempting to do. Are you merely trying to determine whether a gzipped file is empty or did you plan on reading it and decompress it first? If it's the former, stat would be the easiest. If it's the latter, use the IO::Compress::Gzip module and not a bunch of system commands to call gzip. The IO::Compress::Gzip comes with all Perl distributions 5.10 and greater, so it's the default way of handling Zip. A: To check the content of a compressed tar-file, use tar -ztvf file.tgz To list content of a .gz-file, use gzip --list file.gz Wrap that in perl and check the uncompressed field in the output $ gzip --list fjant.gz compressed uncompressed ratio uncompressed_name 26 0 0.0% fjant
unknown
d14131
val
you don't keep the number the use enter in the while loop. you need to input the readline to a variable. var num = Console.Readline(); sum += num; //parse first A: Inside your while loop you need to update num: int num = Convert.ToInt32(Console.ReadLine()); while (Console.ReadLine() != "OK") { num = Int32.Parse(Console.ReadLine()); sum += num; } Also just as a note, if you need your program to be a little safer, you can you use the following: int num; if(Int32.TryParse(Console.ReadLine(), out num)) { //do something.. } else { //do something else.. like end program, throw exception etc. } Int32.TryParse: Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded This way you can do something in the instance that the input string was not a valid conversion. Example: if someone input cat, which can not be converted to an int, it would crash your program without the TryParse. A: You need to input the number once per iteration, and store it each time. So each value retrieved from Console.ReadLine() needs to be captured in an assignment statement, then converted to a number if it is not "OK". I think you're after this: int sum = 0; string input; Console.WriteLine("Enter number: "); while ((input = Console.ReadLine()) != "OK") { int inputNum = Convert.ToInt32(input); sum += num; Console.WriteLine("Enter number: "); } The statement (input = Console.ReadLine() assigns the user input to the input variable, then the assignment statement returns the value of input. Then that value is compared against OK. An alternative way to get input, then check it is: Console.WriteLine("Enter number: "); input = Console.ReadLine() while (input != "OK") { ... Console.WriteLine("Enter number: "); input = Console.ReadLine() } A: int sum = 0; Console.WriteLine("Enter number:"); int num = int.Parse(Console.ReadLine()); while (sum< num) { sum++; } Console.WriteLine(sum);
unknown
d14132
val
Try this, using .isin method for Seires: mask = ~df['label'].isin(df['label2']) df_output = df[mask] print(df_output) Output: label label2 0 A C 1 B D 2 G O A: You can use drop to remove duplicate label between 2 columns: df.drop(df[df['label'].isin(df['label2'])].index, inplace=True) print(df) # Output: label label2 0 A C 1 B D 2 G O
unknown
d14133
val
Does q unify with a single element list? Yes. (== (list x) q) is the same as (== q (list x)). Both q and x are fresh before the execution of this unification goal (and q does not occur in (list x)). Afterwards, it is recorded in the substitution that the value of q is (list x). No value for x is recorded. Is the result (_0) because q unifies with the fresh variable x (even if it's in a list) or because it doesn't unify with anything at all? Or would in that case the result have been ()? No, q does not unify with x, but rather with a list containing x. When the final value of the whole run* expression is returned, the variables are "reified", replaced with their values. x has no value to be replaced with, so it is printed as _0, inside a list as it happens, which list is the value associated with q. The value of (run* q ...) is a list of all valid assignments to q, as usual. There is only one such association, for the variable q and the value (list x). So ( (_0) ) should be printed as the value of the (run* q ...) expression -- a list of one value for q, which is a list containing an uninstantiated x, represented as a value _0.
unknown
d14134
val
when(myClass.myMethod(Mockito.any(SecondClass.class))).thenReturn(null); A: You can use Mockito.any(SecondClass.class) or (SecondClass)any() A: Actually the best way to do it is doReturn(object).when(myClass).myMethod(???); in ??? you have some possibilities. * *You can pass a given object and then you wait for an especific one *Or you can pass Mockito.any(Clazz.class) and then you will accept any object of that kind
unknown
d14135
val
If you are asking how to open YAML files, then you can use some common editors like NotePad++ in windows or vim in linux. If your question is about running the compose yaml file, then run this command from the directory where compose file is residing: docker-compose -f {compose file name} up You can avoid -f if your filename is docker-compose.yml A: To manage .yml files you have to install and use Docker Compose. Installation instructions can be found here: https://docs.docker.com/compose/install/ After the installation, go to your docker-compose.yml directory and then execute docker-compose up to create and start services in your docker-compose.yml file. If you need more information, take a look to Docker Compose docs: https://docs.docker.com/compose
unknown
d14136
val
It should work ideally, it is best if you can see which style is applying on control using inspect element. May be it is overrided by form-control class. You might have to use ! Important in class.
unknown
d14137
val
Regardless the fact T-SQL has more functionality than plain SQL, in general data warehousing you have two main approaches: * *Put business logic closer to the data. This way you develop lots of T-SQL functions and apply many optimizations available there to improve performance of your ETL. Pros is greater performance of your ETL and reports. But cons are the cost of making changes to the code and migration cost. The usual case for growing DWH is migration to some of the MPP platforms. If you have lots of T-SQL code in MSSQL, you'll have to completely rewrite it, which will cost you pretty much money (sometimes even more than the cost of MPP solution + hardware for it) *Put business logic to the external ETL solution like Informatica, DataStage, Pentaho, etc. This way in database you operate with pure SQL and all the complex logic (if needed) is the responsibility of your ETL solution. Pros are simplicity of making changes (just move the transformation boxes and change their properties using GUI) and simplicity of changing the platform. The only con is the performance, which is usually up to 2-3x slower than in case of in-database implementation. This is why you can either find a tutorial on T-SQL, or tutorial on ETL/BI solution. SQL is very general tool (many ANSI standards for it) and it is the basic skill for any DWH specialist, also ANSI SQL is much simpler as it does not have any database-specific stuff
unknown
d14138
val
Take a look at ngrok. The basic version is free. ngrok allows you to expose a web server running on your local machine to the internet. Just tell ngrok what port your web server is listening on.
unknown
d14139
val
We can use mapply to get the corresponding element of 'lst' based on the index in 'ind'. mapply(`[`, lst, ind) #[1] 1 2 3
unknown
d14140
val
I might personally go along with stripping anything resembling the script tag, as such an approach would provide an extra layer of security against validation bugs in your Markdown parser. But your mileage may vary depending on your application. If you do need to encode, see https://stackoverflow.com/a/236106/131903 for a reasonable encoding approach (that is, use \x3c to replace the less-than sign). This will work: <html> <script> alert("1 \x3c/script> 2"); </script> </html>
unknown
d14141
val
You are currently using an undefined variable $prev_month, and have forgotten the "date" parameter in the URL. Is it possible you meant to use $sun_prev_month or $print_date?
unknown
d14142
val
It is possible to boot the device without the external storage, which allows you to test what happens when you do not get the Environment.MEDIA_MOUNTED state. Just create an AVD with an existing SD card .iso file. Then, rename the file. When you load this AVD, it will work just fine but it won't have the external storage loaded. This allows you to test your logic for when the external media isn't mounted. I created a separate AVD for testing the no-external-storage scenario, but you could rename the .iso file and restart the emulator if you want to run both tests on the same one. I did try the umount method above, and while it's useful (as Torp mentions, it's a harsher test), the system still thinks the SD card is mounted and my alternate logic isn't run. A: Hmm i just started an emulator, got a root shell with adb shell and started unmounting things. It seemed to work just fine. Had to do umount /mnt/sdcard/.android_secure and then umount /mnt/sdcard on a 2.3.3 VM but it seemed to work. Check what's on your VM with mount before umounting. Of course this is a much "harsher" solution than umounting from the Android UI - kind of simulates an user that removes the sd card without umounting it first - but it may help with your testing. A: You can't mount/unmound virtual SD card while the emulator is running as explained here (re)mounting the SD card on android emulator If you want to test your app, I suggest you to find a real device. A: Sorry for my ignorance but why can't you go to Android Setting menu then select Storage and unmount SD card? You can mount it back in same way. It works under emulator called using Eclipse. My version ADT adt-bundle-windows-x86_64-20140702
unknown
d14143
val
First of all, your query is wrong. Update it to this: $query="SELECT COUNT(*) AS reservationCount FROM reservations WHERE reservationDate='$reservationDate' AND reservationTime='$reservationTime'"; Reason why your query was wrong was because, if you add as reservationCount after your table name, it becomes a table alias, not result field alias. Then update the code that does the check like this: if ($row['reservationCount'] <= 10){ P.S. your code looks open to SQL Injection. Look into using MySQLi library in object orientated way and bind params to prevent sql injection. Take a look at this example, it covers both recommendations: http://php.net/manual/en/mysqli.prepare.php#refsect1-mysqli.prepare-examples A: The COUNT(*) returns one single value in one single row, and you're checking for the number of rows, so it will always be true because 1 <= 10 is always true. Change it to: if ($row[0] <= 10){
unknown
d14144
val
Minutes SELECT NUMBER, MAX([SYSMODTIME]) AS Closed, MIN([SYSMODTIME]) AS Open, (DATEDIFF (mi, MAX([LoginDateTime]), MIN([SYSMODTIME]))) AS [datediff] FROM table GROUP BY NUMBER Hours SELECT NUMBER, MAX([SYSMODTIME]) AS Closed, MIN([SYSMODTIME]) AS Open, (DATEDIFF (hh, MAX([LoginDateTime]), MIN([SYSMODTIME]))) AS [datediff] FROM table GROUP BY NUMBER
unknown
d14145
val
Basically Raw Input Api serves my goal. One needs to register the window with RegisterRawInputDevices and get WM_INPUT message. The incoming data passes relative mouse movements not limited by the screen boundaries.
unknown
d14146
val
Use this code: var Identity = this.User.Identity.Name; var Username = Identity.Split('\\')[0] + @"\\" + Identity.Split('\\')[2].ToLower(); Of course you should check before in the name have the \ character, etc. A: You can use Regex.Replace to achieve it : Username = Regex.Replace(this.User.Identity.Name, @"(?<=ACCOUNTS\\).+", n => n.Value.ToLower()), The regex pattern (?<=ACCOUNTS\\).+ will match for anything after ACCOUNTS\, and the match is then replaced by its lower case equivalent. A: As mentioned in other answers, you can use Regex or Split, but here's a substring approach specific to your case. var user = new User { Username = this.User.Identity.Name.Substring(0,9) + this.User.Identity.Name.Substring(9, name.Length - 9).ToLower(), IsAuthenticated = this.User.Identity.IsAuthenticated };
unknown
d14147
val
For us the Dispatching Shutdown event occurred in both cases. Web and Mobile senders. So I'm not sure what's happening on your end but will definitely need more information regarding what you're doing in order to look further into it. Anyhow, if you are setting addEventListeners on your end like this: context.addEventListener(cast.framework.system.ShutdownEvent, ()=>{ console.log("ShutdownEvent Called"); }); context.addEventListener(cast.framework.system.SenderDisconnectedEvent, ()=>{ console.log("SenderDisconnectedEvent called"); }); Which will result in your calls not firing. You should instead be doing: context.addEventListener(cast.framework.system.EventType.SHUTDOWN, ()=>{ console.log("ShutdownEvent Called"); }); context.addEventListener(cast.framework.system.EventType.SENDER_DISCONNECTED, ()=>{ console.log("SenderDisconnectedEvent called"); }); Here's the docs for their reference: https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.EventType
unknown
d14148
val
There are 3 main problems in your code: * *You are not returning anything from insert.php via ajax. *You don't need to replace the whole comment_part, just add the new comment to it. *Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content. In your ajax: $.ajax({ type: "GET", url: "insert.php", data : { field1_name : $('#userInput').val() }, beforeSend: function(){ } , complete: function(){ } , success: function(html){ //this will add the new comment to the `comment_part` div $("#comment_part").append(html); } }); Within insert.php you need to return the new comment html: $userInput= $_GET["field1_name"]; if(!empty($userInput)) { $field1_name = mysqli_real_escape_string($link, $userInput); $field1_name_array = explode(" ",$field1_name); foreach($field1_name_array as $element){ $query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' "; $query_link = mysqli_query($link,$query); if(mysqli_num_rows($query_link)>0){ $row = mysqli_fetch_assoc($query_link); $goodWord = $row['replaceWord']; $element= $goodWord; } $newComment = $newComment." ".$element; } //Escape user inputs for security $sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')"; $result = mysqli_query($link, $sql); //attempt insert query execution mysqli_close($link); //here you need to build your new comment html and return it return "<div class='comment'>...the new comment html...</div>"; } else{ die('comment is not set or not containing valid value'); } Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment. You can return a better structured response using json_encode() but that is outside the scope of this question. A: You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.
unknown
d14149
val
If you can think of a better way (perhaps like what DashClock does) I'm all ears :) Design your API around IPC. Have third-party plugins implement a Service, a ContentProvider, and/or a BroadcastReceiver that your host app works with. While a bound service using AIDL would seem to be the most natural way of converting your existing API to one that uses IPC, bound services for plugins have all sorts of issues (e.g., API versioning) that are messy to deal with over time. In your own app, you might wrap the low-level IPC plumbing in some classes that resemble your existing API. And if you wanted to have third-party developers use some library that you publish to have them create their plugins, you're welcome to do that too. You'll want to create a few plugins yourself, to test out your API and provide samples for third-party developers. Given all of that, there are any number of ways that you can discover when plugins are installed and removed. ACTION_PACKAGE_ADDED and ACTION_PACKAGE_REMOVED broadcasts, for example, can tell you when other apps are added and removed. You can then use PackageManager to see if they are one of your plugins (e.g., do they implement your IPC endpoint?). Or, use methods on PackageManager like queryIntentServices() to poll for plugin implementations, if that makes more sense. A: An actual app that uses plugins might give you ideas. Here is the plugin developer page of an app that uses them: http://www.twofortyfouram.com/developer
unknown
d14150
val
Well for one thing, don't you have a typo: '/reviews/review ' ? there is no element called anywhere in your example. Your XML isn't well formed, you have overlapping tags, you have mismatched reviews/Reviews (XML is case sensitive) and in your query you have reviews/review but your xml has /review (no s on the end). –
unknown
d14151
val
It's extremely hard to tell what the issue might be. I'm assuming mail works normally from the command prompt? That said, have you tried MIME::Lite? use MIME::Lite; my $body = <<EndHTML; <h2>Thank You</h2> <p>Thank you for writing!</p> <p>Return to our <a href="index.html">home page</a>.</p> EndHTML my $msg = MIME::Lite->new( Type => 'text/html', From => '[email protected]', To => '[email protected]', Subject => 'Form Data', Data => $body ); $msg->send; A: Impossible to give much help without knowing what errors you are getting. But it's 2014 and we can probably do a little better than talking directly to sendmail to send an email. For email handling, you should probably be looking in the Email::* namespace on CPAN. In particular, Email::Sender is the recommended approach for sending email.
unknown
d14152
val
The issue is that you did not link the library. The steps are usually the following: 1) npm install THE_PACKAGE --save 2) react-native THE_PACKAGE If the package does not contain any issues it will be linked, otherwise you need to link it manually, or switch to another solution, for example, https://www.npmjs.com/package/react-native-view-pdf. There you can also find a readme which describes the steps need to be done. It's generic, so you can apply for any package.
unknown
d14153
val
Have you got a chance to take a look at this section in tutorials, which explains how to display the artifacts of ExampleGen component? You can modify the code below (Source: TFX Tutorial) to achieve the same. # Get the URI of the output artifact representing the training examples, which is a directory train_uri = os.path.join(example_gen.outputs['examples'].get()[0].uri, 'Split-train') # Get the list of files in this directory (all compressed TFRecord files) tfrecord_filenames = [os.path.join(train_uri, name) for name in os.listdir(train_uri)] # Create a `TFRecordDataset` to read these files dataset = tf.data.TFRecordDataset(tfrecord_filenames, compression_type="GZIP") # Iterate over the first 3 records and decode them. for tfrecord in dataset.take(3): serialized_example = tfrecord.numpy() example = tf.train.Example() example.ParseFromString(serialized_example) pp.pprint(example)
unknown
d14154
val
As you note in your comment, if each value has a different corresponding key then they will not be reduced in the same reduce call, and you'll get the output you're currently seeing. Fundamental to Hadoop reducers is the notion that values will be collected and reduced for the same key - i suggest you re-read some of the Hadoop getting started documentation, especially the Word Count example, which appears to be roughly what you are trying to achieve with your code.
unknown
d14155
val
Semantically tables should be used for tabular data. Check out the answer to this question for some options. Depending on the age of the browsers you want to support, you could also consider using a flex box layout. Flex box is nice and easy to code but not fully supported in all browsers yet. A: According to me this shouldn't be accomplished using tables, the better way to do is by using CSS3 column-count property, this way you can cut-split your content to whatever number of columns you want to, this way you don't have to use tables too.. Demo Demo (Added -webkit support) html, body { width: 100%; height: 100%; } .wrap { column-count: 3; -moz-column-count: 3; -webkit-column-count: 3; } .holder { border: 1px solid #f00; } img { max-width: 100%; } Note: column-count CSS3 property is not widely supported, but there are many polyfills available out, you can search online and use it for cross browser compatibility
unknown
d14156
val
* *I have fixed your navigation issue. You may need to change the style of the navigation items. *I also fix your icon display issue, you need to use Font Awesome 4 style. fa fa-heart-o *Finally, I also add in CSS code to make the background of the card body becomes 80% transparent. Class .card background-color need to set to transparent and class card-footer background-color need to set to white. .card { background-color: transparent !important; } .card-body { background-color: gray; opacity: 80%; } .card-footer { background-color: #fff !important; } #header { background-color: transparent; background-position: center bottom; } h1 { color: white; text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.2); font-family: 'Source Sans Pro', sans-serif; } .navbar-brand { color: white; text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.2); font-family: 'Source Sans Pro', sans-serif; } .navbar.bg-dark.navbar-dark { background-color: transparent !important; } body { background-image: url('https://images.unsplash.com/photo-1588774210246-a1dc467758df?ixlib=rb-1.2.1&auto=format&fit=crop&w=1934&q=80') } .card-body { font-family: 'Source Sans Pro', } .lead { color: white; text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.2); font-family: 'Source Sans Pro', sans-serif; } .card { background-color: transparent !important; } .card-body { background-color: gray; opacity: 80%; } .card-footer { background-color: #fff !important; } .card-title { color: white; font-family: 'Source Sans Pro', sans-serif; } .card-text { color: white; font-family: 'Source Sans Pro', sans-serif; } <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <nav class="navbar navbar-expand-lg bg-dark navbar-dark"> <!-- <div class="container" style="background: yellow;"> --> <a href="" class="navbar-brand">Quarantine Pal</a> <!-- </div> --> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="nav navbar-nav mr-auto"> <li class="nav-item active"><a class="nav-link" href="">Home</a></li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> About </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Our Mission</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Our Team</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">FAQ</a> </div> </li> <li class="nav-item"><a class="nav-link" href="">Contact</a></li> <li class="nav-item"><a class="nav-link" href="">Our Founder</a></li> <li class="nav-item"><a class="nav-link" href="">Press</a></li> </ul> <ul class="nav navbar-nav navbar-right "> <li class="nav-item"><a class="nav-link" href="#">Sign Up <i class="fa fa-user-plus"></i></a></li> <li class="nav-item"><a class="nav-link" href="#">Login <i class="fa fa-user"></i></a></li> </ul> </div> <!-- /.navbar-collapse --> <!-- </div> --> </nav> <section id="header" class="jumbotron text-center"> <h1 class="display-3">Quarantine State of Mind</h1> <p class="lead">Exploring the 'New Normal'</p> <a href="" class="btn btn-primary">Sign Up</a> <a href="" class="btn btn-success">Login</a> </section> <div class="container"> <div class="card-deck"> <div class="card"> <img src="https://images.unsplash.com/photo-1588776409240-05d32e7614f5?ixlib=rb-1.2.1&auto=format&fit=crop&w=1400&q=80" class="card-img-top" alt="Sailor Moon"> <div class="card-body"> <h5 class="card-title text-center">Self-Care and Burn Out</h5> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> <div class="card-footer"> <a href="" class="btn btn-outline btn-success btn-sm">Download</a> <a href="" class="btn btn-outline btn-danger btn-sm"><i class="fa fa-heart-o"></i></a> </div> </div> <div class="card"> <img src="https://images.unsplash.com/photo-1588779851655-558c2897779d?ixlib=rb-1.2.1&auto=format&fit=crop&w=1400&q=80" class="card-img-top" alt="Inuyasha"> <div class="card-body"> <h5 class="card-title text-center">Help Fight Coronavirus</h5> <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> <div class="card-footer"> <a href="" class="btn btn-outline btn-success btn-sm">Download</a> <a href="" class="btn btn-outline btn-danger btn-sm"><i class="fa fa-heart-o"></i></a> </div> </div> <div class="card"> <img src="https://images.unsplash.com/photo-1588777308282-b3dd5ce9fb67?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1400&q=80" class="card-img-top" alt="Dragon Ball Z"> <div class="card-body"> <h5 class="card-title text-center">Pandemic Socializing</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> <div class="card-footer"> <a href="" class="btn btn-outline btn-success btn-sm">Download</a> <a href="" class="btn btn-outline btn-danger btn-sm"><i class="fa fa-heart-o"></i></a> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
unknown
d14157
val
you cant use .close use this out = Output() def to_next_page(x): out.clear_output() with out: display(next_page) and for displaying everytime use: with out: display(anything) and for closing use: out.clear_output()
unknown
d14158
val
Take advantage of the event object e, like this: function onEdit(e) { if (!e) { throw new Error('Do not run this code in the script editor.'); } if (!e.oldValue || !e.range.getSheet().getName().match(/^(IC|FTE)$/i)) { return; } e.range.setBackground('#faec15'); } See Apps Script at Stack Overflow, Clean Code JavaScript, and these onEdit(e) optimization tips. A: some ways to ignore empty data in apps-script: // 1. assume you have one column of data: // if your data may contains 0 or false: function test1() { const values = [ ['value_1'], [0], ['value_2'], [false], ['value_3'], [''], ['value_4'] ] for(const row of values) { if(row[0]==undefined || row[0]=='') continue; console.log(row); } } function test2() { // if your data do not contains 0 or false: const values = [ ['value_1'], [''], ['value_2'], [''], ['value_3'], [''], ['value_4'] ] for(const row of values) { if(!row[0]) continue; console.log(row); } } test1() /** output: ["value_1"] ["value_2"] ["value_3"] ["value_4"] */ test2() /** output: ["value_1"] ["value_2"] ["value_3"] ["value_4"] */ // 2. Assume you have a set rows and columns as data: // Assume all the test samples below does not contains 0 or false: function test3(arg) { const values = [ ['value_1-1','value_1-2','value_1-3'], ['','value_2-2','value_2-3'], ['value_3-1','','value_3-3'], ['value_4-1','value_4-2',''], ['','',''], ['value_5-1','value_5-2','value_5-3'] ]; switch(arg) { case 1: // 2-1. if you only want to check one column: { for(row of values) { if(!row[1]) continue; // check only column B of each row. console.log(row); } } break; case 2: // 2-2. if you need to check the whole row and skip only if the entire row is empty: { for(row of values) { if(row.every(col => !col)) continue; // check every columns of each row. console.log(row); } } break; case 3: // 2-3. if you need to check the whole row and skip if that row contains 1 or more empty cell: { for(row of values) { if(row.some(col => !col)) continue; // check every columns of each row. console.log(row); } } break; } } test3(1) /** output: ["value_1-1","value_1-2","value_1-3"] ["","value_2-2","value_2-3"] ["value_4-1","value_4-2",""] ["value_5-1","value_5-2","value_5-3"] */ test3(2) /** output: ["value_1-1","value_1-2","value_1-3"] ["","value_2-2","value_2-3"] ["value_3-1","","value_3-3"] ["value_4-1","value_4-2",""] ["value_5-1","value_5-2","value_5-3"] */ test3(3) /** output: ["value_1-1","value_1-2","value_1-3"] ["value_5-1","value_5-2","value_5-3"] */
unknown
d14159
val
I'm using qTranslate on my project and I do not do any of that stuff you do in your code above and have no problem switching between languages. All I do is call qts_language_menu() function that creates language menu, nothing else. This will create necessary links which ables you to switch between languages but stay on the same page. A: You don't need to use get_permalink() you can just pass an empty string as url and the language as 2nd param and the function will do rest ! just like: $my_translated_content_url = qtrans_convertURL("", "en"); infact if you see at the function definition: function qtrans_convertURL($url='', $lang='', $forceadmin = false) { global $q_config; // invalid language if($url=='') $url = esc_url($q_config['url_info']['url']); // <-You don't need the url if($lang=='') $lang = $q_config['language']; [... the function continue...] A: The links are stored in the $qTranslate_slug object. I made a function to make it easy to get the link for the current page in the desired language: function getUrlInTargetLanguage($targetLang){ global $qtranslate_slug; return $qtranslate_slug->get_current_url($targetLang); } So for example, if you wanted to get the english link, you should write: getUrlInTargetLanguage("en"); A: May be this late but following good functions to easy call check current language or auto generate any language URL for qTranslate: // check language function check_lang() { return qtranxf_getLanguage(); } // Generate language convert URL function get_lan_url($lang){ echo qtranxf_convertURL('', $lang); } // generate inline translate short code add_shortcode( 'translate_now', 'get_translate' ); function get_translate( $atts, $content = null ) { extract( shortcode_atts( array( 'ar' => '', 'en' => '', 'es' => '', 'fr' => '', ), $atts ) ); if ( check_lang() == 'ar' ) { echo $atts['ar']; } if ( check_lang() == 'en' ) { echo $atts['en']; } if ( check_lang() == 'es' ) { echo $atts['ar']; } if ( check_lang() == 'fr' ) { echo $atts['ar']; } } function translate_now($ar,$en,$es,$fr){ $content = '[translate_now ar="'.$ar.'" en="'.$en.'" es="'.$es.'" fr="'.$fr.'"]'; echo do_shortcode($content); } So now you can check current language using check_lang() function for example: <?php if(check_lang() == 'ar'): echo 'Ω…Ψ±Ψ­Ψ¨Ψ§'; endif;?> <?php if(check_lang() == 'en'): echo 'Hello'; endif;?> <?php if(check_lang() == 'es'): echo 'Hola'; endif;?> <?php if(check_lang() == 'fr'): echo 'Bonjour'; endif;?> Also you can use function translate_now()to translate inline by passing values: <?php translate_now( 'Ω…Ψ±Ψ­Ψ¨Ψ§', // ar 'Hello', //en 'Hola', //es 'Bonjour' //fr ); ?> Also to generate any langauge convert URL use function get_lan_url() passing requested language: <a href="<?php get_lan_url('ar');?>">Ψ§Ω„ΨΉΨ±Ψ¨ΩŠΨ©</a> <a href="<?php get_lan_url('en');?>">English</a> <a href="<?php get_lan_url('es');?>">EspaΓ±a</a> <a href="<?php get_lan_url('fr');?>">FranΓ§ais</a>
unknown
d14160
val
Just use .read() to get the contents and write it to a file path. def save(url,path): g = urllib2.urlopen(url) with open(path, "w") as fH: fH.write(g.read())
unknown
d14161
val
After seeing several Meteor projects make use of OT (i.e. http://cocodojo.meteor.com/), I decided to go for a proper integration. I've created a smart package to integrate ShareJS into meteor. Please come check it out and add your pull requests: https://github.com/mizzao/meteor-sharejs Demo App: http://documents.meteor.com A: An in-browser collaborative text editor has two major components: the text area itself, which must behave well in coordinating the user's typing with other edits that are received from the server; and the data model for sending, receiving, and combining these edits. Meteor today doesn't provide special help for either of these things specifically, but it does provide real-time data transport, and a way to move data automatically between the client and server. If I were to implement EtherPad on Meteor, I've always imagined I would use a collection as an "operation log". User changes would be sent to the server, where they would be appended to the official log of operations (basically diffs) which would automatically stream to all clients. The client would have the work of applying diffs that come in and reconciling them with typing that hasn't been acknowledged by the server yet. It's a tough implementation challenge. Good luck!
unknown
d14162
val
Peppermintology offered 2 ways and both has problems: Maybe extract the writeOff function into a service of its own which is injected into your ItemService and BagService it works only on situations like this, when you need to use "writeoff" on both services, but when you need to use some method like "updateProductPrice" (which is only used in product) then you should have this method in "ProductSercice"? or in third service? I think it will be confusion when to use third service and when to use main Product or Bag service. It might also be that ItemService and BagService can and should be combined into a single service with a writeOff method I think it is more clear solution to split "resources" in separate services (like ProductService, BagService), combined service will have a lot of code in single file and I think it is not clear solution. I am also interested if there is any other solutions or how to solve problems of offered solutions.
unknown
d14163
val
Assuming you mean this test, I think I found a library that will help you. Check out the Gnu Regression, Econometrics and Time-series Library.
unknown
d14164
val
Using the allDivs.length in the condition field will accesses the length property each time the loop iterates. So declare a variable for the length outside the function and specify the variable name in the condition field. function appendChildren() { var allDivs = document.getElementsByTagName("div"); var len = allDivs.length; for (var i = 0; i < len ; i++) { var newDiv = document.createElement("div"); decorateDiv(newDiv); allDivs[i].appendChild(newDiv); } } // Mock of decorateDiv function for testing purposes function decorateDiv(div) {} A: getElementsByTagName returns Live NodeList, which keeps the length increasing for every new div added. Either use document.querySelectorAll() which is Not a Live NodeList. let allDivs = document.querySelectorAll("div"); or Convert the Live NodeList to array. With ES6 [...spread] operator its really simple. let allDivs = [...document.getElementsByTagName("div")]; A: You're running into the fact that .getElementsByTagName() returns a live NodeList. That means that the new <div> elements that you're adding to the page become part of the list as soon as you do so. What you can do is turn that NodeList into a plain array beforehand: var allDivs = document.getElementsByTagName("div"); allDivs = [].slice.call(allDivs, 0); Now using "allDivs" in the loop will just append your new elements into the ones that were there when you originally went looking for them.
unknown
d14165
val
You can use a renderer to augment the displayed value of the cell. columns: [{ xtype: 'gridcolumn', dataIndex: 'name', text: 'Driver Name', flex: 1, editor: { xtype: 'textfield' } }, { xtype: 'gridcolumn', renderer: function(value) { if (value == 'free') { return 'xf09c@FontAwesome' } else { return 'xf023@FontAwesome' } }, getEditor: function(record) { var value; if (record.get('state') == 'free') { value = 'xf09c@FontAwesome' } else { value = 'xf023@FontAwesome' } return Ext.create('Ext.grid.CellEditor', { field: { xtype: 'image', glyph: value } }); }, text: 'State', flex: 1, dataIndex: 'state' }] Docs: - http://docs.sencha.com/extjs/5.1/5.1.0-apidocs/#!/api/Ext.grid.column.Column-cfg-renderer
unknown
d14166
val
You can use serialize() and then hash it. $cache = hash('sha1', serialize($game));
unknown
d14167
val
Almost all of this is already in comments by @IanH and @Vladimi. I suggest mixing in a little Fortran 90 into your FORTRAN 77 code. Write all of your numbers with "E". Change your other program to write the data this way. Don't bother with "D" and don't try to use the infrequently supported "Q". (Using "Q" in constants in source code is an extension of gfortran -- see 6.1.8 in manual.) Since you want the same source code to support two precisions, at the top of the program, have: use ISO_FORTRAN_ENV WP = real128 or use ISO_FORTRAN_ENV WP = real64 as the variation that changes whether your code is using double or quadruple precision. This is using the ISO Fortran Environment to select the types by their number of bits. (use needs to between program and implicit none; the assignment statement after implicit none.) Then declare your real variables via: real (WP) :: MyVar In source code, write real constants as 1.23456789012345E+12_WP. The _type is the Fortran 90 way of specifying the type of a constant. This way you can go back and forth between double and quadruple precision by only changing the single line defining WP WP == Working Precision. Just use "E" in input files. Fortran will read according to the type of the variable. Why not write a tiny test program to try it out?
unknown
d14168
val
The default alignment for the INTNX function is the beginning of the interval. If you want it to go back 3 months, that's different than quarters. You can adjust these by looking at the fourth parameter of the INTNX function which controls the alignment. Options are: * *Same *Beginning *End If you want three months, try the MONTH.3 interval instead of quarter. http://support.sas.com/documentation/cdl/en/lefunctionsref/63354/HTML/default/viewer.htm#p10v3sa3i4kfxfn1sovhi5xzxh8n.htm
unknown
d14169
val
Of your two attepts the 2nd one doesn't make any sense to me. Maybe in other languages it would. So from your two proposed approaces the 1st one is better. Still I think the pythonic way would be something like Matt Luongo suggested. A: Bogdan's answer is best. In general, if you need a loop counter (which you don't in this case), you should use enumerate instead of incrementing a counter: for index, value in enumerate(lines): # do something with the value and the index A: A Pythonic solution might a bit like @Bogdan's, but using zip and argument unpacking workflowname, paramname, value = zip(*[line.split(',') for line in lines]) If you're determined to use a for construct, though, the 1st is better. A: Version 1 is definitely better than version 2 (why put something in a list if you're just going to replace it?) but depending on what you're planning to do later, neither one may be a good idea. Parallel lists are almost never more convenient than lists of objects or tuples, so I'd consider: # list of (workflow,paramname,value) tuples items = [] for line in lines: items.append( line.split(",") ) Or: class WorkflowItem(object): def __init__(self,workflow,paramname,value): self.workflow = workflow self.paramname = paramname self.value = value # list of objects items = [] for line in lines: items.append( WorkflowItem(*line.split(",")) ) (Also, nitpick: 4-space tabs are preferable to 8-space.)
unknown
d14170
val
Perhaps getString() returns a pointer to a statically allocated buffer, whose value is overwritten each time it is called? Maybe you're overflowing an array and corrupting your stack or heap? Maybe you're storing a pointer to a string that was allocated on the stack and has gone out of scope? With some more information about or code for getString(), someone could probably give you a definitive answer. A: Well, not knowing how getString() is implemented, or any of your other code, it could be anything. That is part of the problem with C's (over)use of pointers. My first guess would be that getString() actually returns a pointer to an internal (static) string, and thus each call obliterates the value retrieved from the last. If you are actually using C++, then I would strongly advise you to ditch this code and use std::string instead. I bet your problem magically goes away. A: Aside from what the other's posted here there's also that you should avoid names like class, CLASS_ID and CLASS_NAME because they are #defined in many librarys you might include in the future and debug for hours to find out what's suddenly wrong.
unknown
d14171
val
The answer is yes, the default network is removed if you specify them manually. I went ahead and tried it. You can specify 'default' in the networks list, however, and it apparently does not need to be declared in the top-level list.
unknown
d14172
val
I was having the same issues. I was not able to get the IDE to even break at a breakpoint set inside a script tag. However when I added "debugger;" as the first line in the script tag was able to get the IDE to respond but then only to say that the disassebly was not availble. However, I was able to click on the debug tools like "step into" and "step over". When I did this the IDE did progress into some of the external scripts that I am using (JQuery and Google Maps). So I took the JavaScript code block out of the view and put it into a separate .js file in the "Content" folder. Then I added a script tag to reference this new .js file (url = "/Content/Test.js"). It worked... a little bothersome that you have to go through this effort but maybe there is something to be said for JavaScript not being included directly in a view. I hope this is a bug they intend to fix. A: When debugging on IE, VS seems to add a folder called 'Script Documents' to the Solution Explorer. Inside this folder there is another folder called 'Windows Internet Explorer', and inside of it I see all the loaded js scripts and the (compiled) HTML file currently being displayed on IE. Setting breakpoints on the script tags in this HTML file does work for me. A: The debugger cannot debug both Silverlight code and Script code at the same time, if the Silverlight debugger is selected JavaScript debugging is switched off. * *Go to the Project's Properties (Alt+Enter). *For a Web Site Project: Select "Start Options". Or for a Web Appliction: Go to the Web tab and at the bottom you will see the Debuggers option. *Check that the Silverlight checkbox is NOT ticked if you want to be able to debug JavaScript. (It is unfortunate that the UI here is not clear about this side effect.) A: To resolve this go to the Project's Properties and select "Start Options". Then Check the Native Code Check Box. and Uncheck the Silverlight Checkbox because both options not works together. A: CTRL+Alt+P (Attach to Process), select IE, select 'script' for the debugging type. A: As Ryan noted above, I moved my script to a seperate file under the Scripts folder. I also added debug into the name of the script so it became MyTestScript.debug.js. I included the script via a script tag and could set break points in the script file which the debugger hit. A: I have found that the Google Chrome devloper tool shows the JavaScript perfectly. In my case, I'm normally loading the script with jQuery's getScript function and execution of the code is typically by way of a jQuery callback upon loading a page or handling an event. With Visual Studio 2010, I frequently encountered the "No source" bug. Sad I need Chrome to debug JavaScript that is part of my Visual Studio project. A: Using a separate js file has its drawbacks. For instance, you can't use MVC helpers. Microsoft really needs to figure this one out. Intellisense also does not work properly in script blocks on a view, even if you include the reference comments like this: /// <reference path="/Scripts/jquery-1.6-vsdoc.js" /> /// <reference path="/Scripts/jquery-1.6.js" /> Intellisense works fine in the js file with this approach though.
unknown
d14173
val
Are you on an older version of Visual Studio 2017? Make sure you are on version 15.3. 15.2 includes TypeScript 2.2, but 15.3 also allows different versions of TypeScript to be selected per project. Once you have updated, you should be able to go to Properties/TypeScript Build for your project and ensure 2.2 is selected. For future TypeScript updates you can install the TypeScript SDK for Visual Studio 2017. Check https://github.com/Microsoft/TypeScript/wiki/Updating-TypeScript-in-Visual-Studio-2017 for details. (The instructions you referred to are for Visual Studio Code.)
unknown
d14174
val
You are not actually aggregating rows, so the new aggregate FILTER clause is not the right tool. A window function is more like it, a problem remains, however: the frame definition of a window cannot depend on values of the current row. It can only count a given number of rows preceding or following with the ROWS clause. To make that work, aggregate counts per day and LEFT JOIN to a full set of days in range. Then you can apply a window function: SELECT t.*, ct.ct_last4days FROM ( SELECT *, sum(ct) OVER (ORDER BY dt ROWS 3 PRECEDING) AS ct_last4days FROM ( SELECT generate_series(min(dt), max(dt), interval '1 day')::date AS dt FROM tbl t1 ) d LEFT JOIN (SELECT dt, count(*) AS ct FROM tbl GROUP BY 1) t USING (dt) ) ct JOIN tbl t USING (dt); Omitting ORDER BY dt in the widow frame definition usually works, since the order is carried over from generate_series() in the subquery. But there are no guarantees in the SQL standard without explicit ORDER BY and it might break in more complex queries. SQL Fiddle. Related: * *Select finishes where athlete didn't finish first for the past 3 events *PostgreSQL: running count of rows for a query 'by minute' *PostgreSQL unnest() with element number A: I don't think there is any syntax that means "current row" in an expression. The gram.y file for postgres makes a filter clause take just an a_expr, which is just the normal expression clauses. There is nothing specific to window functions or filter clauses in an expression. As far as I can find, the only current row notion in a window clause is for specifying the window frame boundaries. I don't think this gets you what you want. It's possible that you could get some traction from an enclosing query: http://www.postgresql.org/docs/current/static/sql-expressions.html When an aggregate expression appears in a subquery (see Section 4.2.11 and Section 9.22), the aggregate is normally evaluated over the rows of the subquery. But an exception occurs if the aggregate's arguments (and filter_clause if any) contain only outer-level variables: the aggregate then belongs to the nearest such outer level, and is evaluated over the rows of that query. but it's not obvious to me how. A: https://www.postgresql.org/docs/release/11.0/ Window functions now support all framing options shown in the SQL:2011 standard, including RANGE distance PRECEDING/FOLLOWING, GROUPS mode, and frame exclusion options https://dbfiddle.uk/p-TZHp7s You can do something like count(dt) over(order by dt RANGE BETWEEN INTERVAL '3 DAYS' PRECEDING AND CURRENT ROW)
unknown
d14175
val
$BH,"",1) I am using ArrayFormula in "DataBank" Sheet to create a unique text report based on values pulled "Form Responses". This report needs to be emailed to each respondent upon form submit. the report is pulled in CH column thru (ArrayFormula), and once the mail is sent, I am marking "1" in CM column so to ensure duplicate mails are not sent every time the script runs. =ArrayFormula(IF(ROW($B:$B)=1,"Breif Report",IF(ISBLANK($B:$B),"",if(NOT(ISBLANK($CM:$CM)),"",iferror(vlookup(BU:BU&BV:BV&BW:BW&BX:BX,BriefProfile!$E:$F,2,0),""))))) Formula Explanation: where Cell in B column is not blank, and where cell in CM column is not blank (mail not sent), then bring the pre-written text based on the look-up value within columns (BU,BV,BW,BX). What works correct: 1) The ArrayFormula works perfect (it pulls correct pre-written text) 2) Mail Script Works perfect (it sends to mails to those who have not been sent mail earlier) What does not work: 1) The text report picked for a respondent is same for all respondents. When I remove ArrayFormula and ValuePaste the text report instead of calling it thru the formula mentioned above, then mail script picks up the correct unique report for each respondent and sends mail. My mail script is mentioned below: function sendEmails() { // Sends non-duplicate emails with data from the current spreadsheet. var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DataBank"); var Avals = sheet.getRange("A1:A").getValues(); // helps getting last fillled row^ var Alast = Avals.filter(String).length; // helps getting last fillled row^ var startRow = 2; // First row of data to process var numRows = Alast-1; // Number of rows to process - last filled row^ var dataRange = sheet.getRange(startRow, 1, numRows, 91); // Fetch the range of cells A2:B3 //.getrange(row,column,numRows,numColumns) numColumns should equal to max column number where data process is required. var data = dataRange.getValues(); for (var i = 0; i < data.length; ++i) { var row = data[i]; var emailAddress = row[1]; // second column, actual column minus one var message = row[85]; // 85th column, actual column minus one var emailSent = row[90]; // 90th column, actual column minus one if (emailSent !== EMAIL_SENT) { // Prevents sending duplicates var subject = row[84] //'Sending emails from a Spreadsheet'; MailApp.sendEmail(emailAddress, subject, message); sheet.getRange(startRow + i, 91).setValue(EMAIL_SENT); Utilities.sleep(120000); // keeps the script waiting untill the sheet gets updated values from "ArrayFormula" } SpreadsheetApp.flush(); // Make sure the cell is updated right away in case the script is interrupted } } Can you review my mail script and help me improve it so that it picks up correct unique report? A: I just solved it. declaring var data = dataRange.getValues(); within the for loop solved my problem. I found the solution just now Thank you all!. by declaring the variable before the for loop, I was actually storing the static data and the same was used in each iterations. When I declared the variable within for loop, the data started changing at each iteration.
unknown
d14176
val
I tried a small setting on chrome and it turned out to work for me. I enabled: chrome://flags/#unsafely-treat-insecure-origin-as-secure and provided my HTTP server link along with the port. It worked for me. You could refer to the following: 1. https://stackoverflow.com/a/61472984/12906501 2. https://medium.com/@Carmichaelize/enabling-the-microphone-camera-in-chrome-for-local-unsecure-origins-9c90c3149339 Hope it helps!! Thanks. A: Since version 74 of Chrome navigator.getUserMedia, navigator.webkitGetUserMedia and navigator.mediaDevices can be used only in secure context (https), otherwise they are undefined. I've understood what the problem was while writing the question, as usual... A: In my case HTTP was the cause of undefined for navigator.mediaDevices with HTTPS works as expected
unknown
d14177
val
In Lucene term (an indexed element) consists of two parts: a field name and value. So in you case it will be one inverted index and will be look like this: title:java -> doc1 title:book -> doc1 content:java -> doc1 content:book -> doc1 content:selling -> doc1
unknown
d14178
val
Here is how I resolve my question: First my program launch a PopUp with the file list in argument. Popupdownload inputDialog = new Popupdownload(FileList); The Popupdownload windows : public partial class Popupdownload: Window { // Global Clock for speed processing Stopwatch sw = new Stopwatch(); // PopUp Initialisation public Popupdownload(List<string> listFiles) { InitializeComponent(); DowloadListASync(listFiles, type); } // List processing with Progress Status Update public async void DowloadListASync(List<string> listFiles) { int counter = 0; long totalSize = 0; int totalcounter = listFiles.Count(); progressLabelTotal.Content = 1 + "/" + totalcounter.ToString(); var sw = Stopwatch.StartNew(); foreach (string e in listFiles) { progressBarTotal.Value = 100 * (double)counter / (double)totalcounter; FileInfo TempFile = new FileInfo(System.IO.Path.Combine(App.folderpath, e)); Uri myUri = new Uri("http://www.XXXX/" + e, UriKind.Absolute); if (!TempFile.Directory.Exists) { TempFile.Directory.Create(); } if (TempFile.Exists) TempFile.Delete(); await DownloadAFile(myUri, TempFile.FullName); counter++; TempFile = new FileInfo(System.IO.Path.Combine(App.folderpath, e)); if (TempFile.Exists) { totalSize += TempFile.Length; } else { totalcounter--; counter--; } var totalSpeed = (totalSize / 1024d / (sw.Elapsed.TotalSeconds)); if (totalSpeed < 800) { labelTotalSpeed.Content = string.Format("{0} kb/s", totalSpeed.ToString("0.00")); } else { totalSpeed = ((totalSize / 1024d) / 1024d / (sw.Elapsed.TotalSeconds)); labelTotalSpeed.Content = string.Format("{0} Mb/s", totalSpeed.ToString("0.00")); } progressBarTotal.Value = 100 * (double)counter / (double)totalcounter; labelTotalPerc.Content = ((double)counter / (double)totalcounter).ToString("P"); progressLabelTotal.Content = (counter != totalcounter) ? (1 + counter).ToString() + "/" + totalcounter.ToString() : "TΓ©lΓ©chargment effectuΓ©"; } Close; } //async Download file with HttpClient, and keep progress public async Task DownloadAFile(Uri URL, string location) { using (var client = new HttpClientDownloadWithProgress(URL.AbsoluteUri, location)) { var watch = Stopwatch.StartNew(); FileInfo TempFile = new FileInfo(location); client.ProgressChanged += (totalFileSize, totalBytesDownloaded, progressPercentage) => { Nomfichier.Content = TempFile.Name; labelPerc.Content = progressPercentage.ToString() + "%"; progressBar.Value = (double)progressPercentage; // labelSpeed.Content = string.Format("{0} kb/s", (totalBytesDownloaded / 1024d / (watch.Elapsed.TotalSeconds)).ToString("0.00")); var speed = (totalBytesDownloaded / 1024d / (watch.Elapsed.TotalSeconds)); if (speed < 800) { labelSpeed.Content = string.Format("{0} kb/s", speed.ToString("0.00")); } else { speed = ((totalBytesDownloaded / 1024d) / 1024d / (watch.Elapsed.TotalSeconds)); labelSpeed.Content = string.Format("{0} Mb/s", speed.ToString("0.00")); } // Console.WriteLine($"{progressPercentage}% ({totalBytesDownloaded}/{totalFileSize})"); }; await client.StartDownload(); Nomfichier.Content = ""; } } and the HttpClientDownload class used like in comment: public class HttpClientDownloadWithProgress : IDisposable { private readonly string _downloadUrl; private readonly string _destinationFilePath; private HttpClient _httpClient; public delegate void ProgressChangedHandler(long? totalFileSize, long totalBytesDownloaded, double? progressPercentage); public event ProgressChangedHandler ProgressChanged; public HttpClientDownloadWithProgress(string downloadUrl, string destinationFilePath) { _downloadUrl = downloadUrl; _destinationFilePath = destinationFilePath; } public async Task StartDownload() { _httpClient = new HttpClient { Timeout = TimeSpan.FromDays(1) }; using (var response = await _httpClient.GetAsync(_downloadUrl, HttpCompletionOption.ResponseHeadersRead)) await DownloadFileFromHttpResponseMessage(response); } private async Task DownloadFileFromHttpResponseMessage(HttpResponseMessage response) { response.EnsureSuccessStatusCode(); var totalBytes = response.Content.Headers.ContentLength; using (var contentStream = await response.Content.ReadAsStreamAsync()) await ProcessContentStream(totalBytes, contentStream); } private async Task ProcessContentStream(long? totalDownloadSize, Stream contentStream) { var totalBytesRead = 0L; var readCount = 0L; var buffer = new byte[8192]; var isMoreToRead = true; using (var fileStream = new FileStream(_destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true)) { do { var bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length); if (bytesRead == 0) { isMoreToRead = false; TriggerProgressChanged(totalDownloadSize, totalBytesRead); continue; } await fileStream.WriteAsync(buffer, 0, bytesRead); totalBytesRead += bytesRead; readCount += 1; if (readCount % 100 == 0) TriggerProgressChanged(totalDownloadSize, totalBytesRead); } while (isMoreToRead); } } private void TriggerProgressChanged(long? totalDownloadSize, long totalBytesRead) { if (ProgressChanged == null) return; double? progressPercentage = null; if (totalDownloadSize.HasValue) progressPercentage = Math.Round((double)totalBytesRead / totalDownloadSize.Value * 100, 2); ProgressChanged(totalDownloadSize, totalBytesRead, progressPercentage); } public void Dispose() { _httpClient?.Dispose(); } } My last wish would be to be able to run downloads in bundles of 3-4 and handle 404 errors when the target file is missing. Work In Progress. If anyone has a clue. Thanks @steeeve for your comment.
unknown
d14179
val
I think you're getting confused... you don't need any commands here, you can just use bindings. * *Do I need two Commands for LimitChk (enable and disable) or just one (toggle)? You need none. Just create a LimitEnabled property in your ViewModel, and bind the CheckBox to it (IsChecked="{Binding LimitEnabled}") * *If I bind an int to LimitTxt, what happens if I make it empty and disable it? Disabling it has no effect. If you make the TextBox empty, the binding will fail because an empty string can't be converted to an int (at least not with the default converter) * *Is it a clean way to just use Parse(Int32.Parse(LimitTxt.Text)) when ParseBtn is pressed? You don't need to. Just create a Limit property in your ViewModel, and bind the TextBox to it. You might want to add an ExceptionValidationRule to the Binding so that it highlights invalid input. The button is not necessary, the parsing will be done automatically when the TextBox loses focus (if you use the default UpdateSourceTrigger). If you want to customize the way it's parsed, you can create a custom converter to use in the binding. A: Just some high level thoughts, leaving out superfluous stuff like Color and alignment attributes, WrapPanels, etc. Your ViewModel has a a couple properties: public bool? LimitIsChecked { get; set; } public bool LimitTextIsEnabled { get; set; } //to be expanded, below public ICommand ParseCommand { get; private set; } // to be expanded, below public string LimitValue { get; set; } // further explanation, below Your XAML has CheckBox and TextBox definitions something like: <CheckBox Content="Limit Enabled" IsChecked="{Binding LimitIsChecked}" /> <TextBox Text="{Binding LimitValue}" IsEnabled="{Binding LimitIsEnabled}" /> <Button Content="Parse" Command="{Binding ParseCommand}" /> You'll want to initialize ParseCommand something like this: this.ParseCommand = new DelegateCommand<object>(parseFile); Now, let's fill in that LimitTextIsEnabled property too: public bool LimitTextIsEnabled { // Explicit comparison because CheckBox.IsChecked is nullable. get { return this.LimitIsChecked == true; } private set { } } Your parseFile method would then pass the value of the LimitValue property to the logic doing the actual parsing. I declared the LimitValue property as string here to avoid cluttering up the code with an explicit converter, or other validation code. You could choose to handle that "LimitValue is a valid int" verification/conversion in several different ways. Of course, I haven't implemented this in its entirety, but I wanted to outline a pattern where you are not using Commands to update the state of the other widgets. Instead, bind those attributes to properties that are managed in your ViewModel.
unknown
d14180
val
It works as it should. COMMIT commits all operations in the transaction. The one involving world had problems so it was not included in the transaction. To cancel the transaction, use ROLLBACK, not COMMIT. There is no automatic ROLLBACK unless you specify it as conflict resolution with e.g. INSERT OR ROLLBACK INTO .... And use ' single quotes instead of β€œ for string literals. A: This documentation shows the error types that lead to an automatic rollback: SQLITE_FULL: database or disk full SQLITE_IOERR: disk I/O error SQLITE_BUSY: database in use by another process SQLITE_NOMEM: out or memory SQLITE_INTERRUPT: processing interrupted by application request For other error types you will need to catch the error and rollback, more on this is covered in this SO question.
unknown
d14181
val
Just add that isEmpty method to Employee class and implement it there, or use a null object pattern instead of doing new Employee(). As to what you are actually trying to do in your code, I suggest to do it like that instead: Employee employee = repository.getEmployee(id).orElseGet(() -> { Employee emp = new Employee(); emp.id(1); emp.name("Thirumal"); emp.mobile("+91-8973-697-871"); return repository.save(emp); });
unknown
d14182
val
I have managed to fix the issue. The command I used for building is: CXX=/usr/local/opt/llvm/bin/clang++ \ LDFLAGS+='-L/usr/local/opt/llvm/lib \ -L/usr/local/Cellar/llvm/5.0.1/lib -lclang' \ CPPFLAGS=-I/usr/local/opt/llvm/include \ make myprog I had to link against the libclang.dylib and add -lclang
unknown
d14183
val
Try this: $("h1").click(function(){ var lorem = $("#lorem"), clone = lorem.clone(true); clone.children().filter(function() { return $.inArray('#' + this.id, arrRed) != -1; }).addClass("red").end().filter(function() { return $.inArray('#' + this.id, arrBlue) != -1; }).addClass("blue"); lorem.replaceWith(clone); }); Fiddle Create a clone, filter the children of this new cloned element twice to apply the classes and finally replace the old element entirely with the new one. Or, if you prefer, using find instead of filter while iterating over the arrays: $("h1").click(function(){ var lorem = $("#lorem"), clone = lorem.clone(true); $.each(arrRed, function(i, v) { clone.find(v).addClass("red"); }); $.each(arrBlue, function(i, v) { clone.find(v).addClass("blue"); }); lorem.replaceWith(clone); }); Fiddle
unknown
d14184
val
GestureDetector( onTap: () { FocusScope.of(context).requestFocus(FocusNode()); }, behavior: HitTestBehavior.translucent, child: rootWidget ) A: onPressed: () { FocusScope.of(context).unfocus(); }, This works for me. A: This will work in the latest flutter version. GestureDetector( onTap: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) { FocusManager.instance.primaryFocus.unfocus(); } }, child: MaterialApp( theme: ThemeData.dark().copyWith( primaryColor: Color(0xFF0A0E21), scaffoldBackgroundColor: Color(0xFF0A0E21), ), home: LoginUI(), ), ); A: Updated Starting May 2019, FocusNode now has unfocus method: Cancels any outstanding requests for focus. This method is safe to call regardless of whether this node has ever requested focus. Use unfocus if you have declared a FocusNode for your text fields: final focusNode = FocusNode(); // ... focusNode.unfocus(); My original answer suggested detach method - use it only if you need to get rid of your FocusNode completely. If you plan to keep it around - use unfocus instead. If you have not declared a FocusNode specifically - use unfocus for the FocusScope of your current context: FocusScope.of(context).unfocus(); See revision history for the original answer. A: Best for me. I wrap since Material App because global outside touch FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) { FocusManager.instance.primaryFocus.unfocus(); } Resolve below, I check Platform iOS only because Android can dismiss the keyboard the back button. Listener( onPointerUp: (_) { if (Platform.isIOS) { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) { FocusManager.instance.primaryFocus.unfocus(); } } }, child: MaterialApp( debugShowCheckedModeBanner: true, home: MyHomePage(), ... ), ), So happy your coding. Flutter version A: If you want to do this "the right way", use Listener instead of GestureDetector. GestureDetector will only work for "single taps", which isn't representative of all possible gestures that can be executed. Listener( onPointerDown: (_) { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.focusedChild.unfocus(); } }, child: MaterialApp(...), ); A: You are doing it in the wrong way, just try this simple method to hide the soft keyboard. you just need to wrap your whole screen in the GestureDetector method and onTap method write this code. FocusScope.of(context).requestFocus(new FocusNode()); Here is the complete example: new Scaffold( body: new GestureDetector( onTap: () { FocusScope.of(context).requestFocus(new FocusNode()); }, child: new Container( //rest of your code write here ), ), ) Updated (May 2021) return GestureDetector( onTap: () => FocusManager.instance.primaryFocus?.unfocus(), child: Scaffold( appBar: AppBar( title: Text('Login'), ), body: Body(), ), ); This will work even when you touch the AppBar, new is optional in Dart 2. FocusManager.instance.primaryFocus will return the node that currently has the primary focus in the widget tree. Conditional access in Dart with null-safety A: Wrap whole screen in GestureDetector as new Scaffold( body: new GestureDetector( onTap: () { // call this method here to hide soft keyboard FocusScope.of(context).requestFocus(new FocusNode()); }, child: new Container( - - - ) ) A: I just developed a small package to give any widget the kind of behavior you are looking for: keyboard_dismisser on pub.dev. You can wrap the whole page with it, so that the keyboard will get dismissed when tapping on any inactive widget. A: With Flutter 2.5 GestureDetector.OnTap hasn't worked for me. Only this worked: return GestureDetector( //keyboard pop-down onTapDown: (_) => FocusManager.instance.primaryFocus?.unfocus(), behavior: HitTestBehavior.translucent, child: Scaffold( A: child: Form( child: Column( children: [ TextFormField( decoration: InputDecoration( labelText: 'User Name', hintText: 'User Name'), onTapOutside: (PointerDownEvent event) { FocusScope.of(context).requestFocus(_unUsedFocusNode); }, ), ], ), ), define focus Node FocusNode _unUsedFocusNode = FocusNode(); override the onTapOutside method in TextFromField onTapOutside: (PointerDownEvent event) { FocusScope.of(context).requestFocus(_unUsedFocusNode); }, Edit: Note: it will work in sdk Flutter 3.6.0-0.1.pre Dart SDK 2.19.0-374.1.beta A: I've added this line behavior: HitTestBehavior.opaque, to the GestureDetector and it seems to be working now as expected. @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(AppLocalizations.of(context).calculatorAdvancedStageTitle), ), body: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { FocusScope.of(context).requestFocus(new FocusNode()); }, child: Padding( padding: const EdgeInsets.only( left: 14, top: 8, right: 14, bottom: 8, ), child: Text('Work'), ), ) ); } A: Just as a small side note: If you use ListView its keyboardDismissBehavior property could be of interest: ListView( keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, children: [], ) A: try this if you are on a stack body: GestureDetector( onTap: () { FocusScope.of(context).requestFocus(new FocusNode()); }, child: Container( height: double.infinity, width: double.infinity, color: Colors.transparent, child: Stack(children: [ _CustomBody(_), Positioned( bottom: 15, right: 20, left: 20, child: _BotonNewList()), ]), ), ), A: This will work Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return GestureDetector( onTap: () { FocusScopeNode focus = FocusScope.of(context); if (!focus.hasPrimaryFocus && focus.focusedChild != null) { focus.focusedChild.unfocus(); } }, child: MaterialApp( title: 'Flutter Demo', A: so easy solution for beginner here is the smoothest solution for you while you need to hide-keyboard when user tap on any area of screen. hope its help you a lot. Step - 1 : you need to create this method in Global class, this method wrap you main widget into GestureDetector so when user tap outside the textfield it will hide keyboard automatically Widget hideKeyboardWhileTapOnScreen(BuildContext context, {MaterialApp child}){ return GestureDetector( onTap: () { if (Platform.isIOS) { //For iOS platform specific condition you can use as per requirement SystemChannels.textInput.invokeMethod('TextInput.hide'); print("Keyboard Hide"); } }, child: child, ); } this method wrap you main widget into Listener so when user touch and scroll up it will hide keyboard automatically Widget hideKeyboardWhileTapOnScreen(BuildContext context, {MaterialApp child}){ return Listener( onPointerUp: (_) { if (Platform.isIOS) { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) { FocusManager.instance.primaryFocus.unfocus(); print("Call keyboard listner call"); } } }, child: child, ); } Step - 2 : here is how to use Global method @override Widget build(BuildContext context) { return hideKeyboardWhileTapOnScreen(context, child: MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold(body: setAppbar())), ); } Widget setAppbar2() { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData(primarySwatch: Colors.orange), home: Scaffold( resizeToAvoidBottomInset: false, appBar: AppBar(), ), ); } A: The simplest way - just write some code in your MaterialApp's builder method: void main() { runApp(const MyApp()); } Widget build(BuildContext context) { return MaterialApp( home: const MyHomePage(), builder: (context, child) { // this is the key return GestureDetector( onTap: () => FocusManager.instance.primaryFocus?.unfocus(), child: child, ); }, ); } Then in all the pages it works. A: As of Flutters latest version v1.7.8+hotfix.2, you can hide keyboard using unfocus() instead of requestfocus() FocusScope.of(context).unfocus() so whenever you tap in the body part keyboard gets hidden @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: Text("Login"), ), body: GestureDetector( onTap: () { FocusScope.of(context).unfocus(); }, child: Container(...) ), ); } A: If you want the behavior to be accessible on any screen in your app, wrap MaterialApp with GestureDetector: // main.dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return GestureDetector( onTap: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } }, child: MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ), ); } } Checking hasPrimaryFocus is necessary to prevent Flutter from throwing an exception when trying to unfocus the node at the top of the tree. (Originally given by James Dixon of the Flutter Igniter blog) A: *Update sept 2022 :: on flutter 3.0.2 if you have complex screen, i recommend to use Listener instead. here i face issue before : There is a lag/delay when catch the event on `GestureDetector` with `HitTestBehavior.opaque`? documentation said: Rather than listening for raw pointer events, consider listening for higher-level gestures using GestureDetector GestureDetector listening to high-level gesture. I think its caused some delay or lagging. my workaround: Listener( behavior: HitTestBehavior.opaque, onPointerDown: (_) { FocusManager.instance.primaryFocus?.unfocus(); }, child: Scaffold() this will be catch event when you tap anywhere. A: It is true what maheshmnj said that from version v1.7.8+hotfix.2, you can hide keyboard using unfocus() instead of requestfocus(). FocusScope.of(context).unfocus() But in my case I was still presented with a lot of layout errors, as the screen I navigated to was not capable of handling the layout. ════════ Exception Caught By rendering library ═════════════════════════════════ The following JsonUnsupportedObjectError was thrown during paint(): Converting object to an encodable object failed: Infinity When the exception was thrown, this was the stack #0 _JsonStringifier.writeObject (dart:convert/json.dart:647:7) #1 _JsonStringifier.writeMap (dart:convert/json.dart:728:7) #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:683:21) #3 _JsonStringifier.writeObject (dart:convert/json.dart:638:9) #4 _JsonStringifier.writeList (dart:convert/json.dart:698:9) This was handled by inserting "resizeToAvoidBottomInset: false" in the receiving screens Scaffold() @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, // HERE appBar: AppBar( centerTitle: true, title: Text("Receiving Screen "), ), body: Container(...) ), ); } A: FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } You should check here https://flutterigniter.com/dismiss-keyboard-form-lose-focus/ A: This is best Scaffold( body: GestureDetector( onTap: () { if (messageFocusNode.hasFocus) { messageFocusNode.unfocus(); } }, child: new Container( //rest of your code write here ) ) A: I've found the easiest way to do it, now you can use onTapOutside in the TextField widget TextField( onTapOutside: (event) { print('onTapOutside'); FocusManager.instance.primaryFocus?.unfocus(); },) This is called for each tap that occurs outside of the[TextFieldTapRegion] group when the text field is focused. A: UPDATE NOVEMBER 2021 According to the new flutter webview documentation: Putting this piece of code inside the given full example will solve the keyboard dismiss the issue. @override void initState() { super.initState(); // Enable hybrid composition. if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView(); } Full example code: import 'dart:io'; import 'package:webview_flutter/webview_flutter.dart'; class WebViewExample extends StatefulWidget { @override WebViewExampleState createState() => WebViewExampleState(); } class WebViewExampleState extends State<WebViewExample> { @override void initState() { super.initState(); // Enable hybrid composition. if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView(); } @override Widget build(BuildContext context) { return WebView( initialUrl: 'https://flutter.dev', ); } } A: Wrap your material app with GestureDetector and use below code to hide keyboard from anywhere in app. GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) { FocusManager.instance.primaryFocus?.unfocus(); } }, child: MaterialApp( ... ), ), It will hide keyboard from whole app A: You can dismiss the keyboard thoughout the app. Just by putting this code under builder in MaterialApp and if using Getx then under GetMaterialApp MaterialApp( builder: (context, child) => GestureDetector( onTap: (){ FocusManager.instance.primaryFocus?.unfocus(); }, child: child, ))
unknown
d14185
val
Is there a reason why the StreamBuilder is following your masterListStart().asStream as opposed to the masterList stream? I'm not saying it's wrong, its just not immediately obvious. Either way, it's not rebuilding automatically because the only part of your displayStory method that is reactive to the stream doesn't get built until after the non empty list condition is met. Without implementing a reactive state management solution there's nothing in your code that automatically notifies any listeners that the state of the storysList has changed, which means nothing is triggering a rebuild. Which is why you have to hot reload to see the changes. Without me getting too deep into your code, try returning the StreamBuilder at the top level of the displayStory method and putting all the conditionals inside its its builder method.
unknown
d14186
val
I think the answer on this question might be of use.
unknown
d14187
val
BASH does have return but you may not need it in your function. You can use: push() { a="${1?Enter git shortname for first argument}" [[ $# -eq 1 ]] && b=$(timestamp) b=$2 git add -A . git commit -m $b git push $a echo "push() completed." } a="${1?Enter git shortname for first argument}" will automatically return from function with given error message if you don't pass any argument to it. A: Rewrite it such that it always exits at the bottom. Use nested if constructs so yo don't have to bail out in the middle. A: What's wrong with bash's return statement? push() { a=$1 b=$2 if [ $# -eq 0 ] then echo "Enter git shortname for first argument" return fi if [ $# -eq 1 ] then b=$(timestamp) fi git add -A . git commit -m $b git push $a echo "push() completed." } A: push() { local a="$1" b="$2" #don't overwrite global variables [ "$#" -eq 0 ] && { 1>&2 echo "Enter git shortname for first argument" #stderr return 64 #EX_USAGE=64 } : "${b:=`timestamp`}" #default value git add -A . git commit -m "$b" #always quote variables, unless you have a good reason not to git push "$a" 1>&2 echo "push() completed." } The above should run in dash as well as bash, if case you want to make use of the faster startup time. Why quote? If you don't quote, variables will get split on characters present in $IFS, which by default is the space, the newline, and the tab character. Also, asterisks within the contents of unquoted variables are glob-expanded. Usually, you want neither the splitting nor the glob expansion, and you can unsubscribe from this behavior by double quoting your variable. I think it's a good practice to quote by default, and comment the cases when you don't quote because you really want the splitting or the globbing there. (Bash doesn't split or glob-expand in assignments so local a=$1 is safe in bash, however other shells (most prominently dash) do. a="$1" is ultra-safe, consistent with how variables behave elsewhere, and quite portable among shells.)
unknown
d14188
val
I would think the lifetime issues would not come into play since you've always got a proxy to the normal-scoped bean anyway. You either dereference the conversation-scoped bean while the conversation is active, or it's not active -- but you'll always get the right conversation.
unknown
d14189
val
Maybe you can use VS as an editor ; Make sure that you do not include any windows specific libs; There is an option of using cygwin and doing a cross compilation. Check the links How to cross compile from windows g++ cygwin to get linux executable file I guess it will be more of a pain. Better use Virtual Box --> linuxMint/Ubuntu + Eclipse with C++ plugin or some other C++ editor... A: You can develop the client in C# and the server in C++, if you prefer. Consider that unlike C#, there is no standard socket library yet, and you'll have to rely on either system calls or their higher level wrappers (like boost). I've to tell you that Windows uses BSD sockets (its own version, with some modifications though), therefore with a few preprocessors checks, you can make your application portable. In your case, I'd suggest you to go for boost.asio which will hide all low-level stuff for you. It's even cross-platform.
unknown
d14190
val
It sounds like what you are developing is closer to a game than a standard Windows forms application - using a game development library (such as SDL or Microsoft XNA) might make things more straightfoward. If you are already experienced with the way that the console functioned in the days of old then implementing this should be pretty straightforward - you have your behind-the-sceenes array of characters displayed on the screen + cursor position structure which should be easy to print to the screen each frame, plus a game library will give you the ability to intercept and handle all keyboard events. If you were planning on routing the output of another process onto this "screen" then things might start to become a little more tricky - if this is the case then this might not be the best idea. A: Trying to achieve the look and feel (and responsiveness) of a text mode application using a WPF TextBox will have disappointing results. Take a look at what Pete Brown did when he created a Commodore 64 emulator in WPF and Silverlight. I believe his implementation actually used a writable bitmap to emulate a video card. So the peeks and pokes you refer to would actually take place in a memory buffer instead of the screen and then that would be turned into a screen image frame by frame.
unknown
d14191
val
To get access to the current page DOM you need to write a content script. 1. Specify the content script in manifest.json "content_scripts": [ { "matches": ["http://www.google.com/*"], "css": ["mystyles.css"], "js": ["jquery.js", "myscript.js"] } ] If you need to inject the script sometimes use Programmatic Injection by specifying permissions field: { "name": "My extension", ... "permissions": [ "activeTab" ], ... } 2.I would prefer the latter in this case.In popup.js add the code: function printResult(result){ //or You can print the result using innerHTML console.log(result); } chrome.tabs.executeScript(null, { file: 'content.js' },function(result){ printResult(result); }); 3.In content script u have access to current page/active tab DOM. var result=document.getElementsByTagName("input").length;
unknown
d14192
val
You can have a looping AJAX call in the background that checks every few minutes. If the server returns a URL (or something distinguishable from "no messages") then you'll get the popup, and if they hit OK, are sent to the URL (using a basic confirm() dialog in Javascript). Be careful though, the users patience will wear thin if you munch their CPU power on this. A: You'd have to check regulary with the server if a new message is present for the user, using a timer in your javascript (so clientside code). Due to the nature of HTTP (it being stateless) it is not possible to push this notification from the server. A: You have 3 options: * *Show the message every time the user reloads the page. Easy and fast. *Show the message by sending AJAX requests to the server. Can be really bad when you have many users, so make sure the response take very little time. *Send the message from the server using WebSocket. Most up-to-date technology, but it's only supported in a few browsers, so check the compatibility issues before implementing it. I'd personally use #1, if I don't need instant user reaction. #2 is good for web chatting. #3 is universal, but rarely used yet. Normally you would have an AJAX script in the background, running with long timeout (30+ seconds), and functionality that shows the message after page reload. This combines #1 and #2. A: Firstly you should look at the following: http://stanlemon.net/projects/jgrowl.html you should load jQuery + jGrowl and create a heartbeat function which polls the server every X seconds like. When the server receives a request from the JavaScript you check the database for the latest messages marked un_notified (not read) You compile a list and mark them notified, and then send the list to the JavaScript again, this in turn gets passed to jGrowl and notifications are show,
unknown
d14193
val
You should use str.replace to replace exact appearances of the word amigo: for x in list0: print x.replace("amigo", "") 'hello' 'bye' A: There's a replace method in which you can replace the undesired word for an empty string. list0 = ['amigohello','amigobye'] for x in list0: print(x.replace("amigo", "")) # hello, bye A: list0 = [item.replace('amigo','') for item in list0]
unknown
d14194
val
Assuming you created the project with something like lein new re-frame myapp +handler the code to start the server is on the file src/clj/myapp/server.clj You can open the file and run cider-jack-in-clj, which will ask if you want to launch lein or shadow-cljs. Since it's a CLJ file, choose lein. Once CIDER starts, you can evaluate the -main function (eg. (-main)) to start the server. You can open the URL at http://localhost:3000 and Jetty will serve the resources that are already compiled by shadow-cljs, so you'll see the same output as viewing the other port from CLJS directly. Note that the backend code from the template starts the Jetty server but won't help with reloading the backend. To see how enable hot reloading for the backend, check https://github.com/ring-clojure/ring/wiki/Setup-for-development
unknown
d14195
val
This problem affects SQL Server 2012 SSIS, and, in some occasssions, it doesn't even allow to open SSIS packages. This error is solved with a Microsoft patch which can be downloaded from this page: Micsosoft KB 2832017 Particularly, to solve the problem in VS, as VS is a 32 bit application, you only have to install the x86 download.
unknown
d14196
val
Fixing the HTML and the {choices[index].id} bits cleared this error. E.g.: <div className="col"> <label htmlFor={choices[index].id}>{choices[index].id}</label> <Field name={choices[index].id} placeholder={choices[index].value} type="text"/> <ErrorMessage name={choices[index].id} component="div" className="field-error" /> </div>
unknown
d14197
val
Check the Web Demo Browser example which includes an example with a Download Manager. If you are sharing a default QWebEngineProfile, try: connect(QWebEngineProfile::defaultProfile(), SIGNAL(downloadRequested(QWebEngineDownloadItem*)), this, SLOT(downloadRequested(QWebEngineDownloadItem*))); For a profile defined in a custom QWebEnginePage, try: connect(webView->page()->profile(), SIGNAL(downloadRequested(QWebEngineDownloadItem*)), this, SLOT(downloadRequested(QWebEngineDownloadItem*))); Now handle your download to start: void MainWindow::downloadRequested(QWebEngineDownloadItem* download) { if (download->savePageFormat() != QWebEngineDownloadItem::UnknownSaveFormat) { qDebug() << "Format: " << download->savePageFormat(); qDebug() << "Path: " << download->path(); // If you want to modify something like the default path or the format download->setSavePageFormat(...); download->setPath(...); // Check your url to accept/reject the download download->accept(); } } If you want to show a progress dialog with the download progress, just use signals availables in the class QWebEngineDownloadItem: connect(download, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(setCurrentProgress(qint64, qint64)));
unknown
d14198
val
You should be using os.path.expanduser for working with strings. pathlib.Path.expanduser is a method of pathlib.Path objects. You could convert your string to such an object and do what you want with Path('~\\Users').expanduser().
unknown
d14199
val
Update: With the last update it disappeared almost everything :-) Now there is an add-on toolbar hidden by default. If not over there you can search in the upper right corner where there is a button with the tooltext "Open Menu" (3 horizontal lines). When you press the button it appears a panel, if you select customize on the bottom it will open a page with Additional tools and features. I find over there some of the add-on that I installed. Original: Did you refer to the bar that appear with Shift + F2 ? Under Tools-->Web Developer there is the list of tools directly available. with Crtl + Shift + S you enable the debugger with Ctrl + Shift + I you toggle the tools panel A: this is a working add on for xdebug -- firefox 29.. https://addons.mozilla.org/en-US/firefox/addon/easy-xdebug-with-moveable-/?src=api
unknown
d14200
val
Just do the row_id calculation in the from clause: select d.name, e.id from (select ee.*, (@rowid := if(@d = dept_id, @rowid + 1, if(@d := dept_id, 1, 1) ) ) as rowid from Employee ee cross join (SELECT @rowid := 0, @d := NULL) as init order by ee.dept_id, ee.salary desc ) e join Departament d on d.id = e.dept_id where e.rowid = 5; And, yes, there is an ANSI standard way of doing this. In fact, I can readily think of two approaches. But MySQL supports neither window functions not fetch first 1 row only. A: SELECT X.NAME, X.SALARY AS SAL_5 FROM ( SELECT DEPT.NAME,EMP.SALARY, RANK() OVER (PARTITION BY NAME ORDER BY SALARY DESC) RN FROM EMP, DEPT WHERE EMP.DEPT_ID=DEPT.DEPT_ID ) X WHERE X.RN=5;
unknown