query_id
stringlengths
4
64
query_authorID
stringlengths
6
40
query_text
stringlengths
66
72.1k
candidate_id
stringlengths
5
64
candidate_authorID
stringlengths
6
40
candidate_text
stringlengths
9
101k
da25b877451795663c2eeb077a49236ce83df93abea9ddc953f9540a2a20b224
['4ab31196d6104bcb8c5ba3035b2b81e3']
I have a logstash kafka consumer group subscribing nearly 20topics which isn't performing well for a particular high priority kafka topic to process, so I've decided to remove one topic out of the consumer group and launch a separate consumer group for high priority topics, but unfortunately with that i'm losing the offset that was there in old consumer group. Is there anyway I can start the new logstash consumer group with the initial offset from last consumer group? Thanks
bb441f23b1a969b3fc5cc0101926b419b93bcabe0d3e854522cfe21014bdcf87
['4ab31196d6104bcb8c5ba3035b2b81e3']
i want to upload only the delta of a file in google cloud storage(gcs=google cloud storage). as gcs only allows to get a crc32 hash of the entire file but not the some part of the file (x - y bytes) i'm building local version indexes like git(but a poor version). now i just want to upload the delta of the file, for which i need gcs api methods to insert k bytes at nth location. and delete x-y bytes, modify x-y bytes. i have searched but couldn't find anything about it. and i skirmed through "gsutil rsync" code and came to the conclusion that it is copying the entire file even if there is a small change in the file(please correct me if it is not the case.) ps: if there are no such methods i will try to save 256KB blocks of each file. (my file sizes are in the range of 1MB-50MB) pps: actually i want to upload only the delta of some binary files that i'm storing from android app. if you know any known tool or workflow for this please do answer.
967374e18dffab8edebd0798e05bdf8cce3a614accdd9e7a7ce4e0f513616710
['4aba6e2dc0984710b5cd6326bfea2bdb']
i had this problem too, after spending much more time finally i've found a solution, first thing you shuold manage your code with layouts and then in any pages that uses layouts you must add : import Link From 'next/link' just After importing layout line. i hope this solves your problem
d144d211dcd2621a9fb964a12968c42ae9b8f4cc5c4b2969239b61588483a0c4
['4aba6e2dc0984710b5cd6326bfea2bdb']
here is my code i've got access token , i can create boards and etc but for creating pins errors happens ... i am using official pinterest javascript sdk , and i've added my https://localhost:3000 to white list redirect_urls in my app settings <script> window.pAsyncInit = function() { PDK.init({ appId: "4974350472186969702", // Change this cookie: true }); var acc = ""; PDK.login({ scope : 'read_relationships,write_relationships, read_public , write_public' }, function(response){ if (!response || response.error) { } else { var pins = []; var fianlData = {}; fianlData.data = {}; fianlData.access_token = response.session.accessToken; fianlData.data.board = "behzadkhodapanah/ninja2"; fianlData.data.note = "label"; fianlData.data.link = "https://localhost:3000"; fianlData.data.image_url = "https://localhost:3000/image.jpg"; console.log("FD : ",fianlData.data); PDK.request('v1/pins/?fields=link%2Cnote%2Curl',fianlData, function (response) { if (!response || response.error) { } else { console.log("JSON : ",JSON.stringify(response)); PDK.logout(); } }); } }) }; // } (function(d, s, id){ var js, pjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "sdk.js"; pjs.parentNode.insertBefore(js, pjs); }(document, 'script', 'pinterest-jssdk')); </script>
a4a838927a5511b347baf333654f3eab6719ac5eadc0870ab964f50444497929
['4ac0490f07964465a9df9cce38bee3f3']
i'm trying to use ajax wide browsing on phpfox but i dont understand how it works, any idea please ? i found in static/jscript/main.js this code : $Core.ajax = function(sCall, $oParams) { var sParams = '&' + getParam('sGlobalTokenName') + '[ajax]=true&' + getParam('sGlobalTokenName') + '[call]=' + sCall; if (!sParams.match(/\[security_token\]/i)) { sParams += '&' + getParam('sGlobalTokenName') + '[security_token]=' + oCore['log.security_token']; } if (isset($oParams['params'])) { if (typeof($oParams['params']) == 'string') { sParams += $oParams['params']; } else { $.each($oParams['params'], function($sKey, $sValue) { sParams += '&' + $sKey + '=' + encodeURIComponent($sValue) + ''; }); } } $.ajax( { type: (isset($oParams['type']) ? $oParams['type'] : 'GET'), url: getParam('sJsStatic') + "ajax.php", dataType: 'html', data: sParams, success: $oParams['success'] }); }; I'm trying to fix a module of chat while browsing on my site Any idea plz ?
c07195ba449b5016f431037963f3332f6584eb71c6a9e82a207da9d614749cba
['4ac0490f07964465a9df9cce38bee3f3']
I'm using Hive 1.1.0, cloudera cdh5.4.7, Hadoop 2.6.0. When i ran a query with an aggregation function with hive , i got the following error : ERROR : Job Submission failed with exception 'java.lang.IllegalArgumentException(Can not create a Path from an empty string)' The log file : INFO : Number of reduce tasks not specified. Defaulting to jobconf value of: 1 INFO : In order to change the average load for a reducer (in bytes): INFO : set hive.exec.reducers.bytes.per.reducer=<number> INFO : In order to limit the maximum number of reducers: INFO : set hive.exec.reducers.max=<number> INFO : In order to set a constant number of reducers: INFO : set mapreduce.job.reduces=<number> WARN : Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this. INFO : Cleaning up the staging area /user/hive/.staging/job_1453471005617_0680 ERROR : Job Submission failed with exception 'java.lang.IllegalArgumentException(Can not create a Path from an empty string)' java.lang.IllegalArgumentException: Can not create a Path from an empty string at org.apache.hadoop.fs.Path.checkPathArg(Path.java:127) at org.apache.hadoop.fs.Path.<init>(Path.java:135) at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:215) at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:390) at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:483) at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1306) at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1303) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:415) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1671) at org.apache.hadoop.mapreduce.Job.submit(Job.java:1303) at org.apache.hadoop.mapred.JobClient$1.run(JobClient.java:564) at org.apache.hadoop.mapred.JobClient$1.run(JobClient.java:559) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:415) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1671) at org.apache.hadoop.mapred.JobClient.submitJobInternal(JobClient.java:559) at org.apache.hadoop.mapred.JobClient.submitJob(JobClient.java:550) at org.apache.hadoop.hive.ql.exec.mr.ExecDriver.execute(ExecDriver.java:429) at org.apache.hadoop.hive.ql.exec.mr.MapRedTask.execute(MapRedTask.java:137) at org.apache.hadoop.hive.ql.exec.Task.executeTask(Task.java:160) at org.apache.hadoop.hive.ql.exec.TaskRunner.runSequential(TaskRunner.java:88) at org.apache.hadoop.hive.ql.Driver.launchTask(Driver.java:1638) at org.apache.hadoop.hive.ql.Driver.execute(Driver.java:1398) at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1182) at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1048) at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1043) at org.apache.hive.service.cli.operation.SQLOperation.runQuery(SQLOperation.java:144) at org.apache.hive.service.cli.operation.SQLOperation.access$100(SQLOperation.java:69) at org.apache.hive.service.cli.operation.SQLOperation$1$1.run(SQLOperation.java:196) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:415) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1671) at org.apache.hive.service.cli.operation.SQLOperation$1.run(SQLOperation.java:208) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Any idea please ?
9768f10201a72fff0263ebc373e1df7ffa073a4810c68f5f38ecd743ddcd9414
['4ad2e77766174db8985756557fadac70']
For the version 0.13.5 you will need a different set of parameters: def readExcel(file: String): DataFrame = { sqlContext.read .format("com.crealytics.spark.excel") .option("dataAddress", "'sheet_name'!A1") // Optional, default: "A1" .option("header", "true") // Required .option("treatEmptyValuesAsNulls", "false") // Optional, default: true .option("inferSchema", "true") // Optional, default: false .option("addColorColumns", "false") // Optional, default: false .option("timestampFormat", "MM-dd-yyyy HH:mm:ss") // Optional, default: yyyy-mm-dd hh:mm:ss[.fffffffff] .option("maxRowsInMemory", 20) // Optional, d[#All]efault None. If set, uses a streaming reader which can help with big files .load(file) } maven dependency: <dependency> <groupId>com.crealytics</groupId> <artifactId>spark-excel_2.11</artifactId> <version>0.13.5</version> </dependency>
5e86d71efbf44b5dda94075b41903f24a4f0ab75048ac7a4e872eaf136b3dc73
['4ad2e77766174db8985756557fadac70']
I am having a similar problem. But in my scenario the collection I am parallelizing has less elements than the number of tasks scheduled by Spark (causing spark to behave oddly sometimes). Using the forced partition number I was able to fix this issue. It was something like this: collection = range(10) # In the real scenario it was a complex collection sc.parallelize(collection).map(lambda e: e + 1) # also a more complex operation in the real scenario Then, I saw in the Spark log: INFO YarnClusterScheduler: Adding task set 0.0 with 512 tasks
9d8c950cdce882c0da294acabaae56ef140135f4b6c11cc7b6d5655fc5aa1078
['4ad4d2ee5fea41778ea1904450270103']
The error appears to be in the code below. I revised that part of your code. Try that and see if that works if (data.HasRows) { while (data.Read()) { Session["userid"] = data["UserID"].ToString(); Session["typeid"] = data["TypeID"].ToString(); } //make sure there is no space between these two lines if ((string)Session["typeid"] == "Student") return RedirectToAction("Profile"); //make sure there is no space between these two lines if ((string)Session["typeid"] == "Tutor") return RedirectToAction("TutorProfile"); //###if those two if clauses are not met, there is no return after that. return view(); //? or something else }
9ba59a49b9bc2787d38f398c263f313971648716341ac050d431ea263556e2d0
['4ad4d2ee5fea41778ea1904450270103']
I am not seeing any type of sort on my data when sorting by a "date" field in mongoDb queries. The "date_recorded" field IS a date field. I've also tried sorting on a time_stamp field. The sort order doesn't appear to be working whether it is ascending or descending. I cannot seem to figure out why it isn't working. I've tried it in: - Compass using the Aggregate tab. - Robo3t - VSCode using NodeJs (a schema model query) The output is always the same. Any help to get this working will be greatly appreciated... I've been searching Google and trying different things for about two hours now. Here is my query: db.getCollection('inputData').aggregate( { $match: { "inputData_userID": { $eq: "user1" } } } ,{ $project: { "date": 1 }} ,{ $sort: { "date_recorded": -1 }} ,function (err, docs) {} ) This is the output: /* 1 */ { "_id" : "0f30df7453b6096da524d3b61ce75eb1", "date" : "4/13/2017" } /* 2 */ { "_id" : "081be472b94804ae597706aa2bc4d9f4", "date" : "4/18/2017" } /* 3 */ { "_id" : "0005933cda516a4df346bf0807ab6ca4", "date" : "5/19/2017" } /* 4 */ { "_id" : "3a67cc9a5eb0a9197fa5448773bfec88", "date" : "4/14/2017" } /* 5 */ { "_id" : "1aefe9e79faaf4d65c6194b162311e08", "date" : "4/13/2017" } /* 6 */ { "_id" : "3f4c9d65c207d5cf620a00cee062a4c8", "date" : "4/13/2017" } Here is another query: db.getCollection('inputData').find( { "inputData_userID": { $eq: "user1" } } ,{ "_id": 0, "date": 1, "date_recorded": 1 } ,{ $sort: { "date_recorded": -1 }} ) Here is the output result of this query: /* 1 */ { "date_recorded" : ISODate("2017-04-13T08:54:24.024Z"), "date" : "4/13/2017" } /* 2 */ { "date_recorded" : ISODate("2017-04-18T22:01:20.767Z"), "date" : "4/18/2017" } /* 3 */ { "date_recorded" : ISODate("2017-05-19T00:03:03.081Z"), "date" : "5/19/2017" } /* 4 */ { "date_recorded" : ISODate("2017-04-14T06:12:55.320Z"), "date" : "4/14/2017" } /* 5 */ { "date_recorded" : ISODate("2017-04-13T23:53:22.692Z"), "date" : "4/13/2017" } /* 6 */ { "date_recorded" : ISODate("2017-04-13T08:55:38.721Z"), "date" : "4/13/2017" }
4c3ac5489f7db94e6385df1b8604f46dbb936fbcf3e69ba300e8fc7d2082c28b
['4af24e0d0b314867932f446932efee37']
As you've shown the probability of getting at least one side A in $n$ tosses is $p=\frac{1}{m}\cdot\sum_{k=0}^{n-1}(1-\frac{1}{m})^k$ which features a geometric series of ratio $(1-\frac{1}{m})$. So $p= \frac{1}{m}\cdot\frac{1-(1-\frac{1}{m})^n}{1-(1-\frac{1}{m})} =1-(1-\frac{1}{m})^n$. This gives a hint for a simpler method, as suggested by @MichaelHardy: The probability to have no side A in one toss is $(1 - \frac{1}{m})$, for $n$ tosses it's $(1 - \frac{1}{m})^n$. The probability to have at least one side A in $n$ tosses is the complement $1-(1 - \frac{1}{m})^n$. Both methods work.
91cbc234e2eb90c15e93a80c931cd8d8e627dcb66b81357405c86c9b425469b5
['4af24e0d0b314867932f446932efee37']
You have a few issues: users migration: $table->unique('username'); statement is for creating a unique index, not a column: http://laravel.com/docs/4.2/schema#adding-indexes Change it to this: $table->string('username')->unique(); - this will add a column and unique index for it. encomenda migration: $table->string('username')->unsigned();: unsigned is used only with integers, you can't make a string unsigned. Use the same code as in users migration: $table->string('username')->unique();
2e42ba96bdfb6ead67e74cedb42c210497f8ddff99d811e418ed3f6bb1727dbd
['4af4217301ed4c11ad686382db152d05']
In order to use rectangle1.getPerimeter() or rectangle1.getArea(), you need to create a class that looks something like this: public class SimpleRectangle { double height; double width; SimpleRectangle() { height = 1; width = 1; } double getArea() { return height * width; } double getPerimeter() { return 2 * (height + width); } } Then you need to create the object (as shown below) before you can use rectangle1.getPerimeter(): public class MainClass { public static void main (String[] args) { SimpleRectangle rectangle1 = new SimpleRectangle(); System.out.println("The area of radius " + rectangle1.getPerimeter() + " is " + rectangle1.getArea()); } }
3fc47f36034f2d78d9e8e74df3ba05ba2f8abb22504017b4d5fee32a04254f13
['4af4217301ed4c11ad686382db152d05']
The problem is that you need to create a object derived from class A before you can access its variables/methods using A a = new A(); where "a" is the name of the object. Then you can access the getter method by calling a.getIntI. You can also declare the int variable as static so that you wouldn't have to instantiate any objects. An example of class A with the static variable and getter method would be: public class A { private static int i = 1; public static int getIntI() { return i; } } With this, you can call the getter method with A.getIntI().
a3d24cabd98f731cb3523fd3d69ded07d10276b05b5bf0bd73c5c5e03bc0046c
['4b0304194c584f16a6aa807fed674aa7']
I want to redirect any request to the root of my site to an anchor on the index. So https://example.com/foo Gets sent to https://example.com/#foo I've written this .htaccess file (it also redirects http requests to https, that part works, but is included for completeness) RewriteEngine On RewriteRule ^/(.*) /#$1 [NE,R=302] RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] Based on the discussion in this thread: mod_rewrite with anchor link this should work, but it's not matching for some reason. I tried out the rule given in that thread using this tool: http://htaccess.madewithlove.be/ and it doesn't seem to work there either. I've tried clearing my cache and accessing in incognito mode, to no avail. Any help?
7a4cdaec31659cbfcf1794061303e09f81660c32e3bd072a418036419b94d402
['4b0304194c584f16a6aa807fed674aa7']
I'm using a JQuery UI DatePicker to choose dates on one of the forms in the app I'm writing. Thus, my form input is a generic text field and I'm accepting a free form date string. According to this RailsCast, saving these strings to the database (I'm using MySQL) should "just work." I'm finding that not to be the case though. When I save my form, it's interpreting the date in the form: dd/mm/yyyy, when I'm entering mm/dd/yyyy. Is there a way to tell rails that I'm going to be entering dates in the mm/dd/yyyy format, or do I need to monkey around with the data in my controller?
c9ce8180dcf9d8faba1936ea52a79fca1603e69103db068bdbe9de77f250729e
['4b0b93aa31914e4aa5c5dfdd9133deac']
I would go with the 10 oz. per adult. Children less. Cooked weight. As if extra some will take some home with them. This saves some from staying overnight on your floor to finish it for breakfast. So a good meal but not to much all are happy about. Were I live it is a insult to leave before all meat is gone. To your home. But all like to be well fed & happy.
711c06cada7f51a36d4bf6bf321c125fc2475b5988f99e889fd670f4e6bef354
['4b0b93aa31914e4aa5c5dfdd9133deac']
It is safe as U.S.D.A inspected. I do wonder if it is from tougher breeds of beef? Beef can be aged at 27f to 29f in shipping. To age it. Make it tender. As bacteria works on it at that temp. Tenderizes it. So some what different than American grain fed beef. Little different texture & taste. But safe. I am more familiar with Australian beef that is shipped that way to Europe & Asia.
419702fdbe7496d08860ab85f8762533641b9cb8f696b0b159c71fb645664061
['4b28e125c3f5494cb95c6842f55868d8']
Tesseract provides a parameter to set the page segmentation mode (-- psm). Below are all the modes, as shown in the documentation: Page segmentation modes: 0 Orientation and script detection (OSD) only. 1 Automatic page segmentation with OSD. 2 Automatic page segmentation, but no OSD, or OCR. 3 Fully automatic page segmentation, but no OSD. (Default) 4 Assume a single column of text of variable sizes. 5 Assume a single uniform block of vertically aligned text. 6 Assume a single uniform block of text. 7 Treat the image as a single text line. 8 Treat the image as a single word. 9 Treat the image as a single word in a circle. 10 Treat the image as a single character. 11 Sparse text. Find as much text as possible in no particular order. 12 Sparse text with OSD. 13 Raw line. Treat the image as a single text line, bypassing hacks that are Tesseract-specific. Does -- psm 1 have the same effect as deskewing the image and then using e.g. -- psm 3?
3f63ddc592baf3f7ad8a168dd2c4ec086945c2c0f1ea4a10e73508a6542c3e31
['4b28e125c3f5494cb95c6842f55868d8']
You can convert the pdf to images for each page using fitz. # import packages import fitz import numpy as np import cv2 #set path to pdf path2doc = <path to pdf> #open pdf with fitz doc = fitz.open(path2doc) # determine number of pages pagecount = doc.pageCount # loop over all pages and convert to image (here jpeg) for i in range(pagecount): page = doc[i] pix = page.getPixmap().getImageData(output='JPEG') jpg_as_np = np.frombuffer(pix, dtype=np.uint8) image = cv2.imdecode(jpg_as_np, flags=1) Once this is done, you can send them to the API
2f15b5cb663d59d4bc7a6d6435acaf111a59052804a915de1d6af1986eb9ed4e
['4b36cdca3e5942fcae73f1b074a963d0']
I have an Artist Model which has many Reviews. Also Artists has many Gigs which in turn also has many reviews. The reviews can dierctly come for the Artist and as well as from the Gigs that the Artist does. I want to be able to do something like this: Artist.first.reviews # Should return reviews directly from the artist as well as from artist.gigs How do I model this? Should I define a new method like all_reviews in my model that fetches and merges the reviews or is there any straight forward way through associations?
41eace1b809ba903762993808c189480666a67f4102d308fadb528e272c39bb0
['4b36cdca3e5942fcae73f1b074a963d0']
I wrote some code to generate custom controls. The code returns a jQuery element and the caller appends this jQuery element to the DOM. I apply a custom scrollbar to the control in the generator code, but it doesn't get applied as the element has not been appended to the DOM yet. My question: Is there any onAppend event or something like that, so that I apply the custom scrollbar at the time when the element has been appended to the DOM? Sample code for generator: function getControl(controlParams){ var $control = $('<div/>'); $control.applyCustomScrollBar(); //Not appended to DOM yet, so doesnt work return $control; } Sample code for consumer: var $control = getControl(controlParams); $("body").append($control); //Appending to DOM now Want to do something like: function getControl(controlParams){ var $control = $('<div/>'); $control.onAppend(function(){ $(this).applyCustomScrollBar(); }); return $control; }
a4b81fdda038c7807e5f00e4dc64d234911f0ab2479eb0aef3823e85cc6c8104
['4b6489d347b1457a9ea4898be8b3231c']
I'm trying to find the position of the number typed by the user (int findNumber). I realise that I have to return an instance of the type Position, but I'm not sure how to do it. I created an instance in my 'Main' called "numberPosition", but I can't use it in the other class. This is probably very basic stuff but I really can't figure it out. I'm very new to programming, sorry if the question is worded vaguely. Please go easy on me. Main class Program { Random RNG = new Random(); static void Main(string[] args) { Program FindNumber = new Program(); FindNumber.Start(); } void Start() { int[,] matrix = new int[8, 10]; InitMatrixRandom(matrix, 0, 100); DisplayMatrix(matrix); Console.WriteLine("Give the number to be searched: "); int findNumber = int.Parse(Console.ReadLine()); Position numberPosition = new Position(); numberPosition.FindNumber(matrix, findNumber); Console.WriteLine(numberPosition); Console.ReadKey(); } void InitMatrixRandom(int[,] matrix, int min, int max) { for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { matrix[row, col] = RNG.Next(min, max); } } } void DisplayMatrix(int[,] matrix) { for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { Console.Write(string.Format("{0,3} ", matrix[row, col])); } Console.Write(Environment.NewLine); } } } Class class Position { public Position numberPosition = new Position(); public Position FindNumber(int[,] matrix, int findNumber) { int row = matrix.GetLength(0); int col = matrix.GetLength(1); int y, x; for (y = 0; y < col; y++) { for (x = 0; x < row; x++) { if (findNumber == matrix[y, x]) { return numberPosition; } } } return null; } }
175095dcf04376da1ca5f53f8e19cbbd65295b3cbb909d03ea7d7a29b326fbe0
['4b6489d347b1457a9ea4898be8b3231c']
I'm new to learning C# and I was wondering how to keep adding numbers I type to a total number. Right now instead of adding up all the numbers I typed in before typing 0, it just takes the last typed in number... The number count does go up however, which is why I'm pretty confused. For example: Enter number: 2 Enter number: 6 Enter number: 4 Enter number: 7 Enter number: 0 There are 4 positive numbers (Works like I intended) The total amount is 7 (Is supposed to be 2+6+4+7 = 21) Console.Write("Enter number: "); string numberInput = Console.ReadLine(); double number = double.Parse(numberInput); int count = 0; double begin = 0; double total = 0; while (number != 0) { if (number >= 0) { count++; total = begin + number; } Console.Write("Enter number: "); number = double.Parse(Console.ReadLine()); } double average = total / count; Console.WriteLine("There are {0} positive numbers", count); Console.WriteLine("The total amount is {0}", total); Console.WriteLine("Your average is: {0}", average); Console.ReadKey();
b6e04f438ac156e9609011da5cdd441069028dea2cfd6cf6d965abf5cf893372
['4b6601795f1443549be3adb5260da268']
Try the windows API ShellExecute function. Not sure of the VB syntax (this works in FoxPro)... DECLARE INTEGER ShellExecute IN shell32.dll ; INTEGER hndWin, ; STRING cAction, ; STRING cFileName, ; STRING cParams, ; STRING cDir, ; INTEGER nShowWin cFileName = "d:\MyDocs\myfile.pdf" cAction = "open" ShellExecute(0,cAction,cFileName,"","",1) ...but the user will have to fill in the fields by hand.
4ec6bfce26d6de94a11f4cedab558dfaf6ade36283dea6de0403d265f7d63eeb
['4b6601795f1443549be3adb5260da268']
<PERSON> I installed Key Codes as you suggested. But the left Shift key doesn't show any response. However, if I use mouse to select some text in a page, it is showing the behaviour as if Shift key is pressed and holding! Similarly if I click on a new link, a new window opens (as if I pressed Shift key and clicked the mouse)!
23d68db47b1f18867533bda9da267f46d5bf11ccdd8850af80d3bfcdb9f0176a
['4b6c2a56fd7440129438e243b1b2cce4']
You are comparing two strings and when you save np array to text file the precision before e changes thatswhy even if value are same string doesn't match. I have come up with this solution. I am not master at numpy and python but i know some of this tricks. Feel free to suggest more elegant or obvious ways to do this. import numpy as np #create an example file example=np.array([[1.0, 2.1e-06, 3.3], [5.0, 6.3, 7.8e-03]]) filename='/home/Desktop/example.txt' np.savetxt(filename, example, header ='exmpl') #find the line number of a lookup value in the txt file lookup = 5.0e-00 with open(filename) as fp: for num, line in enumerate(fp): for i in line.split(): #print(i) try: if float(i) == lookup: print(num) except ValueError as e: pass
cfe3e13c9048f7fcb6d2ff364930174fd5a48c5858f7f832bf41f8d4e011cc22
['4b6c2a56fd7440129438e243b1b2cce4']
You just have some syntax errors in your code but your logic is correct.. Here is what you intended to do, inp= int(input()) list1 = [] while inp != 0: list1.append(inp) inp = int(input()) def isPalindrome(N): str1 = "" + str(N) len1 = len(str1) for i in range(int(len1 / 2)): if (str1[i] != str1[len1 - 1 - i]): return False return True list2 = [] for i in list1: if isPalindrome(i): list2.append(i) print(list2) Also if you want to make your program much shorter than i recommend this, def isPalindrome(N): str1 = str(N) if str1[<IP_ADDRESS>-1] == str1: return True else: return False Just a slight change in synatx but logic is though same as yours. It uses string slicing in reverse direction. Also i have type casted the input to integers using int(input()) as you said you need numbers to be printed in list2, if you don't want integers then just replace all int(input()) with input() and change your if condition to int(inp)!=0 at beginning
3e484675112eb797edea46aaf72fce37a82c44558a0141705b4406f75a9308a4
['4b74853a22bd4027b62e1fb40a54580f']
What you are saying in the last paragraph is exactly the reason why I posted. The fact that I have a very small amount of available data made me consider about having both pipelines. After the first pipeline, I would kind of create my new dataset, which would then be considered for the second one. Besides the need of more data before feeding the model, I also need to crop some of the images using OpenCV, so this pre-processing step would contain both the enlargement of the dataset and the cropping of the images when needed! You were very helpful, thank you so much!
b2c7f8f4087ea1d235e64f2095d63ccf42239b5454d6bd1266b75fd5bedc743a
['4b74853a22bd4027b62e1fb40a54580f']
Sendmail supports a feature called 'plussed users'. Once enabled, emails sent to <EMAIL_ADDRESS>, <EMAIL_ADDRESS> and <EMAIL_ADDRESS> are automatically delivered just like mails to <EMAIL_ADDRESS>. There is no need to register or set up these 'plus suffixes'. The user can just use them and set up client-side filtering rules on his own. Does Exchange support a similar mechanism? If so, how to enable it? Note that I don't want answers about other means of filtering, e.g. spam/junk filtering, server-side or client-side rules, email aliases/addresses that are configured explicitly and so on.
d616efab0578d1acfda38b5535a564c08fcdcd3ba1d07bee991e56a4c691bb8b
['4b76608ff52d487db671c7bc682f805f']
I'm working with typescript and I have an object with with fields referred to by both strings and numbers. I know if it is indexed by just strings I can specify the type with var object: {[index: string]: number} Is there a way to do this that will allow the index to be either a string or a number? I've tried var object: {[index: string|number]: number} with no luck.
ed499f00177713999abcbcfed8ef7be6ed535e3a8c4e646c1fe221448663440b
['4b76608ff52d487db671c7bc682f805f']
I have a for loop in a function in the structure func(var, callback) { for(i = 0; i < len; i++) { validate(var, function(value) { if (!value) { callback(value) } } } callback(true); } Where the function validate returns a boolean. I would only like to call my callback with true if it has not been called before. I tried putting a return after callback(value) but that didn't help.
40ad228bf88ca30d49bbe4f5ab8cd8fdb2a704e99693f10decb5fa144022191a
['4b7f806e10f04a46a088f1c10915cb0e']
So I am given a ring of even integers. It is an isomorphism of Z to R that is defined by f(x)=2x+4. I am trying to find the O(R) and the 1(R). I just set the function equal to 0 or 1 but apparently that is not the right thing to do in this case. Any rational as to what I am doing wrong or the correct way to think about it to set it up right? Should you plug in 0 for 2 instead?
4fed3a51ea2095b8711ea871e9e7d444afb473c8175d8c445271b24b8615e0f8
['4b7f806e10f04a46a088f1c10915cb0e']
I think you're right about the species of both snakes as they appear in the movie. They clearly used pythons for filming. <PERSON> in the book, though, seems to be a magical creature created by <PERSON>. Because her species is never given in the books, she may be one of a kind (thus why I think she was created by <PERSON> and not one of a pre-existing species). She does seem to have characteristics of cobras, pythons and maybe green anacondas, but you can't pin her down to any one species known to muggles.
708c808fc895ab163f61fc9d6ee4970dfe63b1e69c4484777d6e8dee592fe4bf
['4b86f9bf21e44c7a8a51c69cbdc24b79']
I'm trying to sort a collection of type Enumerable<DataRow> by using LINQ's OrderBy method on a nullable Int32 field. Because some of the values of this field are null, Visual studio throws a System.ArgumentException with message 'Object must be of type Int32.' Here is the problematic line of code: collection1 = collection1.OrderBy(row => row["Column1"]); where Column1 is the nullable Int32 field and the variable collection1 is declared as: IEnumerable<DataRow> collection1; Is there a way to rewrite the above line so that it ignores the nulls?
39e31ab4d9c6c95430a41f53d600edd88d8fefa9c15993b63c67a70f2119d809
['4b86f9bf21e44c7a8a51c69cbdc24b79']
I have a custom DNN module that works well in DNN 5. After modifying the module to work in DNN 7 and installing it successfully, nothing happens when I drop one of the module's controls on a page. In the event viewer, I see the following log entry of type 'Host Alert': ============================================================================= EventQueue.ProcessMessage: Message Processing Failed ProcessorType: DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke Body: Sender: BusinessControllerClass: Nedoweb.Modules.Survey.SurveyController desktopModuleID: 87 ExceptionMessage: Value cannot be null. Parameter name: type Server Name: MyComputerName ============================================================================= Any help is greatly appreciated!
4ab5cfce7981cb37c942153f6bd0deceda0314b45f3d24038de71a00ce0078b1
['4b883f18a86a44a2bee9a260f13f7f8e']
I am trying to create an animated banner using JQuery, rather than use an animated gif. The Cycle Plugin executes this well in FireFox, but in Safari and Chrome, upon initially loading the page, I do not observe the "slideshow" and only see a single image. I have attempted to resolve this via .load(), preloading the images, and using display: hidden on the subsequent images, each without success. Curiously, I have noticed that the single image that does load is in fact the smallest image (in file size) of all the images. Any input is appreciated. I am stumped. jQuery(document).ready(function() { $('#banner').cycle({ fx: 'none', delay: 0, speed: 500, autostop: true, autostopCount: 8, timeoutFn: function(currElement, nextElement, opts, isForward) { opts.myTimeoutCount = (opts.myTimeoutCount + 1) % opts.myTimeouts.length; return opts.myTimeouts[opts.myTimeoutCount]; }, myTimeouts: [1000,1000,500,500,500,2000,2000,1000], myTimeoutCount: 0 }); }); <div id="banner"> <img src="images/if_300x250_banner_1.gif" width="300" height="250" /> <img src="images/if_300x250_banner_2.gif" width="300" height="250" /> <img src="images/if_300x250_banner_3.gif" width="300" height="250" /> <img src="images/if_300x250_banner_4.gif" width="300" height="250" /> <img src="images/if_300x250_banner_5.gif" width="300" height="250" /> <img src="images/if_300x250_banner_6.gif" width="300" height="250" /> <img src="images/if_300x250_banner_7.gif" width="300" height="250" /> <img src="images/if_300x250_banner_8.gif" width="300" height="250" />
78e08c6cbd59e215382425d42e7fbb73f4f911d3131e1ae70f3c410d6aa6cf23
['4b883f18a86a44a2bee9a260f13f7f8e']
Persistence pays off. It turned out that the problem was not with JQuery, the Cycle Plugin, or the Webkit browsers, but with the images. The source PSD that I used to create the gifs held the Photoshop layers in an animation timeline and that data was being included when I was using "Save for Web & Devices" in Photoshop- interesting that it did not pose a problem in Firefox. The solution was to simply "Delete Animation" in the Animation palette and save the gifs once more. Thanks to all who pondered this one.
88b19863d499f69aa085a01f5ce6f0171b539700a351a2a3088a5f2a6841b913
['4bb2b9fe821b4974b63ea1cfb4d6e34b']
I have an app that imports an excel but the excel in question has black spaces in some of the cells, when I receive it puts those blank spaces in my database. I want to prevent that to happen, i tried to use regex and replace(" ","") and nothing work. Can you help me? This is my code: File file = new File(inFileName); Workbook workBook = WorkbookFactory.create(file); Sheet sheet = workBook.getSheetAt(0); int rowCtr = 34; Row myRow = sheet.getRow(rowCtr++); while (myRow != null) { Cell nif = myRow.getCell(0); Cell marcaexploracao = myRow.getCell(1); Cell numerochip = myRow.getCell(2); Cell marcaauricular = myRow.getCell(3); Cell datanascimento = myRow.getCell(4); //problem I mentioned is is in chipnumber only bd.addAnimais(chipnumber.ToString().replaceFirst("/[^0-9]/","-"),marcaexploracao.toString(),marcaauricular.toString(),datanascimento.toString(),nif.toString(),0,"","","","",0); myRow = sheet.getRow(rowCtr++); } }catch (Exception e){e.printStackTrace(); }
9f1e93dad970946ab813c9e52fcded9b21d4514bbc70029328b1f333a47fbad1
['4bb2b9fe821b4974b63ea1cfb4d6e34b']
I have an application in Android that reads from an excel. I want to replace the while loop and put the for loop. I have only 3 columns so I think theres is another way to do this. Can you show me how to do this while loop with a for loop using only rows and 3 columns? private void readExcelFile() { try{ String inFileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+"ola.xlsx"; File file = new File(inFileName); Workbook workBook = WorkbookFactory.create(file); Sheet sheet = workBook.getSheetAt(0); Iterator<Row> rowIter = sheet.rowIterator(); //this is the loop I talked about while(rowIter.hasNext()){ Row myRow =rowIter.next(); Iterator<Cell> cellIter = myRow.cellIterator(); while(cellIter.hasNext()){ Cell myCell = cellIter.next(); Toast.makeText(getApplicationContext(), "cell Value: " + myCell.toString(), Toast.LENGTH_SHORT).show(); } } }catch (Exception e){e.printStackTrace(); } return; }
5d74f8951b66958f44d332e8f39dc52dc2f7588ff11ff9d8ef592dc5e531e443
['4bbe14ce5ce94b9da347b90d55d6b2e4']
@JeffE I think that was meant relatively, not absolutely -- for example, you might be _known_ in your field, but perhaps only to a certain niche, or by people who read _all_ new papers and have noticed yours. Contrast that with someone who's a household name in the field. (And, of course, there's a full range between the two points.)
9ea7d7a7f3f0999bcddab6f77992e1743b653adb3b534b1bf3dbc3293f6ad4bc
['4bbe14ce5ce94b9da347b90d55d6b2e4']
@CaptainEmacs Oh, I would definitely be mildly put-off and a little colder, for sure. I wasn't saying it would be inappropriate to have _any_ negative feelings for that. It is pretty insulting, after all. It just seems extreme to react that harshly to one incident, no matter the circumstances, as this post implies.
5d1fe4300a85af6adab5169f9e859526cc2ca6cac046abd1d9d7e8929a334318
['4bd20136231d41f08372002ca17883db']
I saw this error when I added songs directly from the "For You" or "New" tabs in iTunes to a playlist. To fix the error for my playlist I manually added the songs to My Library, then added them to a playlist. I was then able to sync that playlist.
5351a3e0e525a93b6cbb903acb7c4199e0367be066ab482974017107c7e68d58
['4bd20136231d41f08372002ca17883db']
I'm working on a project to familiarize myself with more complex sql, I have limited db experience. I'm building a reporting application, and each report will have a series of questions and category types the user can select. I plan to have multiple analytic functions, but to get off the ground I'm simply doing a select *. The result I'd like to see in my app is a list of Report objects like (java) public class Report { // report table columns... List<Questions> questions; List<Cattype> catTypes; } I'm afraid doing this in one massive join'd query will suffer from cartesian explosion. CREATE TABLE report ( reportid bigint not null, useraccount varchar(64) NOT NULL, geotag geometry(POINT, 4326) default null, text varchar(256) not null, CONSTRAINT pk_report PRIMARY KEY (reportid), CONSTRAINT enforce_geotype_geotag CHECK (((geometrytype(geotag) = 'POINT'::text) OR (geotag IS NULL))), CONSTRAINT enforce_srid_geotag CHECK ((st_srid(geotag) = 4326)) ); create table cattype ( cattypeid SERIAL, title varchar(64) not null, CONSTRAINT pk_cattype PRIMARY KEY (cattypeid), CONSTRAINT unique_cattype_title UNIQUE (title) ); create table question ( questionid SERIAL, title varchar(256) not null, CONSTRAINT pk_question PRIMARY KEY (questionid), CONSTRAINT unique_question_title UNIQUE (title) ); create table report_cattype ( id SERIAL, reportid bigint not null, cattypeid integer not null, CONSTRAINT pk_rc PRIMARY KEY (id), CONSTRAINT fk_rc_report FOREIGN KEY (reportid) REFERENCES report (reportid) match <PERSON><IP_ADDRESS>text) OR (geotag IS NULL))), CONSTRAINT enforce_srid_geotag CHECK ((st_srid(geotag) = 4326)) ); create table cattype ( cattypeid SERIAL, title varchar(64) not null, CONSTRAINT pk_cattype PRIMARY KEY (cattypeid), CONSTRAINT unique_cattype_title UNIQUE (title) ); create table question ( questionid SERIAL, title varchar(256) not null, CONSTRAINT pk_question PRIMARY KEY (questionid), CONSTRAINT unique_question_title UNIQUE (title) ); create table report_cattype ( id SERIAL, reportid bigint not null, cattypeid integer not null, CONSTRAINT pk_rc PRIMARY KEY (id), CONSTRAINT fk_rc_report FOREIGN KEY (reportid) REFERENCES report (reportid) match simple, CONSTRAINT fk_rc_cattype FOREIGN KEY (cattypeid) REFERENCES cattype (cattypeid) match simple ); create table report_question ( id SERIAL, reportid bigint not null, questionid integer not null, CONSTRAINT pk_rq PRIMARY KEY (id), CONSTRAINT fk_rq_report FOREIGN KEY (reportid) REFERENCES report (reportid) match simple, CONSTRAINT fk_rq_question FOREIGN KEY (questionid) REFERENCES question (questionid) MATCH SIMPLE ); INSERT into cattype (title) values ('Water'); INSERT into cattype (title) values ('Fire'); INSERT into cattype (title) values ('Structural'); INSERT into question (title) values ('Damage visible from exterior?'); INSERT into question (title) values ('Damage visible in interior?'); INSERT into question (title) values ('Repair?'); INSERT into question (title) values ('Replace?'); insert into report values (1, 'user1', null, 'test1'); insert into report values (2, 'user1', null, 'test2'); insert into report values (3, 'user1', null, 'test3'); insert into report values (4, 'user1', null, 'test4'); insert into report values (5, 'user1', null, 'test5'); insert into report values (6, 'user1', null, 'test6'); insert into report values (7, 'user1', null, 'test7'); insert into report values (8, 'user1', null, 'test8'); insert into report values (9, 'user1', null, 'test9'); insert into report values (10, 'user1', null, 'test10'); insert into report values (11, 'user1', null, 'test11'); insert into report values (12, 'user1', null, 'test12'); insert into report values (13, 'user1', null, 'test13'); insert into report values (14, 'user1', null, 'test14'); insert into report values (15, 'user1', null, 'test15'); insert into report_cattype (reportid, cattypeid) values (1, 2); insert into report_cattype (reportid, cattypeid) values (1, 3); insert into report_cattype (reportid, cattypeid) values (2, 1); insert into report_cattype (reportid, cattypeid) values (3, 3); insert into report_question (reportid, questionid) values (1, 1); insert into report_question (reportid, questionid) values (1, 2); insert into report_question (reportid, questionid) values (1, 4); insert into report_question (reportid, questionid) values (2, 2); insert into report_question (reportid, questionid) values (2, 3); insert into report_question (reportid, questionid) values (3, 1); insert into report_question (reportid, questionid) values (3, 3); Initial query looks like select r.*, rc.*, cattype.*, rq.*, question.* from report r left join report_cattype as rc on (r.reportid = rc.reportid) left join cattype on (rc.cattypeid = cattype.cattypeid) left join report_question as rq on (r.reportid = rq.reportid) left join question on (rq.questionid = question.questionid) Now I'm thinking I'm better off running multiple queries and combining them together in my application - Query all reports, then query table report_question or report_cattype for each report. Thoughts?
87b21ef8c55df20381ceceae86811a0f05cc3b6c5fc0501125790f8423c7bb4b
['4bd335745225449ab4aa93b6d67127bb']
I assume those are control characters (eg. end of line character EOF etc) that are not visible in the text editor, yet still can be copied. Are you using "select all" short-cut like ctrl+a? Try selecting the text with mouse or shift+arrow-keys and end your selection exactly after the last character of your text.
081fe65252dae6b0d1594bc96503b1251ec7a51b6868f6f664cd7dfac35b54c7
['4bd335745225449ab4aa93b6d67127bb']
I had similar problem. I had an iteration, and sometimes execution took so long it timed out. Increasing spark.executor.heartbeatInterval seemed to solve the problem. I increased it to 3600s to ensure I don't run into timeouts again and everything is working fine since then. From: http://spark.apache.org/docs/latest/configuration.html : spark.executor.heartbeatInterval 10s Interval between each executor's heartbeats to the driver. Heartbeats let the driver know that the executor is still alive and update it with metrics for in-progress tasks.
bd392f9c6c992c56f9e3d63b34b1bb04feb0293dfbd1e8fb6ddb86b9c47bfd03
['4bd9e93ddafe4762b77864420e81d001']
In order to improve insert performance and load on server, I've decided to divide a large table into 2. A big table which will only be used for "select" and a smaller table which will be used mainly for "insert" and sometimes also "select". Each time period (I thought about a day) I will merge the smaller table into the big one. Regrading the big table: is there a way I can improve performance by telling the mysql server it's read-only? Considering it's only for select, can I assume it will handle SELECT in less than 1sec. when it will become ~1e9 rows? Regarding the small table: any tuning I should do here? what is the best way to develop an automated merge process from the small to the big table (in php)?
89f99fc186396a8681bd009fbfcfe4c619c05734ba40a5450a1c650927051f04
['4bd9e93ddafe4762b77864420e81d001']
PHP mysql_connect is sometimes failing due to "too many connections". When checking the process status list, I am noticing that when this happens there are very long processes which are in sleep state. How long? time:28490 This is how I init the connection: $this->connection[$server] = mysql_connect( $credentials['dbUrl'], $credentials['dbUser'], $credentials['dbPass'], true); This doesn't happen all the time, just sometimes that connections get 'stuck'. I assume it might have something to do with something on the page not finishing (image not loading? external service stuck?). When does a script officially finish? Is it after the page loads completely? I've thought of two possible solutions: 1. Using mysql_close. 2. Changing max mysql timeout (/etc/my.cnf) 3. Handle script timeout. What reasons can cause a connection to become stuck in 'sleep'? How would you suggest to resolve / further investigate the issue?
d9f8a037779bc16eba318c035787a8c6492a98db5a4bc9fd9c9b7006a2330a38
['4be8c96385ee4fe5b27fe8a4c5d08e3e']
When I was running the following code in a function, I encountered the following error. However, when I run these lines, there is no error. The error appears at Line 185, TypeError: unsupported operand type(s) for +: 'dict' and 'int' Line 183 was my original code, which includes a dictionary. But now I'm not using dictionary anymore, whey the error is about dict?? 183 # N_layer = inputs["N_layer"] 184 N_layer = 18 185 n_uw = np.zeros((N_layer + 2), dtype=int) 186 n_dw = np.zeros((N_layer + 2), dtype=int) 187 n_gas = np.zeros((N_layer + 2), dtype=int) The result should be array of zeros.
e82b2dd1181754e726ee75ba41a86db9caa90f0d8c9fdd82ca1642b1893a2708
['4be8c96385ee4fe5b27fe8a4c5d08e3e']
Before I installed Anaconda in my computer before but accidentally uninstalled it. As I tried to re-download and re-install it, I found a problem. Although the system shows installation is complete, the entire Anaconda3 folder is only 700M+ in size, which is much smaller than normal. Also, I cannot find anaconda in start menu. What should I do to correctly re-install this software? I have tried this for several days. Thank you very much!
3ddda25ea24cb544f989c45818da13a9d30f78b10b186dee97db8c7ca1cc4287
['4c1c1401567f4edabc8935f276a2abc5']
The problem is to push json logs collected by Filebeat to Elasticsearch with defined _type and _id. Default elastic _type is "log" and _id is smth. like "AVryuUKMKNQ7xhVUFxN2". My log row: {"unit_id":10001,"node_id":1,"message":"Msg ..."} Desired record in Elasticsearch: "hits" : [ { "_index" : "filebeat", "_type" : "unit_id", "_id" : "10001", ... "_source" : { "message" : "Msg ...", "node_id" : 1, ... } } ] I know how to do it with Logstash, just use document_id => "%{unit_id}" and document_type => "unit_id" in the output section. The goal is to use only Filebeat. Because it is a very-light weight solution and no intermediate aggregation is needed here.
f331802ebd0cd657b13c15fe1c00f4ee6ce4e5b3ab8e974cb7f3ad4731c04111
['4c1c1401567f4edabc8935f276a2abc5']
Finally the solution is: iptables -A INPUT -i eth0 -p tcp --dport 80 -m hashlimit --hashlimit 1000/sec --hashlimit-burst 5000 --hashlimit-mode dstip --hashlimit-name hosts -j ACCEPT iptables -A INPUT -i eth0 -p tcp --dport 80 -j REJECT Do not block SE-crawlers packets and resists against http-flood like: ab -n 1000 -c 100 http://{host}/
f300677a619a0ca4222fed71866467e4b06b782b43cbb7cca08bc40d92f6d312
['4c231ed41f744edbb6f252d3c61b91a4']
I see what you're saying, I think. I initially tried `paste MASTER.txt ${FILE}_trimmed.txt > MASTER2.txt` but that obviously doesn't work if I'm looping through files. I just end up with the final S file joined to the MASTER. So, still unsure how to get the result I'm looking for. I'm used to working in R, where I could possibly store as a temp variable and then output the file at the end. Unsure if that is plausible here or a good way of doing this...
10288ca0f176af5c95a839e01ae70eb23a491d1792bb4db1188edf5b987b3f16
['4c231ed41f744edbb6f252d3c61b91a4']
Thank you to 1_CR , who answered this in the comments. The > MASTER.txt is truncating the file before the paste actually completes the horizontal join. The answer is to output to a temporary file (e.g. MASTER2.txt) and then rename it (with the mv command) to the proper file name. My Old Code: paste MASTER.txt ${FILE}_trimmed.txt > MASTER.txt Fixed Code: paste MASTER.txt ${FILE}_trimmed.txt > MASTER2.txt && mv MASTER2.txt MASTER.txt
ed3d7910b4e5f5378c1677a951dd7e807697db4359fbbc797a953bda5c891b3d
['4c2727db4c1044e0bf514f2312cf8800']
I'm working on a typo3-based system (Version 4.7), and trying to get the contact-email-form to work. It is a fairly simple one (Name, Email, some fields like Adress and a Question Text) to send a simple text based email. The plugin I'm currently using is powermail. When testing this form on my local version of the system it is sending the email to my adress without a problem - on the live system, however, it only displays the message An error occurred while trying to call Tx_Powermail_Controller_FormsController->createAction(). Error: Required property 'form' does not exist. what I already know: The Problem seems to be that the html form is not submitting any POST data to the extension controller and therefore it has nothing to work with and is displaying that error ... This is not a problem with powermail, building the form with other extensions (mailformplus, the built-in form plugin ...) has the same problem: no post data is sent. It's also not a problem with POST-data on that server in general, calling a simple test script like this: <form method="post" action="test.php?gettest=1" enctype="multipart/form-data"> <input type="text" name="test" value="" /> <input type="submit" name="submit" value="Testen" /> </form> from a script not in the typo3-system displays GET: array (size=1) 'gettest' => string '1' (length=1) POST: array (size=2) 'test' => string 'test' (length=4) 'submit' => string 'Testen' (length=6) correctly in test.php (which is just a var_dump($_POST/$_GET)). However, building the above as a page in the typo3 system shows shows an empty POST array in test.php. The problem is the same with realurl disabled. Now my question is, could there be anything else in typo3 rewriting/redirecting request that POST-data might get lost? As I said, my local system works and I really can't findd any configuration difference between those two ... (but I'm also still far away from understanding every bit of the typo3 CMS' internal working)
3f5e21f32aa0fc4c5cccc0ee2566b29ffb1fa225996f078c1c1a21996803dcdf
['4c2727db4c1044e0bf514f2312cf8800']
This looks to me like a lazy-loading-issue. How do you get the data from the object into the Webservice answer? Doctrine2 is lazy-loading if you don't configure something else, that means your $groups = $em->getRepository("orgGroup")->findAll(); won't return real orgGroup objects, but Proxy objects (Doctrine Documentation). That means a $group object won't have it's description or orgGroupType value until you call $group->getDescription() or $group->getOrgGroupType() (then Doctrine loads them automatically), so you need to do that before writing the data into the JSON-response for the webservice. It won't work if you somehow loop through the object properties without using the getter methods. I hope that was the problem :)
4984d539e62e5d5357506ce3eece94c92b70bd8d4081d3b47044fee081fe9c4c
['4c348e480ed44cf882cc25a540ff2d70']
I am having my main circuit breaker panel replaced (by a licensed electrician) and he told me I can run new circuits for him to hook up to the new panel. Is there any benefit to running 240v circuits for computers, network equipment, other devices that support it? I would probably put a 120v outlet next to any 240v just for convenience (I was thinking on opposite sides of each stud.
70a72ab93b2df81cb97ec0b542a56d213499b8f3408485155d0fd0b8111ed989
['4c348e480ed44cf882cc25a540ff2d70']
Encontrei o problema, o modulo Ng2-Smart-Table necessita da classe LocalDataSource para alimentar a tabela, quando os dados tem origens externas, como o Firebase, ou algum outro service. Outro problema é que a minha variável solicitação estava fora do escopo e assim me retornava undefined. Abaixo o Código atualizado: import { NgxDatatableModule } from '@swimlane/ngx-datatable'; import { LocalDataSource } from 'ng2-smart-table'; import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'; import { forEach } from "@angular/router/src/utils/collection"; @Component({ selector: 'app-tabela', templateUrl: './tabela.component.html', styleUrls: ['./tabela.component.scss'] }) export class TabelaComponent implements OnInit { source: LocalDataSource; filTipo: string = 'todos'; dados: FirebaseListObservable; public solicitacoes: any; constructor(private db: AngularFireDatabase) { this.dados = this.db.list('/solicitacoes'); this.source = new LocalDataSource(); let _self = this; this.dados.forEach(element => { _self.source.load(element); }); } ngOnInit() { } settings = { selectMode: 'multi', columns: { tipo: { title: '<PERSON>', }, endereco: { title: 'Localização', }, descSolicitacao: { title: 'Descrição', }, data: { title: 'Data', }, status: { title: 'Status', }, }, actions: { add: false, edit: false, delete: false, open: true, } }; }
ff960534d0b90cfee53ac0e5cfd9aa7ae251af651d582b9294167d97a60b3b67
['4c4c94444cb145629543a16974799384']
<PERSON> if by "first line" you mean "I understood nothing..." then that is for the OP, because of the messy way he wrote his question, it was there way before your answer. If you talk about the $\leq e$ (or just bounded) part then that is either taken for granted or may be deduced by bounding $1/(k!)\leq 1/(k-1)^2$...
1bfc19c771442a4466578790d1d51bd7281ea1a59bc197b48f4760f2eb313cec
['4c4c94444cb145629543a16974799384']
You do understand that your saying "D does not meet any obstruction on the set of distributions." is exactly as saying that the classic derivative "does not meet any obstruction on the set $C^\infty$."? In the same way one defines the set of functions that admit integral. That is $L^1(\mu)$ when $\mu$ is a probability measure. And in that sense Henstock-Kurzweil integral get the answer for generality.
600a2999e148f7f385c95d3b1465a38b1bc4dd2933a34a5567dd312819e1211c
['4c4f237cf87446e7aa344a31c9afa417']
The powdery, 'cheesy' places are definitely a roof or ac vent leak. The flaking paint, if not accompanied by the cheesiness, is probably just a latex-over-oil issue. Even with multiple layers of cure-all primers and stain killers, some bad paints can't be cured. Try a primer called 'bonding primer'. It should work well to gather up the particulates and really, as the name implies, bond the paintjob together. Go two good coats of this newer style 'paint amd primer in one" paint junk that's so popular now. It's not really primer, just a thickened paint, but it may help to isolate your issue. If that fails, might be time to start thinking of furring the ceiling down and installing a new one.
a6e4471e2c7908f2cf110ed46b1c9ba44a25cb235de6927e0f878340836b85d7
['4c4f237cf87446e7aa344a31c9afa417']
Hi I'm after a way to sanitise input for traceroute/tracepath /well really any bash input. For example: root@meh:~# tracepath http://google.com/ gethostbyname2: Unknown host I'll probably setup an alias in bash, but need to know how to do it first (maybe even shell script?). Cheers!
4222c55460d4a68673e1a57d544b06071a8af93587777a4e36730c416e10e8ae
['4c5de55c3c5b4af9b2d56503cddd454c']
There is a little bit of confusion. What's obviously for LocalForward? Why then you make me look for RemoteForward? And after again an example (completely inconsistent with the example given) with LocalForward. By the way, RemoteForward is what I was looking for, I had found LocalForward and DynamicForward but didn't saw RemoteForward directive before.
0f8e7b63a15402ae94238e334be3efe55a1b089ccdcafda3604878c2d71134af
['4c5de55c3c5b4af9b2d56503cddd454c']
I'm looking for a ssh client config directive like LocalForward that works as the -L CLI parameter but for the -R parameter TL;DR full problem details The data: repoServer -> myComputer -> NAT -> stagingServer I have a local git repository server that is not exposed to the internet and a remote staging server on which I have to deploy my repo. To do so, I ssh into the remote stagingServer with a reverse socket. Current configuration for myComputer: File: ~/.ssh/config Host StagingServer Hostname staging.acme.com User username PreferredAuthentications publickey IdentityFile ~/.ssh/id_username ForwardAgent yes on which I run: ssh StagingServer -R 8022:repository.local:22 Current configuration for stagingServer: File: ~/.ssh/config Host repository Hostname localhost User git Port 8022 PreferredAuthentications publickey IdentityFile ~/.ssh/id_deployer on which I can run: git clone git@repository:myProject.git And all works fine, but... finally The question: Is it possible to specify in the ssh client config file (~/.ssh/config) to open the reverse tunnel so that I haven't to add -R 8022:repository.local:22
e9929b4cad11fecaaf589e36a6c953d990da7b17275c151a6f93839c91555dea
['4c6d61642f574206984a1e2b23d6125e']
object or array formula, can't mix properties together. kindly see the example below. we will define an array of objects and then will join new object to our array. let originalArray = [ { Assigned_CategoryHead_Id: 4, Assigned_CategoryHead_Name: "Head4" }, { Assigned_CategoryHead_Id: 3, Assigned_CategoryHead_Name: "Head3" }, { Assigned_CategoryHead_Id: 2, Assigned_CategoryHead_Name: "Head2" } ]; let object = { Assigned_CategoryHead_Id: 5, Assigned_CategoryHead_Name: "Head5" }; let combinedArray = [object,...originalArray]; console.log(combinedArray); output in browser console: (4) [{…}, {…}, {…}, {…}] 0: {Assigned_CategoryHead_Id: 5, Assigned_CategoryHead_Name: "Head5"} 1: {Assigned_CategoryHead_Id: 4, Assigned_CategoryHead_Name: "Head4"} 2: {Assigned_CategoryHead_Id: 3, Assigned_CategoryHead_Name: "Head3"} 3: {Assigned_CategoryHead_Id: 2, Assigned_CategoryHead_Name: "Head2"}
9c93577d1dbc8a1a7073bca791545de8ba94618d08e4f16b4893c64cdd32b298
['4c6d61642f574206984a1e2b23d6125e']
first of all , make sure url of database.json you can use relative path as below code for example. and you need to change also $scope.datad = response.products; to $scope.datad = response.data.products; response object contain all information about http request and result will coming into data object. finally no need to return $scope.datat, because products assigned to scope. $http.get("./database.json") .then(function(response){ console.log(response);// print response to check. $scope.datad = response.data.products; })
9f88ef2a01fe86a855d6cd4e956db6d06a5d8193c46cf76a6cb7af4736c1c50b
['4c7423ce07d44c04b24d26c334500ab7']
I have been working on some code that tokenizes a string from a line and then creates a temp array to copy the string into it (called copy[]) and it is filled with 0's initially (The end game is to split this copy array into temp arrays of length 4 and store them in a struct with a field char* Value). For some reason my temp arrays of size 4 end up having a size of 6. char* string = strtok(NULL, "\""); printf("%s", string); int len = (int)strlen(string); while(len%4 != 0) { len++; } char copy[len]; for(int i = 0; i < len; i++){ copy[i] = '0'; } printf("%s\n", copy); int copyCount = 0; int tmpCount = 0; char temp[4]; while (copyCount < len) { if(tmpCount == 4) { tmpCount = 0; } while(tmpCount < 4) { temp[tmpCount] = copy[copyCount]; tmpCount++; copyCount++; } printf("%s %d\n", temp, (int)strlen(temp)); } This yields: This is the end 0000000000000000 This is the end0 This� 6 is � 6 the � 6 end0� 6 And should yield: This is the end 0000000000000000 This is the end0 This 4 is 4 the 4 end0 4 I've been messing around with this for awhile and can't seem to figure out why its making temp have a length of 6 when I set it to 4. Also I'm not sure where the random values are coming from. Thanks!
6f90539cd06b8def3e73f37a23ab21ed851ecae119619f71b6f2245a7901ee13
['4c7423ce07d44c04b24d26c334500ab7']
I'm trying to run an application in eclipse which is setup as MVC app and it is the solution code posted by our professor for a homework. After I copy and pasted all of the classes and tried to run it, I got the following error: JOGL> Hello JOAL Exception in thread "main" java.lang.NoClassDefFoundError: com/jogamp/openal/JoalVersion at jogamp.opengl.openal.av.ALDummyUsage.main(ALDummyUsage.java:14) Caused by: java.lang.ClassNotFoundException: com.jogamp.openal.JoalVersion at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more I'm not entirely sure what the issue is and apparently no one else has been having the same issue. My buildpath has a library I titled "JOGL" and I added the external jars gluegen-rt.jar and jogl-all.jar as was instructed by the professor. Thanks for the help!
d7e33a0461b47998c6ed4164a94b777a798a06b7ca846dcbe8adab50a2ee32d0
['4c8088c0e71b445298adae3c80b2a73f']
I have a multi page form that I need to manage state with. I am currently trying to use the scoped model but it's not working. Everything I go to another page the state is cleared. I'm usually the PageView widget to create the multi page form. What I really what do know is why the state is not persisting. Thank you
0c04d4a2cce139e4103526c3f31d8c70f1c6ceab1a00247de868d98f655ac97f
['4c8088c0e71b445298adae3c80b2a73f']
You'll have to use now.json to set up your routes. Also it is important to note that it's now that builds the route so visiting it on the client side wont work if you are using localhost. Build your project with now and it should work. Also the "as" parameter would be as={{ pathname:/user/manage/${variable}}}
07cd44a5abacc31d2fb5a127acdd7436e999b5656bcc81e5acc815fc3b78f570
['4c958e73673c42a08e55c40273e355c4']
I'm looking for a best solution that suits my requirements. I would like to use MySQL with a lot of instances, so I need to be able to add as much master servers with slaves servers as might be needed in the future. There also will be sharding. Currently I've found out that GCP doesn't allow you to add more than one master server to a running instance. If so, what can I do then? I need to create 3 or more master servers and add slave servers to them. And if there is a new row in one of the master servers, the 3 slaves will receive that row and everything will by synchronized, so I'll be able to do a simple SELECT query in one of these slaves to get the actual data. I'm sorry for my english, I'm not a native speaker :)
644c917ae5a56f797fe8361af2212f36b642260342639878f2e3aae792765766
['4c958e73673c42a08e55c40273e355c4']
I've created a BigTable instance in my GC account and when I'm trying to connect to it using Google's library (this is a sample code from Google's docs): require 'vendor/autoload.php'; use Google\Cloud\Bigtable\BigtableClient; /** Uncomment and populate these variables in your code */ $project_id = 'my_project_id'; $instance_id = 'table_instance'; $table_id = 'table_name'; // Connect to an existing table with an existing instance. $dataClient = new BigtableClient([ 'projectId' => $project_id, ]); $table = $dataClient->table($instance_id, $table_id); $key = 'r1'; // Read a row from my-table using a row key $row = $table->readRow($key); $column_family_id = 'cf1'; $column_id = 'c1'; // Get the Value from the Row, using the column_family_id and column_id $value = $row[$column_family_id][$column_id][0]['value']; printf("Row key: %s\nData: %s\n", $key, $value); I'm getting an error: Fatal error: Uncaught BadMethodCallException: Streaming calls are not supported while using the REST transport. in /srv/vendor/google/gax/src/Transport/HttpUnaryTransportTrait.php:119 Stack trace: #0 /srv/vendor/google/gax/src/Transport/HttpUnaryTransportTrait.php(63): Google\ApiCore\Transport\RestTransport->throwUnsupportedException() #1 /srv/vendor/google/gax/src/GapicClientTrait.php(479): Google\ApiCore\Transport\RestTransport->startServerStreamingCall(Object(Google\ApiCore\Call), Array) #2 /srv/vendor/google/gax/src/Middleware/CredentialsWrapperMiddleware.php(61): Google\Cloud\Bigtable\V2\Gapic\BigtableGapicClient->Google\ApiCore\{closure}(Object(Google\ApiCore\Call), Array) #3 /srv/vendor/google/gax/src/Middleware/FixedHeaderMiddleware.php(67): Google\ApiCore\Middleware\CredentialsWrapperMiddleware->__invoke(Object(Google\ApiCore\Call), Array) #4 /srv/vendor/google/gax/src/Middleware/RetryMiddleware.php(85): Google\ApiCore\Middleware\FixedHeaderMiddleware->__invoke(Object(Google\ApiCore\Call), Array) #5 /srv/vendor/google/gax/src/Middleware/OptionsFilterMiddleware.php(64): Google\ApiCore\Middleware\RetryMiddleware->__invoke(Object(Google\ApiCore\Call), Array) #6 /srv/vendor/google/gax/src/GapicClientTrait.php(462): Google\ApiCore\Middleware\OptionsFilterMiddleware->__invoke(Object(Google\ApiCore\Call), Array) #7 /srv/vendor/google/cloud-bigtable/src/V2/Gapic/BigtableGapicClient.php(357): Google\Cloud\Bigtable\V2\Gapic\BigtableGapicClient->startCall('ReadRows', 'Google\\Cloud\\Bi...', Array, Object(Google\Cloud\Bigtable\V2\ReadRowsRequest), 3) #8 [internal function]: Google\Cloud\Bigtable\V2\Gapic\BigtableGapicClient->readRows('projects/project...', Array) #9 /srv/vendor/google/cloud-core/src/ExponentialBackoff.php(80): call_user_func_array(Array, Array) #10 /srv/vendor/google/cloud-bigtable/src/ResumableStream.php(96): Google\Cloud\Core\ExponentialBackoff->execute(Array, Array) #11 /srv/vendor/google/cloud-bigtable/src/ChunkFormatter.php(168): Google\Cloud\Bigtable\ResumableStream->readAll() #12 [internal function]: Google\Cloud\Bigtable\ChunkFormatter->readAll() #13 /srv/vendor/google/cloud-bigtable/src/Table.php(331): Generator->current() #14 /srv/index.php(24): Google\Cloud\Bigtable\Table->readRow('r1') #15 {main} thrown in /srv/vendor/google/gax/src/Transport/HttpUnaryTransportTrait.php on line 119 Any help?
407c48ef455061b0ab4f6613da7af1f13c1a8592f840d1e2bf1f616e388c1000
['4ca3186c97674b95a995558ddba63749']
If you compare it with our Basic Authentication then it will make it easy to understand. Like App ID/Client ID is like your Username/Email and App Secret/Client Secret is like Password. So in OAuth2 when making a request for Authorization Code then you need to send App ID to uniquely identify your app. After that, you are requested to send your App secret to get the Token.
bd2ce6b286a71b14d1edccbb550396e6038b7529d488e88e85f4d4290757b70f
['4ca3186c97674b95a995558ddba63749']
Your question is not clear. But if you want to just assign value then you can do it like this way. <?php $data = '[ { "label": "Policy Number", "field": "account_number", "type": "Number", "is_required": true }, { "label": "Amount", "field": "amount", "type": "Number", "is_required": true }, { "label": "Due Date", "field": "due_date", "type": "Calendar", "is_required": true } ]'; $data = json_decode($data); $fields = array(); for ($i = 0; $i < count($data); $i++) { $fields[$data[$i]->field] = "VALUE OF RESPECTIVE FIELD"; } var_dump($fields); ?>
94a1b8554b07e7cac5a1010a069dba7aec23b6fa4e170db3505e65e59ab2a6a8
['4ca47b9cc4fb489f99c64d58ea3e4f29']
(I will assume in my answer that people have read the discussion on the old question, linked to by the OP.) No, it is not like the aether. It is still true that locally, there is no preferred reference frame. You don't even really need to think about spacetime to see what is going on. Consider a two-dimensional plane, parametrised by $(x,y)$, and roll it into a cylinder by identifying $(x,y) \sim (x + nL, y) ~\forall~ n$, where $L$ is some constant. Locally, this space is still perfectly isotropic, but globally, the $x$ direction has been picked out by the identification. To see what this means, let's imagine drawing two straight line segments, each beginning at $(x, y) = (0,0)$ and ending at $(0,L)$. The first will just be $(0,t)~,~ 0\leq t\leq L$, and the other will be $(t,t)~,~0\leq t\leq L$ (which ends at a point equivalent to $(0,L)$ under the identification, and therefore the same point on the cylinder). Obviously the length of the first line is just $L$, but the length of the second line is $\sqrt{2}L$, by <PERSON>. Although any small patch of the cylinder is perfectly isotropic, we see here that the rotational symmetry is broken globally by the identification. In spacetime, a similar thing happens, replacing rotational symmetry by boost symmetry. Short answer: Generally speaking, there is never a twin paradox: in any spacetime, just write down the metric in any coordinate system you like, and calculate the proper times for the two trajectories of interest. This tells you unambiguously which twin is older and which younger.
06e6779ef82c88812706c34ddba80dabc4c67b499b2adb130107651ae7afa8d2
['4ca47b9cc4fb489f99c64d58ea3e4f29']
Looking for a way to have Google+ automatically add my tweets to my Google+ timeline. Currently, I'm setup so that: Google Reader, Pandora Likes, Ping Likes feed into -> Twitter And Twitter feeds into -> Facebook So If I have something to say, I can plaster it on twitter, and it gets CC'd to my Facebook Status as well. Looking for some way to do the same thing with Google+ ... Ideally I only want to put statuses into one social network.
30e37522421fd31d5171977e688b0faeea47c2503e3ea9deb9cfcbcea3c7d3fe
['4cb771402c3548a28af1c80dd95cf9de']
I have generated a data table using the Datatables jquery plugin. The table is populated with JSON. I want to extract cell values when I make a selection to use in a URL but I can't get it to work. #I'm using django import json #my list users = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']] #my json user_json = json.dumps(users) <table class="table table-striped- table-bordered table-hover table-checkable" id="user-table"> <thead> <tr> <th>Age</th> <th>Record ID</th> <th>First Name</th> <th>Last Name</th> <th>Actions</th> </tr> </thead> </table> <script type="text/javascript"> var userData = {{user_json|safe}}; </script> var SourceHtml = function() { var dataJSONArray = userData; var initTable1 = function() { var table = $('#user-table'); // begin table table.DataTable({ responsive: true, data: dataJSONArray, columnDefs: [ { targets: -1, title: 'Actions', orderable: false, render: function(data, type, full, meta) { //this is where I need help. I need for each a-tag to link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}" return '<a href="" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="Select"><i class="la la-edit"></i></a>'; }, }, ], }); }; return { //main function to initiate the module init: function() { initTable1(); } }; }(); jQuery(document).ready(function() { SourceHtml.init(); }); I need a href link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}" in each a tag. however, I can't get the values from the cells.
a84d2bd88f3b0bba81f023bf8c11887b623241038ccf727313e04679cf6c5034
['4cb771402c3548a28af1c80dd95cf9de']
I'm setting up a web app that allows user to upload a CSV file that saves to MEDIA_ROOT and updates the database with the CSV data. However, I can't seem to get it to work. The file saves okay but the database doesn't update. I had trouble with request.FILES but managed to get to the bottom of that. but I can't seem to update the database with the CSV data. models.py import datetime from django.utils import timezone from django.db import models from django.contrib.auth.models import User class UserData(models.Model): user_user = models.ForeignKey(User, on_delete=models.CASCADE ) user_updated = models.DateTimeField(auto_now=True) user_contract_number = models.CharField(verbose_name="Contract Number",max_length=30, null=True, blank=True) user_ticket_number = models.CharField(verbose_name="Ticket number",max_length=30, null=True, blank=True) user_weigh_bridge_number = models.CharField(verbose_name="Weigh Birdge number",max_length=30, null=True, blank=True) def __str__(self): return f'{self.user.username} Data' views.py from django.http import HttpResponse from django.template import loader from django.contrib import messages from django.contrib.auth import login, authenticate from django.contrib.auth.decorators import login_required from data_user.models import UserData import csv, io from datetime import datetime @login_required def user_data(request): if request.method == 'POST': ud_form = UserDataForm(request.POST, request.FILES, instance=request.user.userprofile) if ud_form.is_valid(): ud_form.save() csv_file = request.FILES['user_user_data'] data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) for column in csv.reader(io_string, delimiter=','): _, created = UserData.objects.update_or_create( user_user=username, user_contract_number=column[0], user_ticket_number=column[1], user_weigh_bridge_number=column[2], ) messages.success(request, f'Congratulations {request.user.first_name} ! You have uploaded your waste data') return redirect('users:profile-overview') else: ud_form = UserDataForm(instance=request.user.userprofile) return render(request, 'users/user_data.html', {'ud_form':ud_form}) user_data.html {% extends 'pages/about_you_profile.html' %} {% load crispy_forms_tags %} {% block profile %} <div class="c-layout-page"> {% include "users/partials/_profile_header.html" %} <div class="container"> {% include 'users/partials/_profile_sidebar.html' %} <div class="c-layout-sidebar-content "> <div class="c-content-title-1"> <h3 class="c-font-uppercase c-font-bold">Upload data</h3> {% include 'users/partials/_profile_user_type_text.html' %} <div class="c-line-left"> </div> <div class="content-section"> <form id="new_user_form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> {{ ud_form|crispy }} </fieldset> <div class="form-group"> <button type="submit" class="btn btn-lg c-theme-btn c-btn-square c-btn-uppercase c-btn-bold">Upload</button> </div> </form> </div> <div class="c-content-box c-size-md "> </div> </div> </div> </div> {% endblock profile %} test_data.csv contract_number,ticket_number,weigh_bridge_number 218,WTN1234,MC1234 231,WTN1235,MC1235 I expected the registered app on admin to include the csv data but nothing appears.
085c0c2c481661051736d7b06908be35f401d16e9e81f3eb6e008537b281f6d0
['4cc43ca9f7d54027895ec640d99dec3e']
I'm trying to track users position and draw a path/his route on a map according to his movement (updatePolyline(), updateCamera(), updateMarker() are responsible for drawing a route). Program compiles, but the crucial error is that onLocationChanged() isn't called when location actually changes, thus, no path is beeing drawn. public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener { private GoogleMap mMap; // Might be null if Google Play services APK is not available. private PolylineOptions mPolylineOptions; LocationManager locationManager; private LatLng mLatLng; double latitude, longitude; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); setUpMapIfNeeded(); // LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); this.locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); longitude = location.getLongitude(); latitude = location.getLatitude(); // if(location != null) { // // onLocationChanged(location); // } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, this); } public void onLocationChanged(Location location) { longitude = location.getLongitude(); latitude = location.getLatitude(); mLatLng = new LatLng(latitude, longitude); runOnUiThread(new Runnable() { @Override public void run() { updatePolyline(); updateCamera(); updateMarker(); } }); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } @Override public void onMapReady(GoogleMap map) { mMap = map; initializeMap(); } private void updatePolyline() { mMap.clear(); mMap.addPolyline(mPolylineOptions.add(mLatLng)); } private void updateMarker() { mMap.addMarker(new MarkerOptions().position(mLatLng)); } private void updateCamera() { mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16)); } private void initializeMap() { mPolylineOptions = new PolylineOptions(); mPolylineOptions.color(Color.BLUE).width(10); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } private void setUpMapIfNeeded() { if (mMap == null) { mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); mMap.setMyLocationEnabled(true); mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() { @Override public boolean onMyLocationButtonClick() { LocationManager lm = null; boolean gps_enabled = false, network_enabled = false; if (lm == null) lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { } try { network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex) { } if (!gps_enabled && !network_enabled) { AlertDialog.Builder dialog = new AlertDialog.Builder(MapsActivity.this); dialog .setTitle("No gps") .setPositiveButton("Atšaukti", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { } }) .setNegativeButton("Open settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); MapsActivity.this.startActivity(myIntent); } }); AlertDialog alert_dialog = dialog.create(); alert_dialog.show(); } return false; } }); } } }
4adf6988f05aca10ab82bc35c32aefe28c592d1321cc987c8ff705c1a5f63f10
['4cc43ca9f7d54027895ec640d99dec3e']
I want to show one icon and 2 items in CollapseActionView on portrait and all 3 icons on landscape mode in ActionBar. I have created two seperate files menu.xml and put it in port and land folders. My port/menu.xml: <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:yourapp="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_search" android:icon="@drawable/ic_action_search" yourapp:showAsAction="always" android:inputType="textNoSuggestions" yourapp:actionViewClass="android.support.v7.widget.SearchView" /> <item android:id="@+id/maps" android:icon="@drawable/checkin" android:title="@string/maps" yourapp:showAsAction="collapseActionView" /> <item android:id="@+id/sort_by" android:icon="@drawable/ic_action_content_sort" android:title="@string/sort_by" yourapp:showAsAction="collapseActionView" /> </menu> land/menu.xml: <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:yourapp="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_search" android:icon="@drawable/ic_action_search" yourapp:showAsAction="always" android:inputType="textNoSuggestions" yourapp:actionViewClass="android.support.v7.widget.SearchView" /> <item android:id="@+id/maps" android:icon="@drawable/checkin" android:title="@string/maps" yourapp:showAsAction="always" /> <item android:id="@+id/sort_by" android:icon="@drawable/ic_action_content_sort" android:title="@string/sort_by" yourapp:showAsAction="always" /> </menu> For some reason ActionBar always shows according to port/menu.xml despite device's orientation. What's wrong?
1ede6f8a3447ce4b38f5e5a5c0ab09efec176b99232cd26fe6b7985eaac14f1c
['4cc8afb1fe624d6ba4a3cc74f0dcf958']
I am trying to add Mutable_Content to my push notifications so I can add a badge count. However I am running into the error: Messaging payload contains an invalid value for the "notification.mutable_content" property. Values must be strings. Here is my code for the payload: const payload = { notification : { title: owner + ' has made a post', body: title + ' - ' + caption, mutable_content : true }, }; I have tried many different tutorials to figure out the right syntax but it is not working. It always comes up with an error. I am using node.js 10 for the engine and firebase/google cloud platform to trigger the function. Can anyone help me with this syntax? Thank you
06ec02a23025a91c608f0d240d7f3cef6d519afa4625ddc6091e0e35d693710b
['4cc8afb1fe624d6ba4a3cc74f0dcf958']
I've created a Shopify store where discount codes can be entered indirectly. Therefore I am trying to disable the discount box as seen below. I've researched it and seen you can edit the code in Themes > Actions > Edit Code. And I've followed some videos: https://www.youtube.com/watch?v=EJi6zfc63RU However I am unable to do it. Has anyone done this before? Please Help!
0811d740dc09dc3f50ee1e30bba411eab84b1305da765409d85450cbbc69882c
['4cd2a61e5ac14c9fb013775ddcdf377c']
yo estoy realizando un proyecto de productos en base de datos local muy similar al proyecto que consultó el usuario <PERSON> Fast Tag Filtro Android Studio , ListView Con adapter Perzonalizado y el usuario <PERSON> le ayudo, he aplicado la solucion que aplico <PERSON> y no me filtra ningun dato solo se borra la lista y no aparece mas no se que estoy haciendo mal, si me podrian ayudar se los agradeceria un monton gracias. esta es mi clase lista3 que seria el equivalente a la clase contactos del ejemplo. public class Lista3 { private String Id, Usuario; private byte[]Imagen; public Lista3(String id,String usuario, byte[] imagen) { super(); Id=id; Usuario = usuario; Imagen = imagen; } public String getId() { return Id; } public void setId(String id) { Usuario = id; } public String getUsuario() { return <PERSON>; } public void setUsuario(String <PERSON>) { Usuario = usuario; } public byte[] getImagen() { return <PERSON>; } public void setImagen(byte[] <PERSON>) { Imagen = imagen; } } este es mi clase adaptador. public class AdaptadorLista3 extends BaseAdapter { private Context context; private ArrayList<Lista3> list; ArrayList<Lista3> copylist=new ArrayList<>(); public AdaptadorLista3(Context context,ArrayList<Lista3> list) { this.context = context; this.list = list; this.copylist.addAll(list); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { Lista3 item=(Lista3)getItem(position); convertView= LayoutInflater.from(context).inflate(R.layout.item_lista_usuarios,null); ImageView imgfoto= (ImageView) convertView.findViewById(R.id.imvicono); TextView Usuario= (TextView) convertView.findViewById(R.id.lblUsuario); TextView Id= (TextView) convertView.findViewById(R.id.lblIdUsuario); byte[] icono=item.getImagen(); Bitmap bitmap= BitmapFactory.decodeByteArray(icono, 0, icono.length); imgfoto.setImageBitmap(bitmap); Usuario.setText(item.getUsuario()); Id.setText(item.getId()); return convertView; } /* Filtra los datos del adaptador */ public void filtrar(String texto) { // Elimina todos los datos del ArrayList que se cargan en los // elementos del adaptador list.clear(); // Si no hay texto: agrega de nuevo los datos del ArrayList copiado // al ArrayList que se carga en los elementos del adaptador if (texto.length() == 0) { list.addAll(copylist); } else { // Recorre todos los elementos que contiene el ArrayList copiado // y dependiendo de si estos contienen el texto ingresado por el // usuario <PERSON> de nuevo al ArrayList que se carga en los // elementos del adaptador. for (Lista3 lista3 : copylist) { if (lista3.getUsuario().contains(texto)) { list.add(lista3); } } } // Actualiza el adaptador para aplicar los cambios notifyDataSetChanged(); } } y lo ejecuto de esta manera. public void onTextChanged(CharSequence s, int start, int before, int count) { adaptadorLista3.filtrar(Buscar.getText().toString()); } no se en que me estaría equivocando, los datos lo estoy llenando desde sqlite solicito su ayuda por favor.
078a7272ce32b808ef0b3988fd9d89f0e81ba7518c6b3587d0f0b553e23e21f7
['4cd2a61e5ac14c9fb013775ddcdf377c']
I can agree on the approach stated above. I needed to renew my passport in less than 12hours (my plane was leaving the next day in the morning and my passport did not qualify for the 6 month rule of Nicaragua). I arrived at the passport office before it opened (7am i think) and there was already a line and brought proof of my urgency (plane ticket) with all my documents with me. The most important part are the witness. I brought one witness with me and the other one was waiting by the phone. The witnesses are the only aspect that can delay the process, if you can get witnesses to pick up the phone directly or even to bring them with you, this will ensure a fast process.My passport was ready 5 hours later, printed and ready for pick up.
4d323c0b7138cf3413bc1384724eead69bc30c300e1e289e9927ce988f36cf90
['4cd7522c5dfc4c869dbc64956ea76d68']
How can I speed up this 2m5s query that has indices? select urls.id as urlId, count(case when s1.hit_type = 0 then 1 end) as aCount, count(case when s1.hit_type = 1 then 1 end) as bCount, count(case when s1.hit_type = 2 then 1 end) as cCount, count(distinct s1.source_id) as sourcesCount from urls join stats s1 on urls.id = s1.url_id where s1.hit_date >= '2017-12-12' group by urls.id order by aCount desc limit 0,100; mysql> show create table stats; | stats | CREATE TABLE `stats` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `url_id` varchar(100) DEFAULT NULL, `hit_date` datetime DEFAULT NULL, `hit_type` tinyint(4) DEFAULT NULL, `source_id` bigint(20) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `url_id_idx` (`url_id`), KEY `source_id` (`source_id`), KEY `stats_hit_date_idx` (`hit_date`), CONSTRAINT `stats_ibfk_1` FOREIGN KEY (`url_id`) REFERENCES `urls` (`ID`), CONSTRAINT `stats_ibfk_2` FOREIGN KEY (`source_id`) REFERENCES `sources` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6027557 DEFAULT CHARSET=latin1 | mysql> describe select... | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+---------+--------+-------------------------------------------------------------------------------------------------+---------+---------+--------------------------+---------+----------------------------------------------+ | 1 | SIMPLE | s1 | ALL | url_id_idx,stats_hit_date_idx | NULL | NULL | NULL | 5869695 | Using where; Using temporary; Using filesort | | 1 | SIMPLE | urls | eq_ref | PRIMARY,urls_email_idx,urls_status_idx,deptId_idx,deptId_status_email_idx | PRIMARY | 102 | db.s1.url_id | 1 | Using index | It doesn't seem to be using the hit_date index or url_id index. I tried using a sub-select (select count(*) from stats where url_id = ... and hit_date >= ... and hit_type = 0) as aCount and it was faster and took 24s. Is there a way to make it less than 5s? The limit for the entire request is 30s. MySQL Server version: 5.6.35-log MySQL Community Server (GPL)
2e7c8e8a5d57ebcc581abb463cb40e1abcbf637a6ab0ac0058c2d6f5fff8ae45
['4cd7522c5dfc4c869dbc64956ea76d68']
<PERSON>, ele não acusa erro, é isso que não entendo. Por exemplo: Ele compila, não acusa erro algum, aí quando vou executar o app ele para de funcionar. Tipo, se ele executasse e quando clicasse no mapa ele parasse eu mesmo poderia procurar o problema, mas nem isso... Já procurei alguns tutoriais, mas é escasso.
1592cbe5b550d2ee3e97df78935c61387a5e98a446b56adc621751aa26eaae94
['4ce826d579e14963bae3d26a071248ab']
I have a late 2018 macbook pro (tb3) and a surface book 2 (usb 3.1 gen 2). I was wondering if I would be able to buy a tb3 dock and have it work with both (albeit with bandwidth constraints on the sb2). The dock would ideally be able to do at least power delivery, a single monitor, and connect a mouse/keyboard.
03b612d7f28b8168e9712adf7c3df7e8c604c20794e15b28bc4340b442986eb1
['4ce826d579e14963bae3d26a071248ab']
The door is open. ("open" is used here as an adjective. It means it is not closed) The door was opened by <PERSON>. ("opened" is used here as a passive form of verb. <PERSON> did the work) The door is closed. ("closed" is used here as an adjective. It means it is not open. It doesn't matter if it was closed by itself or <PERSON> closed it, the word should be "closed") The door was closed by <PERSON>. ("closed" is used here as a passive form of verb. <PERSON> did the work.) I hope it clarifies.
583c6ee8575fd4ca9d49b9ad6bc9d91870a06680a992d8ccd53c03b5eda5bcd5
['4ce9e1576b83431b8ac20cbbf619e1f7']
If, instead, your are looking for rectangles in the map space, whose borders follows paralleles and meridians, the following function works for me. m is the basemap object. def draw_screen_poly( minlat, maxlat, minlon, maxlon, m): lons=np.hstack((np.repeat(minlon,10),\ np.linspace(minlon,maxlon, num=10),\ np.repeat(maxlon,10),\ np.linspace(maxlon,minlon, num=10))) lats=np.hstack((np.linspace(minlat,maxlat, num=10),\ np.repeat(maxlat,10),\ np.linspace(maxlat,minlat, num=10), np.repeat(minlat,10))) m.plot(y=lats,x=lons,latlon=True, lw=2, color='navy', alpha=0.8) x, y = m(lons, lats) xy = zip(x,y) poly = Polygon( np.asarray(xy), linewidth=3) ax.add_patch(poly)
bd6ae1f6dad355b001ebade1376df819fe9d3d1ec4eacf64492cfa902f2e6f08
['4ce9e1576b83431b8ac20cbbf619e1f7']
The command ncdim_def from package ncdf4 is built to encourage the automatic creation of the coordinate variable that goes with the dimension, a very good practice. However, it only allows to create "double" or "integer" precision for this coordinate variable. For external reasons, I need write the coordinate variable "time" as a float. To do so, I use the following structure which consists in creating the coordinate variable separately from the dimension definition ( ie. using the option create_dimvar = FALSE described in the doc of ncdim_def) timevalue= seq(0.5,10.5) VAR1value= seq(10.2,20.2) # define time dim, but without the time var timedim <- ncdim_def( name = 'time' , units = '', vals = seq(length(timevalue)), unlim = TRUE, create_dimvar = FALSE) # define time coordinate variable timevar <- ncvar_def(name = 'time', units = 'days since 1950-01-01 00:00:00', dim = list(timedim), longname = 'time', prec = "float") # define another variable var1var<- ncvar_def(name = 'VAR1', units = 'unit1', dim = list(timedim), missval = -9999.0, longname = 'VAR1 long name') defVar<-list(timevar,var1var) # creating ncfile (removing any previous one for repeated attempt) ncfname='test.nc' if (file.exists(ncfname)) file.remove(ncfname) ncout <- nc_create(ncfname,defVar,force_v4=T, verbose = T) # writing the values ncvar_put(ncout,timevar,timevalue) ncvar_put(ncout,var1var,VAR1value) nc_close(ncout) However, this returns the error : "ncvar_put: warning: you asked to write 0 values, but the passed data array has 11 entries!" Indeed, the resulting netcdf shows (ncdump) : dimensions: time = UNLIMITED ; // (0 currently) variables: float time(time) ; time:units = "days since 1950-01-01 00:00:00" ; float VAR1(time) ; VAR1:units = "unit1" ; VAR1:_FillValue = -9999.f ; VAR1:long_name = "VAR1 long name" ; I guess I need to force the dimension of the unlimited 'time' dimension upon creation, but i don't understand how to this in the frame of ncdf4.
57eacea9374a93947dc69fb6e3439a78c6ac0e2966e855ccf03fb11e73394fee
['4cfc413aed3643b0a070f3ef5c00c477']
I've found a solution using a single html text field! It uses the "leading" css property to remove the spacing between multiple lines inside the "squish" tag I created. import flash.text.StyleSheet; var textStyle:StyleSheet = new StyleSheet(); textStyle.setStyle("right", { textAlign: "right" }); textStyle.setStyle("squish", { leading: -20 }); myTextBox.styleSheet = textStyle; myTextBox.htmlText = "<squish>Stuff on the left!"; myTextBox.htmlText += "\n<right>Stuff on the right!</right></squish>";
d818f79375b02289b2e8cf7b3bfdbe9a529988a972066be23198b6a650f593d4
['4cfc413aed3643b0a070f3ef5c00c477']
How should I go about compressing a very large JSON string to transmit over websockets? (Also later to store in localStorage) It's already minified, but I need something that can do this: http://www.unit-conversion.info/texttools/compress/ (I tried poking about in the source there and couldn't figure it out)
2332e24c4cdbd2931bd6f5cf17615c3b1e0e6d5f9279696451e9b92974ee639b
['4cfe251313464a7d92a45e3d58a2d976']
I've been trying to wrap my head around using loops and arrays and have put together the below example which takes worksheet names from a table on a worksheet and stores them in array from which another loop runs to add a value in cell A1 in those named spreadsheets based on a value in cell D1 found on the activesheet. I keep getting a runtime error but I cannot identify what the value the code is looking that keeps tripping up. The error seems to be located on this line: Sheets(myArray(x)).Range("A1").Value = EntryValue Any help on what I've not done correctly is greatly appreciated. Thanks. Here's the code: Sub WorksheetListLoop() Dim myArray() As Variant Dim EntryValue As String Dim ListRange As Range Dim cell As Range Dim x As Long 'Set the values to go into range Set ListRange = ActiveSheet.ListObjects("tblArrayList").DataBodyRange 'Resize array prior to loading data ReDim myArray(ListRange.Cells.Count) 'Loop through each cell in range and store sheetname in array For Each cell In ListRange.Cells myArray(x) = cell.Value x = x + 1 Next cell 'Use the value in this cell to put into the sheets in the array EntryValue = ActiveSheet.Range("D1").Value 'Loop through list and add value to cell For x = LBound(myArray) To UBound(myArray) Sheets(myArray(x)).Range("A1").Value = EntryValue Next x End Sub
14ff6c34f5f25e0d82a777af6f3bf930a0aa7f37c3c2b41595d5d4d62c299924
['4cfe251313464a7d92a45e3d58a2d976']
I'm trying to open two workbooks from my first workbook which contains the VBA and then activate a specific sheet in the second workbook. The code is below but for some reason the sheet in the second workbook does not get activated. As the files will vary in name and location I have made them a reference in the VBA file so that they can be changed on the front end rather than in the code. The code is below: Sub OpenWorkbooks() Application.ScreenUpdating = False Dim srcFle, dataFle As String Dim wb, wb1, wb2 As Workbook srcFle = ActiveSheet.Range("C7").Value dataFle = ActiveSheet.Range("C10").Value Set wb = ThisWorkbook Set wb1 = Workbooks.Open(srcFle) Set wb2 = Workbooks.Open(dataFle) wb1.Sheets("Sheet1").Activate Application.ScreenUpdating = True End Sub Thanks in advance.
8847b3a0ff127250a85c69351fe5d053959402a1de8b6c6f2183c7b8ed1ff0a2
['4d0e95ace38c49a8b5407ff942ca147d']
finally found the solution; i'm not so sure why now it's working think i was assigning the same variable twice. Anyway this is the solution I've come to: def f(LL, <PERSON>, n, u_mean): f = sum((Sad - (4 * n * LL / u_mean) * ((1 + 70.8 * ((n * LL / u_mean) ** (2)))**(-5 / 6)))**2) return(f) fun = lambda LL: f(LL, <PERSON>, n, u_mean) res = scipy.optimize.minimize(fun=fun, x0=LL0) Lux = res.x Btw, <PERSON> keeps saying that I shouldn't use lambda function but instead define a function.. can anyone tell me why? I was able to translate the "fun" into a function; I've tried with: def fun(LL): f(LL, Sad, n, u_mean) return(f) res = scipy.optimize.minimize(fun=fun, x0=LL0) but it doesn't work. Would be nice if anybody can tell me why. Thanks for your help
68d04d8948b044fadf682be0cd571f826acbd6a4d2dc030665de9a35a75200fd
['4d0e95ace38c49a8b5407ff942ca147d']
It's not so easy to tell with this few information, but i'll try to guess from my experience: you can't just drop out the values you are not interested in like that. You are trying to transform a time signal in the frequencies domain and in this way, I think you are altering the physics if the test. What you want to do is to remove the frequencies content of the signal corresponding to a certains speeds. I would try to use a lowpass filter instead of removing or setting to 0 the values that you don't want. In this way, you can keep the same sampling rate and you are artificially modifying your test's data. Vibration frequencies should be somehow related to driving speed (guessing higher frequencies for higher speed). Hope this can be of any help Ciao
c5fca042c081dd849dae7b76ed3d44c00fa8d476fefb9dfc73cc2f3d0a71be22
['4d16e27f37284f6bb602eb41fc184d2f']
I upgraded my rails version to 4.1.1 from 4.0.4. Whenever I run rake test I get every test having this error: ActiveRecord<IP_ADDRESS>StatementInvalid: PG<IP_ADDRESS>UndefinedTable: ERROR: relation "roles_users" does not exist LINE 1: DELETE FROM "roles_users" ^ : DELETE FROM "roles_users" My user controller has and belongs to many roles has_and_belongs_to_many :some_names, class_name: "Role", join_table: "some_names_users" So it should not be looking for roles_users as a table, but seems to be in the fixtures for my tests. I am using minitest 5.3.4. I am not using the gem turn.
16c61a6ea2d12bb2b0ebc51f5090dc0cce7310ee61fad0152610291f2d323877
['4d16e27f37284f6bb602eb41fc184d2f']
I have some projects that were tracked in SVN, and then imported to git with a full history. I would like to be able to use the existing project locally, which only uses svn, while starting to track in git. The versions should be identical, minus any ignored files. I have done the following, but wondered if there was a better way to do this: git init git add . git commit -m "backing up" git branch -m backup git checkout -b master git remote add origin {repo} git fetch git reset --hard origin/master
5c11e395dbf695f4a230aa25f44a4d0aa39d17ed8899d310069b5cbb1cf395f0
['4d288331b4bd453c8ca3b130139ceb3f']
I have a class A, and a class AStore. My requirement is to prevent all other methods from initializing an instance of class A, which they should get an instance from AStore. In addition, I also need to access the member functions of A from the instance. Factory pattern is not suitable for this problem as the constructor of A is still public. Ideally, it should throw compilation error when calling the constructor of class A while having access to its member functions. Can I get C# solutions to this?
ab8242f019d26218575de2ea338ecb65115732372ff04b1edf6f23555cf7c12c
['4d288331b4bd453c8ca3b130139ceb3f']
I have a data frame reading from csv using pandas.read_csv, each row of data frame looks like this: [1, '10/18/2016 06:00', 1, 14, 0, 5.5] Basically, it consists of integers, string, and floats. Now, I want to generate more data (newrow) based on existing data and append to the original data frame. When I try to call function append with the following code: df.append(list(newrow)) I got the error: RuntimeWarning: unorderable types: str() < int(), sort order is undefined for incomparable objects. result = result.union(other) I think the string type is playing naughty here, but I did not figure out a way to achieve this. In addition, I also tried to convert the df to df.values first, and then use numpy.vstack(df.values, numpy.array(newrow)). However, the result of this code becomes ['1', '10/18/2016 06:00', '1', '14', '0', '5.5'] in which all fields become strings. Any help is appreciated.
1ee9399d6c7fc96bc5a4be1bb14410d325b95e8c38ae6eefccb17ad712e918ae
['4d2c819591974265a59fa690a4755ca1']
<!-- //THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB (IF YOU HAVE ANY QUERY CONTACT:<EMAIL_ADDRESS>) CREATE TABLE `images` ( `id` int(100) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `image` longblob NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB ; --> <!-- this form is user to store images--> <form action="index.php" method="post" enctype="multipart/form-data"> Enter the Image Name:<input type="text" name="image_name" id="" /><br /> <input name="image" id="image" accept="image/JPEG" type="file"><br /><br /> <input type="submit" value="submit" name="submit" /> </form> <br /><br /> <!-- this form is user to display all the images--> <form action="index.php" method="post" enctype="multipart/form-data"> Retrive all the images: <input type="submit" value="submit" name="retrive" /> </form> <?php //THIS IS INDEX.PHP PAGE //connect to database.db name is images mysql_connect("", "", "") OR DIE (mysql_error()); mysql_select_db ("") OR DIE ("Unable to select db".mysql_error()); //to retrive send the page to another page if(isset($_POST['retrive'])) { header("location:search.php"); } //to upload if(isset($_POST['submit'])) { if(isset($_FILES['image'])) { $name=$_POST['image_name']; $email=$_POST['mail']; $fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp } // our sql query $sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');"; mysql_query($sql) or die("Error in Query insert: " . mysql_error()); } ?> <?php //SEARCH.PHP PAGE //connect to database.db name = images mysql_connect("localhost", "root", "") OR DIE (mysql_error()); mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error()); //display all the image present in the database $msg=""; $sql="select * from images"; if(mysql_query($sql)) { $res=mysql_query($sql); while($row=mysql_fetch_array($res)) { $id=$row['id']; $name=$row['name']; $image=$row['image']; $msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " /> </a>'; } } else $msg.="Query failed"; ?> <div> <?php echo $msg; ?>
83ea91fd2ee4e21299a3246967ebcb186e60d2b6865ea98383f3bf5b0df0ef04
['4d2c819591974265a59fa690a4755ca1']
If you are reloading the same page (running the same page after passing arguments to the url) use $_GET method to retrieve the latitude and longitude var mylat = parseFloat(<?php echo $_GET['urllat'] ?>); var mylong = parseFloat(<?php echo $_GET['urllong'] ?>); Using parseFloat will acuallty converts the php output to floating point If this doesn't work or if you are sending the url details to another page then use the following <?php $url=$_SERVER['REQUEST_URI']; //get the url $parts = parse_url($url); parse_str($parts['query'], $query); ?> var mylat = <?php echo $query['urllat']; ?>; var mylong = <?php echo $query['urllong']; ?>; Hope this may solve the issue.
a126363cae9f798bc0167325d5369d13552af3122df99207a5405dcc45f8a930
['4d2fc30234e44f919af513fecb5d359e']
If you change your Email function to public function Email($email, $subject, $content){ $config = array( 'useragent' => 'codeIgniter', 'protocol' => 'mail', 'mailpath' => '/usr/sbin/sendmail', 'smtp_host' => 'localhost', 'smtp_user' => 'Myemail', 'smtp_pass' => 'mypass', 'smtp_port' => 25, 'smtp_timeout' => 55, 'wordwrap' => TRUE, 'wrapchars' => 76, 'mailtype' => 'html', 'charset' => 'utf-8', 'validate' => FALSE, 'priority' => 3, 'crlf' => "\r\n", 'newline' => "\r\n", 'bcc_batch_mode' => FALSE, 'bcc_batch_size' => 200, ); $this->load->library('email', $config); $this->email->set_newline('\r\n'); $this->email->from('myemail'); $this->email->to($email); //email address passed into the function. $this->email->subject($subject); // subject passed into the function $this->email->message($content); //content passed into the function $this->email->set_mailtype('html'); if($this->email->send()){ return TRUE; } else{ return FALSE; } } However, according to the [Codeigniter documentation][1] [1]: https://www.codeigniter.com/user_guide/libraries/email.html?highlight=complete%20web , you need to send a complete web page. Therefore you would need something like - $message = "<html><head><title>Password Reset</title></head><body>Please click on the password reset link <br><a href='".base_url('users/reset?token=').$token."'>Reset Password</a></body></html>"; $this->Email($email, 'Reset Password Link', $message);
615b55f60a0ca78cc9d27b8beeeda8ca8cc577a20676c234e3e2137ec229a27e
['4d2fc30234e44f919af513fecb5d359e']
When we load our netchart, it displays a network where the user can then double-click on a node to expand the network further. The original layout is fine - the chart fits the container perfectly (see netchart-original.png). When the user double-clicks and loads the additional data (using chart.addData()), the chart zooms out (over a period of about 20 seconds) and the node spacing is not correct (see netchart-expanded.png). We have called updateSize, paintNow, resetLayout and have even tried pausing before calling these functions but nothing seems to work. Clicking on the "Rearrange Elements" toolbar button corrects the layout and node distancing and fits the chart within the container.
978d356055187701ee7ef24db70f9935dc36194bf135dce2e6dc8614e12461e5
['4d38f98bf28b45c1a8a9a37e4cf04955']
I have the Following Dataset: A B C 1 2 6 3 2 5 1 2 4 3 2 7 2 2 3 I want to be able to find the average value of C based on the combination of A and B. So basically I want to have the Following dataset as a result : A B Avr_C 1 2 5 3 2 6 2 2 3 Any idea on how to proceed ? Thank you.
ca0c9fa2804dbceadfff78a5578ce99a2049bb202667e7acaafd66fc2f7c3c7c
['4d38f98bf28b45c1a8a9a37e4cf04955']
I'm asked to create a mobile application that loads regulary data from an sql server 2008 and puts it in the local db SQLite and sends it as well. Being a newbie in mobile development i don't even know how to procede. I would be gratefull if anyone leads me or gives me tips. Thanks in advance.
916547c2e36089bd3fb772f4ee65dba18b9c980383f651416bcc8ce605d20b89
['4d3d8fe71f46411392a51fe9dbb05f90']
You can simply use Notepad++ for syntax checking. <PERSON> has been gracious enough to create a custom language for htaccess files and share it here. http://notepad-plus.sourceforge.net/commun/userDefinedLang/Htaccess.xml Just go to View -> User-Defined-Dialogue -> Import and restart Notepad++. You should be able to see the new language under the Language option.
fd86684b110cd65f5b190a6848c500fd7c6e6e139c1f303e3240a0353691f694
['4d3d8fe71f46411392a51fe9dbb05f90']
So basically, when you are putting something in the file system (like when you are taking a screenshot) you have to broadcast ACTION_MEDIA_SCANNER_SCAN_FILE so that other applications are aware of it (otherwise android photo gallery can not display your screenshot). So Snapchat has to wait for that broadcast and when it receives the broadcast it just has to check if you are watching a snap and if it is the case they know that you just took a screenshot. That's probably how they do it.
bce4229962b3281e8e1462f822d69f9e25d803c6772bf62bc46cc953fb41deae
['4d57f431258541059a4865dba41a4a2c']
The message is the same in both of those links. Clients created from the same MessagingFactory instance will use the same underlying AMQP socket connection. For low throughput sending from the same process, then reusing the MessagingFactory is perfectly fine and preferred because it will cause fewer connections on the server-side (and connections are a limited resource). In the doc "Best Practices for performance improvements using Service Bus brokered messaging" that you link to, if you notice further down in the doc it says: Multiple factories: all clients (senders in addition to receivers) that are created by the same factory share one TCP connection. The maximum message throughput is limited by the number of operations that can go through this TCP connection. The throughput that can be obtained with a single factory varies greatly with TCP round-trip times and message size. To obtain higher throughput rates, you should use multiple messaging factories Which is the same message from the Event Hub documentation that you link to.
ceadf99b7a5323c3f180a6bd3379299d04e7a4071eb6a17f259c05c6a4db38cd
['4d57f431258541059a4865dba41a4a2c']
They are very similar but have some nuances to them. For example, AWS does not allow all traffic within the VNET by default, whereas Azure NSGs allow all traffic between VMs in the VNET. Unfortunately, I don't have a guide for translating from one to the other. The best reference for Azure NSGs: https://azure.microsoft.com/en-us/documentation/articles/virtual-networks-nsg/. This documents those default inbound and outbound rules, too.
4c6c0ce52f33e4c9c707ff14bada1f7c29dd5d942c572df34e9f2aaf681a6ae9
['4d5d10cf684e4424bb10d3bdbf8b7207']
Almost there, and what I now have is usable to a great extent, so I'll post this so other users might benefit from my work, which has benefited by the comments of <PERSON> which led me to other documents that could clarify other parts. # see: https://pymotw.com/3/argparse/ # BLOCK FOR SHARED options used at more places, # see also: https://stackoverflow.com/questions/7498595/python-argparse-add-argument-to-multiple-subparsers env_shared = argparse.ArgumentParser(add_help=False) env_shared.add_argument('-env', action="store", help='name of environment <tst|acc|acc2|prod|...>', metavar='<environment>', required=True) ds_shared = argparse.ArgumentParser(add_help=False) ds_shared.add_argument('-ds', action="store", help='name of subsystem to use <ivs-gui|ivs-vpo|...>', metavar='<system name>', required=True) version_shared = argparse.ArgumentParser(add_help=False) version_shared.add_argument('-version', action="store", help='version to use. If used, specify at least sprint as in 1.61', metavar='<version>') tab_shared=argparse.ArgumentParser(add_help=False) tab_shared.add_argument('--tab', required=False, action="store_true", help='Use nice tabulation for output') # END OF SHARED options # MAIN main_p = argparse.ArgumentParser(description="Main cli tool for use in the CD v3 pipeline (%s)" % VERSION, epilog='Defaults are taken from the configuration file, which is pulled from git when needed.', ) # Change formatting of help output for main-parser main_p.formatter_class = lambda prog: argparse.HelpFormatter(prog, max_help_position=30, width=80) main_p.add_argument("--debug", action="store_true", help="Generate debug output and keep temp directories") # MAIN-SUB main_s_p = main_p.add_subparsers(title='Commands', dest='main_cmd') # MAIN-SUB-DASHBOARD dashbrd_p = main_s_p.add_parser('dashboard', aliases=['db'], help="Proces specified dashboards", parents=[ds_shared]) dashbrd_p.formatter_class = lambda prog: argparse.HelpFormatter(prog, max_help_position=40, width=80) dashbrd_p.add_argument('which', help='Proces dashboard for <ALL|Supplier|DEBUG what would happen>. If supplier is specified an optional subsystem to be processed can be passed using -ds') # MAIN-SUB-QUERY query_p = main_s_p.add_parser("query", aliases=['qry'], help="Query database for locks,deployments or promotes") query_p.formatter_class = lambda prog: argparse.HelpFormatter(prog, max_help_position=40, width=80) # MAIN-SUB-QUERY-SUB query_s_p = query_p.add_subparsers(help="additions help", title='sub commands for query', dest='query_cmd') # MAIN-SUB-QUERY-LOCK q_lock_p = query_s_p.add_parser('lock', help='query db for lock(s)', ) # MAIN-SUB-QUERY-LOCK-SUB q_lock_sub = q_lock_p.add_subparsers(help='', title='subcommands for dbquery lock', dest='lock_cmd') # MAIN-SUB-QUERY-LOCK-SUB-SET q_lock_set_p = q_lock_sub.add_parser('set', help='sets a lock', parents=[env_shared, ds_shared]) # MAIN-SUB-QUERY-LOCK-SUB-CLEAR q_lock_clear_p = q_lock_sub.add_parser('clear', help='clears a lock', parents=[env_shared, ds_shared], ) # MAIN-SUB-QUERY-LOCK-SUB-SHOW q_lock_show_p = q_lock_sub.add_parser('show', help='shows a lock/locks', parents=[env_shared, tab_shared]) # MAIN-SUB-QUERY-PROMOTE q_promote_p = query_s_p.add_parser('promote', help='query db for promotions', parents=[env_shared,ds_shared] ) # MAIN-SUB-QUERY-DEPLOY q_deploy_p = query_s_p.add_parser('deploy', help='query db for deployments') # MAIN-SUB-PROMOTE promote_p = main_s_p.add_parser('promote', help='Do a promotion.', parents=[env_shared, ds_shared, version_shared]) promote_p.add_argument('-dest', required=False, action="store", help='If used specifies the destination, otherwise defaults are used. (-dest is optional, -env is not)', metavar='<dest_env>') # MAIN-SUB-DEPLOY deploy_p = main_s_p.add_parser('deploy', help='Deploy software', parents=[ds_shared, env_shared]) # MAIN-SUB-AUTOTAG autotag_p = main_s_p.add_parser('autotag', help="Autotags specified repository", parents=[ds_shared]) print("------------arguments-----------") print(vars(main_p.parse_args())) This creates a lot of the functionality i intended.
b98edf216811bdb71fd1c6a78fa04173bca873a7bf4c526d1f71573c69d7ac6b
['4d5d10cf684e4424bb10d3bdbf8b7207']
Slowliness can be caused by not being able to resolve hostnames. This might be because of wrong entries in /etc/hosts or because of wrong settings in /etc/resolv.conf Verify both so they be correctly configured. After that continue to the sudoers file. Have you used the old hostname in the sudoers file, then update the sudoers content to reflect the changes.
1dbfd4961734d2b67b67362e9a09e2a27dee0e3a6f3e79ed57e05a21b38a9755
['4d5f4da8a2ee40c69a45397661e344fb']
I want to use ApexCharts as a means of visualization in Angular. ng-apexcharts is the npm package that acts as a wrapper. Because the default tooltip of ApexCharts doesn't fit my design, I'd like to make a custom tooltip component. A custom tooltip can be specified the following way: HTML: <apx-chart ... [tooltip]="tooltip"></apx-chart> TypeScript: @Component({...}) export class LineChartComponent implements OnInit { tooltip: ApexTooltip = { custom: ({ series, seriesIndex, dataPointIndex, w }) => { return "<div>Custom tooltip HTML</div>" } }; ... } I have the following problem: When trying to define a template like this as the tooltip HTML `<div class="SOME_CLASS"><mat-card>${SOME_VALUE}</mat-card></div>` and adding this to the component's CSS file .SOME_CLASS { color: red; } the class property and a non-HTML component like mat-card won't translate to the appropriate representations in the DOM. The string is just pasted instead. The HTML-structure can be found here. What would be a way to make Angular bind this template correctly? PS: I don't have access to the tooltip component so specifying <tooltip [innerHtml]="SOME_VARIABLE"></tooltip> won't work either.
7c4521dfeed21826cb9b275e1d20d3427d458090f56d2c266234416d881955e4
['4d5f4da8a2ee40c69a45397661e344fb']
I'm using angular with ngrx store and RxJS to store and transform some personal portfolios and the appropriate quotes. When a new quote comes in, the calculations, which are done by a web worker, should trigger. Initially, I used this code to achieve the desired effect, but I noticed some flaws. this.subs.sink = combineLatest([this.portfolio$, this.transactions$]) .pipe(sample(this.triggerCalculation$)) .subscribe(([portfolio, transactions]) => { if (!portfolio || !transactions || transactions.length === 0) { return } this.worker.postMessage({ message: 'calculate positions', payload: { portfolio, transactions } }) this.subs.sink = combineLatest([ this.store.select((s) => s.performance.positionMembers), this.store.select((s) => s.quotes.currencies), ]).subscribe(([positionMembers, currencies]) => { if (positionMembers.length === 0 || currencies === {}) { return } if (portfolio?.watchlist && positionMembers) { this.worker.postMessage({ message: 'calculate total on static change' }) portfolio.watchlist.all.forEach((a) => { if (positionMembers.includes(a._id)) { this.subs.sink = this.store .select((s) => s.quotes.quotes[a._id]) .subscribe((q) => { if (q?.price) { this.worker.postMessage({ message: 'calculate performance', payload: { id: a._id, quote: q, currency: a.currency, currencies, baseCurrency: portfolio.baseCurrency, }, }) } }) } }) } }) }) I already refactored this to be way better, at least I think so. I also improved some of the filtering: this.subs.sink = this.transactions$ .pipe( sample(this.triggerCalculation$), withLatestFrom(this.portfolio$), filter(([transactions, portfolio]) => portfolio?.watchlist && transactions?.length !== 0), tap(([transactions, portfolio]) => { this.worker.postMessage({ message: 'calculate positions', payload: { portfolio, transactions } }) }), switchMap(([, portfolio]) => { return combineLatest([ this.store.select((s) => s.performance.positionMembers), this.store.select((s) => s.quotes.currencies), of(portfolio), ]).pipe(filter(([members, currencies]) => !!members?.length && Object.keys(currencies).length !== 0)) }), tap(() => { this.worker.postMessage({ message: 'calculate total on static change', }) }) ) .subscribe(([members, currencies, portfolio]) => { portfolio.watchlist.all.forEach((a) => { if (members.includes(a._id)) { this.subs.sink = this.store .select((s) => s.quotes.quotes[a._id]) .pipe(filter((q) => !!q?.price)) .subscribe((q) => { console.warn('subscription') this.worker.postMessage({ message: 'calculate performance', payload: { id: a._id, quote: q, currency: a.currency, currencies, baseCurrency: portfolio.baseCurrency, }, }) }) } }) }) My final question is how to get rid of the inner subscription (last block with portfolio.watchlist.all.forEach), where I create multiple subscriptions. The goal is to have as many subscriptions as quotes. I also change the whole object everytime new quotes are received, so subscribing the whole object would trigger even more often. Note that the subscriptions are created everytime the outer subscription triggers, so there might be an infinite number of inner subscriptions which exactly do the same. I only need them to be created once, but they should also reflect new quotes leading to new subscriptions. If some experienced RxJS programmers could help me, I'd be really glad.
066ffb4f60d55742200f7d9c6695c8993fe1028d7644b45b4ad5b92bfa7d7c52
['4d61f3db33e54f6b90f2a8992d7187c2']
I'm using React and firebase to create a simplified slack and using MDl for styles. I'm trying to integrate a button that opens up a dialog box to get some user input, in this case the name of a new chat room, and then when submitted it will send the data to firebase and store it in the rooms array and display the new room name in the list. I have already set up the form to get user input and then I tried to refactor it to work in a dialog box and I seem stuck on how to get the dialog box to work. Here is my whole component: import React, { Component } from 'react'; import './RoomList.css'; import dialogPolyfill from 'dialog-polyfill'; class RoomList extends Component { constructor(props) { super(props); this.state = { rooms: [] }; this.roomsRef = this.props.firebase.database().ref('rooms'); this.handleChange = this.handleChange.bind(this); this.createRoom = this.createRoom.bind(this); } handleChange(e){ this.setState({ name: e.target.value }); } createRoom(e) { e.preventDefault(); this.roomsRef.push({ name: this.state.name }); this.setState({ name: "" }); } componentDidMount() { this.roomsRef.on('child_added', snapshot => { const room = snapshot.val(); room.key = snapshot.key; this.setState({ rooms: this.state.rooms.concat( room ) }); }) } dialogBox(e){ const dialogButton = document.getElementsByClassName('dialog- button'); const dialog = document.getElementById('dialog'); if (! dialog.showModal) { dialogPolyfill.registerDialog(dialog); } dialogButton.onClick( (e) => { dialog.showModal(); }); dialog.document.getElementsByClassName('submit-close').onCLick( (e) => { dialog.close(); }); } render() { const roomlist = this.state.rooms.map( (room) => <span className="mdl-navigation__link" key={room.key}> {room.name}</span> ); const newListForm = ( <div id="form"> <button className="mdl-button mdl-js-button mdl-button-- raised mdl-js-ripple-effect dialog-button">Add room</button> <dialog id="dialog" className="mdl-dialog"> <h3 className="mdl-dialog__title">Create Room name</h3> <div className="mdl-dialog__content"> <p>Enter a room name</p> </div> <div className="mdl-dialog__actions"> <form onSubmit={this.createRoom}> <div className="mdl-textfield mdl-js-textfield"> <input type="text" value={this.state.name} className="mdl-textfield__input" id="rooms" onChange= {this.handleChange} /> <label className="mdl-textfield__label" htmlFor="rooms">Enter room Name...</label> <button type="submit" className="mdl-button submit- close">Submit</button> <button type="button" className="mdl-button submit- close">Close</button> </div> </form> </div> </dialog> </div> ); return ( <div className="layout mdl-layout mdl-js-layout mdl-layout-- fixed-drawer mdl-layout--fixed-header"> <header className="header mdl-layout__header mdl-color-- grey-100 mdl-color-text--grey-600"> <div className="mdl-layout__header-row"> <span className="mdl-layout-title">Bloc Chat</span> <div className="mdl-layout-spacer"></div> </div> </header> <div className="drawer mdl-layout__drawer mdl-color--blue- grey-900 mdl-color-text--blue-grey-50"> <header className="drawer-header"> <span>{newListForm}</span> </header> <nav className="navigation mdl-navigation mdl-color-- blue-grey-800"> <div>{roomlist}</div> <div className="mdl-layout-spacer"></div> </nav> </div> </div> ); } } export default RoomList;
8658e11db5e6c99f81877a912ca8af52cc5b2e4d80d6184b739750ad66201dc1
['4d61f3db33e54f6b90f2a8992d7187c2']
I have a simple to do app that is working fine, except for the ability to delete items from the list. I have already added the button to each of the list items. I know I want to use the .filter() method to pass the state a new array that doesn't have the deleted to-do but I'm not sure how to do something like this. Here is the App's main component: class App extends Component { constructor(props){ super(props); this.state = { todos: [ { description: 'Walk the cat', isCompleted: true }, { description: 'Throw the dishes away', isCompleted: false }, { description: 'Buy new dishes', isCompleted: false } ], newTodoDescription: '' }; } deleteTodo(e) { this.setState({ }) } handleChange(e) { this.setState({ newTodoDescription: e.target.value }) } handleSubmit(e) { e.preventDefault(); if (!this.state.newTodoDescription) { return } const newTodo = { description: this.state.newTodoDescription, isCompleted: false }; this.setState({ todos: [...this.state.todos, newTodo], newTodoDescription: '' }); } toggleComplete(index) { const todos = this.state.todos.slice(); const todo = todos[index]; todo.isCompleted = todo.isCompleted ? false : true; this.setState({ todos: todos }); } render() { return ( <div className="App"> <ul> { this.state.todos.map( (todo, index) => <ToDo key={ index } description={ todo.description } isCompleted={ todo.isCompleted } toggleComplete={ () => this.toggleComplete(index) } /> )} </ul> <form onSubmit={ (e) => this.handleSubmit(e) }> <input type="text" value={ this.state.newTodoDescription } onChange={ (e) => this.handleChange(e) } /> <input type="submit" /> </form> </div> ); } } And then here is the To-Do's component: class ToDo extends Component { render() { return ( <li> <input type="checkbox" checked={ this.props.isCompleted } onChange={ this.props.toggleComplete } /> <button>Destroy!</button> <span>{ this.props.description }</span> </li> ); } }
07e159e8247c3e030afd6e26cd71f06e47982dc5cbb44f820da1a8e7d98ebdc0
['4d681f1ca88a4531a7c9d7238cfbc4b3']
I have two pandas Dataframes: One a float called sdtarray (representing seconds): z1 z2 z3 ... 0 NaN NaN NaN 1 2.6 3.4 63.0 2 NaN NaN NaN 3 0.1 1.1 60.7 4 4.7 5.2 64.9 5 0.1 0.6 61.1 ... [33945 rows x 95 columns] and another a formatted date (thenewtime): 0 2014-09-01 05:22:00 1 2014-09-01 05:38:00 2 2014-09-01 06:08:00 3 2014-09-01 06:27:00 4 2014-09-01 06:37:00 5 2014-09-01 06:57:00 ... Name: thenewtime, dtype: datetime64[ns] What is the best way to offset each row in the float DataFrame (sdtarray) by the corresponding date (same row index but thenewtime DataFrame) - ending up with a DataFrame of dates? example output would be: z4 z5 z6 … 0 NaN NaN NaN 1 01/09/2014 05:38:02 01/09/2014 05:38:03 01/09/2014 05:39:03 2 NaN NaN NaN 3 01/09/2014 06:27:00 01/09/2014 06:27:01 01/09/2014 06:28:00 4 01/09/2014 06:37:04 01/09/2014 06:37:05 01/09/2014 06:38:04 5 01/09/2014 06:57:00 01/09/2014 06:57:00 01/09/2014 06:58:01 … I am using pandas 0.13.1 which I know doesn't help things but am stuck with this as it has to be compatible with numpy 1.7.1 due to ArcGIS requirements. I managed to get the right output using itertuples on each row (and using a timedelta but it's incredibly slow for large data (34k rows by 100 cols) and there must be a more efficient way not reliant on examining each rol / column in a loop. Any help and guidance would be appreciated :)
f07a744f8a57d41a3ebfad93fde8b9ca2e47698281d79b69105f2d560557056e
['4d681f1ca88a4531a7c9d7238cfbc4b3']
I am having a problem with encoding within Python2.7 I have a string held within an Excel file as I believe utf-8 but when I open it within python, I can't seem to get it decode correctly An example of the text held as utf-8: Belo Horizonte (MG) <PERSON>, <PERSON> When I copy the text into the shell, it decodes as expected: print "Belo Horizonte (MG) <PERSON>, <PERSON>') Belo Horizonte (MG) <PERSON>, <PERSON> But when I try to use the same process on some text held in an Excel file using the following code: import xlrd, codecs ExcelFileName= 'outfinbrazil2.xlsx' workbook = xlrd.open_workbook(ExcelFileName) worksheet = workbook.sheet_by_name("Sheet1") num_rows = worksheet.nrows num_cols = worksheet.ncols for curr_row in range(1, num_rows, 1): row_data = [] theid = worksheet.cell_value(curr_row, 0) data = worksheet.cell_value(curr_row, 2) print data print data.decode('utf-8') I get: Belo Horizonte (MG) Praça Diogo de Vasconcelos, Fundo Correio da Manhã Traceback (most recent call last): File "D:\brazil\test.py", line 15, in <module> print data.decode('utf-8') File "C:\Python27\ArcGIS10.3\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 23-24: ordinal not in range(128) What am I doing wrong?
4333f2df8d23aa539390ab3391ad5fbc8474fe7ff3525ed090dd7e6b27fe4e9a
['4d6c18a88c8449caa89ede22dd4715f1']
On a simple SELECT from the table with a clustered index would come back in the order of the clustered index. Wasn't as clear as I should have been that it was an illustration of when data is ordered by a particular column physically, but it's definitely not a given that in every query it would be returned correctly. Mea culpa.
08a7bbe63191177b96d8bba824899fc28739db112594b379c66bbafd259fb833
['4d6c18a88c8449caa89ede22dd4715f1']
Hi, i've tried the edited approach, all colors dim to 0, with a single button press, no matter if press the up or down brightness. So, if i've chosen the `GREEN` color, it dims to 0, the same applies to all. Crossfade class do the following: When the selected color is `RED` and press the `GREEN` button, then `RED` dims down to `0` and `GREEN` dims up to `100`. So my guess is that we must not use the `Crossfade` class to control brightness.
17d208fa7f53a2103d0a8f21f81ce47c134643dbdc0e0f910be6167d6c530c07
['4d715d579d164493a8e1f193112fe36e']
I am writing a little shellscript that needs to go through all folders and files on an ftp server (recursively). So far everything works fine using cURL - but it's pretty slow, becuase cURL starts a new session for every command. So for 500 directories, cURL preforms 500 logins. Does anybody know, whether I can stay logged in using cURL (this would be my favourite solution) or how I can use ftp with only one session in a shell script? I know how to execute a set of ftp commands and retrieve the response, but for the recursive listing, it has to be a little more dynamic... Thanks for your help!
dd5eb340751fb923ce865723c36614d21a7fe6bfd66f89f804aa89a0b99fbb1d
['4d715d579d164493a8e1f193112fe36e']
This is a very interesting question. You're right, the same origin policy forbids injecting JS. But Google Analytics has an advantage: it already is in your site (the tracker code). So here is how it works (as far as I can see): When you open in-page analytics, you are first taken to https://www.google.com/analytics/reporting/iyp_launch This page redirects to your site and adds a Google session to the url (like http://example.com/#gaso=THESESSION The tracker now checks if the referrer is iyp_launch and gaso is set. If yes, it does not only load the tracker, but also injects the JS needed for requesting further data and rendering the overlays. This way, the JS is executed inside the frame (or window) and bypasses the same-origin policy. Since Google Anaytics already tracks your visit (i.e. identifies you as the same user that viewed the previous page), it can from then on inject the additional JS along with the tracker until your visit is over (i.e. you close the page). This way, the overlays can be rendered again after you click a link. So I guess the bottom line is this: Things like in-page analytics can be done if the site's owner has already trusted you by adding a script you control to his website (this is a good example why one should be very careful before doing such a thing). If you don't have that kind of access to the site, it might be impossible to bypass the same-origin policy - at least, I can't think of another way to do it (except maybe proxying all the requests through your sever, but that leads to other major problems).
68693106c7be45b21fc3cba0e32641ce5c489f9e1eddba8578e7c30f266025fa
['4d874ddc43ee46e199f47edf9d3e1c73']
I am trying to understand the linux kernel and there is one thing that is puzzling me for quite a while. As linux is used across variety of platforms (like smartphones,desktop,supercomputers etc) and also on various architectures, so does the same kernel code is used by all or a different one and also since it includes some assembly codes so it must be architecture specific. so do the developers in linux community apply patches to a single kernel or there are multiple versions of kernel each for different architecture and platforms?
c06c37832da98ce27e68e8bd54866edb246c2b4de6757452062d8da755b6869f
['4d874ddc43ee46e199f47edf9d3e1c73']
I am considering to set up a MySQL database via amazon web services (AWS). Consider the following steps which characterize my workflow: There is a daily data inflow into several AWS EC2 instances On each EC2 instance, incoming data is stored in a RData file (tabular format) RData files from all EC2 instances should be exported as tables to a central database (file size is relatively small, less than 10 MB per file) Using R/RStudio, data cleaning and data aggregation routines need to be performed on the central database All steps must be automated via cron jobs Steps 3 and 4 are my main concern. Is this a standard work flow which can be integrated easily with Amazon Relational Database Service (RDS)? Or should I consider a different approach (for example, running the SQL database on a separate EC2)?
b0dc15f3839d644cd641dd39ade9d2ec2b1ddf4e58603bd11027312c985ccec6
['4daa1273c56b43e5aa6f09c9e9aaaeb0']
I started working for a startup a while ago and they ask me to hire a new programmer, so I did. Then my boss asked me to limit his access, in case something happens.How should I limit his access to repos, AWS, etc? Can I do this in a non evasive way? Thanks for your help.
35a17f13b861c383ba0a4aad892c1eae098b864dfe9a091e0f66c652d0f63e49
['4daa1273c56b43e5aa6f09c9e9aaaeb0']
I am writing my first React Redux ecommerce application and I wondering what is best practice, should I download all the data at ones or use server side pagination. When the user goes into the route "/products" I check to see if the state has the products if it does not then I fetch them. componentDidMount(){ if(this.props.products.length <= 0){ var token = this.props.auth.token; this.props.actions.getProducts(token); } } But I am not sure if I should download all the products (1,000) and save them in the store or request them as needed. Example: I download 100 products and get all the pages and if the user wants to see the next 100 I fetch the next 100 products from server. I will also be using this products in other parts of other forms. What do you think?
bc96829eb4f0cbe1533f9eae9060bfea7f0e41add92690abbca5a359e0b70efc
['4db0cc3ec4d74feeaa09bba786d7f8a4']
Создать многопоточное приложение, которое рисует графики двух функций. За каждую функцию отвечает отдельный поток. Также, должна быть предусмотрена возможность задания приоритетов потокам. Собственно, как это сделать? Насколько я понимаю, графику в окне рисует только один поток. Или же можно реализовать в нескольких? Мои попытки осуществить это: import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.chart.LineChart; import javafx.scene.chart.XYChart; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import static java.lang.Math.*; public class Controller{ @FXML public ChoiceBox cbSecond; @FXML public ChoiceBox cbFirst; @FXML public TextField aLabel; public LineChart ch1; public LineChart ch2; @FXML public void initialize(){ ObservableList<String> items = FXCollections.observableArrayList("1", "2", "4", "5", "6", "7", "8", "9", "10"); cbFirst.setItems(items); cbSecond.setItems(items); cbSecond.getSelectionModel().selectFirst(); cbFirst.getSelectionModel().selectLast(); aLabel.setText("42"); } static double log(double x, double base) { return (Math.log(x) / Math.log(base)); } private double F1(double a, double x){ return (pow(a, 4)) / sqrt(a * a + 2 * sin(pow(abs(x), 3) + 1)); } private double F2(double x){ return (log((x * x + 1), 2) + log(pow(abs(x), 5), 2)) / pow(abs(x), 3) + 1; } public void plotBtnClick(ActionEvent actionEvent) { XYChart.Series firstline = new XYChart.Series(); firstline.setName("F1"); XYChart.Series secondline = new XYChart.Series(); double a = Double.parseDouble(aLabel.getText()); int firstPriority = Integer.parseInt(cbFirst.getValue().toString()); int secondPriority = Integer.parseInt(cbSecond.getValue().toString()); Runnable r1 = () -> { try { for (int i = 0; i < 20; i++) { firstline.getData().add(new XYChart.Data(i, F1(i, a))); } ch1.getData().add(firstline); }catch (Exception e){ e.printStackTrace(); } }; Runnable r2 = () -> { try { for (int i = 0; i < 20; i++) { secondline.getData().add(new XYChart.Data(i, F2(i))); } ch2.getData().add(secondline); }catch (Exception e){ e.printStackTrace(); } }; Thread th1 = new Thread(r1); Thread <PERSON> = new Thread(r2); th1.setPriority(firstPriority); th2.setPriority(secondPriority); th1.start(); th2.start(); } }
6da3fc8826fd079c18954c98fdcd5a93d21ecae1d85fb8d60fb94b8c6f17339b
['4db0cc3ec4d74feeaa09bba786d7f8a4']
Listen, it might be some app. In my case, it's Vox. When Vox is on (and it's set to send audio to the system default device), when I plug in the external soundcard, the system switches to the external, and very quickly switches back to internal speakers. When Vox is off (quit), and I plug in the external soundcard - if it was default before, the system switches to it and stays on it. So in my case, the Vox player makes the difference. Perhaps you could try with some other player, see what happens (and in this case - what doesn't). Oh, this is a 2009 question... now I see... but anyway, this is what happens on my system. It's MacBook Pro Retina Mid 2012 running OS X 10.8.5.
712e35878cb6fa4173013c9db2dff8ea356571ea71aba599b322de17fd26b65c
['4db38d7fd6654fddb3ea130f8a049fa2']
Since your both classes have the same fields java reflection can help to do in a better way. Try this. public UserBO loadData (UserEntity userEntity) throws Exception{ Method[] gettersAndSetters = userEntity.getClass().getMethods(); UserBO userBO = new UserBO(); for (int i = 0; i < gettersAndSetters.length; i++) { String methodName = gettersAndSetters[i].getName(); try{ if(methodName.startsWith("get")){ userBO.getClass().getMethod(methodName.replaceFirst("get", "set") , gettersAndSetters[i].getReturnType() ).invoke(userBO, gettersAndSetters[i].invoke(userEntity, null)); }else if(methodName.startsWith("is") ){ userBO.getClass().getMethod(methodName.replaceFirst("is", "set") , gettersAndSetters[i].getReturnType() ).invoke(userBO, gettersAndSetters[i].invoke(userEntity, null)); } }catch (NoSuchMethodException e) { }catch (IllegalArgumentException e) { } } return null; }
4e5d935c3a229491704ab8c7ef45b62f60c359379d0e81d48f1420bede626afb
['4db38d7fd6654fddb3ea130f8a049fa2']
Change your controller return type to ModelAndView. I have updated your code. Try the following. @ResponseBody @RequestMapping(value = "/jsonTable", method = RequestMethod.GET) public ModelAndView populateJsonTable(@ModelAttribute("model") Person model) { DataTables<Person> dt = new DataTables<Person>(); Map<String, Object> result = new HashMap<String, Object>(); Person person = new Person(); List<Person> personList = person.findMatches(ctxt.getSession(), 1); dt.setEntityData(personList); dt.setiTotalDisplayRecords(5); result.put("personList", JsonUtil.toJson(dt)); return new ModelAndView("your jsp page here e.g page/personForm", result); }
227c5d8127d5a53602ddea1fdb580d95879af7a2f5940d563fbe3e92196e7283
['4dc3c84b69ca422a9e8e2eb6f7fc667c']
Tabbed Layout generated by Android Studio is not Collapsing in Recycler View Scroll. The Scroll for Recycler is working fine, but the toolbar is not collapsing. What am I doing wrong? Activity XML <?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SermonsActivity"> <com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:minHeight="?actionBarSize" android:padding="@dimen/appbar_padding" android:text="Sermons" android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title" /> <com.google.android.material.tabs.TabLayout android:id="@+id/tabs" app:layout_scrollFlags="scroll|enterAlways" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" /> </com.google.android.material.appbar.AppBarLayout> <androidx.viewpager.widget.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" app:srcCompat="@android:drawable/ic_dialog_email" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> Fragment XML <?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/video_recycler_english" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:paddingBottom="100dp" android:nestedScrollingEnabled="true" app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"/> <ProgressBar android:id="@+id/videos_progress_english" style="?android:attr/progressBarStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"/> </androidx.coordinatorlayout.widget.CoordinatorLayout> Tabbed Layout generated by Android Studio is not Collapsing in Recycler View Scroll. The Scroll for Recycler is working fine, but the toolbar is not collapsing. What am I doing wrong?
b9d3d10be6a33c3e1111072dc9a8cba158da682c08337b5fca62ab43bfc4baa6
['4dc3c84b69ca422a9e8e2eb6f7fc667c']
How to download the android project from android.googlesourece.com with the Gradle file!! I want to download the DeskClock app https://android.googlesource.com/platform/packages/apps/DeskClock/+/refs/tags/android-r-preview-2 but the project does not contain the Gradle file, also I did go through the official documentation but I don't really understand well. is there a tutorial guys, can you guys guide me how to get the files with Gradle
5fdeffb6ab47bdffe3a0605e8b5b3e1aaa12fba643399cf6d8185e1dfce7834c
['4ddd6f6e94814c27b3517e9c1bfbd4bc']
This is a most singular problem, with many interdisciplinary ramifications. It focuses on this piece of code (file name mainpp.c): #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int status; if (fork()) { FILE *f=fopen("/tmp/gcc-trace","a"); fprintf(f,"----------------------------------------------------------------\n"); int i; for(i=0;i<argc;i++) { fprintf(f,"%s:",argv[i]); } wait(&status); fprintf(f,"\nstatus=%d",status); fprintf(f,"\n"); fclose(f); } else { execv("g++.old",argv); } sleep(10); return status; } This is used with a bash script: #!/bin/sh gcc -g main.c -o gcc gcc -g mainpp.c -o g++ mv /usr/bin/gcc /usr/bin/gcc.old mv /usr/bin/g++ /usr/bin/g++.old cp ./gcc /usr/bin/gcc cp ./g++ /usr/bin/g++ The purpose of this code ( and a corresponding main.c for gcc) is hopefully clear. it replaces g++ and logs calls to g++ plus all commandline arguments, it then proceeds to call the g++ compiler ( now called g++.old ). The plan is use this to log all the calls to g++/gcc. ( Since make -n does not trace recursive makes, this is a way of capturing calls "in the wild". ) I tried this out on several programs and it worked well. ( Including compiling the program itself. ) I then tried it out on the project I was interested in, libapt-pkg-dev ( Ubuntu repository ). The build seemed to go well but when I checked some executables were missing. Counting files in the project directory I find that an unlogged version produces 1373 whereas a logged version produces 1294. Making a list of these files, I discover that all the missing files are executables, shared libraries or object files. Capturing the standard out of both logged makes and unlogged makes gives the same output. The recorded return value of all processes called by exec is 0. I've placed sleeps in various positions in the code. They do not seem to make any difference. ( The code with the traced version seems to compile much faster per file. I suspected that the exec might have caused the program to terminate while leaving gcc running. I thought that might cause failure because some object files might not be finishing when others need them. ) I have only one more diagnostic to run to see if I can diagnose the problem and then I am out of ideas. Suggestions?
e0d9e378ff18cfca004208ab8df5b8c07ee53b32c2b4de3714eac0a52622d030
['4ddd6f6e94814c27b3517e9c1bfbd4bc']
The first thing that occurs to me is memoization ( on-the-fly caching of function calls ), but both sqr and dist2 it would seem like they are too low level for the overhead associated with memoization to be made up for in savings due to memoization. However at a higher level, you may find it may work well for you. I think a more detailed analysis of you data is called for. Saying that most of the time in the program is spent executing MOV and JUMp commands may be accurate, but it's not going to help yhou optimise much. The information is too low level. For example, if you know that integer arguments are good enough for dist2, and the values are between 0 and 9, then a pre-cached tabled would be 1000 elements--not to big. You can always use code to generate it. Have you unrolled loops? Broken down matrix opration? Looked for places where you can get by with table lookup instead of actual calculation. Most drastic would be to adopt the techniques described in: http://citeseerx.ist.psu.edu/viewdoc/download?doi=<IP_ADDRESS>.8660&rep=rep1&type=pdf though it is admittedly a hard read and you should get some help from someone who knows Common Lisp if you don't.
07124117d64f628dc7d75085c3ccd14ccec2d7996462fabdd7167299de547ad6
['4dff502a018c4baf967b87cf6abeb444']
I've tried everything I've found to setup laravel 5.3 with elixir + webpack + vue + hot module reload and I can't achieve it. When I do gulp watch I can't run the webpack dev server with hot module reload. I've searched for a solution for a few days and I haven't found anything. Do you know how to set it up?
3f7d60db5cdc6075569234cff41dc85c05aa5b62e3f17d681e2db3b40648008e
['4dff502a018c4baf967b87cf6abeb444']
I'm developing an Android application that will need to query to an external MYSQL database. To do that, which is the best way to get the best performance and to trying to avoid overcharging of database: Do a query directly to MYSQL Database, or Do a HTTP POST to a PHP file and do a local query to MYSQL Database (note that using this way I can control the input and play with it before doing the query)
3fb0724efad7928ef0140d572559b9ae15aaf64fb7456e7e57d40cbcc14818e2
['4e0f73ee3c5246fcbd3284f6ee278450']
My __init__ method accepts another function as an argument called func_convert: class Adc: """Reads data from ADC """ def __init__(self, func_convert): """Setup the ADC Parameters ---------- func_convert : [???] user-supplied conversion function """ self._func_convert = func_convert def read(self): data = 0 #some fake data return self._func_convert(data) The argument func_convert allows a custom scaling function to be supplied once at instantiation that gets called to convert the data each time it's read. The function must accept a single int argument and return a single float. One possible example would be: def adc_to_volts(value): return value * 3.0 / 2**16 - 1.5 adc = Adc(adc_to_volts) volts = adc.read() Is there a standard way to document what the expected signature of func_convert is in the parameters section of the __init__ docstring? If it makes a difference, I'm using numpy docstring style (I think).
7167c66bf17ce3c5d1489529f0bcb66a7ff7d3894a36174977d7ea52b1a86f2d
['4e0f73ee3c5246fcbd3284f6ee278450']
First off I'm new to web stuff, so sorry if this question doesn't make sense. I created a Wordpress blog on Bluehost and would like to know how I go about viewing the file structure of my site. Everything I can find on the web references something called cPanel, but when I log into my site, I see a Bluehost Portal, but nothing called cPanel. Ultimately, I'm trying to figure out where my media library is stored so that I can have my NextGEN gallery store its photos in the default Wordpress media library. Is it possible to have the NextGEN gallery plugin use the default media library so that I don't have mulitple copies of everything? Any general info on how the files in a Wordpress/Bluehost site are structured would also be appreciated. Thanks!
0079c53b2edd80e5df452d7b44bc9f8c56116e075002bec31dad9d08b822d14a
['4e14e18ede5d4efd84c43d1800874102']
I have two very large lists. One contains about 130,000 items (List A), the other contains around 600,000 columns (List B). I need to know which items in List A appear in List B, but I'm running into a constraint with processing time. My normal approach would be something like this: Put List A in column A and List B in column B. Put the following in C1: =Not(IsError(Match(A1,B$1:B$600000,0))) Then I would fill that down to C130000. Obviously, this would work with two lists 100 items long. However, the lists are so large that this would take far too long for my computer to handle. Is there a method that I can use in Excel that would work for lists this large without taking a month to process? Or do I need to start looking into other options? Using Office 365
206ce32d97409e1e162e5be0c970f0906786e6e981609d47d013541e0a09561e
['4e14e18ede5d4efd84c43d1800874102']
I found a solution! Thanks largely to this page. Here's what I did: I created made a named range using this formula: =OFFSET(Report!$B$1,1,0,COUNTIF(Report!$B$2:$B$30,"<>-"),1) For that to work, I had to change all the empty cells to output "-" when empty in stead of "". I couldn't get COUNTIF to accept "<>""" or "<>" or any other weird tricks I tried. Using "-" was easier. That makes a dynamic named range that changes size as I put data into the sheet. I named a similar range for everything I'm trying to chart (Approved Status, Call Ready, Not Ready). The chart was able to accept those names and now it's dynamically sized. If I only have three agents on the sheet, it shows three huge bars. With twenty, it shows twenty bars (exactly what I was looking for). One other tip: I changed my first row to output "" when empty, so that COUNTIF(Report!$B$2:$B$30,"<>-") always returns at least 1 (otherwise you get annoying errors because you have a named range referencing a 0-length array).
c9eb1305f86c409a7fa985a6b887e62e8c46ff2147de77773558722a78d3ecb0
['4e1c3e37413f494cacdd2fc7189ea1b7']
I have a windows forms (using c#) application. It displays a webpage and has a textbox/botton combination which can be used to search for text displayed to the user. Currently I search the inner text of all elements for the text in the textbox. And then I weed out the elements that are redundant (for example a word could be in a 'p' and 'b' element where the 'b' is a child element of 'p' so the element returned should be 'b'). Finally I run the ScrollIntoView(true) method on the found element. I'd now like to add a function that highlights the text (like if you search for a term in a real webbrowser). My first thought was to just inject html and or javascript code around the text but that seems like a messy solution. Any ideas on how I should do this? Thanks for your help!
04c41c078b48c31154c479876fffff85c6ab531ca20afd6f3b9f3726212d9135
['4e1c3e37413f494cacdd2fc7189ea1b7']
I have a label next to a text box which has a short cut key. The XAML for the label looks like: <Label>Enter your _Name</Label> Where if you press alt+N it sets focus in the textbox where you would enter your name. I'd like the letter N to be underlined so that when the user sees the label it looks like: Enter your Name (well N is bold here, but I'd like it be underlined :)) Thanks for your help!
49b568ec95eb8512ccf68f650d374a85a9f5c89db52d78f73358b58e245cd221
['4e35c85d2377405c9a47213bfa0e4232']
I am building a new template page that allows my ecommerce store to be displayed via html. I cannot decide whether to use ID or classes here. As it is a template they will only be referenced once. But it seems strange to put # to all the layout content to the right. Below is my code, each line is a new division and I have tabbed to show child elements to the right and the parents to the left. <header></header> <logo><cards><delivery><icons> <nav></nav> <breadcrumb><navlinks> <aside></aside> <category><search><manufacturers><whatsnew> <section></section> <maincontent> <aside></aside> <cart><bestsellers><specials><reviews><information> <footer></footer> <div></div> <footerblock><worldpay><sslcert><paypal></footerblock>
461b70640ce110cb92bcff5e95f6b3bab2470e6a7bbd4a16b2fd23582d7c253c
['4e35c85d2377405c9a47213bfa0e4232']
I am looking to create a table that has 4 tables within it. (These are displayed with tabs for each table) Had a look through the plugins and can't see anything that can do this. Plenty of table stuff but not with tabs. This is what I am trying to achieve https://drive.google.com/file/d/0Bz6miRudGoHUUHpqSWlBMDJVMVE/view?usp=sharing
7a210cd9051b4cc04eea04f428fb926a72adcbe915dd76d93c1ab1e084296be7
['4e3dfd1130e249b6bb8394a2c679f58f']
On my Ubuntu 16.04 box, a MacBook Air 7,2, some recent update that I installed in the last few weeks have caused the WiFi to be disabled upon boot. Network Manager says the network is enabled, but if I go to System Preferences and click on Network, the "WiFi" view shows the wireless device switched off (the top-right button of the light-gray part of the window is switched to "off"). By clicking on that button the wireless becomes enabled and I can use it just fine, but it's really annoying to have to do this each time I boot. Where should I look into to figure out what's causing this nuisance?
6d461b5f1c822988cafeadc9bd6b18fc2be750e1f90e788eb2dea06f3e54dbc8
['4e3dfd1130e249b6bb8394a2c679f58f']
The mirror concatenation of the first 1, 6 and 8 prime numbers with no primes being reversed is a prime ! i.e. 131175323571113 and 19171311753235711131719 are prime numbers! (beautiful primes!). After these I couldn't find other primes with such form up to the first 2500 primes(!). Does there exist prime number of such form after these three ?
5c92fcd885c09c3c49b2c1dddc2164a49d0fedbabf7daf467ae390e2d2260244
['4e4148ba02bc45c188dbd94c499789e2']
I think you could look the solution at here http://www.django-rest-framework.org/api-guide/status-codes/ I had the same problem before this, all you need to fix this is just import status from rest_framework and Response from rest_framework.response from rest_framework import status from rest_framework.response import Response
92506cd5145b9f1f46bbcc1f7436806e18d5b225de2c86ec826344b5c6c9425a
['4e4148ba02bc45c188dbd94c499789e2']
I just found a set of strange characters that I've never seen before from someone (https://paste.villavu.com/show/2991/) (the chars are separated by a space). That person said a char from that characters set can be used to make a person's name field blank in Twitch, Discord, etc, so they will show like they have no name. I've tried to figure out what those chars really are by using Python's ord(). But I got TypeError: ord() expected a character, but string of length X found although I only put 1 char for the ord() argument and all things seem valid. I'm taking a char from that character set, and try to put it in ord() >>> ord(' ') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ord() expected a character, but string of length 3 found Then I continued by assuming that strange char is a set of chars. >>> ' '[0] '\ufeff' >>> ' '[1] ' ' >>> ' '[2] '\ufeff' From what I've found \ufeff is a byte order mark (from here). But still it doesn't make sense to me, especially about how those chars can be packed together so it seems like it is only like 1 character from my computer. And why some platforms treat it as a valid value, e.g for name. Anybody could explain to me about this please?
0c4f80890d73fefe27d74d4e4fc4442a3113cc56041a5e391a8d5ff33eff87b0
['4e4377123bdc43ae981a84cb60a27c81']
В общем, видимо требовалось просто свежая голова. Итак, в конструкторе надо метод Connect() вызывать только в случае подключения по TCP. Т.е. вместо RpcSocket.Connect(RemoteEndPoint); использовать if (ConnectionType == ProtocolType.Tcp) RpcSocket.Connect(RemoteEndPoint); При таком использовании сокет не привязывается к удаленному узлу. Именно по этой причине приходилось переподключать сокет в теле метода. А в методе вызова процедуры CallBroadcast() часть с TCP-соединением повесить на исключение, и оставить только SendTo() для UDP подключения. А вообще я переписал функцию так, чтобы ее можно было использовать и для единичного вызова. Получилось примерно следующее: public Dictionary<EndPoint, RpcReplyMessage> CallBr(RpcCallMessage callProcedure) { Dictionary<EndPoint, RpcReplyMessage> replies = new Dictionary<EndPoint, RpcReplyMessage>(); CallMessage = callProcedure; bool waitReplies = ConnectionType == ProtocolType.Tcp ? false : true; EndPoint ep = new IPEndPoint(IPAddress.Any, 111); byte[] mes = callProcedure.ToBytes(); byte[] finalmes = new byte[sizeof(uint) + mes.Length]; Buffer.BlockCopy(NetUtils.ToBigEndianBytes(xid), 0, finalmes, 0, 4); Buffer.BlockCopy(mes, 0, finalmes, 4, mes.Length); switch (ConnectionType) { case ProtocolType.Tcp: if (!RpcSocket.Connected) RpcSocket.Connect(RemoteEndPoint); RpcSocket.Send(finalmes); break; case ProtocolType.Udp: RpcSocket.SendTo(finalmes, RemoteEndPoint); break; default: throw new Exception(ConnectionType.ToString() + " protocol have not realization of function Call()."); } do { try { byte[] buff = new byte[1024]; int recSize = RpcSocket.ReceiveFrom(buff, ref ep); if (!(CheckXID(buff) && CheckReceive(buff))) continue; recSize -= sizeof(uint); byte[] nbuff = new byte[recSize]; Buffer.BlockCopy(buff, sizeof(uint), nbuff, 0, recSize); replies.Add(ep, new RpcReplyMessage(nbuff)); } catch (SocketException) { waitReplies = false; } } while (waitReplies); return replies; } Так же добавил условие на то, чтобы при TCP-подключении сокет принимал данные только однократно. Касаемо фильтрации по порту отправителя. Видимо это можно устроить только программно проверяя порт, с которого был отправлен ответ.
61e86494672087ede173c95587906fdefbb510d5dd7d591c2e7820e686093f04
['4e4377123bdc43ae981a84cb60a27c81']
Have you tried wkhtmltopdf? It comes with a tool called wkhtmltoimage. It uses QtWebKit (A Qt port of the WebKit rendering engine) to render a web page, and converts the result to PDF or image format of your choice, all done at server side. Because it uses WebKit, it renders everything (images, css and even javascript) just like a modern browser does. You can fine tune the parameters such as tweaking the JavaScript execution grace period. In my use case, the results have been very satisfying and are almost identical to what browsers would render. Here's a list of command options: Name: wkhtmltoimage 0.11.0 rc2 Synopsis: wkhtmltoimage [OPTIONS]... <input file> <output file> Description: Converts an HTML page into an image, General Options: --allow <path> Allow the file or files from the specified folder to be loaded (repeatable) --checkbox-checked-svg <path> Use this SVG file when rendering checked checkboxes --checkbox-svg <path> Use this SVG file when rendering unchecked checkboxes --cookie <name> <value> Set an additional cookie (repeatable) --cookie-jar <path> Read and write cookies from and to the supplied cookie jar file --crop-h <int> Set height for croping --crop-w <int> Set width for croping --crop-x <int> Set x coordinate for croping --crop-y <int> Set y coordinate for croping --custom-header <name> <value> Set an additional HTTP header (repeatable) --custom-header-propagation Add HTTP headers specified by --custom-header for each resource request. --no-custom-header-propagation Do not add HTTP headers specified by --custom-header for each resource request. --debug-javascript Show javascript debugging output --no-debug-javascript Do not show javascript debugging output (default) --encoding <encoding> Set the default text encoding, for input -H, --extended-help Display more extensive help, detailing less common command switches -f, --format <format> Output file format --height <int> Set screen height (default is calculated from page content) (default 0) -h, --help Display help --htmldoc Output program html help --images Do load or print images (default) --no-images Do not load or print images -n, --disable-javascript Do not allow web pages to run javascript --enable-javascript Do allow web pages to run javascript (default) --javascript-delay <msec> Wait some milliseconds for javascript finish (default 200) --load-error-handling <handler> Specify how to handle pages that fail to load: abort, ignore or skip (default abort) --disable-local-file-access Do not allowed conversion of a local file to read in other local files, unless explecitily allowed with --allow --enable-local-file-access Allowed conversion of a local file to read in other local files. (default) --manpage Output program man page --minimum-font-size <int> Minimum font size --password <password> HTTP Authentication password --disable-plugins Disable installed plugins (default) --enable-plugins Enable installed plugins (plugins will likely not work) --post <name> <value> Add an additional post field (repeatable) --post-file <name> <path> Post an additional file (repeatable) -p, --proxy <proxy> Use a proxy --quality <int> Output image quality (between 0 and 100) (default 94) --radiobutton-checked-svg <path> Use this SVG file when rendering checked radiobuttons --radiobutton-svg <path> Use this SVG file when rendering unchecked radiobuttons --readme Output program readme --run-script <js> Run this additional javascript after the page is done loading (repeatable) --disable-smart-width Use the specified width even if it is not large enough for the content --enable-smart-width Extend --width to fit unbreakable content (default) --stop-slow-scripts Stop slow running javascripts (default) --no-stop-slow-scripts Do not Stop slow running javascripts --transparent Make the background transparent in pngs --user-style-sheet <url> Specify a user style sheet, to load with every page --username <username> HTTP Authentication username -V, --version Output version information an exit --width <int> Set screen width, note that this is used only as a guide line. Use --disable-smart-width to make it strict. (default 1024) --window-status <windowStatus> Wait until window.status is equal to this string before rendering page --zoom <float> Use this zoom factor (default 1) Specifying A Proxy: By default proxy information will be read from the environment variables: proxy, all_proxy and http_proxy, proxy options can also by specified with the -p switch <type> := "http://" | "socks5://" <serif> := <username> (":" <password>)? "@" <proxy> := "None" | <type>? <sering>? <host> (":" <port>)? Here are some examples (In case you are unfamiliar with the BNF): http://user:password@myproxyserver:8080 socks5://myproxyserver None Contact: If you experience bugs or want to request new features please visit <http://code.google.com/p/wkhtmltopdf/issues/list>, if you have any problems or comments please feel free to contact me: <<EMAIL_ADDRESS>>
b91e30a458b72b6c08f33b2c8f59844e97c29cca9eb8c1760023da5da0f2e239
['4e534b2f1f43461cb4851b65df166ce3']
docker run -d -v /home/data:/data --name=neo neo4j after I run a neo4j in docker, docker exec -it neo bash ./neo4j-admin dump --database=graph.db --to=/home/2018.dump it will say neo4j is running command failed: the database is in use -- stop Neo4j and try again but ./neo4j stop will get neo4j not running what should i do?
12132c51fbbf086de4613f99beed9ea118d474614a6e0116c16b567394c72f57
['4e534b2f1f43461cb4851b65df166ce3']
What I'd like to do is this: Consume records from a topic count the values for each 1 sec window detect window whose records num < 4 Send the FINAL result to another topic I use suppress to send final result, but I got an error like this. 09:18:07,963 ERROR org.apache.kafka.streams.processor.internals.ProcessorStateManager - task [1_0] Failed to flush state store KSTREAM-AGGREGATE-STATE-STORE-0000000002: java.lang.ClassCastException: org.apache.kafka.streams.kstream.Windowed cannot be cast to java.lang.String at org.apache.kafka.common.serialization.StringSerializer.serialize(StringSerializer.java:28) at org.apache.kafka.streams.kstream.internals.suppress.KTableSuppressProcessor.buffer(KTableSuppressProcessor.java:86) at org.apache.kafka.streams.kstream.internals.suppress.KTableSuppressProcessor.process(KTableSuppressProcessor.java:78) at org.apache.kafka.streams.kstream.internals.suppress.KTableSuppressProcessor.process(KTableSuppressProcessor.java:37) at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:115) at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:146) ..... I think my code is the same as example in developer guide. What's the problem? My code here. final KStream<String, String> views = builder.stream("fluent-newData"); final KTable<Windowed<String>, Long> anomalousUsers = views .map((key, value) -> { JSONObject message = JSONObject.fromObject(value); String[] strArry = message.getString("detail").split(","); return KeyValue.pair(strArry[0], value); }) .groupByKey() .windowedBy(TimeWindows.of(Duration.ofSeconds(1)) .grace(Duration.ofSeconds(20))) .count() .suppress(Suppressed.untilWindowCloses(unbounded())) .filter((windowedUserId, count) -> count < 4); final KStream<String, String> anomalousUsersForConsole = anomalousUsers .toStream() .filter((windowedUserId, count) -> count != null) .map((windowedUserId, count) -> new KeyValue<>(windowedUserId.toString(), windowedUserId.toString() +" c:" + count.toString())); anomalousUsersForConsole.to("demo-count-output", Produced.with(stringSerde, stringSerde));
344eca82e44ce42e917fa97019f45a8cac5168f233dd572725a0dc4509708ef0
['4e63c18412e04eadb74c79bc74faf75a']
you tape for i in d , but the model created is named myuser, so you should put it as the limite of your loop, so try this on your HTML file : <table class="table"> <tr> <th>email</th> <th>firstname</th> <th>lastname</th> </tr> {% for i in myuser %} <tr> <td>{{i.email}}</td> <td>{{i.firstname}}</td> <td>{{i.lastname}}</td> </tr> {% endfor %} </table> I create a table to display them clearly.
f415bd79885755dc26afcf5c5c8b0f8f8961bbae19a56e83e47e852ef65938b6
['4e63c18412e04eadb74c79bc74faf75a']
First thing in the function 'get_absolute_url', in kwargs={'pk':self.pk}), you have to delete 'self.' before 'pk', It's already defined as self_function so it will return a self_primary_key for the image. It will be apear like : def get_absolute_url(self): return reverse("image_detail",kwargs={'pk':pk}) Now, you sould to read all the image pk's in your database, not only the pk for one image, because you will have a lot of images, so if you return only one pk, the browser will show you the first image only, so use a for loop, and your code should apear like : ... <div class="col-lg-3 col-md-4 col-6"> {% for image in p.images.all %} <div class="d-block mb-4 h-100"> <img class="img-fluid img-thumbnail" src="{{ p.image.url }}" alt="hi"> </div> {% endfor %} </div> ... Also in the class 'DayImage' you have to delete the 'self.' before the 'pk' in the return.
77a62fa26fe101c2bd43e298556027acc6c2afdb97d05f2d11066b6634990dc2
['4e6685b4ea4449c5a8c8411a9b1cbc3f']
I have several href tag, and it redirects to different Jsp. I want to send an integer along with URL. Assume I am in a.jsp, Inside I have an href tag like below <a href='app/b?num=1' class='passid'>Link to b.jsp</a> // Is this correct syntax to pass value <a href='app/c?num=2' class='passid'>Link to c.jsp</a> <a href='app/d?num=3' class='passid'>Link to d.jsp</a> If I click Link to b.jsp , then inside b.jsp ready method I have to take that num value that sends through href tag. $(document).ready(function() { needs to check num equals to 1 or not }
246482cb311fac319f8edc72d7844307a660238bdc7d79eb2372cc254275fd6a
['4e6685b4ea4449c5a8c8411a9b1cbc3f']
I am getting an java.net.MalformedURLException: no protocol: /jsp/error.jsp, I have already seen lots of questions related to this, none of that helped me. Here is my full stack trace Caused by: java.net.MalformedURLException: no protocol: /jsp/error.jsp at oracle.xml.xslt.XSLStylesheet.flushErrors(XSLStylesheet.java:2248) at oracle.xml.xslt.XSLStylesheet.execute(XSLStylesheet.java:628) at oracle.xml.xslt.XSLProcessor.processXSL(XSLProcessor.java:364) at oracle.xml.jaxp.JXTransformer.transform(JXTransformer.java:504) Please help me.
cc011fee3159e35b54def962aa3136ad37e2a5bd9f8c6f9ea4295b7efbbee21e
['4e711aa1f2384534ab0748f9a8334306']
Different versions of Android handle AsyncTasks differently. Prior to 1.6, tasks were handled serially. From 1.6 to 2.3.7 they were handled asynchronously with a thread pool. From 3.0 on they went back to handling them serially. You can force the use of a thread pool by explicitly specifying the executer. Instead of calling the following to execute your tasks task.execute(param1, param2, ...) call task.executeOnExecuter(AsyncTask.THREAD_POOL_EXECUTER, param1, param2, ...)
b75c6c1ba2d6f6de8b8a645513adbde662b85a54c4332b5115dcf785bbcdac58
['4e711aa1f2384534ab0748f9a8334306']
You would use a text watcher if you want to be notified that the text has been changed and need to do something in direct response to that event itself. For example if you wanted to do some custom validation on the fly and automatically enable / disable a button based on the value entered. Using getText just simply returns what ever is in the edit text field at that particular time. You might use this if you want to get the text value as a result of some other event like a button click.
638e0a2228d8c87922240ab937935e22f10d087f8241aa13c82561975ffc0588
['4e7171dcc038424a81fb37354009617e']
I'm testing to add a multiselect input in my BO form. But, the multiselect output is broken (however, the value selected is really selected in BO, and values are assigned). When I select a value, the multiselect selects all the values (all the values are highlighted ; just graphically). My XML : <field name="my_field"> <argument name="data" xsi:type="array"> <item name="options" xsi:type="object">MyCompany\MyModule\Model\Config\Source\Content\TagSelect</item> <item name="config" xsi:type="array"> <item name="dataType" xsi:type="string">text</item> <item name="label" translate="true" xsi:type="string">Tags</item> <item name="formElement" xsi:type="string">multiselect</item> </item> </argument> </field> TagSelect File : public function toOptionArray() { return [ ['value' => MyInterface<IP_ADDRESS>TAG_TAG1TEST, 'label' => MyInterface<IP_ADDRESS>TAG_TAG1TEST], ['value' => MyInterface<IP_ADDRESS>TAG_TAG1TEST, 'label' => 'test'], ['value' => MyInterface<IP_ADDRESS>TAG_TAG1TEST, 'label' => 'test'] ]; } Thanks!
88ebd67aadde662ab288793a4c7e4cc5f593bd2932e456e51a11bf95d0c0814a
['4e7171dcc038424a81fb37354009617e']
I am planning a potential trip in the near future where I would be driving a rental car to New York City from Pittsburgh. I will be staying at a hotel near Times Square, but I would like to avoid driving in the city. It seems that the easiest approach would be to drop off the rental car somewhere in the NYC suburbs and transition to mass transit. Are there any train stations where I could do this when coming from the west (probably via I-78)? This is, of course, assuming that the rental car option is cost-effective. I'm currently researching to decide whether it might be a better idea to just fly (in which case getting to mass transit is straightforward). However, in order to evaluate the potential drop-off cost for the rental car, I wanted to identify some potential candidate locations where I could make the transition so I can get some rental car quotes.
b5d63d438b42acc0f4e4dc6f57d9f3402a3a891062023e6b90fac43e6478046a
['4e746ef441614a509cc7ccfc51264ca8']
I tried using the cast method from above but would get the truncated error as describe in the comments. You can also use CAST('2013-09-05T10:10:02Z' AS DATETIME) which does not require a format definition as in STR_TO_DATE(). I would consistently get: Error: Truncated incorrect datetime value: '2011-10-02T23:25:42Z' I fixed it by casting the value to an @ variable before using it in my query. Here is an example in a Stored Procedure: CREATE PROCEDURE `new_procedure`(IN p_date VARCHAR(50), p_text VARCHAR(500)) BEGIN SET @datestring = CAST(p_date AS DATETIME); -- used for debugging SELECT @datestring, p_text; INSERT INTO testtable(timestamp, text) VALUES(@datestring, p_text); END
1b00fd8972fe9829fcca30df4a17a75350b376490ab314d7907989777678bcb2
['4e746ef441614a509cc7ccfc51264ca8']
Use TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM ] str) because you already know what section of the string you want to be removed. Here is a table with dates and a given quantity that I pulled from my database: select date_format(date, '%m/%d %I:%i%p') as Date ... Date | QTY ------------------- 3/5 11:30AM | 46 3/5 11:30PM | 23 3/6 11:30AM | 12 ... Using Trim: select trim(trailing 'M' from date_format(date, '%m/%d %I:%i%p')) as Date ... Date | QTY ------------------- 3/5 11:30A | 46 3/5 11:30P | 23 3/6 11:30P | 12 ... Credit to https://www.w3resource.com/mysql/string-functions/mysql-trim-function.php for helping me understand trim
73a1609895ecf21f7fb1bf4ba6fe56e014c8c56e7ef7b7ac7f04ed26fe5887e9
['4e7b373180b64945b4d8655f8c9be596']
Level 1 page table occupies exactly one page of memory 32 bit virtual address Page size 8kb PTE 4 bytes How many bits for each of the fields? How many entries are in the level 1 table? How many entries are in the level 2 table? How many pages do the level 2 page table map? I tried and got 13 for offset and 11 for level 1 and 8 for level 2. Not sure how to solve the rest.
4851baa7c5cdbc70b5e796e0d4c154f28031fa19500d14bb59325013a7c11d6a
['4e7b373180b64945b4d8655f8c9be596']
I'm having issues with fprintf in my RPC program. It opens a file but won't read the content into a file. It will print the content using printf but fprint leaves the file blank. How do I fix this issue? Thank you #include <rpc/rpc.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include"lab5.h" char * filename(char *str) { file = str; printf("filename = %s\n",file); return file; } int writefile(char *content) { FILE *fp1; fp1 = fopen("recfile.txt", "w"); if(fp1 == NULL) { printf("File can't be created\n"); return 0; } printf("%s\n",content); int i = fprintf(fp1, "%s", content); printf("i = %d\n",i); close(fp1); return 1; } int findwordcount(char* searchword) { char *grep; int count; int status; FILE *fp; grep = (char*)calloc(150, sizeof(char)); strcpy(grep, "grep -c \""); strcat(grep, searchword); strcat(grep, "\" "); strcat(grep, "recfile.txt"); strcat(grep, " > wordcount.txt"); status = system(grep); printf("status = %d\n", status); if(status != 0) { count = 0; } else { fp = fopen("wordcount.txt", "r"); fscanf(fp, "%d", &count); printf("count = %d\n", count); } return count; }
784fa50b68f793b8a7393427e6553d0df140fba8c25c06dbc8c4f15a1928e345
['4e93674ad6f647b1900f1fc9673c0df3']
I know this answer is a bit late, but I thought it might add some new perspective to the conversation. Since about 2015, the best way -- in my opinion -- to enter code is with Stack Exchange's code snippets. This can be done by clicking the little icon to the right of the picture/image icon, or by using the keyboard shortcut CTRL + M (CMD + M on Mac). This is the best way I have found to make sure your code appears as code and doesn't not get accidentally translated. You can past mixed html/javascript/css all in the html box, or you can separate each part into individual boxes. Works much like jsfiddle, without needing to leave Stack Overflow, or rely on a link that might disappear in a few years.
7c93294eca8782d0412c4bb20c6c379a4bc4666a5831f5c174676b774ae0fd00
['4e93674ad6f647b1900f1fc9673c0df3']
@ShadowWizard yes I agree it is a duplicate. Do I need to "unflag" it or something? I'm new to the whole flagging thing. What is the protocol for duplicates? Should I leave my post up for the record, but add a note that I realize it is a duplicate?
0e869f26b1daaa4f650faf116d93bd6de77755f3237c5a79441c4daf08eb37dd
['4e97ea92e68d41ba9d214467f7c2873f']
Check this out https://codepen.io/inijr/pen/EmOEjP?editors=1111 for($i = 1; $i < $('.td-cell').length; $i+=2){ $($('.td-cell')[$i]).hover( function(){ $('.td-cell').css('border-right','none'); }, function(){ $('.td-cell').css('border-right','1px dotted #C1C3D1'); }); } for($i = 1; $i < $('.td-cell-alt').length; $i+=2){ $($('.td-cell-alt')[$i]).hover( function(){ $('.td-cell-alt').css('border-right','none'); }, function(){ $('.td-cell-alt').css('border-right','1px dotted #C1C3D1'); }); }
954b10af456dc975dd911b89b22b9e54bce4e1332d5a42d287e917032da7aca8
['4e97ea92e68d41ba9d214467f7c2873f']
I'm using Python 2.6 in centos. I'm trying to connect with MySQL server. I've tried pip install mysql-connector, mysql-connector-python and mysql-connector-python-rf yet I can't mysql_connector.so not found in pip libs. I get error: module not found MySQL.connector!
f5cb82d426ab79975c8d13805d90366fd5e9f0ca352e7f53c43b56f3553cdc54
['4eee958b0d4e4afcb935b64fac7d508d']
i want to query mongodb in sailsjs. this is structure of my db { "users": [ "52ed09e1d015533c124015d5", "52ed4bc75ece1fb013fed7f5" ], "user_msgs": [ { "sender": "52ed09e1d015533c124015d5", "sendTo": "52ed4bc75ece1fb013fed7f5", "msg": "ss" } ], "createdAt": ISODate("2014-02-06T16:12:17.751Z"), "updatedAt": ISODate("2014-02-06T16:12:17.751Z"), "_id": ObjectID("52f3b461f46da23c111582f6") } I want to search those "users" who who match array [ "52ed09e1d015533c124015d5", "52ed4bc75ece1fb013fed7f5" ] Message.find({user: ["52ed09e1d015533c124015d5","52ed4bc75ece1fb013fed7f5"]}) this query returns all objects which contains 1 OR 2 ..but i need only those which exacly match 1 AND 2, i have also tried $all, and etc.. but did not worked please tell me how to write query with sailsjs supported syntex to get those user
673f6dd043dcdfec92cc913d80b0b5634b6b6a7c655eec5a79fcc57c662da5c1
['4eee958b0d4e4afcb935b64fac7d508d']
<div *ngFor="let item of data"> <p>{{item.level_name}}</p> <input matInput type="text" id="" name="item" value="" placeholder="Search" [(ngModel)]="item.query"> <div *ngFor="let item2 of item.values | search:'id,name':item.query"> <p>{{item2.name}}</p> </div> You need to update your code here. and following model { "level_id": 10, "query":"", "values": [...]}
e8fa3303b610201bd0804dc5223e6e38e9fb29ca02fc3c4fb1be6b4a80d85dcc
['4ef9d9aa064c47c781bec09e471e9ab5']
I get the following error when I go to a page with charts in my Flutter app, then go to another page and then return to the page. Then the error is displayed. I cannot find any reason for this error. Therefore here is my code. I/flutter ( 8555): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter ( 8555): The following NoSuchMethodError was thrown building LayoutId-[<chartContainer>](id: chartContainer): I/flutter ( 8555): The getter 'length' was called on null. I/flutter ( 8555): Receiver: null I/flutter ( 8555): Tried calling: length I/flutter ( 8555): I/flutter ( 8555): The relevant error-causing widget was: I/flutter ( 8555): LayoutId-[<chartContainer>] I/flutter ( 8555): file:///C:/flutter/.pub-cache/hosted/pub.dartlang.org/charts_flutter-0.9.0/lib/src/base_chart_state.dart:116:26 I/flutter ( 8555): I/flutter ( 8555): When the exception was thrown, this was the stack: I/flutter ( 8555): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5) I/flutter ( 8555): #1 new MutableSeries (package:charts_common/src/chart/common/processed_series.dart:96:30) I/flutter ( 8555): #2 BaseChart.makeSeries (package:charts_common/src/chart/common/base_chart.dart:514:15) I/flutter ( 8555): #3 CartesianChart.makeSeries (package:charts_common/src/chart/cartesian/cartesian_chart.dart:286:32) I/flutter ( 8555): #4 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31) I/flutter ( 8555): #5 ListIterator.moveNext (dart:_internal/iterable.dart:343:26) I/flutter ( 8555): #6 new List.from (dart:core-patch/array_patch.dart:57:19) I/flutter ( 8555): #7 BaseChart.draw (package:charts_common/src/chart/common/base_chart.dart:450:9) I/flutter ( 8555): #8 ChartContainerRenderObject.reconfigure (package:charts_flutter/src/chart_container.dart:170:14) I/flutter ( 8555): #9 ChartContainer.createRenderObject (package:charts_flutter/src/chart_container.dart:62:49) I/flutter ( 8555): #10 RenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5491:28) I/flutter ( 8555): #11 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6117:11) I/flutter ( 8555): ... Normal element mounting (7 frames) I/flutter ( 8555): #18 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) I/flutter ( 8555): #19 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6236:32) I/flutter ( 8555): ... Normal element mounting (15 frames) I/flutter ( 8555): #34 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) I/flutter ( 8555): #35 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6236:32) I/flutter ( 8555): ... Normal element mounting (41 frames) I/flutter ( 8555): #76 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) I/flutter ( 8555): #77 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18) I/flutter ( 8555): #78 SliverMultiBoxAdaptorElement.updateChild (package:flutter/src/widgets/sliver.dart:1158:36) I/flutter ( 8555): #79 SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1143:20) I/flutter ( 8555): #80 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2683:19) I/flutter ( 8555): #81 SliverMultiBoxAdaptorElement.createChild (package:flutter/src/widgets/sliver.dart:1136:11) I/flutter ( 8555): #82 RenderSliverMultiBoxAdaptor._createOrObtainChild.<anonymous closure> (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:350:23) I/flutter ( 8555): #83 RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:1883:59) I/flutter ( 8555): #84 PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:915:15) I/flutter ( 8555): #85 RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:1883:14) I/flutter ( 8555): #86 RenderSliverMultiBoxAdaptor._createOrObtainChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:339:5) I/flutter ( 8555): #87 RenderSliverMultiBoxAdaptor.insertAndLayoutChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:485:5) I/flutter ( 8555): #88 RenderSliverList.performLayout.advance (package:flutter/src/rendering/sliver_list.dart:231:19) I/flutter ( 8555): #89 RenderSliverList.performLayout (package:flutter/src/rendering/sliver_list.dart:274:19) I/flutter ( 8555): #90 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #91 RenderSliverEdgeInsetsPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:132:12) I/flutter ( 8555): #92 RenderSliverPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:371:11) I/flutter ( 8555): #93 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #94 RenderViewportBase.layoutChildSequence (package:flutter/src/rendering/viewport.dart:507:13) I/flutter ( 8555): #95 RenderShrinkWrappingViewport._attemptLayout (package:flutter/src/rendering/viewport.dart:1904:12) I/flutter ( 8555): #96 RenderShrinkWrappingViewport.performLayout (package:flutter/src/rendering/viewport.dart:1862:20) I/flutter ( 8555): #97 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #98 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #99 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #100 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #101 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #102 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #103 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #104 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #105 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #106 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #107 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #108 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #109 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #110 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #111 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #112 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #113 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #114 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #115 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #116 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #117 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #118 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14) I/flutter ( 8555): #119 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #120 RenderSliverMultiBoxAdaptor.insertAndLayoutLeadingChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:457:19) I/flutter ( 8555): #121 RenderSliverFixedExtentBoxAdaptor.performLayout (package:flutter/src/rendering/sliver_fixed_extent_list.dart:234:32) I/flutter ( 8555): #122 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #123 RenderSliverEdgeInsetsPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:132:12) I/flutter ( 8555): #124 _RenderSliverFractionalPadding.performLayout (package:flutter/src/widgets/sliver_fill.dart:170:11) I/flutter ( 8555): #125 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7) I/flutter ( 8555): #126 RenderViewportBase.layoutChildSequence (package:flutter/src/rendering/viewport.dart:507:13) I/flutter ( 8555): #127 RenderViewport._attemptLayout (package:flutter/src/rendering/viewport.dart:1561:12) I/flutter ( 8555): #128 RenderViewport.performLayout (package:flutter/src/rendering/viewport.dart:1470:20) I/flutter ( 8555): #129 RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1634:7) I/flutter ( 8555): #130 PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:884:18) I/flutter ( 8555): #131 RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:436:19) I/flutter ( 8555): #132 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:914:13) I/flutter ( 8555): #133 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:302:5) I/flutter ( 8555): #134 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15) I/flutter ( 8555): #135 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1055:9) I/flutter ( 8555): #136 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:971:5) I/flutter ( 8555): (elided 3 frames from dart:async) I/flutter ( 8555): I/flutter ( 8555): ════════════════════════════════════════════════════════════════════════════════════════════════════ Here is my code: import 'dart:convert'; import 'package:Trimlog/app_localizations.dart'; import 'package:Trimlog/models/boat.dart'; import 'package:Trimlog/models/trim.dart'; import 'package:flutter/material.dart'; import 'package:global_configuration/global_configuration.dart'; import 'package:provider/provider.dart'; import 'package:http/http.dart' as http; import 'package:charts_flutter/flutter.dart' as charts; Map<String, dynamic> trimOptions = {}; Map<String, dynamic> trimOption = {}; class AnalyticsGraphs extends StatefulWidget { final Boat boat; AnalyticsGraphs(this.boat); @override _AnalyticsGraphsState createState() => _AnalyticsGraphsState(); } class _AnalyticsGraphsState extends State<AnalyticsGraphs> { bool loading = true; // Enable loading Future getBoatClassTrimTemplate() async { String boatClassJson = (await http.get(GlobalConfiguration().getValue("static_api")["boatClasses"] + "/" + widget.boat.boatClass)).body; trimOptions = await json.decode(boatClassJson)["trimTemplate"]; } @override void initState() { super.initState(); getBoatClassTrimTemplate().then((value) { setState(() { loading = false; }); }); } // Execute once on form open @override Widget build(BuildContext context) { final trims = Provider.of<List<Trim>>(context) ?? null; List<charts.Series<dynamic, num>> series = [ charts.Series( measureFn: (dynamic trim, _) => trim.weather["windSpeed"], domainFn: (dynamic trim, _) => trim.trim[trimOption.keys.first], colorFn: (dynamic trim, _) { if (trim.satisfaction < 20) { return charts.ColorUtil.fromDartColor(Colors.red); } else if (trim.satisfaction < 40) { return charts.ColorUtil.fromDartColor(Colors.deepOrange); } else if (trim.satisfaction < 60) { return charts.ColorUtil.fromDartColor(Colors.orange); } else if (trim.satisfaction < 80) { return charts.ColorUtil.fromDartColor(Colors.lightGreen); } else if (trim.satisfaction <= 100) { return charts.ColorUtil.fromDartColor(Colors.green); } return charts.ColorUtil.fromDartColor(Colors.grey); }, id: "windSpeed", data: trims, ), ]; return Column( children: [ Padding( padding: const EdgeInsets.fromLTRB(25.0, 10.0, 25.0, 10.0), child: DropdownButton<String>( isExpanded: true, hint: Text(AppLocalizations.of(context).translate("boats.trimOption")), elevation: 16, style: Theme.of(context).textTheme.bodyText1, value: trimOption.isNotEmpty ? trimOption.keys.first : null, onChanged: (String val) { setState(() { trimOption.clear(); trimOption[val] = trimOptions[val]; }); }, items: trimOptions .map((key, value) { return MapEntry( key, DropdownMenuItem<String>( value: key, child: Text(AppLocalizations.of(context).translate(value["labels"]["label"])), ), ); }) .values .toList(), ), ), trimOption.isNotEmpty ? Padding( padding: const EdgeInsets.fromLTRB(25.0, 10.0, 25.0, 10.0), child: SizedBox( height: 400.0, child: charts.LineChart( series, behaviors: [ new charts.ChartTitle(AppLocalizations.of(context).translate(trimOption.values.first["labels"]["label"]), behaviorPosition: charts.BehaviorPosition.bottom, titleStyleSpec: charts.TextStyleSpec(fontSize: 11), titleOutsideJustification: charts.OutsideJustification.middleDrawArea), new charts.ChartTitle(AppLocalizations.of(context).translate("weather.windSpeed") + " (" + AppLocalizations.of(context).translate("units.knots") + ")", behaviorPosition: charts.BehaviorPosition.start, titleStyleSpec: charts.TextStyleSpec(fontSize: 11), titleOutsideJustification: charts.OutsideJustification.middleDrawArea) ], defaultRenderer: new charts.LineRendererConfig( includeLine: true, includePoints: true, ), animate: false, animationDuration: Duration(seconds: 0), defaultInteractions: false, ), ), ) : Container(), ], ); } } If I then change to another page I get the next error which makes the app stop working completely. I/flutter ( 8555): Another exception was thrown: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 3427 pos 12: 'child._parent == this': is not true. I/flutter ( 8555): Another exception was thrown: A RenderViewport expected a child of type RenderSliver but received a child of type RenderErrorBox. I/flutter ( 8555): Another exception was thrown: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 4345 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
04eb26d3e1a0a4a652a4d396eee3bfcdda09c003f3b9d03dbc7add176dffa045
['4ef9d9aa064c47c781bec09e471e9ab5']
I am trying to position a close button (x) to the top-right corner of an image. That's just before the footer of my page: <div class="modal" id="modal"> <span class="close" id="close">✖</span> <img class="modal-content" id="modal-content"> </div> How I show the modal: function showModal(name) { modal.style.display = "block"; modalImg.src = document.getElementById(name).src; } And here is my styling: /* Background when image is shown */ #modal { display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 1; /* Sit on top */ padding-top: 100px; /* Location of the box */ left: 0; top: 0; width: 100%; /* Full width */ height: 100%; /* Full height */ overflow: auto; /* Enable scroll if needed */ background-color: rgb(119, 119, 119); /* Fallback color */ background-color: rgba(119, 119, 119, 0.9); /* Black w/ opacity */ } /* Image */ #modal-content { /* Horizontally center image */ margin: auto; /* Sizing */ display: block; max-width: 90%; max-height: calc(100vh * 0.5); width: auto; /* Zoom (image gets bigger) on open */ animation-name: zoom; animation-duration: 0.6s; /* Style */ border: 10px solid #ffffff; box-shadow: rgba(0, 0, 0, 0.54) 0px 0px 7px 4px; /* Vertically center image */ position: relative; top: 40%; transform: translateY(-40%); } @keyframes zoom { from { transform: scale(0) } to { transform: scale(1) } } /* Close Button */ #close { /* Position */ position: absolute; top: 10px; right: 10px; /* Style */ color: #ffffff; font-size: 20px; font-weight: bold; transition: 0.3s; background-color: #000000; border: 3px solid #ffffff; box-shadow: rgba(0, 0, 0, 0.5) 0px 0px 25px 3px; /* Makes the Button round */ border-radius: 50%; padding-left: 7px; padding-right: 7px; padding-bottom: 3px; } /* Change cursor when pointing on button */ #close:hover, #close:focus { text-decoration: none; cursor: pointer; } /* 100% image width on smaller screens */ @media only screen and (max-width: 700px) { .modal-content { width: 100%; } } The problem is that position: absolute; top: 10px; right: 10px; positions the close button in the top-right corner of the page, not at the top right corner of the image. How can I fix that?
c9a3bc3cf734c64f894087c539e0cd7f0040d32a0b3869503b6fbb10ba49e15e
['4effa840b41444fc8087686445ccd8a6']
I have odoo 8 controller which returns certain data that is only accessible to logged users. Web site is located on different server then odoo itself. How can i request authentication from my page (as mentioned on different server)? p.s. On my development environment it all works since im calling from localhost/index.html requesting to a localhost/getData (through a reverse proxy to localhost:8069/getData for cors). But when i put it on our real server it responds with some missing session error Thank you
5a83f71cead7a0265adf2250bc7cc4eff0de309dbdd31b67ee53f0ae054d9195
['4effa840b41444fc8087686445ccd8a6']
I am trying to read companies data with: for company in self.pool('res.company').browse(cr, uid, uid): company.vat <=== code breaks here If i use the administrator (uid 1) account i see company.vat. But if i use any other account (which have permissions to res.company) i get a message: "One of the documents you are trying to access has been deleted..." Is this a permission issue or a coding error of sorts? Mind that if I hard code 1 instead of uid as a parameter to browse function it works. Thank you
fb5669c162ebcf33be39a8f1768dbaeddd1ffb3c07da145651d1bc3d1dc2503c
['4f1fc17956be46d194c25d6395cd2e34']
Yes: you would get (after multiplication by $N+1$), $rN(N+1)(1 - \frac{N}{q}) - N - N(N+1) = 0$, from which you can factor out an $N$ to get the solutions $N=0$ and $r(1 + (1 - \frac{1}{q})N - \frac{N^2}{q}) - 1 - (N+1) = 0$. The latter equation implies that $N$ is a solution of the quadratic $ \frac{r}{q}x^2+(1-r(1 - \frac{1}{q}))x + 2 - r = 0$. The roots are $$\frac{-1+r(1-1/q) \pm \sqrt{(1 - r(1-1/q))^2 - 4r(2-r)/q}}{2r/q}$$
260fd0135745b624c1b301f7a96d1cdadf29da24adb64d247a9053b3ad9b6876
['4f1fc17956be46d194c25d6395cd2e34']
Since $\lim_{m \to \infty} s_m(j) = g_j'(x) < \infty$, you can let $M$ be large enough so that $m \geq M$ implies $s_m(j) \leq g_j'(x) + 2^{-j}$. This is an integrable function which eventually dominates $\{s_m\}$ therefore. It is integrable by the hypothesis that the sum is finite. Also, I'd appreciate a comment from whoever downvoted.
b1384bc0c3cb80bfea914bafc9e82bbb609a8969417dc31461306adf9f20e3f0
['4f3d03b877324c9ba59a9b17acfb6b0b']
For example, if I have this class: class Counter { public: int* j = new int[5]; } A pointer variable is initialized as a data member. If in my copy constructor, I have something like int* j = new int[7] OR int* j = new int[5](), therefore initializing the the data member as well, will it create a memory leak for the first one since it wasn't deleted beforehand? Or will the original data member not even initialize?
289c1007349977f1a95264301f8bb1237318522569d136370118a98d9a562eb9
['4f3d03b877324c9ba59a9b17acfb6b0b']
I am learning about bucket sort and it seems a lot of the material insist that it is efficient when the key values are "uniformly distributed and when used to sort integers from a known range". I understand the uniformly distributed part, but do you have to know the range too? If the range is not provided, when creating the auxiliary array during bucket sort, could you instead simply create a dynamic array (ArrayList) which can expand by itself?
bbc19941ec77189309b3f005ccb3c424193fc7ec2febbf50ed9de48578fcc2e9
['4f3e877c878a46dabd8a56a60ccd461a']
I have an AsyncTask class that I would like to pass some primitive parameters to it through its constructor. Then do some manipulation on variables in onPreExecute (Running in Main Thread) method and then use the variables inside doInBackground (Running in a worker Thread). Is it OK to do that? Or it does need some sort of synchronization? private class MyClass extends AsyncTask<Void, Void, Void> { //shared variables Long Num1; int Num2; private MyClass (Long num1, int num2){ Num1 = num1; Num2 = num2; } @Override protected void onPreExecute() { //do some changes on Num1 & Num2 } @Override protected Void doInBackground(Void... voids) { //Use Num1 and Num2 } }
c91b070e8612426cb92de6e3d286b92ed7be5e6c17fa861c6e0fb790a25d9e5f
['4f3e877c878a46dabd8a56a60ccd461a']
I highly recommend reading this topic : Context.startForegroundService() did not then call Service.startForeground() From my experience (Working on the same scenario), you will face lots of unexpected bugs on different devices and different SDK versions by starting a Foreground Service using startForegroundService command. Just use the old startService method and you'll be fine. Also what's the purpose of using START_STICKY while it's a Foreground Service and it's guaranteed to be running as long as the ongoing notification displays?
84a731de2c242498a8dd2110c00d36ab466150bacb9ba7f6034a4c1629fcb150
['4f433d082d4c4d58a598cb336d180e37']
I'm developing an app to store one phone number at time using core data, the user should be able to enter a new phone number into ui text field,if it's equal to nil, it should store a new phone number,else it should replace old number with new number; it should store only one value. but the code doesn't work as it should what's wrong in my code? let moContext: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let context: NSManagedObjectContext = moContext.managedObjectContext let phoneNu = NSEntityDescription.insertNewObjectForEntityForName("Setting", inManagedObjectContext: context) let fetchRequest = NSFetchRequest(entityName: "Setting") fetchRequest.predicate = NSPredicate(format: "phoneNumber = %@", phoneNumber) // phoneNu.setValue(phoneNumber.text, forKey: "phoneNumber") do{ let request = NSFetchRequest(entityName: "Setting") let phoneN = try context.executeFetchRequest(request) if phoneN.count == 0{ phoneNu.setValue(phoneNumber.text, forKey: "phoneNumber") }else if phoneN.count != 0{ for item in phoneN as! [NSManagedObject]{ let number = item.valueForKey("phoneNumber") number?[0]?.setValue(phoneNumber.text, forKey: "phoneNumber") } } }catch{ print("error") } do{ let request = NSFetchRequest(entityName: "Setting") let phoneNumber = try context.executeFetchRequest(request) if phoneNumber.count > 0{ for item in phoneNumber as! [NSManagedObject]{ let number = item.valueForKey("phoneNumber") print(number!) } } }catch{ }
8a257ef2be54aa7277fcb41b434965fe7c148def750ff2bb15d9c717b31d78a5
['4f433d082d4c4d58a598cb336d180e37']
I'm facing a lot of issues with nil, it causes my app crash, and this one of issues I'm facing. when the database is empty or equal to nil, it should tell me that you sould give my phone number when fetchPhoneNumber function finds database empty by displaying UIAlertController, but instead my app keep crashing. all my attempts have failed, and below one of my attempts. How I can fix this issue? func fetchPhoneNumber(){ do{ let request = NSFetchRequest(entityName: "Setting") let phoneNumber = try managedObjectContext.executeFetchRequest(request) if phoneNumber.count > 0{ for item in phoneNumber as! [NSManagedObject]{ number = item.valueForKey("phoneNumber") as? String print(number!) } }else{ let alertController = UIAlertController(title: "Warning !", message: "You Need to Provide us With Your Phone Number", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in // ... } alertController.addAction(cancelAction) presentViewController(alertController, animated: true, completion: nil) } }catch{ let error as NSError! print("error: \(error)") } phone = number! }
2dff2f46c9b9aa9307ce8ffed76eb2a8e2f464e9f13c3f20a966a64a28ba616c
['4f46c287c22c4d63b6bd454cfddf4526']
import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Param; public interface TestMapper { ... @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id") @Insert({ "<script>", "INSERT INTO test_table", "(column_one, column_two)", "VALUES" + "<foreach item='item' collection='list' open='' separator=',' close=''>" + "(" + "#{item.columnOne,jdbcType=VARCHAR},", "#{item.columnTwo,jdbcType=VARCHAR}" + ")" + "</foreach>", "</script>"}) void insertBatchTestTable(@Param("list") List<TestObject> testObjs); } ps.: Set keyColumn and keyProperty Use @Param("list") MyBatis will set objects keyProperty by reflection
a2e42aa42f8ccbb85e75cd197472113698c77883792e3ce5ee39258e1541e435
['4f46c287c22c4d63b6bd454cfddf4526']
You can use annotations (@org.apache.ibatis.annotations.Insert) for executing a single insert for your entire list. Remember: You wont need any sql provider class. public interface SomethingMapper { @Insert({ "<script>", "INSERT INTO your_database_name.your_table_name", "(column1_int, column2_str, column3_date, column4_time)", "VALUES" + "<foreach item='each_item_name' collection='theCollection' open='' separator=',' close=''>" + "(" + "#{each_item_name.column1,jdbcType=INTEGER},", "#{each_item_name.column2,jdbcType=VARCHAR},", "(SELECT SOME_DB_FUNCTION(#{each_item_name.column3,jdbcType=DATE})),", "#{each_item_name.period.start,jdbcType=TIME}" + ")" + "</foreach>", "</script>"}) void insertBatchSomething(@Param("theCollection") List<Something> theCollection); } Output SQL if you have 2 items: SQL: INSERT INTO your_database_name.your_table_name (column1_int, column2_str, column3_date, column4_time) VALUES (?, ?, (SELECT SOME_DB_FUNCTION(?)), ?), (?, ?, (SELECT SOME_DB_FUNCTION(?)), ?) P.S. @Insert receives a String[], so for each value it will add a whitespace between Strings.
2fa79bcaaaec32f00b21cdba5adcb247eb827540bb1064ca4e345d848966ed26
['4f4d484f438240f6a5fda9bf2380edc7']
try with another port on external, many routers don't forward external 22 (also 80, 443). try with eg 2222 forward to 22 on your computer and you MUST test it outside your router network, you can't test it from internal. of course like <PERSON> said, check if your destination is listening on port 22 from all networks `netstat -anutp grep :22` to check.
b0d8875a2a42685be051a029f5b37adb3c40031b07f354ec5a06be26750e41a3
['4f4d484f438240f6a5fda9bf2380edc7']
In the provided log output we can see that the client and server are using different OpenSSL versions: client: SSH-2.0-OpenSSH_7.8 server: SSH-2.0-OpenSSH_6.7p2 Which in this case was the reason that the connection got closed. OP removed SSH server and installed the correct version which resolved his issue.
230953f82ad6c239eb94f8c735bf250c8c1dfc26e3cc38e07bb388434bdb9855
['4f509f02b4ea458682c8372b0e82d3d8']
It is not allow that two variables add same object. This is a segment. for (var i = 0; i < categories.length; i++) { var categoryId= categories[i].getElementsByTagName("CategoryID")[0].firstChild.nodeValue; var categoryName = categories[i].getElementsByTagName("CategoryName")[0].firstChild.nodeValue; var eleOpt = document.createElement("option"); var txtOpt = document.createTextNode(categoryName); var catelogryAddOption = new Option(categoryName, categoryId); sel.options.add(catelogryAddOption); sel2.options.add(catelogryAddOption); //Here is an exception. } However, it can work when I declare other Object, which is catelogryAddOption2. enter code herefor (var i = 0; i < categories.length; i++) { var categoryId= categories[i].getElementsByTagName("CategoryID")[0].firstChild.nodeValue; var categoryName = categories[i].getElementsByTagName("CategoryName")[0].firstChild.nodeValue; var eleOpt = document.createElement("option"); var txtOpt = document.createTextNode(categoryName); var catelogryAddOption = new Option(categoryName, categoryId); sel.options.add(catelogryAddOption); var catelogryAddOption2 = new Option(categoryName, categoryId); //This is catelogryAddOption2 sel2.options.add(catelogryAddOption2); // It can work } Although the problem is solved, I don't understand the reason. Does anyone explain it? Thanks.
711aa132b4125e322f667d1911f2e65682e073ba0d510cf1fae8626b88d551e1
['4f509f02b4ea458682c8372b0e82d3d8']
According to the HttpClient in the Angular document. The HttpClient.get() method parsed the JSON server response into the anonymous Object type. It doesn't know what the shape of that object is. My problem is I cannot get the Json directly. I still need to Json.parse in dash-board.component.ts dash-board.component.ts import { PhoneBasicInfo } from './../Models/PhoneBasicInfo'; import { DashBoardServiceService } from './../Services/dash-board-serv ice.service'; import { Component, OnInit } from '@angular/core'; import { PhoneRecord } from '../Models/PhoneRecords'; @Component({ selector: 'app-dash-board', templateUrl: './dash-board.component.html', styleUrls: ['./dash-board.component.css'] }) export class DashBoardComponent implements OnInit { constructor(private service: DashBoardServiceService) { } temp:any; basicInfo: PhoneBasicInfo; ngOnInit() { this.service.getPhoneBasicInfo() .subscribe( basic => { console.log(basic['companyName']) <- I should get the Json Object. console.log(JSON.parse(basic)); <- I should not do this. } ); } } Sorry my reputation is not enough to embed a picture The console picture I use JSON.parse to get the data. However, it seems not correct. So my question is what is the correct way to get the Json via the HttpClient? Thank you so much. dash-board-service.service.ts import { PhoneBasicInfo } from './../Models/PhoneBasicInfo'; import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { CATCH_ERROR_VAR } from '@angular/compiler/src/output/abstract_emitter'; @Injectable({ providedIn: 'root' }) export class DashBoardServiceService { private url = 'http://localhost:57302/api/Phone'; constructor(private http:HttpClient) { } getPhoneBasicInfo(): Observable<PhoneBasicInfo>{ return this.http.get<PhoneBasicInfo>(this.url); } } PhoneBasicInfo.ts export class PhoneBasicInfo{ companyName:string; firstTrade: string; }
f74c5c21f5dc8dab383c2e011e6f87a1ef9f1bdaa8843f082493ae67a732c52e
['4f5f8cb58fe94c2ea021a8b209499109']
So there was an update. I hate this thing pn windpws 10, because it is unexpected. I turned off updates somehow some time ago and then wondows turned it on automatically. So, after an update, I have a strange problem - turning on my pc, windows boot stucks at a logo screen (black with Win logo). Hard restart (via the button) helps all the time, but the problem still exists. Also teying to restart from the windows (Win - Restart) won't get me to this problem.
9829282ea9e24c18692da5207103525bd3b824f15682f15a49c4089b8ff9801e
['4f5f8cb58fe94c2ea021a8b209499109']
This is my first time posting on this site, so I apologize for not posting according to guidelines. For the first part of the question "How many different results are possible" I multiplied 6 five times and got 7776. I'm stuck on the second part "Of those, in how many ways can there be exactly 2 rolls of 4?" Any guidance would be greatly appreciated!
c019be41ca22d259d950426873e596092640eeeb050153d434d0ef8d217c08e9
['4f6f936832dd4ee7a1217af18e8102ed']
i think i personally would make merged cars into a dictionary, where every key is a string of (color + number + type) and the values are the car objects. Then adding the new car data is simple and fast, and getting all of the cars out is just merged_cars.values() merged_cars = { "white4354312volkswagen": { "type": "volkswagen", "number": 4354312, "color" : "white" }, "black453435BMW": { "type": "BMW", "number": 453435, "color" : "black" } } color = data["color"] for car in data["cars"]: key = color + str(car['number']) + car['type'] merged_cars[key] = car print(merged_cars.values())
5d43ba2b106c757ad39d7bf45d858f872c61777d24b2535fb0fc527bd9c10219
['4f6f936832dd4ee7a1217af18e8102ed']
Here is how I do it is a private repo and I use the branch name: pip install "git+ssh://<EMAIL_ADDRESS>/your_repo.git@your_branch_name" Note for authentication, your password might be a token from github if you have set that up. Checkout this answer for more ways to pip install: https://stackoverflow.com/a/13754517/5042916
509b66548b36ab55503184c8b44e6d90718c53985c33db4703397ae96296681d
['4f70ac53bf3a409c8f5bc4a3ae4b8b4f']
If f(n) = O(g(n)), 2^(f(n)) not equal to O(2^g(n))) Let, f(n) = 2log n and g(n) = log n (Assume log is to the base 2) We know, 2log n <= c(log n) therefore f(n) = O(g(n)) 2^(f(n)) = 2^log n^2 = n^2 2^(g(n)) = 2^log n = n We know that n^2 is not O(n) Therefore, 2^(f(n)) not equal to O(2^g(n)))
f48ea3c35937d98f285512cf5577bfa22c2a7189d22e058b65055e7ef6596c8e
['4f70ac53bf3a409c8f5bc4a3ae4b8b4f']
Here is a python script to identify those fault jpg images in a directory. import glob import os import re import logging import traceback filelist=glob.glob("/path/to/*.jpg") for file_obj in filelist: try: jpg_str=os.popen("file \""+str(file_obj)+"\"").read() if (re.search('PNG image data', jpg_str, re.IGNORECASE)) or (re.search('Png patch', jpg_str, re.IGNORECASE)): print("Deleting jpg as it contains png encoding - "+str(file_obj)) os.system("rm \""+str(file_obj)+"\"") except Exception as e: logging.error(traceback.format_exc()) print("Cleaning jps done")
d4bf06f34aaab5439682e083295ae66e7956c262f786d01bf32343dbf7c58bd6
['4f8d952267364cada4b710967460d14e']
The token auth class (https://github.com/pyeve/eve/blob/52a927fe69ff05d3098d62145efe1fbfaddb5cf9/eve/auth.py#L230) has an authorized() method that you can override. However, it's not a documented method for overriding, so know that doing so you could run into issues in different versions of Eve. The way I modified the method was to have it look for a Cookie header, and if found, try to get an auth token from it. If it finds one and check_auth returns true, call set_user_or_token and return. If there's no cookie header, or the token does not check_auth successfully, fall through to the parent class' authorized method to handle other cases (such as an Authorization header). class MyTokenAuth(TokenAuth): def authorized(self, allowed_roles, resource, method): auth = None if request.headers.get("Cookie"): auth = self.try_to_get_auth_from_cookie(request.headers.get("Cookie")) if auth and self.check_auth(auth, allowed_roles, resource, method): super().set_user_or_token(auth) return True return super().authorized(allowed_roles, resource, method)
3bd85cb4b0f619d72b8f0ceb1e55e9038f6d15e2e413e2f2c4ea6d6f8a04378d
['4f8d952267364cada4b710967460d14e']
I found a way, not sure if this is the best/right way though. I take the eve_swagger blueprint that's provided, and add a before_request with an authorization function. Something "like" this: import eve_swagger from flask import current_app as app def authorize_swagger: # my auth logic eve_swagger.swagger.before_request(authorize_swagger) app.register_blueprint(eve_swagger.swagger) The result of doing this is now when I call the default /api-docs route, my authorization function is called and processed before the request. This way if my function decides the request is not authorized, it can stop the request.
4ff0c24dc546ef5f852f6cb6f199294175a3b186214e4d4493eae3e45ef1a994
['4fa0b148d78b4e8ea1b487a3da7c1ef0']
My function randomly flips 2 characters of a word besides the first and last character. I want to use this function to write another function build_sentence(string) that uses my function to flip 2 characters of each word in the sentence. The function build_sentence(string) should return a string containing the full sentence where the letters of each word have been scrambled by scrambled(word). for example: I dn'ot gvie a dman for a man taht can <PERSON> a wrod one way. (<PERSON>) import random def scramble(word): i = random.randint(1, len(word) - 2) j = random.randint(1, len(word) - 3) if j >= i: j += 1 if j < i: i, j = j, i return word[:i] + word[j] + word[i + 1:j] + word[i] + word[j + 1:] def main(): word = scramble(raw_input("Please enter a word: ")) print (word) main()
8c0d7cde337cc444a6d5243fd5eb476bdf1be211d4e19cbfca29535456b9ad99
['4fa0b148d78b4e8ea1b487a3da7c1ef0']
credit_num = input("Enter the credit card number: ").replace(" ", "") tot1 = 0 tot2 = 0 for i in credit_num[-1<IP_ADDRESS>-2]: tot1 += int(i) for i in credit_num[-2<IP_ADDRESS>-2]: tot2 += sum(int(x) for x in str(int(i)*2)) rem = (tot1 + tot2) % 10 if rem == 0: print("The entered numbers are valid.") else: print("The entered numbers are not valid.") This works in Python 3.5. What do I modify in order for it to work in Python 2.7?
1d1eea14a3af6c7c5ea1a1f660a7f7125b14cecfdd9d77a58b2ff1fcbb4023b3
['4fa2f33e4a8a4f7681f390bcc0797bce']
I am trying to apply a conditional format to a range of cells based on the size of the Dataframe: percent_fmt = workbook.add_format({'num_format': '0.00%'}) range_1 = ## This should have the range of rows starting cell 'C23' to the number of rows in the dataframe I plan to get the get the size of the Dataframe using df.shape[0] and I trying to add this count to the value in range_1. So if df.shape[0] = 30 then range_1 = "C23:C53". <- Because formatting should start from C23 and then format the next 30 rows. The count of 30 is obtained from the size of the Dataframe. worksheet.conditional_format(range_1, {'type': 'no_blanks', 'format': percent_fmt})
56d1ddd39c46143c29deac175c5444a00ec62442eb53b90bc4f247c73dec50a2
['4fa2f33e4a8a4f7681f390bcc0797bce']
I am trying to have one of the columns in the Dataframe to be assigned value of a variable. For example: I have a column called : Count of sales done in the past 10 days I am trying to have the value of 10 in the column name changed dynamically from another variable called date So each time I update the Dataframe I want the value assigned to the variable date be shown in the column name For example if date = 4, column name should be Count of sales done in the past 4 days and so on. I tried to pass df.columns = date but get a KeyError