_id
stringlengths
2
6
text
stringlengths
4
46k
title
stringclasses
1 value
d14601
An aurelia attribute do get the correct parent injected. So I used it instead of the aurelia binding.
d14602
Until Java beans came along with the get/set naming convention, one quite often saw functions (particularly methods in C++ and other OO languages) that did exactly as you describe. They were often named after the variable that they set or got, e.g.: int counter_; int counter () { return counter_; } int counter (int c) { counter_ = c; return counter_; } In languages with different namespaces for variables and functions, you could even have the variable and the get/set functions have exactly the same name (without the need for a trailing _ as I've shown here). In languages with default parameters, you could potentially write the getter and setter as one function, e.g. something like this: int counter (int c = MAX_INT) { if (c != MAX_INT) { counter_ = c; } return counter_; } ... though I wasn't particularly keen on that approach because it led to subtle bugs if someone called counter (MAX_INT), for instance. I always thought that this naming approach made some sense and I've written some libraries that worked that way. This naming convention did, however, potentially confuse the reader of the code, particularly in languages where one could call a parameterless function without the trailing parentheses, so it was hard to see if a function was being called or if a public variable was being accessed directly. Of course some would call the latter a feature rather than a problem ... A: How about just name the function after the name of the variable it populates? Like a property, when the parameter passed is null or other special value, then it is get, otherwise it is set.
d14603
You can find the Table elements in your Document via findElement(elementType). If that's the only Table in your Document, as in the sample you shared, this is immediate. Once you retrieve the Table, you can loop through its rows and cells and come up with a 2D array with the values from the table: function getTableValues() { const doc = DocumentApp.getActiveDocument(); const body = doc.getBody(); const table = body.findElement(DocumentApp.ElementType.TABLE).getElement(); let tableValues = [[]]; for (let i = 0; i < table.getNumRows(); i++) { const tableRow = table.getRow(i); for (let j = 0; j < tableRow.getNumCells(); j++) { const tableCell = tableRow.getCell(j); const text = tableCell.getText(); tableValues[i].push(text); } if (i == table.getNumRows() - 1) break; tableValues.push([]); } return tableValues; } Once you've done that, you just need to copy it to your spreadsheet via setValues(values): function copyToSheet(tableValues, spreadsheetId) { const sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName("Sheet1"); sheet.getRange(1, 1, tableValues.length, tableValues[0].length).setValues(tableValues); } Calling both of these in the same function, you would get this: function main() { const tableValues = getTableValues(); const spreadsheetId = "{your-spreadsheet-id}"; copyToSheet(tableValues, spreadsheetId); } Note: * *getActiveDocument() is used to retrieve the Document, so this assumes the script is bound to your Document. If that's not the case, use openById(id) or openByUrl(url) instead.
d14604
Since your string is always in the format as above, you do not need a regex. Use a mere explode: explode("/", $s)[1] See this demo. Another non-regex approach: use strstr to get the substring after and including /, and then get the substring from the 1 char: substr(strstr($s, "/"),1); See another PHP demo A: Your problem is that you aren't escaping the / character with a backslash. Another problem you could face immediately after solving that one, is that you are using the $ character, which means end of line. If there are more characters afterwards, even just a single space, then it won't match. If you try: user-profile\/(id=\d+) You'll probably find that it matches just fine. The brackets I added in will capture id=3 in capture group #1. A: If you just want to extract id=3 I recommend to use preg_replace. Like: $str = 'user-profile/id=3'; $after_preg = preg_replace('/user-profile\//', '', $str); echo $after_preg; If you want to get just a number it can be as follows: $str = 'user-profile/id=3'; $after_preg = preg_replace('/user-profile\/id=/', '', $str); echo $after_preg; More about it you can read in PHP Manual: preg_replace If you want to check if you string is like user-profile/id=3 you can use regex: user-profile\/id=\d*
d14605
Seems like you need to swap the order of the loops, basically. Open your connection, then create a sheet and use it until a counter hits 1 million, then close it and create another. Here's some basic pseudocode. count = 0 sheet = new writer = new writer(sheet) using (reader) { foreach (row in reader) { if (count % 1,000,000 == 0) { writer.close sheet = new writer = new writer(sheet) } writer.write(reader.read) count++ } } writer.close
d14606
You maybe looking for a negative look-behind. pattern = "(?<!\\.\\s)\\b[[:upper:]]\\w+\\b" m = gregexpr(pattern,muffins, perl=TRUE) regmatches(muffins,m) # [[1]] # [1] "Dear" "Sarah" # # [[2]] # [1] "Muffins" # # [[3]] # [1] "Sincerely" # # [[4]] # [1] "Bob" The look behind part (?<!\\.\\s) makes sure there's not a period and a space immediately before the match. A: The below regex would match only the names Bob, Sarah and Muffins, (?<=^)[A-Z][a-z]+(?=$)|(?<!\. )[A-Z][a-z]+(?=,[^\n])|(?<= )[A-Z][a-z]+(?=,$) DEMO A: Trying to use regular expressions to identify names becomes a problem. There is no hope of working reliably. It is very complicated to match names from arbitrary data. If extracting these names is your goal, you need to approach this in a different way instead of simply trying to match an uppercase letter followed by word characters. Considering your vector is as you posted in your question: x <- c('Dear Sarah,', 'I love your dog, Muffins, who is adorable and very friendly. However, I cannot say I enjoy the "muffins" he regularly leaves in my front yard. Please consider putting him on a leash outside and properly walking him like everyone else in the neighborhood.', 'Sincerely', 'Bob') m = regmatches(x, gregexpr('(?<!\\. )[A-Z][a-z]{1,7}\\b(?! [A-Z])', x, perl=T)) Filter(length, m) # [[1]] # [1] "Sarah" # [[2]] # [1] "Muffins" # [[3]] # [1] "Bob"
d14607
You can do this by doing like below DECLARE @ID INT; SELECT @ID=ISNULL(MAX(ID),0) FROM dbo.Register --Isnull to handle first record for the table INSERT INTO dbo.Register (ID, Name, State, Comment) Select ROW_NUMBER() OVER(ORDER BY(SELECT 1))+ @ID, Name, State, Comment From dbo.OtherTable Per the edit there is no need of specifying the column in Insert list. You can skip the column and do INSERT & SELECT. INSERT INTO dbo.Register ( Name, State, Comment) Select Name, State, Comment From dbo.OtherTable Better you need to look at IDENTITY (Property) (Transact-SQL) A: Run next script .... ALTER TABLE dbo.Register DROP column ID ALTER TABLE dbo.Register add ID int identitity (1, 1) INSERT INTO dbo.Register (Name, State, Comment) Select Name, State, Comment From dbo.OtherTable EDIT: With new info, just do INSERT INTO dbo.Register (Name, State, Comment) Select Name, State, Comment From dbo.OtherTable ID Column will take care of itself ... A: If you can't make ID an IDENTITY column which would be a much better idea, you could instead use a SEQUENCE. CREATE SEQUENCE [dbo].[RegisterId] START WITH 153309 INCREMENT BY 1; GO and then, INSERT [dbo].[Register] ( [ID], [Name], [State], [Comment] ) SELECT NEXT VALUE FOR [dbo].[RegisterId] [ID], [Name], [State], [Comment] FROM [dbo].[OtherTable]; alternatively, if you can't change the schema you could use a temporary table to make use of an IDENTITY column, DECLARE @maxId INT = SELECT MAX([ID]) + 1 FROM [dbo].[Register]; DECLARE @createTemp NVARCHAR(4000) = N' CREATE TABLE #TempRegister ( [ID] INT IDENTITY(' + CAST(@maxId, NVARCHAR(14)) + ', 1), [Name] NVARCHAR(?), [State] NVARCHAR(?), [Comment] NVARCHAR(?) );'; EXEC sp_executesql @createTemp; GO INSERT #TempRegister ( [Name], [State], [Comment] ) SELECT [Name], [State], [Comment] FROM [dbo].[OtherTable]; INSERT [dbo].[Register] SELECT [ID], [Name], [State], [Comment] FROM #TempRegister; DROP TABLE #TempRegister;
d14608
I wouldn't recommend it. See this thread for answer why. If you really want to do this, I'd use a session instead.
d14609
This isn't really a Bing Maps question, but more of a Spring MVC question. Looking at your HTML the first issue I see is that each item in your table has an ID assigned to them. ID's are meant to be unique in HTML, but with the code you have you will end up creating multiple elements with the same ID which is technically creating an invalid HTML and you will only be able to retrieve the last item by ID. Pulling your data from t a table like this likely isn't the best way to implement your application. There is likely some way to generate a JSON object using Spring MVC, however I'm not familiar with Spring MVC development. If you want to continue with the method you are using I would suggest changing the ID's to classes and then you will be able to retrieve the elements by class name. Here is an example worth trying. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap' async defer></script> <style> #myMap {; width: 800px; height: 600px; } #inputForm { padding: 10px; background-color: white; border: 1px solid #000; border-radius: 10px; } </style> </head> <body> <div id="myMap" style=""></div> <script type='text/javascript'> var map, infobox, currentPushpin; function GetMap() { map = new Microsoft.Maps.Map('#myMap', { credentials : 'bing map key', zoom : 0 }); //Create a reusable infobox infobox = new Microsoft.Maps.Infobox(map.getCenter(), {visible: false}); infobox.setMap(map); document.getElementById('inputForm').style.display = ''; var lats = document.getElementsByClassName('lat'); var lons = document.getElementsByClassName('lon'); var titles = document.getElementsByClassName('titles'); var descriptions = document.getElementsByClassName('description'); //The lats, lons, titles and descriptions values should be arrays of equal length. var loc, pin; for(var i = 0, len = lats.length; i < len; i++){ loc = new Microsoft.Maps.Location(parseFloat(lats[i].value), parseFloat(lons[i].value)); pin = pin.metadata = { title : titles[i].value, description : descriptions[i].value }; Microsoft.Maps.Events.addHandler(pin, 'click', pushpinClicked); map.entities.push(pin); } } function pushpinClicked(e) { //Create an infobox that will render in the center of the map. infobox.setOptions({ location: e.target.getLocation(), title : e.target.metadata.title, description : e.target.metadata.description, visible: true }); } </script> <div id="inputForm" style="display: none;"> <TABLE> <c:forEach var="message" items="${list}"> <tr> <td><input class="lat" type="hidden" value="${message.lat}" /> <input class="lon" type="hidden" value="${message.lon}" /> <input class="title" type="hidden" value="${message.title}" /> <input class="description" type="hidden" value="${message.description}" /> </td> </tr> </c:forEach> </TABLE> </div> </body> </html>
d14610
If your only goal is to obtain the TLS key/cert from Azure Key Vault, then you're probably better of going with the Key Vault FlexVolume project from Azure. This would have the advantage of not using init containers at all and just dealing with volumes and volume mounts. Since you explicitly want to use Hexadite/acs-keyvault-agent and in default mode (which uses volume mounts btw) there is a full example of how to do this in the projects examples folder here: examples/acs-keyvault-deployment.yaml#L40-L47. Obviously you need to build, push, and configure the container correctly for your environment. Then you will need to conifgure Nginx to use the CertFileName.pem and KeyFilename.pem from the /secrets/certs_keys/ folder. Hope this helps.
d14611
Interesting problem. I am using mongoose in an app and have not seen this issue. See schema below: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const schema = new Schema({ createdBy: Object, created: { type: Date, default: Date.now }, matchName: { type: String, required: true }, matchType: { type: String, required: true }, matchActive: { type: Boolean, default: false }, matchPrivate: { type: Boolean, default: true }, matchTime: { type: String, required: true }, matchDate: { type: String, requried: true }, matchPassword: String, matchMembers: [], course: Object, subCourse: Object, par: { type: Number, required: true }, numberOfHoles: { type: Number, required: true }, frontBackNine: { type: String, required: true, default: null }, completed: { type: Boolean, default: false }, compeletedOn: { type: Date }, winner: { type: String }, startingHole: { type: Number, default: 1 }, scorecardSettings: { type: String, required: true }, tournamentGroups: { type: Array, default: [] }, }); module.exports = mongoose.model("Matches", schema); However I am not using moment.js. Two thoughts here: * *try removing commenting out moment.js code and use: Date.now in place of the moment formatted date. This is just to see if moment is causing the issue or not and will not actual give you a solution *How are you creating the collection and document? Are you creating a document when the server is started or when the user uploads the file? A: Think about when that variable is evaluated and assigned; is when the schema is created, that happens just one time. In any case, you should assign that value at the time when you save the record, assign the value as any other. But, moongose already has an option to assign timestamps to records when are created and updated. See it here: https://mongoosejs.com/docs/guide.html#timestamps Your code should look like: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const codeSchema = new Schema({ code: { type: String }, createdAt: { type: String, default: formattedDate }, }, { collection: "codes", timestamps: true } ); module.exports = mongoose.model("Code", codeSchema); About the format, I highlight recommend take care of that after at the final point when you use the data. A: You are assigning a predefined value, that's why it is not working, you should create a function and assign the function as a default value to get the value when the document. const mongoose = require("mongoose"); const Schema = mongoose.Schema; const moment = require("moment"); var createdAt = function(){ var d = new Date(); var formattedDate = moment(d).format("MM-DD-YYYY, h:mm:ss a"); return formattedDate; }; let codeSchema = new Schema({ code: { type: String }, createdAt: { type: String, default: createdAt }, }, { collection: "codes" } ); module.exports = mongoose.model("Code", codeSchema);
d14612
Maybe I don't understand the question but if you want to use the matrix x instead of [a, b, c] why don't you just define it as x = [1, 2, 3]; From your question it sounds to me as if you are overcomplicating the problem. You begin by wanting to declare a = 1; b = 2; c = 3; but what you want instead according to the end of your question is x = [1, 2, 3]; If you define x as above you can the refer to the individual elements of x like >> x(1), x(2), x(3) ans = 1 ans = 2 ans = 3 Now you have the best of both worlds with 1 definition. You can refer to a, b and c using x(1), x(2), x(3) instead and you've only had to define x once with x = [1, 2, 3];. A: You cannot deal into a numeric array, but you can deal into a cell array and then concatenate all the elements in the cell array, like this: [x{1:3}] = deal(1, 2, 3); % x is a cell array {1, 2, 3} x = [x{:}]; % x is now a numeric array [1, 2, 3]
d14613
I hope I understand your question correctly: you have images in an actual Table element (<table></table>) and images in some cells. You have a canvas placed below it which you want to draw lines on to connect the images in the table. To do this just subtract the canvas element's absolute position from the image's absolute position. This will make the image's position relative to the canvas. For example var canvas = document.getElementById('myCanvas'); var canvasPos = canvas.getBoundingClientRect(); var position = image.getBoundingClientRect(); var x = position.left - canvasPos.left; var y = position.top - canvasPos.top; var contexto = canvas.getContext('2d'); contexto.beginPath(); contexto.moveTo(x, y); ... next image A: jsBin demo Let's say you have a table and canvas inside a parent like: <div id="wrapper"> <canvas id="lines"></canvas> <table id="table"> <!-- 7*7 --> </table> </div> #wrapper{ position:relative; margin:0 auto; width: 700px; height:700px; } #wrapper canvas{ display:block; position:absolute; } #wrapper table{ position: absolute; } #wrapper table td{ background: rgba(0,0,0,0.1); width: 100px; height: 100px; vertical-align: middle; } #wrapper table td img{ display: block; opacity:0.4; } You need to connect your images using lines, you're probably interested for the image center but you need also to account the parent offset, so you need to subtract that position from the brc (getBoundingClientRect) of each image and it's td parentNode height/width: var table = document.getElementById("table"); var images = table.getElementsByTagName("img"); var canvas = document.getElementById("lines"); var ctx = canvas.getContext("2d"); var x, y; // Remember coordinates canvas.width = table.offsetWidth; canvas.height = table.offsetHeight; function connect( image ) { var im = new Image(); im.onload = function(){ // make sure image is loaded var tabBcr = table.getBoundingClientRect(); var imgBcr = image.getBoundingClientRect(); ctx.beginPath(); ctx.moveTo(x, y); x = imgBcr.left + (image.parentNode.offsetWidth / 2) - tabBcr.left; y = imgBcr.top + (image.parentNode.offsetHeight / 2) - tabBcr.top; ctx.lineTo(x, y); ctx.stroke(); }; im.src = images[i].src; } for(var i=0; i<images.length; i++){ connect( images[i] ); }
d14614
Check if there is a routing issue in your application. Try to access your REST URL from a web browser, developer console such as Firebug, or simply ping it. If you still get a 404, adjust the request URL to match your web service route, or fix the routing. Please note that the correct naming for the content type in this case is application/json. If this typo is also in your code, maybe start by adjusting it.
d14615
If the numbers are twos complement, then signed is the correct type. With that either: 1. Make the ports signed rather than std_logic_vector or 2. Use signed internally and cast all inputs to signed and outputs to std_logic_vector once: signal I1_sv : signed(11 downto 0) ; . . . signal result : signed(11 downto 0) ; . . . I1_sv <= signed(I1) ; . . . O <= std_logic_vector(result) ; . . . All the individual type conversions (casting) you are doing in the code makes it difficult to read.
d14616
There might be invalid html appearing. Check you hints for buttons, etc. There might be non-escaped texts on the page. A: I've resolve this some time ago... in the sublayout definition on sitecore there was a redundant/wrong compatible rendering definition. Once I removed that, the save button appeared and the sublayout started to work as expected
d14617
Load this page into Firefox and use Firebug to inspect it and see what CSS is being applied. You can adjust the CSS right there in Firebug to figure out how you want it to look. After you figure out the CSS you want to use, add it to your source file. A: Debug this element in in Chrome if even firefox and try to add overflow: visible; to your css
d14618
You need functions to be exported using __declspec(dllexport) when creating a DLL. You can use such functions from another DLL by declaring those functions using __declspec(dllimport). These work great for regular functions. However, for class templates and function templates, the templates are instantiated on an as needed basis. They don't get exported to the DLL in which they are defined. Hence, they can't get imported from the DLL either. For this reason, you don't use __declspec(dllexport) or __declspec(dllimport) with class templates and function templates.
d14619
Contains 1 column consisting of unique IDs ID Name Department 1 John IT 2 Jason Sales 3 Dany IT 4 Mike HR 5 Alex HR Sample TableB: Contains multiple columns, including ID from TableA. For example: ID AccountNumber WebID 1 10725 ABC1 1 10726 ABC1 1 10727 ABC1 2 20100 ABC2 2 20101 ABC2 3 30100 ABC3 4 40100 NULL I want to get the following results: ID Name WebID 1 John ABC1 2 Jason ABC2 3 Dany ABC3 4 Mike NULL 5 Alex NULL I tried the following query, which is returning the correct rows for these sample tables: Select count(a.ID), a.ID, a.Name, b.WebID from TableA a left join TableB b on a.ID = b.ID group by a.ID, a.Name, b.WebID But my Actual Database tables, this query does not return correct number of rows: (30992) TableA contains 29066 rows and TableB contains 23033 rows The query should return 29066 rows, as it is Left Join. When I checked the IDs that are in TableA, but not in TableB, there were 6033 rows: Select * from TableA where ID not in (Select ID from TableB) Am I missing something in the query? A: TABLE B has duplicates of the ID column... the code below should work (but might not be the results you expect since I just do a max on the webid column which is fine if it is always the same but I need a rule if not) I just saw you had a count... I added that in. SELECT A.ID, A.Name, B.WebID FROM TABLEA A LEFT JOIN ( SELECT ID, MAX(WebID) AS WebID, count(*) as CNT FROM TABLEB GROUP BY ID ) B ON A.ID = B.ID A: I think your query is as simple as that: select a.ID,a.Name,b.WebID from TableA a left join TableB b on a.ID = b.ID
d14620
It seems that helping the compiler out with type annotation makes this compile: val topping: ToppingDef[ _ >: Papperoni with Mushroom <: Ingredient with Product with Serializable] = if (true) { PepperoniDef } else { MushroomDef } I don't think this has to do with the Serializable class specifically, it seems like a compiler quirk to me since the produced type has a mixed in type including Product with Serializable anyway. You can also "relax" the type signature by making T covariant, meaning Topping[Ingredient] will be inferred. This happens because the "is subtype of" relation Papperoni <: Ingredient on a covariant ToppingDef[+T] means ToppingDef[Papperoni] <: ToppingDef[Ingredient], thus allowing the common supertype for T: trait ToppingDef[+T] val topping: ToppingDef[Ingredient with Product with Serializable] = if (true) { PepperoniDef } else { MushroomDef } And this also compiles without type annotation. Edit: Making Ovens type parameter an existential instead of a universally quantified type seems to work as well with the Serializable trait: class Oven[_ <: Ingredient](val topping: ToppingDef[_]) val topping: Serializable with ToppingDef[_ <: Ingredient] = if (true) { PepperoniDef } else { MushroomDef } new Oven(topping) A: You need to add some type information to your trait: trait ToppingDef[+T <: Ingredient] {} Right now the topping variable is not able to figure out that T is supposed to be an Ingredient so you need to tell it.
d14621
JSON Schema validation is not aware of the URI that the data being validated came from (if any). You can use JSON Hyper-Schema to tell your users how to send that data in the way you expect, but you will still need to do an additional check on the server-side to validate that the request was sent properly. Before I get into the solution, I want to point out a couple things. Your $schema is set to "draft-03". If you really need "draft-03", this solution won't work. anyOf, allOf and the array form of required were added in "draft-04". hrefSchema was added in "draft-06". Since "draft-06" is brand new and is not well supported yet and you don't need hrefSchema anyway, I'm going to assume "draft-04" ("draft-05" was effectively skipped). The next thing to mention is that you are using id wrong. It should be the identifier for your schema. You usually don't need this, but if you do, it should be the full URI identifying your schema. That is how my solution uses it. Last thing before I get into the solution. If you are using the link keyword, you are using JSON Hyper-Schema and your $schema should reflect that. It should have "hyper-schema" instead of "schema" at the end of the URI. Now the solution. I broke it into two parts, the schema that you put through the validator and the hyper-schema that tells users how to make the request. You've got the first one right. I only fixed the $schema and id. { "$schema": "http://json-schema.org/draft-04/schema#", "id": "http://example.com/schema/my-foo-schema", "type": "object", "properties": { "foo": { "enum": ["fooBar", "fooBaz"] }, "bar": { "type": "string" }, "baz": { "type": "string" } }, "anyOf": [ { "properties": { "foo": { "enum": ["fooBar"] } }, "required": ["bar"] }, { "properties": { "foo": { "enum": ["fooBaz"] } }, "required": ["baz"] } ] } Next is the hyper-schema. You can't reference anything external (href, instance data) in a request schema, but you can write your schema so that it matches your href. The duplication is unfortunate, but that's the way you have to do it. { "$schema": "http://json-schema.org/draft-04/hyper-schema#", "links": [ { "rel": "http://example.com/rel/my-foo-relation", "href": "/path/to/endpoint/fooBar", "method": "POST", "schema": { "allOf": [{ "$ref": "http://example.com/schema/my-foo-schema" }], "properties": { "foo": { "enum": ["fooBar"] } } } }, { "rel": "http://example.com/rel/my-foo-relation", "href": "/path/to/endpoint/fooBaz", "method": "POST", "schema": { "allOf": [{ "$ref": "http://example.com/schema/my-foo-schema" }], "properties": { "foo": { "enum": ["fooBaz"] } } } }, { "rel": "self", "href": "/path/to/endpoint" } ] } Usually when I come across something that is difficult to model with hyper-schema, it means that I am doing something overly complicated with my API and I need to refactor. I suggest taking a few minutes to think about alternative designs where this switching on an enum isn't necessary.
d14622
Googling for "extend UIComponentELTag" or "extends UIComponentELTag" should yield enough hints. This is one of my favourites: http://blogs.steeplesoft.com/2006/12/jsf-component-writing-check-list/ A: RichFaces includes CDK (component development kit) that can be used for components development. Here is the link to the guide: RichFaces CDK Developer Guide
d14623
in opencv3 the old cv or cv2.cv api was removed, to use opencv correctly in python is enough with import cv2. another package would be opencv-contrib-python
d14624
Assuming its always the second column. Change the columnNumber if its a different column (I'm counting this from 1 and not 0 for ease of use). import csv newData = [] columnNumber = 2 with open('data.csv') as csvfile: line = csv.reader(csvfile, delimiter = ',') for row in line: cStr = row[columnNumber-1].split(';') for i in range(0,len(cStr)): temp = [] for j in range(0, len(row)): if(j==columnNumber-1): temp.append(cStr[i]) else: temp.append(row[j]) newData.append(temp) with open('output.csv', 'w', newline="") as outFile: writer = csv.writer(outFile) writer.writerows(newData) A: Here's a Python 3 solution. Note use of newline='' per csv read/writer documentation: import csv with open('source.csv',newline='') as fin: with open('target.csv','w',newline='') as fout: r = csv.reader(fin) w = csv.writer(fout) # Read original three columns for country,places,other in r: # Write a row for each place for place in places.split(';'): w.writerow([place,country,other]) If still using Python 2, use the following open syntax instead: with open('source.csv','rb') as fin: with open('target.csv','wb') as fout: A: If you have a csv file then the simplest way is to open Excel, then navigate to File>Open and select "All Files" and navigate to the csv file you want to modify. When you open this file, it should give you the option to state what character you want to use as the delimiter, and you can enter ";". There should be a few more options that you just agree to, and then you will have an xls file with the fields split by the ";". In order to get from this to the table you want, I would suggest creating a pivot table. My answer is based on this being a one-off, whereas if you will have to repeat this function it would be better to write something in Excel VBA or Python. Happy to advise further if you get stuck. A: Using Miller (https://github.com/johnkerl/miller) is very simple. Using this command mlr --nidx --fs "," nest --explode --values --across-records -f 2 then reorder -f 2 input.csv you have Place1,Country A,Other info Place2,Country A,Other info Place3,Country A,Other info Place4,Country B,Other stuff Place5,Country B,Other stuff Place6,Country B,Other stuff Place7,Country C,Other examples Place8,Country C,Other examples Place9,Country C,Other examples
d14625
It depends on what you know. I'll choose the easiest: If you know the position of the original rectangle, just find the intersection of the lines that go through the matching corners.
d14626
You might compare your approach to the one shown here with regard to clearing the buffer: g2d.setComposite(AlphaComposite.Clear); g2d.fillRect(0, 0, w, h); In the worst case, you can break at a point in which your image is accessible and set a watch on the expression image.getRGB(0,0) with the display set to hexadecimal. The high order byte is the alpha value: FF is opaque, and 00..FE represents varying transparency.
d14627
I think what you are looking for is .slice() $('#dvNames > div').slice(12).remove() Demo: Fiddle A: Use the :gt pseudo-selector to select all DIVs after 11 (it counts starting with 0). $('#dvNames div:gt(11)').remove();
d14628
First make sure your processor supports virtualization technology Intel processors from i3 supports it. If your processor is above i3, then Go to BIOS and look for an option named VTx or virtualization and Enable it...save changes and exit Now open your web browser and search for HAxm drivers and install the latest one. You should be good P.S: if your processor is below i3, you cannot run avd A: If your computer does not support Virtualization, there are emulators that don't require it. I know one that many people use is Genymotion. Alternatively, of course, you can test on a physical device.
d14629
The problem is here: np.tanh[(x-a)/b] That might be the mathematical notation, but it's not valid python syntax. Function are called with parentheses (). So it should be: np.tanh((x-a)/b)
d14630
Did you forgot a script tag or am I missing jQuery being loaded someplace else? This is working for me: <!DOCTYPE html> <script type="text/javascript" src="/js/jquery-1.7.2.min.js"></script> <script> // $.noConflict(); window.setInterval(getAjax, 3000); // This is getting hoisted function getAjax() { $.ajax({ type: "POST", url: '/index', data: "some-data" }); } </script> https://gist.github.com/3505792
d14631
If you are using visual studio 2017, you need to go to the visual studio installer, and select a few more checkboxes:
d14632
Change the string calldata to string memory in your bid() function returns statement. The string literal is loaded to memory (not to calldata) and then returned. If you wanted to return calldata, you'd need to pass the value as calldata first: function foo(string calldata _str) public pure returns (string calldata) { return _str; } Docs: https://docs.soliditylang.org/en/v0.8.10/types.html#data-location
d14633
Use Series.str.count for number of matched values to new column added to DataFrame by DataFrame.assign and then pivoting with sum: df_m = (df.reset_index() .assign(count= df['Message'].str.count('image')) .pivot_table(index='Date', columns='Name', values='count' , aggfunc='sum', fill_value=0)) print (df_m) Name James Michael Tom Date 2020-01-01 0 1 1 2020-01-02 3 0 0 A: This is for the fun of it, and an alternative to the same answer. It is just a play on the different options Pandas provides : #or df1.groupby(['Date','Name']) if the index has a name res = (df1.groupby([df1.index,df1.Name]) .Message.agg(','.join) .str.count('image') .unstack(fill_value=0) ) res Name James Michael Tom ‎ Date 2020-01-01 0 1 1 2020-01-02 3 0 0
d14634
Issue was I had mxa.mailgun.org and mxb.mailgun.org added in my MX Records on my host (Linode). Removing those records fixed the issue.
d14635
You should use the native notification which Phonegap supports. Specifically the .confirm() method taken from link above; // process the confirmation dialog result function onConfirm(button) { alert('You selected button ' + button); } // Show a custom confirmation dialog // navigator.notification.confirm( 'You are the winner!', // message onConfirm, // callback to invoke with index of button pressed 'Game Over', // title 'Restart,Exit' // buttonLabels ); A: navigator.notification.confirm( 'Are you sure you want to signup ', // message onConfirm, // callback to invoke with index of button pressed 'SignUp', // title ['yes','no'] // buttonLabels ); function onConfirm(buttonIndex){ alert('You selected button ' + buttonIndex); if(buttonIndex==2){ alert('You selected button - no'); }else{ alert('You selected button - yes'); } }
d14636
The difference between scroll and fling events is that the user lifts his finger in the end of the movement in order to make it a fling. (and the speed is higher). Therefore, I think it is not possible to combine both events as they are (too) similar to detect (before ending them) which one is being performed. Also from a user perspective, using both gestures at the same time is confusing (due to the similarity). So the answer is: no there is no way to keep the ordinary scroll behaviour and still detect the fling. (at least I tried in the past and did not succeed in using both events in a proper way) A: I'm not sure this will be your problem, but why do you return true if your condition is met? If you don't want the event to be consumed, you should return false (or super.onFling). That's what the return value is for.
d14637
For lack of a GPS in your laptop, core-location on OSX uses the (skyhook) service, or something similar. The service maintains a database of WIFI access-points and their positions (possibly updated by iPhones that do have GPS and wifi enabled) which is queried. So by feeding a list of access points you can see, and their relative signal strengths the system is able to triangulate roughly where you are. So you need both wifi enabled, and a working internet link (but internet shouldn't need to be over wifi, you can leave the airport un-associated) A: I've noticed this too. If you open the Time Zone tab of the Date & Time pane in System Preferences while connected to the internet via ethernet, it says to connect to a wireless network to determine your current location. This leads me to believe that CoreLocation does, in fact, require a wireless connection.
d14638
There is a special type of axis - time and it can be used to automatically scale the X axis labels. The time scale is used to display times and dates. When building its ticks, it will automatically calculate the most comfortable unit based on the size of the scale. labels option is not needed and data should be reshaped into array of { x: new Date('2020-12-01'), y: 123 }. const data = [ { x: new Date('2020-12-01'), y: 123 }, { x: new Date('2020-12-02'), y: 134 }, { x: new Date('2020-12-03'), y: 154 }, // etc. ], X axis also needs to be configured to use time type (it does not seem to detect it automatically) var myChart = new Chart(canvas_link, { type: 'bar', data: { // labels: xvalues, (not needed) datasets: [{ label: area_option, data: data, // note: should be new data not the old one backgroundColor: 'rgba(255, 99, 132, 1)', }] }, options: { scales: { xAxes: [{ type: 'time', display: true, scaleLabel: { display: true, labelString: 'Date' }, ticks: { major: { fontStyle: 'bold', fontColor: '#FF0000' } } }], } } }) You can find my code here. UPDATED: X axis shows only quarters/months. Adding unit: 'quarter' or unit: 'month' can group X axis labels by quarter or month. Other supported units can be found in docs. Updated version can be found here var myChart = new Chart(canvas_link, { type: 'bar', data: { datasets: [{ data: data, label: 'Data', backgroundColor: 'rgba(255, 99, 132, 1)', }] }, options: { scales: { xAxes: [{ type: 'time', display: true, scaleLabel: { display: true, labelString: 'Date' }, time: { unit: 'quarter', }, ticks: { major: { fontStyle: 'bold', fontColor: '#FF0000' } } }], } } })
d14639
Try: var mystage = stage.toImage(config); to convert the canvas to an image, then you can transition images. But if you want the whole stage saved as an object you just do: var json = stage.toJSON(); and that saves your stage for reloading later, which you can do with: var stage = Kinetic.Node.create(json, 'container');
d14640
For starters saveAsNewAPIHadoopFile expects a RDD of (key, value) pairs and in your case this may happen only accidentally. The same thing applies to the value format you declare. I am not familiar with Elastic but just based on the arguments you should probably try something similar to this: kpi1.rdd.map(lambda row: (None, row.asDict()).saveAsNewAPIHadoopFile(...) Since Elastic-Hadoop provide SQL Data Source you should be also able to skip that and save data directly: df.write.format("org.elasticsearch.spark.sql").save(...) A: As zero323 said, the easiest way to load a Dataframe from PySpark to Elasticsearch is with the method Dataframe.write.format("org.elasticsearch.spark.sql").save("index/type") A: You can use something like this: df.write.mode('overwrite').format("org.elasticsearch.spark.sql").option("es.resource", '%s/%s' % (conf['index'], conf['doc_type'])).option("es.nodes", conf['host']).option("es.port", conf['port']).save()
d14641
actually I found a way to do so using "revsets" of mercurial. in order to list all ancestors for specific changeset, we can use the command hg log -r "ancestors(84e5bc6fd673)" now in order to find specific changeset in these parents, we can use the matching function like below hg log -r "ancestors(84e5bc6fd673) and id(hh6cjb9c48se)" so if hh6cjb9c48se is part of 84e5bc6fd673 parents it will be printed to the terminal.
d14642
List all GIDs from /etc/passwd that don't exist in /etc/group: comm -23 <(awk -F: '{print $4}' /etc/passwd | sort -u) \ <(awk -F: '{print $3}' /etc/group | sort -u) Fix them: nogroup=$(awk -F: '($1=="nobody") {print $3}' /etc/group) for gid in $( comm -23 <(awk -F: '{print $4}' /etc/passwd | sort -u) \ <(awk -F: '{print $3}' /etc/group | sort -u)); do awk -v gid="$gid" -F: '($4==gid) {print $1}' /etc/passwd | xargs -n 1 usermod -g "$nogroup" done A: I'm thinking along these lines: if ! grep "^$(groups $USERNAME | cut -d\ -f 1):" /etc/group > /dev/null; then usermod -g users $USERNAME fi Where groups $USERNAME | cut -d\ -f 1 gives the primary group of $USERNAME by splitting the output of groups $USERNAME at the first space (before the :) and grep ^foo: /etc/group checks if group foo exists. EDIT: Fix in the code: quoting and splitting at space instead of colon to allow the appended colon in the grep pattern (otherwise, grep ^foo would have also said that group foo existed if there was a group foobar).
d14643
The risk of changing the registry is simply that you can damage the system. If you really want to run it on a customers machine: * *Read all the documentation you can find about the registry entries you change *Take into account that different windows versions and different product versions may have different registry entries *Ask someone who ever changed these values *Make sure your application will have the permission to do this (say: run as administrator, which should not be done for regular usage. Only for instance in an installer). *Make sure you can uninstall the changes A: The registry is an environment that is controlled by the OS and may be subject of unexpectable updates from it. I think that the main risk is to be unable to know what really happens with your data (for example : if Windows thinks it is a good idea to reset or overwrite your values, you lose it all). Also, like someone said in a comment to another answer, invalid entries may lead to data loss, especially if your data exceeds the maximum length allowed by the registry. If you need to modify the registry, you may test if the key do exist and keep trace of original values before overwriting. Of course, you need to be sure that altering the key won't have unexpected effects.
d14644
You're incrementing $i when you shouldn't... When you don't print li elements, you should not increment $i: $i = 0; foreach ($query->result() as $inboxresult) { if ($inboxquery->num_rows()>0) { if ($i % 4 == 0) { echo '<ul class="msgdisplayul item">'; } $parentid = $inboxresult->id; echo '<li class="msgdisplayli"> <div class="msgfullarea"> <div class="displyusrimge"> <input type="hidden" id="status'.$inboxresult->id.'"> <a href="">'; echo '<img src="'.base_url().'images/friend_avatar_default.jpg" alt="Default User Avatar" />'; echo '</a> </div> </div> <div class="clear"></div> </li>'; // if you increment $i here, you don't need to worry if $i = 0 to close the ul $i++; if ($i % 4 == 0) { echo '</ul>'; } } } Oh, and mixing logic with HTML output, very bad idea ;-)
d14645
Your call to knex.insert() returns a promise. You need to include this promise in the promise chain by returning it inside the handler you pass to the then method. By returning a promise inside the then handler, you are effectively telling it to wait for that promise to resolve. Because you are returning nothing (specifically, undefined), your seed function deletes the posts but does not need to know it has to wait for any other operations to finish before completing. In the future, if you had multiple promises to return, you could use Promise.all() to return all of them: exports.seed = function (knex, Promise) { return knex('posts').del() .then(function () { return Promise.all([ knex('bar').insert(), knex('foo').insert(), ]) }) }; Then your promise chain would wait for all the promises inside Promise.all() to resolve before continuing. In this particular case, however, there's no need to call knex.insert() multiple times because it can accept an array of objects instead of a single object: exports.seed = function (knex, Promise) { return knex('posts').del() .then(function () { const posts = [] for (let index = 0; index < dataLength; index++) { posts.push({ title: faker.lorem.sentence(), description: faker.lorem.paragraph(), createdAt: faker.date.recent(), updatedAt: faker.date.recent(), deletedAt: faker.date.recent(), deleted: faker.random.boolean(), tags: faker.random.arrayElement(["tag1", "tag2", "tag3", "tag4"]) }) } return knex('posts').insert(posts) }); };
d14646
You need to use an AppForegroundListener and/or AppReOpenedListener. See this example: public static void main(String[] args) { final JFrame frame = new JFrame(); Application app = Application.getApplication(); app.addAppEventListener(new AppForegroundListener() { @Override public void appMovedToBackground(AppForegroundEvent arg0) { System.out.println("appMovedToBackground"); } @Override public void appRaisedToForeground(AppForegroundEvent arg0) { System.out.println("appRaisedToForeground"); frame.setVisible(true); } }); app.addAppEventListener(new AppReOpenedListener() { @Override public void appReOpened(AppReOpenedEvent arg0) { System.out.println("app reoponed"); frame.setVisible(true); } }); frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); frame.setSize(200, 200); frame.setVisible(true); } If you develop on Windows, you'll need to include stubs of the Mac/Java classes or else you'll get compiler errors. See here. If you develop on Mac, just make sure the code is not executed when running on Windows.
d14647
You can use status to mask the condition, like this: where k.ReqCode == t.ReqCode && (!status || k.Name.Contains(Name)) If the status is false, the OR || will succeed immediately, and the AND && will be true (assuming that we've got to evaluating the OR ||, the left-hand side of the AND && must have been true). If the status is true, on the other hand, the k.Name.Contains(Name) would need to be evaluated in order to finish evaluating the condition. A: An alternative option to dasblinkenlight's answer (which should work fine) is to build up the query programmatically. In this case you're effectively changing the right hand side of the join, so you could use: IQueryable<Owner> owners = Tbl_HouseOwner; if (status) { owners = owners.Where(k => k.Name.Contains(Name)); } Then: var query = from t in Houses join k in owners on t.HouseCode equals k.HouseCode where k.ReqCode == t.ReqCode select new { ... }; Which approach is the most suitable depends on your scenario. If you want to add a variety of different query filters, building it up programmatically can be cleaner - and make the final SQL easier to understand for any given query. For a one-off, dasblinkenlight's approach is simpler. Also note that in LINQ to Objects at least, it would be more efficient to join on both columns: var query = from t in Houses join k in owners on new { t.HouseCode, t.ReqCode } equals new { k.HouseCode, k.ReqCode } select new { ... }; In any flavour of LINQ which translates to SQL, I'd expect this to be optimized by the database or query translation anyway though. A: I do it this way: IQueryable<X> r = from x in Xs where (x.Status == "Active") select x; if(withFlagA) { r = r.Where(o => o.FlagA == true); } To fit this to your example, firstly you could do this: IQueryable<YourOwnerType> filteredOwners = Tbl_HouseOwner; if( status ) { filteredOwners = filteredOwners.Where( o => o.Name.Contains(Name) ); } Then substitute Tbl_HouseOwner with filteredOwners. var List = from t in Houses join k in filteredOwners on t.HouseCode equals k.HouseCode where k.ReqCode== t.ReqCode //Nothing here select new { ... name = k.Name, ... }; Now, you may know this, but the point here is that the initial .Where does not 'reach out' to the database. Your query doesn't get executed either until you start enumerating it (e.g. foreach) or call a method like ToList(), First(), FirstOrDefault(). This means you can call .Wheres after your selects if you prefer and the final query will still be efficient.
d14648
In the end I've managed the situation by parsing a parameter in the url something like http://apps.facebook.com/MyTestApp/index.php?p=goto#item/48 so, by one hand, as soon as I land on the index.php, via php I check for the $_GET['vairable'] and use that as a trigger to get the hash string to feed a javascript variable that is directly executed, before the angluar is included. So as soon as the mainController (the angular controller associated with the index) is executed the variable with the path is already instantiated. At this point angular detects that there is a variable that forces the path to go somewhere and it will get the routing there. here's some code the index.php in the tag, right after the jquery lib inclusion and right before the angular includes <script language="javascript" type="text/javascript"> var redirect_to = null; $(function() { <?php // redirecting rulez if(isset($_GET['p'])) { ?> redirect_to = window.parent.location.hash.substring(1); <?php } ?> }); </script> the mainControl.js that is the one that get hit al the times that you load the index.php if(redirect_to != null) $location.path(redirect_to); in the other controllers if(redirect_to != null) window.parent.location.hash = "#" + $location.path(); repeat for all the other controllers. enjoy
d14649
In TypeScript, you can convert a string date to an actual date using: const start = new Date(item.start); Or if it's bound in a template, you can just use the date pipe: {{ item.start | date }}
d14650
You are passing a Models.Evaluation instance to your view, which is bound to a model of another type. Models.Evaluation data = new Models.Evaluation(); if (TryUpdateModel(data, "evaluations")) { // ... } return View(data); If TryUpdateModel returns false (which happens when the form does not pass validation, for example), you are effectively passing data to the View, which is of type Models.Evaluation. Try mapping it to type FOOBAR.Areas.Evaluation.ViewModels.EvaluationFormViewModel before passing it to the view.
d14651
You need to actually define the color: <color name="white">#FFFFFF</color> that is, give its hexadecimal code. A: <color name="actionbar_title"></color> the color is empty i see. <color name="actionbar_title">#000000</color> A: You should put your file under "values" folder instead of the "color" folder.
d14652
Just an example I made for sorting Files by date using a Long comparator: public File[] getAllFoldersByDescendingDate(File folder) { if (!folder.isDirectory()) { return null; } allFiles = folder.listFiles(); Arrays.sort(allFiles, new Comparator<File>() { public int compare(final File o1, final File o2) { return Long.compare(o2.lastModified(), o1.lastModified()); } }); return allFiles; } A: Long.compare( x , y ) If you have an object that you want to sort on a long value, and it implements Comparable, in Java 7+ you can use Long.compare(long x, long y) (which returns an int) E.g. public class MyObject implements Comparable<MyObject> { public long id; @Override public int compareTo(MyObject obj) { return Long.compare(this.id, obj.id); } } Call Collections.sort(my_objects) where my_objects is something like List<MyObject> my_objects = new ArrayList<MyObject>(); // + some code to populate your list A: It depends on how you want to do things? Do you want to keep the current implementation of Comparable? If yes, use the sort method which takes a Comparator and implement a custom comparator which uses the actual "long" values of the string (Long.parseLong(dist)). If no, then just modify the current compareTo and use the Long values of the "dist". BTW, I'd revisit the logic and ask myself why "dist" is of type String when it is actually a Long? A: why not actually store a long in there: public class Tree implements Comparable<Tree> { public long dist; //value is actually Long public int compareTo(Tree o) { return this.dist<o.dist?-1: this.dist>o.dist?1:0; } } that or first compare the length of the strings and then compare them public String dist; //value is actually Long public int compareTo(Tree o) { if(this.dist.length()!=o.dist.length()) return this.dist.length()<o.dist.length()?-1:1;//assume the shorter string is a smaller value else return this.dist.compareTo(o.dist); } A: well if the dist variable is actually long then you might try using public int compareTo(Tree o) { return Long.valueOf(this.dist).compareTo(Long.valueOf(o.dist)); } A: Why not public class Tree implements Comparable<Tree> { public Long dist; public int compareTo(Tree o) { return this.dist.compareTo(o.dist); } }
d14653
Depending on the context you could define a primary key or unique index on (Col1,Col2) and let the plain Insert fail if there is a duplicate. Or define a procedure that runs the Select and checks the return code. However, the closest match to your SQL example would be a MERGE statement like MERGE into tablexyz using ( values (1,2,9) ) newdata(val1,val2,val3) on tablexyz.Col1 = newdata.val1 and tablexyz.Col2 = newdata.val2 when not matched then insert values(val1,val2,val3);
d14654
First. Once you have your projects setup correctly then the same wizard that generated your client library will copy it to your Android project and extra the source files. then you will find the packages you need in the endpoint-libs folders in your project explorer. Take a look at this post for tips on getting that working. Then you invoke an endpoint using Android code like this: final HttpTransport transport = AndroidHttp.newCompatibleTransport(); JsonFactory jsonFactory = new JacksonFactory(); endpointname.Builder builder = new endpointname.Builder( transport, jsonFactory, null ); builder.setApplicationName( appName ); endpointname service = builder.build(); try { response = service.methodName( parameters ).execute(); } catch (IOException e) { Log.e(...); }
d14655
I managed to get something kinda working. For the first part: def mapFirst(string): return ''.join(bin(a.index(c))[2:].zfill(6) for c in string) I have removed a bunch of unnecessary clutter: * *ord(chr(x)) == x (assuming x:int < 256), because ord is an inverse of chr. *str(bin(x)) == bin(x), because bin already returns a string. *bin(x).replace('0b', '') == bin(x)[2:], because bin will always return a string starting with 0b, so you can use string (list) slicing. For the second part: def binaryToLetter(binNew): return ''.join(reversed([chr(int(binNew[max(0, i - 8):i], 2)) for i in range(len(binNew), 0, -8)])) To break it down a little: * *I am using range(len(binNew), -1, -8) to generate decreasing a sequence from len(binNew) to 0 (inclusive) in steps of -8. *I am then using the list slicing again to get the 8-bit long chunks from binNew, making sure that I don't overshoot the last one (that what the max() is for). *I am turning these 8 char strings to a number with int(..., 2) and turning that number to chr. *Because I am "chopping" away the 8 long substrings starting from the back, I need to reverse the order. But reversed doesn't accept generators, so I change the original generator into a list.
d14656
Last time I looked, Genius Lyrics' APIs do not include timestamps unfortunately. There are alternatives out there, such as Musixmatch - although they're not free (and apparently not cheap). I did find Lyrics Plus though. It's an integration for Spotify. Maybe their code on GitHub could help. Good luck!
d14657
Google Analytics offers a feature called "event tracking". You can use this feature to track clicks on specific HTML Dom Elements (Buttons, Links, Images etc.) and generate analytics data for your website. Read more about GA Event Tracking
d14658
Use .eq(): $(".dataTables_wrapper").eq(i).show(); jQuery arrays contain the underlying DOM elements at each index, so when you access them the DOM functions are available but not the jQuery methods. A: $(".dataTables_wrapper")[i] returns a std java script object, not a jQuery object so you could: $($(".dataTables_wrapper")[i]).show() or use nth child or similar
d14659
No, codepoints outside of the Basic Multilingual Plane use two UTF-16 words (so 4 bytes). For codepoints in the U+0000 to U+D7FF and U+E000 to U+FFFF ranges, the codepoint and UTF-16 encoding map one-to-one. For codepoints in the range U+10000 to U+10FFFF, two words in the range U+D800 to U+DFFF are used; a lead surrogate from 0xD800 to 0xDBFF and a trail surrogate from 0xDC00 to 0xDFFF. See the UTF-16 Wikipedia article on the nitty gritty details. So, most UTF-16 big-endian bytes, when printed, can be mapped directly to Unicode codepoints. For UTF-16 little-endian you just swap the bytes around. For UTF-16 words in starting with a 0xD8 through to 0xDF byte, you'll have to map surrogates to the actual codepoint.
d14660
It most likely has something to do with the conversion, and I suspect the application namespace. I don't know how thorough the conversion process is, but you might need to update the user control directives and code-behind files. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyUserControl.ascx.cs" Inherits="MyNamespace.MyApplication.Controls.MyUserControl" %> Code-behind: namespace MyNamespace.MyApplication.Controls { public partial class MyUserControl : UserControl { ... } } Also, make sure that the user controls are mapped properly in the web.config: <pages> <controls> <add tagPrefix="Custom" src="~/controls/myusercontrol.ascx" tagName="MyUserControl" /> ... </controls> </pages>
d14661
You do not want to be calling tableView registerClass:... inside of cellForRowAtIndexPath. Instead, you should be registering your classes/nibs a single time. This is often done in the controller's viewDidLoad method. Your cellForRowAtIndexPath implementation can then look something like this: -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary* cellDetails = self.tableData[indexPath.section][kRows][indexPath.row]; NSString *reuseIdentifier = (/*some condition*/ ? @"TTTextFieldCell" : @"TTPickerCell"); UITableViewCell<TTTableViewCell> *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; [cell setCellDetails:cellDetails]; return cell; } EDIT: I should mention dequeueReusableCellWithIdentifier always returns a cell from iOS 6 on. If you are targeting an earlier version of iOS you need to account for creating cells in the even this method returns nil. A: Ok, this is what I found to be the answer. * *Do not register the class for the reuse identifier. Comment out lines A and B. *Do not copy and paste prototype cells, unless you take great care to review the IBOutlets. The pasted prototype cell doesn't care what UITableViewCell subclass you assign it too, it doesn't validate the IBOutlets are present. Fixed up #2 and all was well. Doh! A: I used 2 types of cells loaded from NIB and NSMutable array with my objects, objects have texts, titles and imagens that i want to use in cells. In method cellForRowAtIndexPath... u put content from objects to cell. U can init without nib. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if (your condition){ NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CellClass1" owner:self options:nil]; CellClass1 *cell = (CellClass1 *)[topLevelObjects objectAtIndex:0]; }else{ NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CellClass2" owner:self options:nil]; CellClass2 *cell = (CellClass2 *)[topLevelObjects objectAtIndex:0];} //get your content for cell at array or your own estructure Content *content = [contents objectAtIndex:indexPath.row]; cell.description.text = content.description; return cell; }
d14662
I did not find the problem but I re created the problem sections "SELECT dropdown menus" and it seemed to format fine. So I deleted the bad versions. not sure if this will help anyone in the future.
d14663
Try reading this. It's the least thing you can do other than doing your own research. Advance KML 1: Easy Note Advance KML 2: Google Tutorial
d14664
Mongoose connection using Singleton Pattern Mongoose Connection File - db.js //Import the mongoose module const mongoose = require('mongoose'); class Database { // Singleton connection = mongoose.connection; constructor() { try { this.connection .on('open', console.info.bind(console, 'Database connection: open')) .on('close', console.info.bind(console, 'Database connection: close')) .on('disconnected', console.info.bind(console, 'Database connection: disconnecting')) .on('disconnected', console.info.bind(console, 'Database connection: disconnected')) .on('reconnected', console.info.bind(console, 'Database connection: reconnected')) .on('fullsetup', console.info.bind(console, 'Database connection: fullsetup')) .on('all', console.info.bind(console, 'Database connection: all')) .on('error', console.error.bind(console, 'MongoDB connection: error:')); } catch (error) { console.error(error); } } async connect(username, password, dbname) { try { await mongoose.connect( `mongodb+srv://${username}:${password}@cluster0.2a7nn.mongodb.net/${dbname}?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true } ); } catch (error) { console.error(error); } } async close() { try { await this.connection.close(); } catch (error) { console.error(error); } } } module.exports = new Database(); call the connection from app.js const express = require("express"); // Express Server Framework const Database = require("./utils/db"); const app = express(); Database.connect("username", "password", "dbname"); module.exports = app; A: When you call mongoose.connect, it will set up a connection with the database. However, you attach the event listener for open at a much later point in time (when a request is being handled), meaning that the connection is probably already active and the open event has already been called (you just weren't yet listening for it). You should rearrange your code so that the event handler is as close (in time) to the connect call as possible: var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log("h"); }); exports.test = function(req,res) { res.render('test'); }; A: I had the same error popping up. Then I found out that I didn't have a mongod running and listening for connections. To do that you just need to open another command prompt (cmd) and run mongod A: The safest way to do this, it to "listen for the connect event". This way you don't care how long it takes for the DB to give you a connection. Once that is done - you should start the server. Also.. config.MONGOOSE is exposed across your app, so you only have one DB connection. If you want to use mongoose's connection, simply require config in your module, and call config.Mongoose. Hope this helps out someone! Here's the code. var mongoURI; mongoose.connection.on("open", function(ref) { console.log("Connected to mongo server."); return start_up(); }); mongoose.connection.on("error", function(err) { console.log("Could not connect to mongo server!"); return console.log(err); }); mongoURI = "mongodb://localhost/dbanme"; config.MONGOOSE = mongoose.connect(mongoURI); A: Mongoose's default connection logic is deprecated as of 4.11.0. It is recommended to use the new connection logic: * *useMongoClient option *native promise library Here is the example from npm module: mongoose-connect-db // Connection options const defaultOptions = { // Use native promises (in driver) promiseLibrary: global.Promise, useMongoClient: true, // Write concern (Journal Acknowledged) w: 1, j: true }; function connect (mongoose, dbURI, options = {}) { // Merge options with defaults const driverOptions = Object.assign(defaultOptions, options); // Use Promise from options (mongoose) mongoose.Promise = driverOptions.promiseLibrary; // Connect mongoose.connect(dbURI, driverOptions); // If the Node process ends, close the Mongoose connection process.on('SIGINT', () => { mongoose.connection.close(() => { process.exit(0); }); }); return mongoose.connection; } A: A simple way i make a connection: const mongoose = require('mongoose') mongoose.connect(<connection string>); mongoose.Promise = global.Promise; mongoose.connection.on("error", error => { console.log('Problem connection to the database'+error); });
d14665
I fixed the issue by adding protected $name property in App\Mail\Received class.
d14666
In our software we define a path to a directory where we store extensions written in Lua. Then we use the opendir(), readir() etc. to find files in that directory, and when they end in '.lua' we load and execute them. So use just need to copy their scripts to that location. In some applications we even store the Lua scripts in a text column of a (PostgreSQL) database table.
d14667
Replace = for answer in @question.answers = answer.content With - for answer in @question.answers = answer.content (The first version prints out the content of @question.answers, the second just runs the loop) See the haml documentation for inserting ruby vs running ruby
d14668
It is because dereferencing1 this always produces an lvalue, irrespective of the fact that it is pointing to a temporary object or not. So when you write this: f(); it actually means this: this->f(); //or (*this).f() //either way 'this' is getting dereferenced here So the overload of f() which is written for lvalue is invoked from g() — and const-correctness is applied accordingly as well. Hope that helps. 1. Note that this is a prvalue; only after dereferencing it produces an lvalue. A: ref-qualifiers affect the implicit object parameter, §13.3.1/4: For non-static member functions, the type of the implicit object parameter is * *“lvalue reference to cv X” for functions declared without a ref-qualifier or with the & ref-qualifier *“rvalue reference to cv X” for functions declared with the && ref-qualifier where X is the class of which the function is a member and cv is the cv-qualification on the member function declaration. Overload resolution is, roughly speaking, performed on the object argument to object parameter conversion just as any other argument->parameter conversion. However, f() is transformed into (*this).f() (§9.3.1/3), and *this is an lvalue. §5.3.1/1: The unary * operator performs indirection: […] and the result is an lvalue referring to the object or function to which the expression points. Hence the overloads of f with the & qualifier are preferred - in fact, the rvalue overloads are entirely ignored since initializers of rvalue object references must be rvalues (last bullet point in §8.5.3/5). Also, non-const references are preferred over const ones in overload resolution (§13.3.3.2/3, last bullet point concerning standard conversions). A: The call f() is interpreted as (*this).f(). The result of dereferencing a pointer is always an lvalue, so *this is an lvalue and the lvalue-qualified function is called. This behaviour even makes sense, at least to me. Most of the time the object referred to by an rvalue expression will either be destroyed at the end of the full-expression (a temporary) or at the end of the current scope (an automatic local variable that we choose to std::move). But when you're inside a member function, neither of those is true, so the object should not treat itself as an rvalue, so to speak. This is also why it makes sense for the name of an rvalue reference function parameter to be an lvalue within the function. If you want the rvalue-qualified f to be called, you can do this: std::move(*this).f(); A: Well, for f() the right qualifier is always lvalue reference since you use it on this. All your f calls are nothing else than this->f() and this is always lvalue. It doesn't matter that for the outside world the object is rvalue this is lvalue for the object insides.
d14669
CSS counter's default value is always 0 and that's not the problem in your case. The problem is that you are incrementing the value to 1 when the first tr is encountered itself. There are multiple ways in which you can solve this: * *Assign the initial value of the counter as -1 during counter-reset property. This means that when the first tr is encountered the counter value increments from -1 to 0 and so it looks as though the header row is not numbered. tr.odd { background-color: #FFFFFF } tr.even { background-color: #F2F2F2 } table { counter-reset: rowNumber -1; } table tr { counter-increment: rowNumber; } table tr td:first-child::before { content: counter(rowNumber); min-width: 1em; text-align: center; } <table> <tr> <th>Rank</th> <th>Name</th> <th>Points</th> <th>Wins</th> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> </table> *Increment counter value only from the second tr that is encountered. This can be done using the + (adjacent sibling selector) or ~ (general sibling selector) or nth-child(n+2). Using one of these would mean the selector would be matched only by the second and subsequent tr within the table. tr.odd { background-color: #FFFFFF } tr.even { background-color: #F2F2F2 } table { counter-reset: rowNumber; } table tr + tr { counter-increment: rowNumber; } table tr td:first-child::before { content: counter(rowNumber); min-width: 1em; text-align: center; } <table> <tr> <th>Rank</th> <th>Name</th> <th>Points</th> <th>Wins</th> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> </table> *Best and recommended solution: Wrap the headers inside a thead, the contents inside tbody and modify the selector within which the counter is incremented. This is recommended because it gives a proper structure to the table and doesn't look hackish. tr.odd { background-color: #FFFFFF } tr.even { background-color: #F2F2F2 } table { counter-reset: rowNumber; } table tbody tr { counter-increment: rowNumber; } table tr td:first-child::before { content: counter(rowNumber); min-width: 1em; text-align: center; } <table> <thead> <tr> <th>Rank</th> <th>Name</th> <th>Points</th> <th>Wins</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table>
d14670
It depends on the type of webservice you need to expose and consume: For exposing SOAP based webservices, you can use some strategies, 1) Proxying webservices with Protocol Bridging or WSProxyService https://docs.mulesoft.com/mule-user-guide/v/3.7/proxying-web-services 2) Proxying webservices with CXF https://docs.mulesoft.com/mule-user-guide/v/3.7/proxying-web-services-with-cxf 3) Building a webservice with CXF https://docs.mulesoft.com/mule-user-guide/v/3.7/building-web-services-with-cxf For exposing RESTful webservices, you should design a RAML and then use the APIKit component http://raml.org/ https://docs.mulesoft.com/anypoint-platform-for-apis/apikit-tutorial For consuming SOAP based webservices, you should use the Webservice Consumer component https://docs.mulesoft.com/mule-user-guide/v/3.7/web-service-consumer For consuming REST webservices, you should use the HTTP Request Connector : https://docs.mulesoft.com/mule-user-guide/v/3.7/http-request-connector So, if you want to expose a SOAP webservice (not a proxy service), that internally consumes a SOAP webservice, you can use: HTTPListener->CXF->WebserviceConsumer If you want to expose a webservice proxy you can use the ProtocolBridging or CXF strategy. If you want to expose a REST webservice, that internally consumes a REST webservice, you can use: HTTPListener->APIKit->HTTPRequest And so on.. A: This describes a scenario that you are trying to fulfill https://docs.mulesoft.com/anypoint-platform-for-apis/proxying-your-api
d14671
Seem that child composer file is ignored https://getcomposer.org/doc/04-schema.md#repositories Repositories are not resolved recursively. You can only add them to your main composer.json
d14672
Node runs on server side so its not possible to view it in the web console. you can only view the data coming from node server on HTTP or socket call.so relax and happy coding .
d14673
I found URI.js. However, if you don't want to use that library, I think this function will do what you're looking for (not so sure about decodeURIComponent): var urlString = "http://somehost:9090/cars;color=red;make=Tesla?page=1&perPage=10" var getParams = function (urlString) { return decodeURIComponent(urlString) // decode the URL (?) .match(/\/((?!.+\/).+)\?/) // the regex looks for a slash that is NOT // followed by at least one character and eventually another slash // given var urlString = "http://somehost:9090/cars;color=red;make=Tesla?page=1&perPage=10" // we don't want -------^ ^ ^ // we want this slash ------| | // all the way until this question mark --------------------------------| // regex explanation: /* \/ first slash ( open capturing group (?! lookbehind for NOT .+\/ any character followed by a slash (/) ) .+ capture one or more characters (greedy) past ) the close of the capturing group and until \? a question mark */ [1] // match will return two groups, which will look like: // ["/cars;color=red;make=Tesla?", "cars;color=red;make=Tesla"] // we want the second one (otherwise we'd have to .slice(1,-1) the string) .split(";") // split it at the semicolons // if you know you're always going to have "name" followed by a semicolon, // you might consider using .slice(1) on this part, so you can get rid of // the if statement below (still keep the p[c[0]] = c[1] part though ) .reduce(function (p, c) { // split it at the equals sign for a key/value in indices 0 and 1 c = c.split("="); // if the length is greater than one, aka we have a key AND a value // e.g., c == ["color", "red"] if (c.length > 1) { // give the previous object a key of c[0] equal to c[1] // i.e., p["color"] = "red" p[c[0]] = c[1]; } return p; // return p, so that we can keep adding keys to the object }, {}); // we pass an object, which will act as p on the first call } console.log(getParams(urlString)); // { color: "red", make: "Tesla" } Instead of the regular expression, you can also use what I posted in my comment above: urlString.split("?")[0].split("/").pop().split(";").reduce( /* etc */) Now I want a Tesla… A: I recently wrote a Node.js Middleware for parsing Matrix Parameters. I've specified the rules that it follows and the format of the output that it generates. So for instance, here's what your app.js looks like: let app = require ('express') (), matrixParser = require ('matrix-parser'); app.use (matrixParser ()); app.get ('/cars*', (req, res) => { //notice the asterisk after '/cars' console.log (JSON.stringify (req.matrix, null, 2)); res.send ('Thanks=)'); }); app.listen (9090); and your URI looks like: http://localhost:9090/cars;color=red;make=Tesla?page=1&perPage=10 then, you could test the matrix parser feature with curl like: curl "http://localhost:9090/cars;color=red;make=Tesla?page=1&perPage=10" Then req.matrix is set to the following object: [ { "segment": "cars", "matrix": { "color": "red", "make": "Tesla" } } ] The query strings (page, per_page) are left untouched (you can see this by simply writing req.query) Probably too late in writing an answer at this point, but it might still come handly in future. Here's the repo: https://github.com/duaraghav8/matrix-parser npm install matrix-parser EDIT: Sorry for not providing a more elaborate answer with code earlier, this is my first contribution to SO, I'll take some time to get the hang of it.
d14674
This isn't the exact thing that I'm looking for but I've found somewhat of a workaround. You can create global keyboard shortcuts and thereby circumvent the metro/start screen altogether. To do so, create a shortcut of the program/folder/file you want to easily access (the shortcut can be placed anywhere). Then, go to the properties of the shortcut and go to the shortcut tab where you can enter a global shortcut key (about half way down the box). Of course, there are limitations to this because there are only a few keys (key combinations) free that you can use globally whereas with the XP method I was looking for, you could essentially have up to 36 different items you can access with just two keystrokes (26 letters, 10 numbers - not sure if other characters worked). If anyone has figured out the XP method, though, that would be great.
d14675
When the terminal is closed, your program will get a SIGHUP, which kill it by default. add a signal handler to handle the SIGHUP do whatever you want. and if you program write to the console after it has been close, you may also get SIGPIPE, handle it properly
d14676
One simple way uses exists: select t.* from t where exists (select 1 from t t2 where t2.id = t.id and t2.rating = t.rating and t2.candidateid <> t.candidateid ); A: You can use analytics function for this as well SELECT ID,CANDIDATEID,RATING,NAME FROM T QUALIFY COUNT(*)OVER(PARTITION BY ID,RATING)>=2 based on your database, you can change syntax for count(*) over. This syntax works in teradata.
d14677
I guess they are using different approaches interpreting the color precision. A 32-bit screen is in fact only 24-bit color (the 8 last bits is not part of the color space). Mozilla defines it as: Returns the color depth of the screen. Chrome seem to read it directly from the system as-is, while FF and IE9 seem to correctly (based on that definition) identify the color precision (color depth) of the screen. Please note that screen.colorDepth is not part of any standard and it's up to the implementers how it actually works. The more correct way of checking color-precision in regards to color depth would therefor be: case 16: document.bgColor = "..." ; break; case 24: case 32: document.bgColor = "..."; //32 = 24 bit color depth + 8 bits alpha break;
d14678
fileList.Q = "mimeType != 'application/vnd.google-apps.folder' and 'Admin' in parents"; The issue you are having is that you are using the name of the directory 'Admin' you need to use the file id of the Admin directory. Do a file.list and search for the admin directory get its file id then pass it to that instead. fileList.Q = "name ='Admin' and mimeType != 'application/vnd.google-apps.folder'";
d14679
I think the issue is in the data maybe somewhere in your data you have 95.7 and since you are converting it into int so that's why it is breaking your code. You should try lines[1] = int(float(lines[1])) lines[2] = int(float(lines[2])) A: Your problem is you're using integers (whole numbers). Either your lines in the csv are not whole numbers, or when calculating total, you are dividing into decimals. To solve this, you have to use a floating-point number. Replace your uses of integers with floats. eg. lines[1] = int(lines[1]) should become lines[1] = float(lines[1]) You will however find you start getting numbers with long decimal places, so you can round them with the round() function, like this: lines[1] = round(float(lines[1]), '.2f') Which will set it to 2 decimal places. You can change that 2 to any number of decimal places you'd like. lines[1] = round(float(lines[1]), '.2f') lines[2] = round(float(lines[2]), '.2f')
d14680
You have a nested array and must check against each item like so: function in_multidimensional_array($val, $array) { foreach($array as $key => $value) { if (in_array($val, $array[$key])) { return true; } } return false; } Now you can check if the value 496891 exists using: if(in_multidimensional_array('496891', $result_array)) { print 'true'; } else { print 'false'; } A: Krister's solution only works if you only have one row in your MySQL-loop. This would check against all the results. while($row = mysql_fetch_assoc($result)) { $result_array[] = $row; } $found = false; foreach ($result_array as $v) { if (in_array("496891", $v)) { $found = true; } } if ($found == true) echo 'true'; else echo 'false'; A: You are searching for a string, but your array is holding numeric values. You would need to make sure that you insert it specifically as a string to get it to return true, or each field as a string prior to the search.
d14681
You can implement GoogleMap.OnMapClickListener and GoogleMap.OnMapLongClickListener to achieve this public class CreateFenceActiviy extends AppCompatActivity implements GoogleMap.OnMapClickListener, GoogleMap.OnMapLongClickListener{ private GoogleMap mGoogleMap; private SupportMapFragment mMapFragment; private ArrayList<double[]> mLatLongArray =null; private Polygon mPolygon; private PolygonOptions mPolygonOptions; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.create_fence_activity); mLatLongArray = new ArrayList<double[]>(); if (mGoogleMap == null) { mMapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_create_fence)); mGoogleMap = mMapFragment.getMap(); mGoogleMap.setOnMapClickListener(this); mGoogleMap.setOnMapLongClickListener(this); mGoogleMap.setOnMarkerClickListener(this); isMarkerClicked = false; } } @Override public void onMapClick(LatLng point) { if(mGoogleMap != null){ mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(point)); isMarkerClicked = false; } } @Override public void onMapLongClick(LatLng point) { if(mGoogleMap != null) { mGoogleMap.addMarker(new MarkerOptions().position(point).title(point.toString())); double latitudeNew = point.latitude; double longitude = point.longitude; mLatLongArray.add(new double[]{latitudeNew, longitude}); isMarkerClicked = false; } } } XML for Map view will contain this component <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map_create_fence" class="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" />
d14682
You could use numpy.where() with a boolean mask to identify your rows that contain 'K': mask = df['Numbers'].str.contains('K') df['Numbers'] = np.where(mask, df['Numbers'].str.extract(r'([\d\.]+)', expand=False).astype(float)*1000, df['Numbers']) Yields: Numbers 0 100000 1 25200 2 250000 3 33450 4 250 5 100 6 10 7 5 8 4 9 1 A: Here's a way to do using a custom function: import re def func(s): # extract the digits with decimal s = float(re.sub('[^0-9\\.]', '', s))*1000 return s is_k = df['col'].str.contains('K') df.loc[is_k, 'col2'] = df.loc[is_k, 'col'].apply(func) df['col2'] = df['col2'].combine_first(df['col']) col col2 0 100 K 100000 1 25.20 K 25200 2 250 K 250000 3 250 250 4 100 100 5 10 10 Sample Data s=["100 K", "25.20 K", "250 K", "250", "100","10"] df = pd.DataFrame({'col': s})
d14683
Thanks to #pyramid in the IRC i got the first hint, which is mentioned in the comment. But..never ever name a key 'value' or 'values'!
d14684
You can do it on the server or the client side Server side To implement it server side, you need to maintain some kind of mapping in the server between client sockets and handles, so that when you broadcast a message from a socket, you can retrieve its handle and prepend it to the message before sending. In order to know the handle of the clients, they can send it to the server as the first message when they connect. The server will interpret this first message as the handle, and store it mapping it to the socket from what it has been received. The advantage of this approach is that the server can validate the handle before it accepts it from the clients, and if it is already in use, reject the handle or abort the connection. Also, the clients cannot fake their handle later in the conversation, as it is the server that sends them. Client side This is the easiest implementation, as you only need to modify the client and prepend the handle before sending each message. # user entered a message msg = sys.stdin.readline() s.send(person + ": " + msg) sys.stdout.write( person + '[Me]: '); sys.stdout.flush() The drawbacks of this approach are that a malicious client can fake the handle to pretend to be another person, and that two clients can have the same handle at the same time, making them indistinguishable from each other.
d14685
To browse a txt file * *Using sg.FileBrowse to select file and send filename to previous element sg.Input *Set option file_types=(("TXT Files", "*.txt"), ("ALL Files", "*.*")) of sg.FileBrowse to filter txt files. Read txt file by * *open(filename, 'rt', 'utf-8') as f *read all text from f Create another popup window with element sg.Multiline with text read from txt file. from pathlib import Path import PySimpleGUI as sg def popup_text(filename, text): layout = [ [sg.Multiline(text, size=(80, 25)),], ] win = sg.Window(filename, layout, modal=True, finalize=True) while True: event, values = win.read() if event == sg.WINDOW_CLOSED: break win.close() sg.theme("DarkBlue3") sg.set_options(font=("Microsoft JhengHei", 16)) layout = [ [ sg.Input(key='-INPUT-'), sg.FileBrowse(file_types=(("TXT Files", "*.txt"), ("ALL Files", "*.*"))), sg.Button("Open"), ] ] window = sg.Window('Title', layout) while True: event, values = window.read() if event == sg.WINDOW_CLOSED: break elif event == 'Open': filename = values['-INPUT-'] if Path(filename).is_file(): try: with open(filename, "rt", encoding='utf-8') as f: text = f.read() popup_text(filename, text) except Exception as e: print("Error: ", e) window.close() May get problem if txt file with different encoding. A: On linux you have an environment variable called editor like this EDITOR=/usr/bin/micro You can get that env using os file_editor = os.getenv("EDITOR", default = "paht/to/default/editor") Then you can spawn a process os.spawnlp(os.P_WAIT, file_editor, '', '/path/to/file') This essentially be a popup. Windows probably uses a different env name Leaving the above because this is essentially what this does: os.system('c:/tmp/sample.txt') The above snippet is a one liner to do basically what I mentioned above A: I don't know what is your platform. Anyway, opening a file will involve: * *choosing a file to be opened (from your formulation, I understand that in your case it's a given file with a known path; otherwise you'd need to use, e.g., sg.FileBrowse()); and *executing a command to open the file using a default or a specified reader or editor. I use the following function (working in MacOS and Windows) to execute a command: import platform import shlex import subprocess def execute_command(command: str): """ Starts a subprocess to execute the given shell command. Uses shlex.split() to split the command into arguments the right way. Logs errors/exceptions (if any) and returns the output of the command. :param command: Shell command to be executed. :type command: str :return: Output of the executed command (out as returned by subprocess.Popen()). :rtype: str """ proc = None out, err = None, None try: if platform.system().lower() == 'windows': command = shlex.split(command) proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) out, err = proc.communicate(timeout=20) except subprocess.TimeoutExpired: if proc: proc.kill() out, err = proc.communicate() except Exception as e: if e: print(e) if err: print(err) return out and call it this way to open the file using the default editor: command = f'\"{filename}\"' if platform.system().lower() == 'windows' else \ f'open \"{filename}\"' execute_command(command) You can tweak command to open the file in an editor of your choice the same way as you would do in CLI. This is quite a universal solution for various commands. There are shorter solutions for sure :) Reference: https://docs.python.org/3/library/subprocess.html
d14686
As in arrays.xml champ_image Array item is @drawable/aatrox means champ_image is typed Array instead of int. so use obtainTypedArray method which return TypedArray as: TypedArray imgsTypedArray = getResources().obtainTypedArray(R.array.champ_image); Now use TypedArray.getResourceId to get drawable id's and pass it to ChampionItemModel as: for(int i=0;i<length;i++){ int drawableId= imgsTypedArray.getResourceId(i, -1); championItemModel = new ChampionItemModel(champsNames[i], champsRoles[i], drawableId); champItems.add(championItemModel); } A: I assume you are trying to load images from drawable folder. Then declare 'champsImages' array like following: int[] champsImages = {R.drawable.image1, R.drawable.image2, R.drawable.image3, ...to more}; I think it will help to achieve your expected result. A: http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray XML file saved at res/values/arrays.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <array name="icons"> <item>@drawable/home</item> <item>@drawable/settings</item> <item>@drawable/logout</item> </array> <array name="colors"> <item>#FFFF0000</item> <item>#FF00FF00</item> <item>#FF0000FF</item> </array> </resources> This application code retrieves each array and then obtains the first entry in each array: Resources res = getResources(); TypedArray icons = res.obtainTypedArray(R.array.icons); Drawable drawable = icons.getDrawable(0); TypedArray colors = res.obtainTypedArray(R.array.colors); int color = colors.getColor(0,0);
d14687
I think this is down to the formatting in your yaml. When I knitted your code R Studio did some re-formatting of the title, but in the process replaced the ' with " in your date, causing the error. I don't have your .bib file so I can't test your exact code, but the following worked for me: --- title: Are shifts between points of view challenging for readers? An examination of readers' eye movements in response to Woolf's *To the Lighthouse* and *Mrs Dalloway* author: "Giulia Grisot, Kathy Conklin, Violeta Sotirova - The University of Nottingham" date: '`r format(Sys.time(), "%d %B %Y")`' output: pdf_document: default html_notebook: fig_caption: yes force_captions: yes number_sections: no theme: readable --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE) ``` ```{r, include=F} library(tidyverse) #library(ggpubr) ``` # Abstract
d14688
I find the way for the buttons...and change query code. But i don't be able to change the interval by the input form Here my code... $('.ppt li:gt(0)').hide(); $('.ppt li:last').addClass('last'); $('.ppt li:first').addClass('first'); $('#play').hide(); var cur = $('.ppt li:first'); var interval; var time= 3000; function start() { interval = setInterval( "forward()", time ); } function stop() { clearInterval( interval ); } function forward() { cur.fadeOut( 0 ); if ( cur.attr('class') == 'last' ) cur = $('.ppt li:first'); else cur = cur.next(); cur.fadeIn( 0 ); } function goFwd() { stop(); forward(); start(); } function back() { cur.fadeOut( 0 ); if ( cur.attr('class') == 'first' ) cur = $('.ppt li:last'); else cur = cur.prev(); cur.fadeIn( 0 ); } function goBack() { stop(); back(); start(); } function showPause() { $('#play').hide(); $('#stop').show(); } function showPlay() { $('#stop').hide(); $('#play').show(); } $('#fwd').click( function() { goFwd(); showPause(); } ); $('#back').click( function() { goBack(); showPause(); } ); $('#stop').click( function() { stop(); showPlay(); } ); $('#play').click( function() { start(); showPause(); } ); $(function() { start(); } ); </script>
d14689
In this working example, notice the variable results below: func runQuery() { let env = BespokeEnvironment(mainQueue: .main, networkQuery: NetworkQuestionRequestor()) results = env.networkQuery.reviewedQuestionsQuery(pageCount: 1) .sink( receiveCompletion: { print($0)}, receiveValue: { values in returnValues.append(contentsOf: values) }) } I originally had: let results = ... And was not getting any records. It turns out the method was completing and returning before the publisher had finished. In the non-working code, the cancellable was not being saved long enough for the publisher to complete. So I moved results into the parent view and made it a @State variable. Everything now works correctly. @State var results: AnyCancellable? = nil
d14690
I haven't experience with the Kotlin DSL, but apparently the extractApi task could be re-written as val assets by configurations.creating dependencies { assets("somegroup", "someArtifact", "someVersion") } tasks { val extractApi by creating(Sync::class) { dependsOn(assets) from(assets.map { zipTree(it) }) into("$buildDir/api/") } }
d14691
I do not think there is a need for another model Payslip, also you have no ForeignKey connections between the two models for it to work. Considering your requirement, property decorator should work. Read up on how @property works. Basically, it acts as a pseudo model field, keep in mind the value of this field is not stored anywhere in the database, but it is tailor-made for situations like this where the field changes based on other fields and is needed for read-only. Try this class Employee(models.Model): name = models.CharField(max_length=20) rate = models.IntegerField() absent = models.IntegerField() def __str__(self): return self.name @property def compute_pay(self): daily = self.rate / 20 return (self.rate - (daily*self.absent)) you can get the employee's salary by Employee.compute_pay just like any other model field
d14692
that's probably because one super is calling the other. Something like this: // super.setContentView(layoutResID); code is: View v = LayoutInflater.from(getContext()).inflate(layoutResId); setContentView(v); // then super.setContentView(view); code is: setContentView(view, null); // then super.setContentView(view, params); this one now actually do real work. Hence, 3 calls!
d14693
Every resource is automatically tagged with the fully qualified name of the class or defined type in which it is declared, and with every namespace segment of the class or type name, among other tags. You can use those tags to filter the resources that will be applied during a given catalog run. In the particular example you describe, you could use puppet agent --no-daemonize --onetime --tags keyconfig to apply only the resources declared in class keyconfig (and in any other class declared by keyconfig, recursively, but in this case there are no such other classes). You can also declare tags manually by using the tag metaparameter in your resource declarations. That can allow you to provide for identifying custom collections of resources. And speaking of collections, you can use tags in the selection predicates of resource collectors, too. A: The only way to do that is to have that node contain only the class you are wanting to have applied. In your site.pp you would have the following where the 'myhost.dns' is your fqdn. and $mycluster would be replaced by your cluster string. node 'myhost.dns' { class { 'keyconfig': cluster => $mycluster, } }
d14694
Not possible. You can however put a "fake" from header in the mail. You'll only risk it to end up in the junk folder. HTML doesn't provide any functionality to send mails. You'll really need to do this in the server side. How exactly to do this depends on the server side programming language in question. In PHP for example, you have the mail() function. In Java you have the JavaMail API. And so on. Regardless of the language used, you'll need a SMTP server as well. It's the one responsible for actually sending the mail. You can use the one from your ISP or a public email provider (Gmail, Yahoo, etc), but you'll be forced to use your account name in the from header. You can also register a domain with a mailbox and just register something like noreply@example.com and use this to send mails from. Update: JavaScript can't send mails as well. Like HTML it's a client side language. You'll need to do it with a server side language. All JavaScript can do is to dump the entire page content back to the server side. jQuery may be useful in this: $.post('/your-server-side-script-url', { body: $('body').html(); }); with (PHP targeted example) $to = 'to@example.com'; $subject = 'Page contents'; $body = $_POST['body'] $headers = prepare_mail_headers(); mail($to, $subject, $body, $headers); Update 2: if you actually want to hide the to header in the mail, then you'll need to use the bcc (Blind Carbon Copy) instead. This way the recipient addres(ses) will be undisclosed. Only the from, to, cc stays visible. A: If you mean doing so on a client side, using mailto: link - you can not. If you mean any way, yes - you submit the form contents back to your server, and have your back end script send the email. A: You can do the form in HTML, but the posting will need to be done in a script. Even if you don't expose the email address, the script can be used to spam that email address. This is why you see captcha being used in such cases. There are scripts available for most languages. Check to make sure their are no known security problems for the scripts. The original Matt's script in perl had problems, and the Perl community created a more secure version.
d14695
Remove contentType: "application/json; charset=utf-8", to send the data as url encoded
d14696
Any clues? I'm not sure in this case, but I did some experiments with iframes (on a somewhat similar topic) about a year ago. I would assume, that gwt-calendar tries to communicate with the host page via javascipt's parent reference. AFAIR, that's not allowed, when the host page isn't loaded from the same origin (including protocol). A: There other snippets of Javascript that can also cause a problem. Please see: http://blog.httpwatch.com/2009/09/17/even-more-problems-with-the-ie-8-mixed-content-warning/ Also, have a look through the pile of comments on: http://blog.httpwatch.com/2009/04/23/fixing-the-ie-8-warning-do-you-want-to-view-only-the-webpage-content-that-was-delivered-securely/ Some of the commenters have found and fixed other causes of the warning too. A: This can happen if you have your app running over HTTPS and are fetching images or some other resource over over plain HTTP. Check if you have image or css paths hardcoded to http://. For example, if your app if running at https://example.com and you wish to load an image foo.jpg , the html you should be using is: <img src="https://example.com/images/foo.jpg"/> or (ideally) <img src="images/foo.jpg"/> and not <img src="http://example.com/images/foo.jpg"/> Note that the third example fetches the foo.jpg image over http instead of https. Hence it would cause the issue which you are facing. To avoid such problems, the best practice is either to use ImageResources and relative URLs.
d14697
Use 'android.hardware.camera' instead of 'android.hardware.camera2' API and that allows you to use that API with API level 16.
d14698
The project I was working with had two gradle files, repositories.gradle & build.gradle I was adding the nexus URL to repositories.gradle file in the repositories block. But the URL was not being searched for dependencies. After a bit of exploration I found that the build.gradle file also has a repositories block: allProjects { . . . . . . . . . . repositories { . . . . . . . . . . . . . . . . . . . . } } This seems to be overriding the repositories block in repositories.gradle file. When I added the nexus URL in here the dependencies were resolved. Hope that helps anyone having a similar issue :) A: As an updated information and solution for me was in the settings.gradle There is another repositories block in dependencyResolutionManagement.
d14699
You can put img and input in flex div : .comment-profile-pic { border-radius: 50%; width: 50px; } .wrapper { display: flex; align-items: center; } <div class="wrapper"> <img class="comment-profile-pic" src="https://drgsearch.com/wp-content/uploads/2020/01/no-photo.png" alt=""> <input type="text" class="post-comment"> </div> A: use flexboxs, wrap both items in a div and then add a class with display:flex A: You can also do, that image and input top would be in the same line. <html> <head> <title>Example</title> <style> .comment-profile-pic { width: 100px; } .one-line { display: flex; align-items: top; } input { height: 25px; } </style> </head> <body> <div class="one-line"> <img class="comment-profile-pic" src="https://drgsearch.com/wp-content/uploads/2020/01/no-photo.png" alt=""> <input type="text" class="post-comment"> </div> </body> </html>
d14700
If I understand correctly your question, I think you can use the following property of fresh-line (see the manual): fresh-line returns true if it outputs a newline; otherwise it returns false. to define something like: (defun my-fresh-line () (unless (fresh-line) (terpri))) If, on the other hand, you want always a blank line after the current written text, be it terminated with a new line or not, you can define something like: (define blank-line () (fresh-line) (terpri)) and then call it after the current output.