_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d4401
train
I think the following code works proxy : { type : 'ajax', url : Proximity.util.Config.getBaseUrl() + '/index.php/candidate/getcandidatebest', withCredentials: false, useDefaultXhrHeader: false, extraParams: { id: localStorage.getItem('id') }, reader : { filters: [ Ext.create('Ext.util.Filter', { property: 'ind_id', property: 'fun_id', property: 'role_id', property: 'id' }) ] } } and then use the filtering facility of store to pass the localstorage value. To do that give filter permission remoteFilter: true, this. A: Ahh i found an awesome trick. Instate of setting extraParams in your Model, set it in the store of the same model. My new code is as follows. Ext.define('Proximity.model.RecruiterbestlistModel', { extend: 'Ext.data.Model', config: { store:'Proximity.store.RecruiterbestStore', fields: [ { name: 'id', type: 'int' }, { name: 'name', type: 'string' }, { name: 'img', type: 'string' }, { name: 'company', type: 'string' }, { name: 'summary', type: 'string' }, { name: 'address', type: 'string' }, { name: 'industry', type: 'string' }, { name: 'functionnml', type: 'string' }, { name: 'role', type: 'string' } ], proxy : { type : 'ajax', url : Proximity.util.Config.getBaseUrl() + '/index.php/recruiter/getrecruiterbest/', withCredentials: false, useDefaultXhrHeader: false, reader : { filters: [ Ext.create('Ext.util.Filter', { property: 'ind_id', property: 'fun_id', property: 'role_id' }) ] } } } }); Look i have removed the code extraParams: { "id": localStorage.getItem('id') }, from Model. And in my store i have added listeners: { beforeload: function(store){ this.getProxy().setExtraParams({ id: localStorage.getItem('id') }); return true; }, So my new store code is as follows Ext.define('Proximity.store.RecruiterbestStore', { extend: 'Ext.data.Store', alias: 'store.recruiterbeststore', config: { model: 'Proximity.model.RecruiterbestlistModel', autoLoad: true, remoteFilter: true, storeId: 'recruiterbeststore' }, listeners: { beforeload: function(store){ this.getProxy().setExtraParams({ id: localStorage.getItem('id') }); return true; } } }); And its solved my problem. But now i am having another issue. after running sencha app build native(using cordova bild), again i am having same issue, the extraParam are not added to proxy request. Please help me to solve this.
unknown
d4402
train
It appears from this issue that Azure is not implementing a service tag, but instead thinking of creating a product where you can spin up semi-managed build agents inside your own subscription. Details can be found on the design in github A: Azure DevOps Service Tag have been released Now that a service tag has been set up for Azure DevOps Services, customers can easily allow access by adding the tag name AzureDevOps to their NSGs or firewalls programmatically using Powershell and CLI. The portal will be supported at a later date. Customers may also use the service tag for on-prem firewall via a JSON file download. Azure Service Tags are supported for inbound connection only from Azure DevOps to customers’ on-prem. Outbound connection from customers’ networks to Azure DevOps is not supported. Customers are still required to allow the Azure Front Door (AFD) IPs provided in the doc for outbound connections. The inbound connection applies to the following scenarios documented here. Note: Service Tag AzureDevOps is available from the portal now. However this will not cover IP Ranges of MS Hosted agents
unknown
d4403
train
If you want to test which of the sub-paths in your path the user clicks on. You will need to separate them into separate path definitions. Then run the Region.contains() test on each of them individually. A: Your given paths don't have bezier curves. And shouldn't as counties don't tend to define curved boundaries with each other (save a couple examples where we use longitude like the US Canada border has a curve, because Earth is curved). But, if you want. The formula to calculate the centermost point in a bezier curve, is: t = 0.5; x = (1 - t) * (1 - t) * p[0].x + 2 * (1 - t) * t * p[1].x + t * t * p[2].x; y = (1 - t) * (1 - t) * p[0].y + 2 * (1 - t) * t * p[1].y + t * t * p[2].y; Which answers your first question. The answer to the proper question, how can you tell which touch is part of which path is a harder one, and given that you actually have a polygon the correct answer is to implement a path in polygon algorithm. But, really what you want is something that works. Might I recommend a handle. Simply draw something at the center of the shape for each regional shape. Then when the person touches the screen, find the closest point, to that point. Most countries are vaguely roundish or typically not weirdly curved, so simply find the bounding region then do distance to the center point. Divide up the paths for each country. Get a bounding box for the county. Check whether that touch is inside any bounding box. If it is, compare the closeness of that touch to the center of that bounding box for all countries whose hit box was hit by that touch.
unknown
d4404
train
You can use something like this: var d = new Date(); var dd = d.getDate(); var mm = d.getMonth() + 1; var yy = d.getFullYear(); var myDateString = dd + '_' + mm + '_' + yy; And change the last variable to anything you want. A: Firstly you need to timestamp from geolocation plugin in a variable like lat let us consider timestamp in timestamp variable Then Try it this.gpsCoordsRef$.push({ latitude: this.lat, longitude: this.long, accuracy: this.acc, altitude: this.alt, altitudeAccuracy: this.altacc, speed: this.spd, dateTime: new Date(timestamp) }); Check converting timestamp to dateTime click here
unknown
d4405
train
EDIT: read comments pls, i don't want to delete it, because it may help other who fell into the same trap... Be careful with static variables!! I wrote an app which uses them, but on some devices it works, on some it doesn't. the problem is, if one activity edits that variable, finishes and the focus returns to another activity, the changes are not recognized. i haven't found a solution for this and somehow i don't get it working with getApplicationContext either... Usually i would say that i made a mistake, but in both cases, it is working on an SGSII with Android 4.0.4 but it isn't on SGSIII with 4.1... :( So as a consequence i assume that they've changed the use of global variables, maybe out of security reasons, so that every activity gets an own instance of that variable or so, i have no idea
unknown
d4406
train
You want to take a look at cmd /? output and http://ss64.com/nt/. Using start along with cmd /c will give an external window and using cmd /k will keep it in the nppexec console. One thing I don't like about the /k option is that it really isn't true as 'any key' doesn't do the trick and Enter needs to be used. Test it out with cmd /k pause and start cmd /c pause. Notice the start option has the window close, so any history will go away too. If that's important then substitute /k for the /c and use exit when done.
unknown
d4407
train
Will $url and $dir always be pointing to the same place? Yes <?php $some_relative_path = "hello"; $server_url = $_SERVER["SERVER_NAME"]; $doc_root = $_SERVER["DOCUMENT_ROOT"]; echo $url = $server_url.'/'. $some_relative_path."<br />"; echo $dir = $doc_root.'/'. $some_relative_path; Output: sandbox.phpcode.eu/hello /data/sandbox//hello A: Answer to question 1: Yes you need a variable which explicitly sets the root path of the website. It can be done with an htaccess file at the root of each website containing the following line : SetEnv APP_ROOT_PATH /path/to/app http://httpd.apache.org/docs/2.0/mod/mod_env.html And you can access it anywhere in your php script by using : <?php $appRootPath = getenv('APP_ROOT_PATH'); ?> http://php.net/manual/en/function.getenv.php A: You shouldn't need to ask the user to provide any info. This snippet will let your code know whether it is running in the root or not: <?php // Load the absolute server path to the directory the script is running in $fileDir = dirname(__FILE__); // Make sure we end with a slash if (substr($fileDir, -1) != '/') { $fileDir .= '/'; } // Load the absolute server path to the document root $docRoot = $_SERVER['DOCUMENT_ROOT']; // Make sure we end with a slash if (substr($docRoot, -1) != '/') { $docRoot .= '/'; } // Remove docRoot string from fileDir string as subPath string $subPath = preg_replace('~' . $docRoot . '~i', '', $fileDir); // Add a slash to the beginning of subPath string $subPath = '/' . $subPath; // Test subPath string to determine if we are in the web root or not if ($subPath == '/') { // if subPath = single slash, docRoot and fileDir strings were the same echo "We are running in the web foot folder of http://" . $_SERVER['SERVER_NAME']; } else { // Anyting else means the file is running in a subdirectory echo "We are running in the '" . $subPath . "' subdirectory of http://" . $_SERVER['SERVER_NAME']; } ?> A: I have just had the same problem. I wanted to reference links and other files from the root directory of my website structure. I tried the following but it would never work how I wanted it: $root = $_SERVER['DOCUMENT_ROOT']; echo "<a href="' . $root . '/index.php">Link</a>"; echo "<a href="' . $root . '/admin/index.php">Link</a>"; But the obvious solution was just to use the following: echo "<a href="../index.php">Link</a>"; echo "<a href="../admin/index.php">Link</a>";
unknown
d4408
train
The first query benefits from this index: PRIMARY KEY(ProductCode, Model, Added_Date) All the other queries could not fully benefit from either of your indexes. The Optimizer guessed at one index in one case; the other index in the other. This would work well for both cases: INDEX(ProductCode, Id) One reason for the timing differences is the distribution of data in the table. Your examples may not show the same timings if you change the 78342 to some other value. The new index I recommend will make those queries "fast" regardless of the ProductCode searched on. And "Rows" will say "1" or "2" instead of about "25000". It sounds like there are about 25K rows with ProductCode = 78342.
unknown
d4409
train
1> what shall I implement in ExtractObjectsFn() so that the records gets converted into BeamRecords ? In the processElement() method of ExtractObjectsFn, you simply need to convert a CSV line from the input (String) to a Clorox type. Split the string by the comma delimiter (,), which returns an array. Iterate over the array to retrieve the CSV values and construct the Clorox object. 2> How to write the final output to a csv file ? Similar process as above. You simply need to apply a new transform that will convert a BeamRecord to a CSV line (String). Members of the BeamRecord can be concatenated into a string (CSV line). After this transform is applied, the TextIO.Write transform can be applied to write the CSV line to file.
unknown
d4410
train
If your rules are really as simple as that then simply having "old_value" and "new_value" in the table should suffice, with a single statement to fix all of the data: UPDATE MT SET description = REPLACE(description, old_value, new_value) FROM dbo.My_Table MT INNER JOIN dbo.Fix_Table FT ON MT.description LIKE '%' + FT.old_value + '%' You might need to adjust the query if you expect multiple matches on a single product. Also, be careful of strings that might be part of another string. For example, fixing "ax" to "axe" might cause problems with a "fax machine". There are a lot of little details like this that might affect the exact approach. A: Have a table like bad_val and good_val (call it tblMod). you can write a stored procedure that loops on tblMod and generate SQL statement and execute the statement as dynamic SQL. loop on tblMod -- generate SQL statements like: set sqlText = 'update myTable set description = ' + good_val + ' where description = ' + bad_val sp_execute sqlText This approach also allows you to use SQL functions or any other functions in good_val field of tblMod. for instance you can have below data in good_val field: 'upper(description)' or 'substring(description, 1 ,4)' as you are generating dynamic SQL, those will work. in this case your sqlText will be something like 'update myTable set description = substring(description, 1, 4) where description = 'some bad value' example above might not be correct but I hope you get my idea.
unknown
d4411
train
Same full calendar is available as Module @ https://github.com/angular-ui/ui-calendar Please look at it Or Check the below URL http://jsfiddle.net/joshkurz/xqjtw/59/ Check the controller part of above url: $scope.eventSource = { url: "http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic", className: 'gcal-event', // an option! currentTimezone: 'America/Chicago' // an option! }; Here "$scope.eventSource" is static you can make it dynamic by Create service function and use $http and inject service function in your controller below is the example for the same : app.factory('myService', function($http) { return { getList:function(params){ var promise= $http({url: 'ServerURL',method: "POST", params: params}).then(function(response,status){ return response.data; }); // Return the promise to the controller return promise; } } }); app.controller('MainCtrl', function($scope, myService) { myService.getList(function(data) { $scope.eventSource = data; }); });
unknown
d4412
train
Since all newlines are escaped, and read reads till an unescaped newline, it reaches end-of-file without getting one. And, as help read says: Exit Status: The return code is zero, unless end-of-file is encountered, read times out (in which case it's greater than 128), a variable assignment error occurs, or an invalid file descriptor is supplied as the argument to -u. Note that line still contains the lines read so far: $ while read line; do echo "$line"; done < foo; echo $line dog cat apple
unknown
d4413
train
It's not clear from your question if you are trying to convert an integer or a floating point value to a binary string representation. For an integer, use this code: void Main() { Console.WriteLine("You have chosen binary, input a number then it will be converted to binary."); string num1input = Console.ReadLine(); int num1 = int.Parse(num1input); var binary = Convert.ToString(num1, 2); Console.WriteLine("{0} converted to binary is {1} ", num1, binary); } For a double, this code might be what you want: void Main() { Console.WriteLine("You have chosen binary, input a number then it will be converted to binary."); string num1input = Console.ReadLine(); double num1 = double.Parse(num1input); long bits = BitConverter.DoubleToInt64Bits(num1); var binary = Convert.ToString(bits, 2); Console.WriteLine("{0} converted to binary is {1} ", num1, binary); } A: I found this exercise interesting, so here is what I did : public IEnumerable<char> ConvertToBase2(int myNumber) { while(myNumber != 0) { var returnValue = (myNumber%2 == 0) ? '0' : '1'; myNumber = (myNumber % 2 == 0) ? myNumber / 2 : (myNumber - 1) / 2; yield return returnValue; } } Console.Write(String.Concat( ConvertToBase2(9).Reverse() )); It works only for integers. I don't remember exactly how floating points numbers are implemented. By the way, this is a better answer ;-)
unknown
d4414
train
Try this: @model DropDownListViewModel <script type="text/javascript"> $(function() { $("select").on("change", function () { $.ajax({ type: "POST", url: '@Url.Action("ListItemChanged", "Controller")', data: { "Value": $(this).val() } }); }); }) </script> @Html.DropDownListFor(m => m.Value, Model.Items, "(Select)") A: What you have to understand is, the @expressions are parsed inside the server. You also have to understand that MVC model binder distinguishes the fields based on their name. Inside the data object of the jquery ajax function, where you are passing the object literal, you have to specify the name of the variable as your action method is expecting it to be (in your case, selectedItem). So the correct approach should be: $("select").on('change', function () { $.ajax({ type: 'POST', url: '@Url.Action("ListItemChanged", "Controller")', data: { "selectedItem": $(this).val() } }); }); //Server [HttpPost] public ActionResult ListItemChanged(string selectedItem) { // Stuff. }
unknown
d4415
train
You will probably not have success with building an x64 Android without any x86 binaries. Every module can decide to be built in the target architecture, a fixed one or both and a lot of modules do that. If you start to grep for LOCAL_MULTILIB in Android.mk and compile_multilib in Android.bp, you will find lots of modules and have to figure out the reason for every one of them to build for x86, x64 or both. grep -rn "compile_multilib" --include="Android.bp" grep -rn "LOCAL_MULTILIB" --include="Android.mk" You can find out what the configurations mean here: https://source.android.com/setup/develop/64-bit-builds
unknown
d4416
train
'This is a ' + type(somevariable).__name__ A: somevariable.__class__.__name__ is one way.
unknown
d4417
train
Solved. The solution is on github gave be Kevin.
unknown
d4418
train
Your code doesn't have any issue, be careful that you've called your $('select[name=materialSelect]').change(function(){ alert("Changed"); }); after which your html is loaded. For sample binding the document load to a function that called your code. A: There is a on change function of jquery available already you are binding it with body load which means your select doesn't exists when you call the function, you should do this : $(document).on('change', '#materialSelect', function () { alert('changed'); }); A: Your code is fine as long as the HTML element (on which you are binding the event) is present when the binding script is running. To be on safe side, always bind to a parent element (body for example) which will delegate the event it to the child. So, try this, $('body').on('change', 'select[name=materialSelect]', function(){ alert("Changed"); }); Hope it helps. A: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> </head> <body> <select name="materialSelect" id="materialSelect"> <option value="">-----Select Material-----</option> <option value="0">Material</option> </select> <script type="text/javascript"> $(document).ready(function(){ $('select[name=materialSelect]').change(function(){ alert("Changed"); }); }); </script> </body> </html> A: First, I'd look into where jQuery is being loaded. jQuery needs to be loaded before any scripts that use it. Incorrect: <script> $('.something').change(... </script> <script src=""></script><!-- jquery --> Correct: <script src=""></script><!-- jquery --> <script> $('.something').change(... </script> Secondly, you should be using some kind of document on ready function. This will ensure your HTML is rendered before applying your events (eg "onchange") Correct: <script src=""></script><!-- jquery --> <script> $(function () { // DOM is now ready $('.something').change(... }) </script>
unknown
d4419
train
Try this small user defined function: Public Function MakeList(rng As Range) As String Dim c As Collection, r As Range, s As String Set c = New Collection For Each r In rng ary = Split(r.Value, ",") For Each a In ary On Error Resume Next c.Add a, CStr(a) If Err.Number = 0 Then MakeList = MakeList & "," & a Else Err.Number = 0 End If On Error GoTo 0 Next a Next r MakeList = Mid(MakeList, 2) End Function For example:
unknown
d4420
train
So to be clear, I think the second way you have it is totally reasonable and is the way to go. But to answer your question, you can generate each function dynamically to avoid having to retype the commands. class Foo commands = foo: ['a', 'b', 'c'] bar: ['my neighbor totoro'] dim: [1,2,3] for own name, args of commands Foo::[name] = -> @emit 'data', name, args... and assuming you want the functions to useful stuff, you can still use functions. // ... commands = foo: (args...) -> return ['a', 'b', 'c'] // ... for own name, cb of commands Foo::[name] = (command_args...) -> args = cb.apply @, command_args @emit 'data', name, args... A: This is what I would have done: class Something extends Stream constructor: -> @foo = helper.bind @, "foo", "a", "b", "c" @bar = helper.bind @, "bar", "my neighbor totoro" @dim = helper.bind @, "dim", 1, 2, 3 @sum = helper.bind @, "sum", "hello", "world" helper = (command, params...) -> @emit 'data', command, params... The advantages of this method are: * *The helper function is a private variable. It can't be accessed directly via an instance. *The helper function is only declared once and is shared between all instances. *The functions foo, bar, dim and sum are partial applications of helper. Hence they don't consume more memory for the function body. *It doesn't require a loop like @loganfsmyth's answer does. *It's cleaner. Edit: An even cleaner approach would be: class Something extends Stream constructor: -> @foo = @emit.bind @, "data", "foo", "a", "b", "c" @bar = @emit.bind @, "data", "bar", "my neighbor totoro" @dim = @emit.bind @, "data", "dim", 1, 2, 3 @sum = @emit.bind @, "data", "sum", "hello", "world" Sure, it's a little redundant but you can't expect more from a language like JavaScript. It's not Factor. However it is readable, clean, easily understandable, and above all - correct.
unknown
d4421
train
So what you need to do in order to setup your mapping is first of all define the base url of your API, like so: AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"URL_TO_YOUR_API"]]; RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client]; Then you need to set a response descriptor for the url that outputs the json above: [[RKObjectManager sharedManager] addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:sideMenuMapping method:RKRequestMethodAny pathPattern:@"/mainScreenData" keyPath:@"displayMenuList.MenuList" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]]; "RKRequestMethodAny" should be replaced by the Request Method you are using e.g. "RKRequestMethodGET". Then you just retrieve the objects by calling: [[RKObjectManager sharedManager] getObjectsAtPath:@"/mainScreenData" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { NSArray *sideMenuList = [NSMutableArray arrayWithArray:[mappingResult array]]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"%@",[error localizedDescription]); }]; I would highly recommend you having a look at the demos that are supplied by RestKit. That makes the whole process a lot clearer. Cheers, Sebastian
unknown
d4422
train
Answer from JimBobSquarePants on GitHub: Octree only supports a single transparent color . For Png you need to use the Wu quantizer which is the default quantizer. However, if you are trying to reduce the colors in a png you should be saving it in indexed format by setting the PngColorType in the encoder along with a custom Wu quantizer with your max color count. Not sure that is a full answer, but my issue was closed so that's all I'm getting.
unknown
d4423
train
Solve issue, Actually problem with protected page. My page is open after user login. I have a remove permission and publish to solve my issue. Thanks.
unknown
d4424
train
Try to make the build smarter, if it isn't already: The GWT (client) part should only be re-compiled, when the client source changes. I assume, it's mostly you who changes that source, so the other developers won't experience the pain. Caveat: This doesn't work of course, if your client source shares code with the existing project (I assume, it's a Java project on the server side?). But maybe you should avoid shared code in your case: Even though that's violating the DRY (Don't Repeat Yourself) principle, realize that you'd violate it anyway, if you didn't use GWT. However, if you do reuse code from the server project, then you have a good argument, why you used GWT. A: If developers have to compile the whole GWT stuff (all the permutations) in order to develop application it is real pain. Starting from GWT 2 you can configure the webapp project to be run in "development mode". It can be started directly from eclipse (Google plugin) thanks to built in jetty container. In such scenario only requested resources are compiled, and the process is incremental. I find this very convenient - GWT compilation overhead in our seam+richfaces+GWT application is very small during development cycle. When it comes to application builds there are several options which can speed up GWT compilation. Here is checklist: * *disable soyc reports *enable draftCompile flag which skips some optimization *by adjusting localWorkers flag you can speed things a bit when building on multi-core CPU *compile limited set of permutation: e.g. only for browsers used during development and only for one language Release builds of the webapp should have draftCompile disabled though. Also all the laguage variants should be enabled. Maven profiles are very useful for parametrization of builds. A: What was the reason you used GWT instead of JSON/jQuery? I would ask the same question since for what you need, GWT may not be legitimately needed. A: In my experience, I totally understand the complaints you are getting. GWT is a wonderful technology, and it has many benefits. It also has downsides and one of them is long compile time. The GWT compiler does lots of static code analysis and it's not something that has an order-of-magnitude solution. As a developer, the most frustrating thing in the world is long development-deploy-test cycles. I know how your developers feel. You need to make an architectural decision if the technological benefits of GWT are worth it. If they are, your developers will need to get used to the technology, and there are many solutions which can make the development much easier. A: If there was a good reason for using GWT instead of pure javascript, you should tell them this reason (skills, debugging for a very hard to implement problem, you didn't want to deal with browser compatibility, etc). If there is no good reason, maybe they're right to be upset. I use GWT myself and I know about this compile time :-) If you used GWT for an easy-to-implement-in-javascript widget or something like that, maybe you should have consider using javascript instead. A: What tool you're using to compile project? Long time ago I've used ant and it was smart enough to find out that, when none of source files for GWT app (client code) has changed, the GWT compiler task was not called. However, after that I've used maven and it was real pain, because it's plugin didn't recognize the code hasn't changed and GWT compilation was run all and over, no matter if it was needed or not. I would recommend ant for GWT projects. Alternative would be rewriting the maven plugin or getting developers used to long compile time.
unknown
d4425
train
The function is called and the if statement executed correctly. Here, I've edited the console.log lines. Run the snippet. Click the text box, use the tab key to select the button, then hit the enter key. Et voila! 3 console.log statements run. Perhaps you need to refine your understanding of what's happening and from that, your question. :) document.querySelector(".subText").addEventListener("keyup", function(event) { if (event.keyCode === 13) { let x = document.querySelector("#fname").value; // console.log(x); console.log("console.log(x); (1)"); } }); function addNote() { let x = document.querySelector("#fname").value; // console.log(x); console.log("console.log(x); (2)"); let divN = document.createElement("div"); divN.classList.add("notesList"); let para = document.createElement("p"); para.classList.add("notesInput"); divN.appendChild(para); let paraText = document.createTextNode(x); // console.log(paraText); console.log("console.log(paraText); (3)"); para.appendChild(paraText); let but = document.createElement("button"); but.classList.add("deleteBut"); but.setAttribute("onclick", "deleFunc()") divN.appendChild(but); let y = document.querySelector(".test"); y.appendChild(divN); } <body> <div class="wrapper"> <div class="container"> <div class="toDo"> <!-- <svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512"> <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M224 184h128m-128 72h128m-128 71h128"/> <path d="M448 258c0-106-86-192-192-192S64 152 64 258s86 192 192 192 192-86 192-192z" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="32"/> <circle cx="168" cy="184" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/> <circle cx="168" cy="257" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/> <circle cx="168" cy="328" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/> </svg> --> <p class="toDoText">To-do List</p> </div> <div> <input type="text" id="fname" name="fname" placeholder="I need to..." class="inputText"> <input type="submit" value="Submit" class="subText" onclick="addNote()"> </div> </div> <div class="test"> <!-- <div class="notesList"> <p class="notesInput">ddbd</p> <button class="deleteBut" onclick="deleFunc()"> </button> </div> --> </div> </div> </body> A: With the if statement I am just trying to insert an additional functionality when someone enters the "Enter" button - Idk WHY it's not working! You added the listener on the button, instead of adding a listener to the input field. and with the rest of the code inside addNote() function, I am trying to create an element every time the user inserts a new input -similar to that, which is commented out at HTML code. However, it seems that styling from the element generated from JS just breaks in contrary with the div I have commented out in HTML... I rearranged your code, so it's more readable. I would suggest to refactor each creation and attribute changes for each element to methods of their own, to make the code even more readable. During my rearrangement, I automatically solved your problem, by putting the code in the right order. Now the generated code looks like your commented code. I also added an event listener to your button. If you remove the button, you need to remove the event listener too, otherwise there will be a memory leak. I would also like to suggest that you start using id and getElementByID instead of querySelect and class, just to create a pattern where id on an element indirectly says that it's used together with javascript. document.getElementById("fname").addEventListener("keyup", function(event) { if (event.key === "Enter") { addNote(); } }); function addNote() { let x = document.querySelector("#fname"); let divN = document.createElement("div"); let para = document.createElement("p"); let paraText = document.createTextNode(x.value); let but = document.createElement("button"); let y = document.querySelector(".test"); x.value = ''; divN.classList.add("notesList"); para.classList.add("notesInput"); but.classList.add("deleteBut"); but.addEventListener('click', (event) => { console.log('clicked removed') } ); divN.appendChild(para); para.appendChild(paraText); divN.appendChild(but); y.appendChild(divN); } <body> <div class="wrapper"> <div class="container"> <div class="toDo"> <!-- <svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512"> <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M224 184h128m-128 72h128m-128 71h128"/> <path d="M448 258c0-106-86-192-192-192S64 152 64 258s86 192 192 192 192-86 192-192z" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="32"/> <circle cx="168" cy="184" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/> <circle cx="168" cy="257" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/> <circle cx="168" cy="328" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/> </svg> --> <p class="toDoText">To-do List</p> </div> <div> <input type="text" id="fname" name="fname" placeholder="I need to..." class="inputText"> <input type="submit" value="Submit" class="subText" onclick="addNote()"> </div> </div> <div class="test"> <!-- <div class="notesList"> <p class="notesInput">ddbd</p> <button class="deleteBut" onclick="deleFunc()"> </button> </div> --> </div> </div> </body>
unknown
d4426
train
I checked with Azur support and they mentioned that not all the methods provided by Hadoop are implemented. So in my case LISTSTATUS_BATCH is not implmented.
unknown
d4427
train
Try this, this will output last 2 days. SELECT 'ID,Acct/LnNbr,NoteCreatedDate,CollectorId,ApplytoAll,Note' UNION ALL SELECT ID + ',' + ID + ',' + NoteCreatedDate + ',' + CollectorId + ',' + 'No' + ',' + Note FROM ( SELECT CASE WHEN SUBSTRING(A.CMS301,LEN(A.CMS301),1) = 'S' THEN SUBSTRING(A.CMS301,1,LEN(A.CMS301) - 1) ELSE A.CMS301 END + '-' + CASE WHEN SUBSTRING(A.CMS301,LEN(A.CMS301),1) = 'S' THEN 'S' ELSE 'L' END AS [ID] ,REPLACE(CONVERT(varchar,A.CMS501,10),'-','') AS [NoteCreatedDate] ,CASE WHEN U.CMS1201 IS NOT NULL THEN U.CMS1205 + ' ' + U.CMS1204 ELSE (SELECT CMS1205 + ' ' + CMS1204 FROM sysUSER WHERE CMS1201 = 'PSUSER') END AS CollectorId ,CAST(A.CMS512 AS nvarchar(max)) AS [Note] FROM ACTIVITY AS A LEFT JOIN sysUSER AS U ON A.CMS503 = U.CMS1201 WHERE A.CMS504 NOT IN (411,500,511,711,804,900,901,903,907,2000,999777) AND A.CMS504 NOT BETWEEN 1102 AND 1199 AND A.CMS502 >= DATEADD(D, -2, GETDATE()) ) AS S
unknown
d4428
train
Using str.strip and str.split: >>> '[X:Y:Z]'.strip('[]') 'X:Y:Z' >>> '[X:Y:Z]'.strip('[]').split(':') ['X', 'Y', 'Z'] >>> '[X:Y:Z]'.strip('[]').split(':')[1] 'Y' UPDATE As Blender commented, stripping the brackets off is not necessary. >>> '[X:Y:Z]'.split(':') ['[X', 'Y', 'Z]'] >>> '[X:Y:Z]'.split(':')[1] 'Y' A: Y = "[X:Y:Z]".split(':')[1] That's a quick one liner for it. A: There are dozens of ways you could achieve this for the single example you've posted, e.g.: full_string = '[X:Y:Z]' first, middle, last = full_string.split(':') print(middle) Out[5]: 'Y' To narrow down what will or won't work, you may have to post some more examples that make clearer how your data format looks, and what pieces of information you need to extract from it.
unknown
d4429
train
PHP has a function called getimagesize(). list($width, $height, $type, $attr) = getimagesize("img.jpg"); as can be seen in the documentation: http://php.net/manual/en/function.getimagesize.php So, just check the height and width before submitting to the database A: You can check the height of width of the image by creating an image from the uploaded file. $("#fileUploadForm").submit(function(e){ var window.URL = window.URL || window.webkitURL; var fileInput = $(this).find("input[type=file]")[0], file = fileInput.files ? fileInput.files[0] : null; if( file ) { var img = new Image(); img.src = window.URL.createObjectURL( file ); img.onload = function() { var width = img.naturalWidth, height = img.naturalHeight; window.URL.revokeObjectURL( img.src ); if( width == height) {//perfect square this.submit(); } else { //fail } }; } });
unknown
d4430
train
For once the \\\\n is \\n after resolving the special characters. Therefore you have to use \\n if you want it to be \n which would be the character \ and the letter n. This would be correct for replaceAll. For replace which takes a character you would even have to use '\n' directly. Same for \rand \t. However i would prefer a single regex for this. This call should do it: theString.matches("\\s*\\d.*");. \s stands for any whitespace character \d for any digit and . for any other trailing character.
unknown
d4431
train
Modern Spring 5+ answer using WebClient instead of RestTemplate. Configure WebClient for a specific web-service or resource as a bean (additional properties can be configured). @Bean public WebClient localApiClient() { return WebClient.create("http://localhost:8080/api/v3"); } Inject and use the bean from your service(s). @Service public class UserService { private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3); private final WebClient localApiClient; @Autowired public UserService(WebClient localApiClient) { this.localApiClient = localApiClient; } public User getUser(long id) { return localApiClient .get() .uri("/users/" + id) .retrieve() .bodyToMono(User.class) .block(REQUEST_TIMEOUT); } } A: Create Bean for Rest Template to auto wiring the Rest Template object. @SpringBootApplication public class ChatAppApplication { @Bean public RestTemplate getRestTemplate(){ return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ChatAppApplication.class, args); } } Consume the GET/POST API by using RestTemplate - exchange() method. Below is for the post api which is defined in the controller. @RequestMapping(value = "/postdata",method = RequestMethod.POST) public String PostData(){ return "{\n" + " \"value\":\"4\",\n" + " \"name\":\"David\"\n" + "}"; } @RequestMapping(value = "/post") public String getPostResponse(){ HttpHeaders headers=new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<String> entity=new HttpEntity<String>(headers); return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody(); } Refer this tutorial[1] [1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm A: As has been mentioned in the various answers here, WebClient is now the recommended route. You can start by configuring a WebClient builder: @Bean public WebClient.Builder getWebClientBuilder(){ return WebClient.builder(); } Then inject the bean and you can consume an API as follows: @Autowired private WebClient.Builder webClientBuilder; Product product = webClientBuilder.build() .get() .uri("http://localhost:8080/api/products") .retrieve() .bodyToMono(Product.class) .block(); A: Does Retrofit have any method to achieve this? If not, how I can do that? YES Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface. For more information refer the following link https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial A: This website has some nice examples for using spring's RestTemplate. Here is a code example of how it can work to get a simple object: private static void getEmployees() { final String uri = "http://localhost:8080/springrestexample/employees.xml"; RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(uri, String.class); System.out.println(result); } A: Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also, In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below. @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } } Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code, @Autowired private RestTemplate restTemplate; Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem. ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange( URL, HttpMethod.GET, null, new ParameterizedTypeReference<List<POJO>>() { }); List<POJO> pojoObjList = responseEntity.getBody(); Happy Coding :) A: In this case need download whit my API, files hosted in other server. In my case, don't need use a HTTP client to download the file in a external URL, I combined several answers and methods worked in previous code for files that were in my local server. My code is: @GetMapping(value = "/download/file/pdf/", produces = MediaType.APPLICATION_PDF_VALUE) public ResponseEntity<Resource> downloadFilePdf() throws IOException { String url = "http://www.orimi.com/pdf-test.pdf"; RestTemplate restTemplate = new RestTemplate(); byte[] byteContent = restTemplate.getForObject(url, String.class).getBytes(StandardCharsets.ISO_8859_1); InputStream resourceInputStream = new ByteArrayInputStream(byteContent); return ResponseEntity.ok() .header("Content-disposition", "attachment; filename=" + "pdf-with-my-API_pdf-test.pdf") .contentType(MediaType.parseMediaType("application/pdf;")) .contentLength(byteContent.length) .body(new InputStreamResource(resourceInputStream)); } and it works with HTTP and HTTPS urls! A: Since the question explicitly tags spring-boot, it worth noting that recent versions already ship a pre-configured instance of a builder for WebClient, thus you can directly inject it inside your service constructor without the needing to define a custom bean. @Service public class ClientService { private final WebClient webClient; public ClientService(WebClient.Builder webClientBuilder) { webClient = webClientBuilder .baseUrl("https://your.api.com") } //Add all the API call methods you need leveraging webClient instance } https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/boot-features-webclient.html A: Simplest way I have found is to: * *Create an annotated interface (or have it generated from somehing like OpenAPI) *Give that interface to Spring RestTemplate Client The Spring RestTemplate Client will parse the annotations on the interface and give you a type safe client, a proxy-instance. Any invocation on the methods will be seamlessly translated to rest-calls. final MyApiInterface myClient = SpringRestTemplateClientBuilder .create(MyApiInterface.class) .setUrl(this.getMockUrl()) .setRestTemplate(restTemplate) // Optional .setHeader("header-name", "the value") // Optional .setHeaders(HttpHeaders) // Optional .build(); And a rest call is made by inoking methods, like: final ResponseEntity<MyDTO> response = myClient.getMyDto();
unknown
d4432
train
As stated by @emre in comments, there is official text about it: ... the Management Center is compatible with Hazelcast IMDG cluster members having the same or the previous minor version. For example, Hazelcast Management Center version 3.12.x works with Hazelcast IMDG cluster members having version 3.11.x or 3.12.x. from Hazelcast Management Center Documentation. The Exception message (DeserializationException: nodeState field is null) is not really helpful to realize that. The same happend to me, I was using Spring boot parent in version 1.5.9.RELEASE and therefore it had old the dependency of hazelcast (3.7.8). You can always check for versions of spring autoconfigured dependencies in spring-boot-dependencies projects's pom.xml file. There you can see hazelcast version in properties section defined like this: <hazelcast.version>3.7.8</hazelcast.version> You can * *change the spring-boot-starter-parent version to newer (e.g. 2.2.0.RELEASE) and the issue should dissapear or *overwrite only the properties in your own pom.xml with newer hazelcast version.
unknown
d4433
train
Use nulls first and order by all retrieved columns. Select empid, name, address, phone, zip, gender from TABLE Order by empid nulls first, name nulls first, address nulls first, phone nulls first, zip nulls first, gender nulls first; And you really should supply the query(ies) you've tried. A: If all of address, phone, zip, gender is NULL, then put row first. Else sort by pk etc. Select empid, name, address, phone, zip, gender from TABLE Order by case when coalesce(address, phone, zip, gender) is null then 0 else 1 end, empid, name, address, phone, zip, gender;
unknown
d4434
train
I hadn't saved names of images in the SQLite database so the first problem was because of that, and the second problem was in my adapter code. I had to write "viewHolder" instead of "holder" in onBindViewHolder(), so the correct method is: @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { switch (viewHolder.getItemViewType()){ case 0: ViewHolder1 vh1 = (ViewHolder1) viewHolder; configureViewHolder1(vh1, position); break; case 1: ViewHolder2 vh2 = (ViewHolder2) viewHolder; configureViewHolder2(vh2, position); break; } } A: First make sure the given statement must only return 0 or 1. because view type must start with 0 int view_type=mDataset.get(position).getView_type(); No need to create the below viewHolder as a member of class RecyclerView.ViewHolder viewHolder; Don't check viewType in onBindViewHolder . Instead check holder instanceOf @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if(holder instanceOf ViewHolder1){ (ViewHolder1) holder.getLabel1().setText(mDataset.get(position).getName()); } else { try { Resources res = context.getResources(); int resourceId = res.getIdentifier(mDataset.get(position).getImg(), "mipmap", context.getPackageName()); (ViewHolder2) holder.getImageView().setImageResource(resourceId); } catch (Exception e) {} } } A: i had the same problem values changes after the scroll, then i overide these methods @Override public long getItemId(int position) { return position; } @Override public int getItemCount() { return dataList.size(); }, This solved my problem and for the Image heck the image resourceId is null or not i am not sure if your way is good to set the Resource. A: While using multiple view types with dynamic data some users may face issues like duplicate data items, data being swapped between questions. To avoid that you have to set a unique view type id for every item. @Override public int getItemViewType(int position) { // Here you can get decide from your model's ArrayList, which type of view you need to load. Like if (list.get(position).type == Something) { // Put your condition, according to your requirements return VIEW_TYPE_ONE; } return VIEW_TYPE_TWO; } The above code for getItemViewType can fail where 3 consecutive items will have the same type. For example, if the user enters ans1 in item 1 edit text,ans2 in item 2 edit text, ans3 in item 3 edit text and scroll the recycler view up and down then some users may face issues like duplicate data items, data being swapped between questions. Formula to create unique view type id : Formula : pos * Constants.Max + viewType; set value Constants.Max = 100000; class DataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final int VIEW_TYPE_EDIT_TEXT = 1; private final int VIEW_TYPE_IMAGE_VIEW = 2; private final ArrayList<DataModel> dataModelArrayList = new ArrayList<>(); @Override public int getItemViewType(int position) { String dataType = dataModelArrayList.get(position).getDataType(); int viewType = VIEW_TYPE_EDIT_TEXT; switch (dataType) { case "A": case "E": viewType = VIEW_TYPE_EDIT_TEXT; break; case "I": viewType = VIEW_TYPE_IMAGE_VIEW; break; } int pos = position + 1; return pos * Constants.Max + viewType; } @Override public long getItemId(int position) { return position; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) { int count = (int) Math.ceil(type / Constants.Max); int viewType = type - count * Constants.Max; if (viewType == VIEW_TYPE_EDIT_TEXT) { return new ViewHolderTypeEditText(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_et_item, parent, false)); } else if (viewType == VIEW_TYPE_IMAGE_VIEW) { return new ViewHolderTypeImageView(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_sp_item, parent, false)); } return new ViewHolderTypeEditText(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_et_item, parent, false)); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int pos) { int type = holder.getItemViewType(); int count = (int) Math.ceil(type / Constants.Max); int viewType = type - count * Constants.Max; if (viewType == VIEW_TYPE_EDIT_TEXT) { DataAdapter.ViewHolderTypeEditText viewHolderTypeEditText = (DataAdapter.ViewHolderTypeEditText) holder; } else if (viewType == VIEW_TYPE_IMAGE_VIEW) { DataAdapter.ViewHolderTypeImageView viewHolderTypeImageView = (DataAdapter.ViewHolderTypeImageView) holder; } } @Override public int getItemCount() { return dataModelArrayList.size(); } public class ViewHolderTypeEditText extends RecyclerView.ViewHolder { EditText etText; public ViewHolderTypeEditText(@NonNull View itemView) { super(itemView); etText = itemView.findViewById(R.id.et_text); } } public class ViewHolderTypeImageView extends RecyclerView.ViewHolder { ImageView imageView; public ViewHolderTypeImageView(@NonNull View itemView) { super(itemView); imageView = itemView.findViewById(R.id.image_view); } } }
unknown
d4435
train
Values coming from a request are by default str type but Django does the conversion directly. Since you're overwriting the save method, you need to convert them to int, like this: otherdiscountpercentage = request.POST.get("otherdiscountpercentage") if otherdiscountpercentage: otherdiscountpercentage = float(otherdiscountpercentage) Beware that using request.POST.get('param_name') means the param is optional. So you should put some condition or give a default float value before any calculation. A: you can do this otherdiscountpercentage = request.POST.get("otherdiscountpercentage") S_price = request.POST.get("price") otherdiscountprice = request.POST.get("otherdiscountprice") discountpercentage = request.POST.get("discountpercentage") discountprice = request.POST.get("discountprice") insert_data = Product( price=float(S_price), discount_percentage=float(discountpercentage), discount_price=float(discountprice), Other_discount_percentage=float(otherdiscountpercentage), Other_discount_price=float(otherdiscountprice), )
unknown
d4436
train
You can use build definition to build your project and generate the deployment packages and then use release definition to deploy the packages. In the release definition, you can add three environment to deploy to Dev, QA & Staging. For how to build and deploy Asp.Net Core app, please refer to this link for details: Build and deploy your ASP.NET Core RC2 app to Azure.
unknown
d4437
train
Use group by! SELECT playerID, AVG(score) AS avg_score FROM dbo.scores GROUP BY playerID A: The use of dbo suggests that you are using SQL Server. SQL Server does an integer average of integer values, so the average of 0 and 1 is 0, not 0.5. I would recommend: SELECT s.playerID, AVG(10. * s.score) AS avg_score FROM dbo.scores s GROUP BY s.playerID
unknown
d4438
train
Your code is not valid JS Here is something that does work - I am using setInterval here var i = 20220215155 function increment() { i++; // increment document.getElementById('test').innerHTML += i + "<br/>"; // add it with a breakline } setInterval(increment, 1000); <div id="test"></div> You can use a template literal for the string too `${i}<br/>` A: You can use setTimeout to call the function after a set time while also increasing the number you initially pass into the function. // Cache the element const test = document.querySelector('#test'); let n = 20220215155; // `increment` accepts `n` as an argument function increment(n) { // Add a new HTML string to the element test.innerHTML += `${n}</br>`; // Call the function again with an new `n` setTimeout(increment, 1000, ++n); } increment(n); <div id="test"></div> Additional documentation * *Template/string literals
unknown
d4439
train
You can do it without sed, if you want: for i in `find -name '*_test.rb'` ; do mv $i ${i%%_test.rb}_spec.rb ; done ${var%%suffix} strips suffix from the value of var. or, to do it using sed: for i in `find -name '*_test.rb'` ; do mv $i `echo $i | sed 's/test/spec/'` ; done A: You mention that you are using bash as your shell, in which case you don't actually need find and sed to achieve the batch renaming you're after... Assuming you are using bash as your shell: $ echo $SHELL /bin/bash $ _ ... and assuming you have enabled the so-called globstar shell option: $ shopt -p globstar shopt -s globstar $ _ ... and finally assuming you have installed the rename utility (found in the util-linux-ng package) $ which rename /usr/bin/rename $ _ ... then you can achieve the batch renaming in a bash one-liner as follows: $ rename _test _spec **/*_test.rb (the globstar shell option will ensure that bash finds all matching *_test.rb files, no matter how deeply they are nested in the directory hierarchy... use help shopt to find out how to set the option) A: The easiest way: find . -name "*_test.rb" | xargs rename s/_test/_spec/ The fastest way (assuming you have 4 processors): find . -name "*_test.rb" | xargs -P 4 rename s/_test/_spec/ If you have a large number of files to process, it is possible that the list of filenames piped to xargs would cause the resulting command line to exceed the maximum length allowed. You can check your system's limit using getconf ARG_MAX On most linux systems you can use free -b or cat /proc/meminfo to find how much RAM you have to work with; Otherwise, use top or your systems activity monitor app. A safer way (assuming you have 1000000 bytes of ram to work with): find . -name "*_test.rb" | xargs -s 1000000 rename s/_test/_spec/ A: This happens because sed receives the string {} as input, as can be verified with: find . -exec echo `echo "{}" | sed 's/./foo/g'` \; which prints foofoo for each file in the directory, recursively. The reason for this behavior is that the pipeline is executed once, by the shell, when it expands the entire command. There is no way of quoting the sed pipeline in such a way that find will execute it for every file, since find doesn't execute commands via the shell and has no notion of pipelines or backquotes. The GNU findutils manual explains how to perform a similar task by putting the pipeline in a separate shell script: #!/bin/sh echo "$1" | sed 's/_test.rb$/_spec.rb/' (There may be some perverse way of using sh -c and a ton of quotes to do all this in one command, but I'm not going to try.) A: you might want to consider other way like for file in $(find . -name "*_test.rb") do echo mv $file `echo $file | sed s/_test.rb$/_spec.rb/` done A: I find this one shorter find . -name '*_test.rb' -exec bash -c 'echo mv $0 ${0/test.rb/spec.rb}' {} \; A: Here is what worked for me when the file names had spaces in them. The example below recursively renames all .dar files to .zip files: find . -name "*.dar" -exec bash -c 'mv "$0" "`echo \"$0\" | sed s/.dar/.zip/`"' {} \; A: For this you don't need sed. You can perfectly get alone with a while loop fed with the result of find through a process substitution. So if you have a find expression that selects the needed files, then use the syntax: while IFS= read -r file; do echo "mv $file ${file%_test.rb}_spec.rb" # remove "echo" when OK! done < <(find -name "*_test.rb") This will find files and rename all of them striping the string _test.rb from the end and appending _spec.rb. For this step we use Shell Parameter Expansion where ${var%string} removes the shortest matching pattern "string" from $var. $ file="HELLOa_test.rbBYE_test.rb" $ echo "${file%_test.rb}" # remove _test.rb from the end HELLOa_test.rbBYE $ echo "${file%_test.rb}_spec.rb" # remove _test.rb and append _spec.rb HELLOa_test.rbBYE_spec.rb See an example: $ tree . ├── ab_testArb ├── a_test.rb ├── a_test.rb_test.rb ├── b_test.rb ├── c_test.hello ├── c_test.rb └── mydir └── d_test.rb $ while IFS= read -r file; do echo "mv $file ${file/_test.rb/_spec.rb}"; done < <(find -name "*_test.rb") mv ./b_test.rb ./b_spec.rb mv ./mydir/d_test.rb ./mydir/d_spec.rb mv ./a_test.rb ./a_spec.rb mv ./c_test.rb ./c_spec.rb A: To solve it in a way most close to the original problem would be probably using xargs "args per command line" option: find . -name "*_test.rb" | sed -e "p;s/test/spec/" | xargs -n2 mv It finds the files in the current working directory recursively, echoes the original file name (p) and then a modified name (s/test/spec/) and feeds it all to mv in pairs (xargs -n2). Beware that in this case the path itself shouldn't contain a string test. A: if you have Ruby (1.9+) ruby -e 'Dir["**/*._test.rb"].each{|x|test(?f,x) and File.rename(x,x.gsub(/_test/,"_spec") ) }' A: In ramtam's answer which I like, the find portion works OK but the remainder does not if the path has spaces. I am not too familiar with sed, but I was able to modify that answer to: find . -name "*_test.rb" | perl -pe 's/^((.*_)test.rb)$/"\1" "\2spec.rb"/' | xargs -n2 mv I really needed a change like this because in my use case the final command looks more like find . -name "olddir" | perl -pe 's/^((.*)olddir)$/"\1" "\2new directory"/' | xargs -n2 mv A: I haven't the heart to do it all over again, but I wrote this in answer to Commandline Find Sed Exec. There the asker wanted to know how to move an entire tree, possibly excluding a directory or two, and rename all files and directories containing the string "OLD" to instead contain "NEW". Besides describing the how with painstaking verbosity below, this method may also be unique in that it incorporates built-in debugging. It basically doesn't do anything at all as written except compile and save to a variable all commands it believes it should do in order to perform the work requested. It also explicitly avoids loops as much as possible. Besides the sed recursive search for more than one match of the pattern there is no other recursion as far as I know. And last, this is entirely null delimited - it doesn't trip on any character in any filename except the null. I don't think you should have that. By the way, this is REALLY fast. Look: % _mvnfind() { mv -n "${1}" "${2}" && cd "${2}" > read -r SED <<SED > :;s|${3}\(.*/[^/]*${5}\)|${4}\1|;t;:;s|\(${5}.*\)${3}|\1${4}|;t;s|^[0-9]*[\t]\(mv.*\)${5}|\1|p > SED > find . -name "*${3}*" -printf "%d\tmv %P ${5} %P\000" | > sort -zg | sed -nz ${SED} | read -r ${6} > echo <<EOF > Prepared commands saved in variable: ${6} > To view do: printf ${6} | tr "\000" "\n" > To run do: sh <<EORUN > $(printf ${6} | tr "\000" "\n") > EORUN > EOF > } % rm -rf "${UNNECESSARY:=/any/dirs/you/dont/want/moved}" % time ( _mvnfind ${SRC=./test_tree} ${TGT=./mv_tree} \ > ${OLD=google} ${NEW=replacement_word} ${sed_sep=SsEeDd} \ > ${sh_io:=sh_io} ; printf %b\\000 "${sh_io}" | tr "\000" "\n" \ > | wc - ; echo ${sh_io} | tr "\000" "\n" | tail -n 2 ) <actual process time used:> 0.06s user 0.03s system 106% cpu 0.090 total <output from wc:> Lines Words Bytes 115 362 20691 - <output from tail:> mv .config/replacement_word-chrome-beta/Default/.../googlestars \ .config/replacement_word-chrome-beta/Default/.../replacement_wordstars NOTE: The above function will likely require GNU versions of sed and find to properly handle the find printf and sed -z -e and :;recursive regex test;t calls. If these are not available to you the functionality can likely be duplicated with a few minor adjustments. This should do everything you wanted from start to finish with very little fuss. I did fork with sed, but I was also practicing some sed recursive branching techniques so that's why I'm here. It's kind of like getting a discount haircut at a barber school, I guess. Here's the workflow: * *rm -rf ${UNNECESSARY} * *I intentionally left out any functional call that might delete or destroy data of any kind. You mention that ./app might be unwanted. Delete it or move it elsewhere beforehand, or, alternatively, you could build in a \( -path PATTERN -exec rm -rf \{\} \) routine to find to do it programmatically, but that one's all yours. *_mvnfind "${@}" * *Declare its arguments and call the worker function. ${sh_io} is especially important in that it saves the return from the function. ${sed_sep} comes in a close second; this is an arbitrary string used to reference sed's recursion in the function. If ${sed_sep} is set to a value that could potentially be found in any of your path- or file-names acted upon... well, just don't let it be. *mv -n $1 $2 * *The whole tree is moved from the beginning. It will save a lot of headache; believe me. The rest of what you want to do - the renaming - is simply a matter of filesystem metadata. If you were, for instance, moving this from one drive to another, or across filesystem boundaries of any kind, you're better off doing so at once with one command. It's also safer. Note the -noclobber option set for mv; as written, this function will not put ${SRC_DIR} where a ${TGT_DIR} already exists. *read -R SED <<HEREDOC * *I located all of sed's commands here to save on escaping hassles and read them into a variable to feed to sed below. Explanation below. *find . -name ${OLD} -printf * *We begin the find process. With find we search only for anything that needs renaming because we already did all of the place-to-place mv operations with the function's first command. Rather than take any direct action with find, like an exec call, for instance, we instead use it to build out the command-line dynamically with -printf. *%dir-depth :tab: 'mv '%path-to-${SRC}' '${sed_sep}'%path-again :null delimiter:' * *After find locates the files we need it directly builds and prints out (most) of the command we'll need to process your renaming. The %dir-depth tacked onto the beginning of each line will help to ensure we're not trying to rename a file or directory in the tree with a parent object that has yet to be renamed. find uses all sorts of optimization techniques to walk your filesystem tree and it is not a sure thing that it will return the data we need in a safe-for-operations order. This is why we next... *sort -general-numerical -zero-delimited * *We sort all of find's output based on %directory-depth so that the paths nearest in relationship to ${SRC} are worked first. This avoids possible errors involving mving files into non-existent locations, and it minimizes need to for recursive looping. (in fact, you might be hard-pressed to find a loop at all) *sed -ex :rcrs;srch|(save${sep}*til)${OLD}|\saved${SUBSTNEW}|;til ${OLD=0} * *I think this is the only loop in the whole script, and it only loops over the second %Path printed for each string in case it contains more than one ${OLD} value that might need replacing. All other solutions I imagined involved a second sed process, and while a short loop may not be desirable, certainly it beats spawning and forking an entire process. *So basically what sed does here is search for ${sed_sep}, then, having found it, saves it and all characters it encounters until it finds ${OLD}, which it then replaces with ${NEW}. It then heads back to ${sed_sep} and looks again for ${OLD}, in case it occurs more than once in the string. If it is not found, it prints the modified string to stdout (which it then catches again next) and ends the loop. *This avoids having to parse the entire string, and ensures that the first half of the mv command string, which needs to include ${OLD} of course, does include it, and the second half is altered as many times as is necessary to wipe the ${OLD} name from mv's destination path. *sed -ex...-ex search|%dir_depth(save*)${sed_sep}|(only_saved)|out * *The two -exec calls here happen without a second fork. In the first, as we've seen, we modify the mv command as supplied by find's -printf function command as necessary to properly alter all references of ${OLD} to ${NEW}, but in order to do so we had to use some arbitrary reference points which should not be included in the final output. So once sed finishes all it needs to do, we instruct it to wipe out its reference points from the hold-buffer before passing it along. AND NOW WE'RE BACK AROUND read will receive a command that looks like this: % mv /path2/$SRC/$OLD_DIR/$OLD_FILE /same/path_w/$NEW_DIR/$NEW_FILE \000 It will read it into ${msg} as ${sh_io} which can be examined at will outside of the function. Cool. -Mike A: I was able handle filenames with spaces by following the examples suggested by onitake. This doesn't break if the path contains spaces or the string test: find . -name "*_test.rb" -print0 | while read -d $'\0' file do echo mv "$file" "$(echo $file | sed s/test/spec/)" done A: This is an example that should work in all cases. Works recursiveley, Need just shell, and support files names with spaces. find spec -name "*_test.rb" -print0 | while read -d $'\0' file; do mv "$file" "`echo $file | sed s/test/spec/`"; done A: $ find spec -name "*_test.rb" spec/dir2/a_test.rb spec/dir1/a_test.rb $ find spec -name "*_test.rb" | xargs -n 1 /usr/bin/perl -e '($new=$ARGV[0]) =~ s/test/spec/; system(qq(mv),qq(-v), $ARGV[0], $new);' `spec/dir2/a_test.rb' -> `spec/dir2/a_spec.rb' `spec/dir1/a_test.rb' -> `spec/dir1/a_spec.rb' $ find spec -name "*_spec.rb" spec/dir2/b_spec.rb spec/dir2/a_spec.rb spec/dir1/a_spec.rb spec/dir1/c_spec.rb A: Your question seems to be about sed, but to accomplish your goal of recursive rename, I'd suggest the following, shamelessly ripped from another answer I gave here:recursive rename in bash #!/bin/bash IFS=$'\n' function RecurseDirs { for f in "$@" do newf=echo "${f}" | sed -e 's/^(.*_)test.rb$/\1spec.rb/g' echo "${f}" "${newf}" mv "${f}" "${newf}" f="${newf}" if [[ -d "${f}" ]]; then cd "${f}" RecurseDirs $(ls -1 ".") fi done cd .. } RecurseDirs . A: More secure way of doing rename with find utils and sed regular expression type: mkdir ~/practice cd ~/practice touch classic.txt.txt touch folk.txt.txt Remove the ".txt.txt" extension as follows - cd ~/practice find . -name "*txt" -execdir sh -c 'mv "$0" `echo "$0" | sed -r 's/\.[[:alnum:]]+\.[[:alnum:]]+$//'`' {} \; If you use the + in place of ; in order to work on batch mode, the above command will rename only the first matching file, but not the entire list of file matches by 'find'. find . -name "*txt" -execdir sh -c 'mv "$0" `echo "$0" | sed -r 's/\.[[:alnum:]]+\.[[:alnum:]]+$//'`' {} + A: Here's a nice oneliner that does the trick. Sed can't handle this right, especially if multiple variables are passed by xargs with -n 2. A bash substition would handle this easily like: find ./spec -type f -name "*_test.rb" -print0 | xargs -0 -I {} sh -c 'export file={}; mv $file ${file/_test.rb/_spec.rb}' Adding -type -f will limit the move operations to files only, -print 0 will handle empty spaces in paths. A: I share this post as it is a bit related to question. Sorry for not providing more details. Hope it helps someone else. http://www.peteryu.ca/tutorials/shellscripting/batch_rename A: This is my working solution: for FILE in {{FILE_PATTERN}}; do echo ${FILE} | mv ${FILE} $(sed 's/{{SOURCE_PATTERN}}/{{TARGET_PATTERN}}/g'); done
unknown
d4440
train
This will process the data into the format you're after. The source data is in Sheet1 and the reformatted data is placed into Sheet2: Option Explicit Sub MapCell2Cells() Dim sht1 As Worksheet, sht2 As Worksheet Set sht1 = Worksheets("Sheet1") Set sht2 = Worksheets("Sheet2") Dim strG As String, strL As String Dim arrH() As String, arrI() As String, arrJ() As String Dim i As Integer, j As Integer, idx As Integer, lastRow As Integer lastRow = sht1.Cells(Rows.Count, "G").End(xlUp).Row idx = 1 For i = 1 To lastRow: With sht1 strG = Replace(.Cells(i, "G").Value, vbLf, "") arrH = Split(.Cells(i, "H").Value, vbLf) arrI = Split(.Cells(i, "I").Value, vbLf) arrJ = Split(.Cells(i, "J").Value, vbLf) strL = Replace(.Cells(i, "L").Value, vbLf, "") End With With sht2 For j = LBound(arrH) To UBound(arrH) .Cells(idx, "G").Value = strG .Cells(idx, "H").Value = arrH(j) .Cells(idx, "I").Value = arrI(j) .Cells(idx, "J").Value = arrJ(j) .Cells(idx, "L").Value = strL idx = idx + 1 Next End With Next End Sub
unknown
d4441
train
FoursquareAPI twitter account has told me that I needed to pass m=foursquare in addition to version information. The correct endpoint information is like https://api.foursquare.com/v2/users/USER_ID/tastes?oauth_token=TOKEN&v=20150420&m=foursquare The detailed information about v and m parameters are below. https://developer.foursquare.com/overview/versioning
unknown
d4442
train
From what I have gathered, 64-bit limits are new, especially in the web browsers. Chrome supports them, Opera maybe, and I see a patch for Firefox that hasn't landed yet. I've read posts that say IE returns negative Content-Length, which means it's likely to use 32-bits. 64-bit HTTP lengths looks like the future, but we aren't there yet.
unknown
d4443
train
def temp(self): id = [] for child in root: temp_id=child.get('id') id.append(temp_id) return id and I am getting the function value in class B, class B (A): fun=A value = fun.temp() for x in value: return x While printing the return value instead of printing all the values, I am getting only the first value [1,1,1,1,1] Can some one please let me know on how to solve this, thanks. A: Standard functions can only return a single value. After that, execution continues from where that function was called. So, you're trying to loop through all the values, but return upon seeing the first value, then the function exits and the loop is broken. In your case, you could simply return fun.temp(). Or, if you want to process each value, then return the new list, you could run something like: new_list = [] value = fun.temp() for x in value: # do something with x here new_list.append(x) return new_list Also, it appears you may be a bit confused about how inheritance works. DigitalOcean has a great article on it, if you want to take a look.
unknown
d4444
train
This question was old, but not answered very well and I ran across this same problem earlier today. jHtmlArea can be used on a responsive page with a couple of small modifications to its source code. The original documentation for jHtmlArea can be found here: https://pietschsoft.com/post/2009/07/22/jhtmlarea-the-all-new-html-wysiwyg-editor-for-jquery The original source code has migrated to GitHub: https://github.com/crpietschmann/jHtmlArea To make jHtmlArea responsive, simply replace the init function code in jHtmlArea-0.8.js with the code below: init: function (elem, options) { if (elem.nodeName.toLowerCase() === "textarea") { var opts = $.extend({}, jHtmlArea.defaultOptions, options); elem.jhtmlareaObject = this; var textarea = this.textarea = $(elem); var container = this.container = $("<div/>").addClass("jHtmlArea").insertAfter(textarea); var toolbar = this.toolbar = $("<div/>").addClass("ToolBar").appendTo(container); priv.initToolBar.call(this, opts); var iframe = this.iframe = $("<iframe/>").height(textarea.height()); iframe.width('inherit'); var htmlarea = this.htmlarea = $("<div/>").width('100%').append(iframe); container.append(htmlarea).append(textarea.hide()); priv.initEditor.call(this, opts); priv.attachEditorEvents.call(this); // Fix total height to match TextArea iframe.height(iframe.height() - toolbar.height()); // toolbar.width(textarea.width()); if (opts.loaded) { opts.loaded.call(this); } } }, Hopefully this will save someone else some time. A: jHtmlArea is a nice WYSIWYG editor is very simple to use // Turn all <textarea/> tags into WYSIWYG editors $(function() { $("textarea").htmlarea(); }); You can download the library from here http://pietschsoft.com/demo/jHtmlArea/
unknown
d4445
train
You can join the elements of args[] with space using String#join: public class Main { public static void main(String[] args) { System.out.println(String.join(" ", args)); } }
unknown
d4446
train
you can do z = rand(-1, 1) rxy = sqrt(1 - z*z) phi = rand(0, 2*PI) x = rxy * cos(phi) y = rxy * sin(phi) Here rand(u,v) draws a uniform random from interal [u,v] A: You don't need trigonometry if you can generate random gaussian variables, you can do (pseudocode) x <- gauss() y <- gauss() z <- gauss() norm <- sqrt(x^2 + y^2 + z^2) result = (x / norm, y / norm, z / norm) Or draw points inside the unit cube until one of them is inside the unit ball, then normalize: double x, y, z; do { x = rand(-1, 1); y = rand(-1, 1); z = rand(-1, 1); } while (x * x + y * y + z * z > 1); double norm = sqrt(x * x + y * y + z * z); x / norm; y /= norm; z /= norm; A: It looks like you can see that it's the cartesian coordinates that are creating the concentrations. Here is an explanation of one right (and wrong) way to get a proper distribution.
unknown
d4447
train
The 3 in input is the number to represent that the input image is RGB (color image), also known as color channels, and if it were a black and white image then it would have been 1 (monochrome image). The 32 in output of this represents the number of neurons\number of features\number of channels you are using, so basically you are representing the image in 3 colors with 32 channels. This helps in learning more complex and different set of features of the image. For example, it can make the network learn better edges. A: By assigning stride=2 you can reduce the spatial size of input tensor so that the height and width of output tensor becomes half of that input tensor. That means, if your input tensor shape is (batch, 32, 32, 3) (3 is for RGB channel) to a Convolution layer having 32 kernels/filters with stride=2 then the shape of output tensor will be (batch, 16, 16, 32). Alternatively, Pooling is also widely used to reduce the output tensor size. The ability of learning hierarchical representation by stacking conv layer is considered as the key to success of CNN. In CNN, as we go deeper the spatial size of the tensor reduces whereas the number of channel increases that helps to handle the variations in appearance of complex target object . This reduction of spatial size drastically decreases the required number of arithmetic operations and computation time with the motive of extracting prominent features contributing towards final output/decision. However, finding this optimal number of filter/kernel/output channel is time consuming and, therefore, people follow the proven earlier architectures e.g. VGG.
unknown
d4448
train
You can pass the -rpath option to ld to specify search directories for dynamic libraries. Using -rpath . (-Wl,-rpath . to pass it from GCC) will enable loading the libraries from the executable's directory. Just put the appropriate .so files there and they will be found. A: You could statically link you libs, that way no need to have SDL installed. A way to do it : g++ -o program [sources.cpp] -Wl,-Bstatic -lSDL2 -lSDL2_image \ -lSDL2_mixer -lSDL2_ttf -Wl,-Bdynamic [dynamically linked libs] Note : If you use SDL2, you must use the SDL2 builds of peripheral libs otherwise you risk all kinds of errors.
unknown
d4449
train
Threading problems can be categorized like this: Correctness (nothing bad happens) * *race condition Liveness (something good happens eventually) * *deadlock *starvation *livelock I do not know of a further categorization of race conditions. A data race is a more lower level problem and happens if you have conflicting memory accesses (so at least one of them is a write) on the same memory location and these are not ordered by a happens before relation. Data races are part of memory models like the Java Memory Model and that of C++ 11. A race condition and a data race are different types of problems.
unknown
d4450
train
Error messages exist to give developers, and also users, a clue when something goes wrong. I suspect that you're mistyping SIGINT as SIGNIT. The error message you're getting is consistent with a typo in your statement. I feel like this shows poor research effort because if you had read the error message before asking help, you would have figured it out. A: I would like to answer this because I solved the similar problem recently. When you call kill -s SIGINT, you may use sh to run the script. Unfortunately, sh which is different from bash(linux shell kill signal SIGKILL && KILL) will run in compatibility mode and not recognize SIGINT. The best solution is to use /bin/bash explicitly. By the way, #!/bin/bash doesn't work when you sh the script, either. Hope it helps. A: It's possible that the shell executing the script is using a built-in "kill" command while your command-line shell is using an external binary, or vice-versa. Use /bin/kill explicitly and see if that helps be more consistent. kill -SIGINT is, I believe, the more common way of doing this (instead of "-s SIGINT"). Also, kill normally takes a process-id and not a process-name. Built-in vs external "kill" commands may also support (or not support) this differently.
unknown
d4451
train
Try this. You can pass whatever value you want and it'll loop through until it reaches 0. Too high of a number throws an arithmetic error. Function: CREATE FUNCTION dbo.timeoutFunction(@P1 int) RETURNS @table TABLE ( Id int ) AS BEGIN WHILE @P1 > 0 BEGIN SET @P1 -= 1 INSERT INTO @table SELECT @P1 END RETURN END Call: SELECT * FROM timeoutfunction(1000000)
unknown
d4452
train
You are missing an upstream block where you refer to in proxy_pass http://app_server;. You can put it above the server block like this. upstream app_server { server 127.0.0.1:8080 fail_timeout=0; } server { listen 80; root /home/rails/public; server_name _; index index.htm index.html; ...
unknown
d4453
train
I can suggest the following approach: * *You can use a standard asp LinkButton control to display a link. When the link has been clicked, *Create a temporary CSV file from the data in your ImportFile table. *Create a URL to the generated CSV file (you can use the WebLink.url method). *Open the generated URL. When I was working on a similar task (generate and download PDF) I also had to modify some standard classes such as WebSession and EPDocuGetWebLet.
unknown
d4454
train
Is this what you need? You have not mentioned what the second dictionary is for since the sample output only refers to the first dictionary. inp = {'entities': [{'title': 'WarnerMedia', 'wikild': 'Q191715', 'label': 'Organization'}, {'title': 'Time (magazine)', 'wikild': 'Q43297', 'label': 'Organization'}, {'title': 'AOL', 'wikild': 'Q27585', 'label': 'Organization'}, {'title': 'Google', 'wikild': 'Q95', 'label': 'Organization'}, {'title': 'Warner Bros.', 'wikild': 'Q126399', 'label': 'Organization'}, {'title': 'U.S. Securities and Exchange Commission', 'wikild': 'Q953944', 'label': 'Organization'} ], 'relations': [{'source': 'Time (magazine)', 'target': 'WarnerMedia', 'type': 'owned by'}, {'source': 'WarnerMedia', 'target': 'Time (magazine)', 'type': 'subsidiary'}, {'source': 'WarnerMedia', 'target': 'Time (magazine)', 'type': 'owned by'}, {'source': 'WarnerMedia', 'target': 'U.S. Securities and Exchange Commission', 'type': 'subsidiary'}, {'source': 'U.S. Securities and Exchange Commission', 'target': 'WarnerMedia', 'type': 'subsidiary'}, {'source': 'WarnerMedia', 'target': 'AOL', 'type': 'subsidiary'}, {'source': 'AOL', 'target': 'WarnerMedia', 'type': 'subsidiary'} ] } df = pd.DataFrame(inp['relations']) #Simply conversion to dataframe output = df[['source','type','target']] #Reordering columns output A: I suppose the data come as a string, but I'm not sure if they come as one object or as multiple objects. In my answer, I suppose each time there is only an object if not; then the only difference is having a for-loop appending the data. import json import pandas as pd JSON=""" { 'entities': [ {'title': 'WarnerMedia', 'wikild': 'Q191715', 'label': 'Organization'}, {'title': 'Time (magazine)', 'wikild': 'Q43297', 'label': 'Organization'}, {'title': 'AOL', 'wikild': 'Q27585', 'label': 'Organization'}, {'title': 'Google', 'wikild': 'Q95', 'label': 'Organization'}, {'title': 'Warner Bros.', 'wikild': 'Q126399', 'label': 'Organization'}, {'title': 'U.S. Securities and Exchange Commission', 'wikild': 'Q953944', 'label': 'Organization'} ], 'relations': [ {'source': 'Time (magazine)', 'target': 'WarnerMedia', 'type': 'owned by'}, {'source': 'WarnerMedia', 'target': 'Time (magazine)', 'type': 'subsidiary'}, {'source': 'WarnerMedia', 'target': 'Time (magazine)', 'type': 'owned by'}, {'source': 'WarnerMedia', 'target': 'U.S. Securities and Exchange Commission', 'type': 'subsidiary'}, {'source': 'U.S. Securities and Exchange Commission', 'target': 'WarnerMedia', 'type': 'subsidiary'}, {'source': 'WarnerMedia', 'target': 'AOL', 'type': 'subsidiary'}, {'source': 'AOL', 'target': 'WarnerMedia', 'type':'subsidiary'} ] } """.replace("'", '"') json_object = json.loads(JSON) df=pd.DataFrame(json_object["relations"]) df.head()
unknown
d4455
train
You can pass pointers to member functions. The syntax for doing it with C++ is tricky, but boost::bind hides it and makes it fairly easy to do. An example would be making completion_condition non-static and passing it to async_read as such:boost::bind(&tcp_connection::completion_condition, this, _1, _2) &tcp_connection::completion_condition is a pointer to the function. this is the object of type tcp_connection to call the function on. _1 and _2 are placeholders; they will be replaced with the two parameters the function is called with.
unknown
d4456
train
The most recent unstable angularjs (1.1.4+) builds include both an ngSwipeLeft and ngSwipeRight directive. You must take care to reference the angular-mobile.js library. https://github.com/angular/angular.js/blob/master/src/ngMobile/directive/ngSwipe.js
unknown
d4457
train
Personally I would use the build-in module queue which is designed to safely retrieve data from threads. Using the LIFO functionality to create piles and then emptying them. Here's a working example: import threading import queue import time sensor_pile = queue.LifoQueue() other_sensor_pile = queue.LifoQueue() def getSensorData(): time.sleep(0.05) class Test: x = "x " + str(time.time()) y = "y " + str(time.time()) time = time.time() return Test def getOtherSensorData(): time.sleep(0.01) class Test: h = "h " + str(time.time()) return Test def thread1(): global connected while connected: sensor_pile.put(getSensorData()) def thread2(): global connected while connected: other_sensor_pile.put(getOtherSensorData()) def save_data(): global connected global results last_time = -float("inf") # Use other_sensor_pile.get() if the first h value should not be None h = None while connected: data = sensor_pile.get() # Will wait to receive data. # As the main pile, the main while loop will keep it empty. try: # Update h to the latest value and then empty the pile. # get_nowait will get the data if it is available # or raise a queue.Empty error if it isn't. h = other_sensor_pile.get_nowait().h while True: other_sensor_pile.get_nowait() except queue.Empty: pass if data.time - last_time >= 0.2: # Shortened for the sake of testing. last_time = data.time results.append({ 'time': last_time, 'x': data.x, 'y': data.y, 'h': h }) if __name__ == '__main__': global connected global results connected = True if 'results' not in globals(): results = [] first_thread = threading.Thread(target=thread1) second_thread = threading.Thread(target=thread2) save_thread = threading.Thread(target=save_data) first_thread.start() second_thread.start() save_thread.start() time.sleep(1) connected = False save_thread.join() second_thread.join() first_thread.join() for line in results: print(line) With the example output: {'time': 1627652645.7188394, 'x': 'x 45.7188', 'y': 'y 45.7188', 'h': 'h 45.7032'} {'time': 1627652645.9584458, 'x': 'x 45.9584', 'y': 'y 45.9584', 'h': 'h 45.9584'} {'time': 1627652646.1991317, 'x': 'x 46.1991', 'y': 'y 46.1991', 'h': 'h 46.1991'} {'time': 1627652646.4394188, 'x': 'x 46.4394', 'y': 'y 46.4394', 'h': 'h 46.4394'} {'time': 1627652646.6793587, 'x': 'x 46.6793', 'y': 'y 46.6793', 'h': 'h 46.6793'} The emptying of the pile isn't very efficient and can cause problems if the data is put in faster than it can be emptied. There may be some other methods to do this but I'm not sure how it would work. See: multithreading - overwrite old value in queue?
unknown
d4458
train
Unit tests are white-box tests, so you are fully aware of what goes on inside the system under test. There's nothing wrong with using that information to help determine what to mock. Yes, it's an implementation detail, and it can make your test "fragile" in the sense of needing to change it when your underlying implementation changes. But in a case like this, I would want to know that when I call adapter.foo(), it calls underlyingService.foo(), and mocks are perfect for this. A: The best rule of thumb I can advice is: try to use behavior setup/verification only in cases it is a part of your contract. In case you test behavior but what you are actually interested in is state, tests tends to break lot more often as the behavior is in fact an implementation detail. In your example, if no one cares for the exact boundary between service and an adapter, feel free to use state verification on adapter class. But if your adapter is supposed to translate specific message calls patterns to another well-defined set of messages, you might want to use behavior verification instead. In other words, if adapter.GetEmployeeById(id) needs to translate to service.GetEmployeeById(id) then it is not an implementation detail.
unknown
d4459
train
Easy enough: DateFormatter.parseDate(yourString); As long as your string is somewhat of a standard format, it should work.
unknown
d4460
train
Try: Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) A: Use : dlg.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) this gets you the path of the desktop for the user who is running the code. A: Apparently, the Desktop in Win 7 doesn't actually exist at the path c:\Users\username\Desktop The system pretends it does at the command prompt and in windows explorer. But since it isn't there, the part of SelectedPath that requires its path to be under RootFolder disallows setting the path in that way.
unknown
d4461
train
I going to attempt an answer but it may be off base. The objective is to have a single realm result that can be observed for changes and also know what the newest delivery is. Here's the code self.packageResults = realm.objects(Package.self).sorted(byKeyPath: "delivered", ascending: false) Then observe self.packageResults. Whenever there's a change the observe closure will fire and deliver the results, sorted descending so the most current delivery will be 'at the top' i.e. index 0. EDIT Based on a comment and update to the question there was a question whether this answer provides a solution. Now there is a bit more data, just a slight modification produces the desired result (almost, keep reading) self.packageResults = realm.objects(Package.self) .filter("deliveryDate => 20190303") .sorted(byKeyPath: "state", ascending: false) then add an observer to self.packageResults. (note that I am using an Int for the timestamp to keep it simple) To test, we use the data provided in the question with our observer code. The code prints the initial state of the data, and then prints the state after any delete, insert or modify. func doObserve() { self.notificationToken = self.packageResults!.observe { (changes: RealmCollectionChange) in switch changes { case .initial: print("initial load complete") if let results = self.packageResults { for p in results { print(p.deliveryDate, p.state.rawValue) } } break case .update(_, let deletions, let insertions, let modifications): if let results = self.packageResults { for p in results { print(p.deliveryDate, p.state.rawValue) } } then we run the code and add the observer. This is the output initial load complete 20190303 1 20190304 0 20190305 0 20190306 0 if we then change the package 20190304 to 'delivered' we get the following output 20190303 1 20190304 1 20190305 0 20190306 0 So we are getting the desired result. HOWEVER, according to the question, the conditions of the query change as the next query would be for dates 20190304 and after. If the conditions of the output change, the conditions of the query would have to change as well. In this case the desired result is to display the most currently delivered package each day, so the query would need to be updated each day to reflect that date. As a possible solution, change the Package object to include a watched property class Package: Object { @objc enum State: Int { case scheduled case delivered } @objc dynamic var state = State.scheduled @objc dynamic var deliveryDate = 0 @objc dynamic var watched = false } and update the query to only observe packages being watched, ignore ones not being watched (where watched = false) self.packageResults = realm.objects(Package.self) .filter("deliveryDate => 20190303 and watched == true") .sorted(byKeyPath: "state", ascending: false) Then, when you no longer need to know about an object, set it's watched property to false, and it will not be included in the results. Using the same process as above with this query, when changing 20190304 to delivered, we also change 20190303 watched property to false and the results are handle item delete, insert or mod 20190304 1 20190305 0 20190306 0 which appears to answer the question.
unknown
d4462
train
You can send requests to a website from an iOS application. You're probably looking to perform a HTTP action. There is a great guide by the Spring development team which guides you through the process of using RESTful services on iOS, this includes Posting data to a web service. RESTful services also allow you the create, retrieve, update and delete data from a webservice too using a variety of HTTP calls.
unknown
d4463
train
You can try like this, hope it help. <!DOCTYPE html> <html> <head></head> <body> <select id="marks" name="studentmarks"> <option value="1">abc-test</option> <option value="2">abc-test2</option> <option value="3">cde-test3</option> </select> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> jQuery(function($){ $('select[name="studentmarks"]').on('change', function(){ var selected_option = $('#marks option:selected'); console.log(selected_option.text()); if (selected_option.text().indexOf("abc") >= 0){ alert('abc'); } else{ alert('None abc'); } }); }); </script> </html> A: One possible approach is below: jQuery(function($) { // here we select the select element via its 'id', // and chain the on() method, to use the anonymous // function as the event-handler for the 'change' // event: $('#marks').on('change', function() { // here we select the element with the id of 'score': We update that property using an // assessment: $('#score') // we update its 'disabled' property via the prop() // method (the first argument is the name of the // property we wish to update, when used as a setter, // as it is here) and we use $(this) to get the current // element upon which the event was fired: .prop('disabled', $(this) // we find the option that was/is selected: .find('option:selected') // we retrieve its text (instead of its value), // since your checks revolve around the text: .text() // text() returns a String, which we use along with // String.prototype.startsWith() - which returns a // Boolean true/false - based on the argument provided. // if the string does start with 'abc' the assessment // then returns true and the '#score' element is disabled, // if the string does not start with 'abc' the // assessment returns false, and the disabled property // is set to false, so the element is enabled: .startsWith('abc')); // here we trigger the change event, so that the '#score' // element is enabled/disabled appropriately on page-load: }).change(); }); *, ::before, ::after { box-sizing: border-box; margin: 0; padding: 0; } label { display: block; } input[disabled] { background: repeating-linear-gradient(45deg, transparent, transparent 5px, #ccca 5px, #ccca 10px); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <label>Student marks: <select id="marks" name="studentmarks"> <option value="1">abc-test</option> <option value="2">abc-test2</option> <option value="3">cde-test3</option> </select> </label> <label>Score: <input id="score" type="text"> </label> </body> JS Fiddle demo. This is, of course, also possible in plain – though relatively modern – native JavaScript: // listening for the DOMContentLoaded event to fire on the window, in order // to delay running the contained JavaScript until after the page's content // is available: window.addEventListener('DOMContentLoaded', () => { // using document.querySelector() to find the first element matching // the supplied selector (this returns one element or null, so in // production do sanity-check and prepare for error-handling): const select = document.querySelector('#marks'), // we create a new Event, in order that we can use it later: changeEvent = new Event('change'); // we use EventTarget.addEventListener() to bind the anonymous function // as the event-handler for the 'change' event: select.addEventListener('change', function(event) { // here we cache variables to be used, first we find the 'score' // element: const score = document.querySelector('#score'), // we retrieve the element upon which the event was bound: changed = event.currentTarget, // we find the selected option, using spread syntax to // convert the changed.options NodeList into an Array: selectedOption = [...changed.options] // we use Array.prototype.filter() to filter that Array: .filter( // using an Arrow function passing in the current <option> // of the Array of <option> elements over which we're // iterating into the function. We test each <option> to // see if its 'selected' property is true (though // truthy values will also pass with the way this is written): (opt) => opt.selected // we use Array.prototype.shift() to retrieve the first Array- // element from the Array: ).shift(), // we retrieve that <option> element's text: optionText = selectedOption.text; // here we set the disabled property of the 'score' element, // again using String.prototype.startsWith() to obtain a // Boolean value indicating whether string does start with // 'abc' (true) or does not start with 'abc' (false): score.disabled = optionText.startsWith('abc'); }); // here we use EventTarget.dispatchEvent() to trigger the created // change Event on the <select> element in order to have the // 'score' element appropriately disabled, or enabled, according // to its initial state: select.dispatchEvent(changeEvent); }); *, ::before, ::after { box-sizing: border-box; margin: 0; padding: 0; } label { display: block; } input[disabled] { background: repeating-linear-gradient(45deg, transparent, transparent 5px, #ccca 5px, #ccca 10px); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <label>Student marks: <select id="marks" name="studentmarks"> <option value="1">abc-test</option> <option value="2">abc-test2</option> <option value="3">cde-test3</option> </select> </label> <label>Score: <input id="score" type="text"> </label> </body> JS Fiddle demo. References: * *JavaScript: *Arrow functions. *Array.prototype.filter(). *Array.prototype.shift(). *EventTarget.addEventListener(). *EventTarget.dispatchEvent(). *HTMLOptionElement. *Spread syntax. *String.prototype.startsWith(). *jQuery: *find(). *on(). *prop(). *text().
unknown
d4464
train
You can try this which this which sets the order of execution during the merge ffmpeg -i $videofile -itsoffet 6 -i $au -acodec copy -vcodec copy $outputfile -map 0:0 -map 1:0
unknown
d4465
train
Change your viewDidLoad method and set UITableView's data source and delegate: - (void)viewDidLoad { [super viewDidLoad]; self.tableView.dataSource = self; self.tableView.delegate = self; } And implement UITableViewDataSource and UITableViewDelegate protocols.
unknown
d4466
train
I couldn't find a solution to the clipping issue so I went with adding a header and footer to the ListView. I changed my ListView height back to match_parent and then, using the post method on my ListView's parent view, I was able to calculate the height of my header and footer like so: // this call should be included in the onCreate method // the post method is called after parentView is ready to be added // so the parentView's height and width can be used parentView.post(addSpace(parentView, myListView)); private Runnable addSpace(final RelativeLayout parent, final ListView list) { return new Runnable(){ public void run() { // create list adapter here or in the onCreate method // R.layout.list_item refers to my custom xml layout file adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.list_item, values); // calculate size and add header and footer BEFORE applying adapter // listItemHeight was calculated previously spacerSize = (parent.getHeight()/2) - (listItemHeight/2); list.addHeaderView(getSpacer(), null, false); list.addFooterView(getSpacer(), null, false); list.setAdapter(adapter); } } } // I used a function to create my spacers private LinearLayout getSpacer(){ // I used padding instead of LayoutParams thinking it would be easier to // change in the future. It wasn't, but still made resizing my spacer easy LinearLayout spacer = new LinearLayout(MainActivity.this); spacer.setOrientation(LinearLayout.HORIZONTAL); spacer.setPadding(parentView.getWidth(), spacerSize, 0, 0); return spacer; } Using this method I was able to add the proper spacing to the top and bottom of my ListView so when I scrolled all the way to the top the top item appeared in the center of my view. PROBLEM: My app allows the user to hide the bottom interface element which should make my parent much taller. I am working out a way to make my header and footer taller dynamically but I may need to simply remove the ListView and recreate it with a larger header and footer. I hope this helps someone from hours of frustration :)
unknown
d4467
train
Maybe you can use this: https://github.com/xieqihui/pandas-multiprocess pip install pandas-multiprocess from pandas_multiprocess import multi_process args = {'width': 137} result = multi_process(func=func, data=df, num_process=8, **args)
unknown
d4468
train
Login your facebook with same user which you have created facebook app with. This error appeared because you logged in facebook with other user. Note: By default Facebook app app is in development mode and can only be used by app admins, developers and testers.
unknown
d4469
train
Maybe you should have a look at validating your HTML. Your problem is this line: <li><a href="#"><span>Calculator</span></a</li> It should be: <li><a href="#"><span>Calculator</span></a></li> You never closed the a tag and therefor everything after it will be part of the link, also the select box. So you are clicking on the link, not the select box. A good way of overcoming these kinds of problems is using a good editor that will complete your code and highlights problems. Another good way is to put your code in the http://validator.w3.org and check for errors there. A: The only problem I see is that some of your </a> tags are cut off so they're just </a. Correcting that, it all works fine for me. A: Many of your tags are not closed correctly (i.e. </a instead of </a>), this fixes it: http://jsfiddle.net/c7nge/1/
unknown
d4470
train
I suggest that you could add speechapi_cxx.h in Properties->VC++ Directories->Include Directories. The path is cognitive-services-speech-sdk-master\quickstart\cpp\windows\from-microphone\packages\Microsoft.CognitiveServices.Speech.1.15.0\build\native\include\cxx_api. Also, you need to add the code using namespace Microsoft::CognitiveServices::Speech::Audio;. Here is the complete code: #include <iostream> #include <speechapi_cxx.h> using namespace std; using namespace Microsoft::CognitiveServices::Speech::Audio; using namespace Microsoft::CognitiveServices::Speech; auto config = SpeechConfig::FromSubscription("real_sub_id", "region"); int main() { std::cout << "Hello World!\n"; auto audioCofig = AudioConfig::FromDefaultMicrophoneInput(); auto recognizer = SpeechRecognizer::FromConfig(config, audioCofig); cout << "Speak " << endl; auto result = recognizer->RecognizeOnceAsync().get(); cout << "RECOGNIZED: Text=" << result->Text; } A: I don't know much about the library you are using, but i am sure that you need to #include something before you can actually use the library.
unknown
d4471
train
Because thats the syntax to make it a new instance.
unknown
d4472
train
It's the [enter] key. Your first scanf is reading the enter key you pressed to terminate the previous iteration. So you need to add another scanf("%c", &function); or getchar(); just before the goto to eat the newline. When reading in numbers, scanf will eat any initial whitespace; but when reading characters, it won't. It gives you the very next byte in the stream. A better way, perhaps, would be to tell `scanf` where to expect all the newlines. This way you don't need that *weird* mystery line that doesn't appear to do anything but isn't commented (!); because that's gonna cause problems when you play with this code again months from now. //scanf("%c\n", &function); /* read a character followed by newline DOESN'T WORK */ ... //scanf("%f\n", &secondnum); /* read a number followed by newline DOESN'T WORK */ This way, trailing newlines are consumed. Which is, I think, the more intuitive behavior (from the User side). Nope. Doesn't work. Wish it did, cause I'd look less foolish. I'm not upset by the goto. It's nice to see an old friend. This is an appropriate use of it if ever there was one. It is exactly equivalent to the while form. So you should certainly be aware that most people will prefer to see while(1) because it tells you more about what's going on than label:. But for an infinite loop in a function smaller than a screen, why not? Have fun. No baby seals will be harmed. :) A: This is why you use loops. (And try not to use goto for this). #include <stdio.h> #include <math.h> int main() { float firstnum, secondnum, answer; char function, buffer[2]; while(1) { printf("\nHello and welcome to my calculator!\n"); printf("\nPlease input the function you would like to use. These include +, -, *, /.\n"); scanf("%s", &buffer); function = buffer[0]; printf("\nNow please input the two variables.\n"); scanf("%f", &firstnum); scanf("%f", &secondnum); if (function == '+') answer = firstnum+secondnum; else if (function == '-') answer = firstnum-secondnum; else if (function == '*') answer = firstnum*secondnum; else if (function == '/') answer = firstnum/secondnum; else printf("Sorry that was an incorrect function. The correct inputs are +, -, *, /."); printf("Your answer is %f \n", answer); } return 0; } This should go in an infinite loop, so use an input from the user to break; the loop to exit the program Note : I have replaced the scanf %c with %s indicating an input of a string & used a buffer. scanf("%s",&buffer); function = buffer[0]; (Updated as per discussion in comments) A: One "best practise" regarding scanf is to check it's return value. In regards to the return value of scanf, I suggest reading this scanf manual carefully and answering the following questions: * *int x = scanf("%d", &foo); What do you suppose x will be if I enter "fubar\n" as input? *Where do you suppose the 'f' from "fubar\n" will go? *If it remains in stdin, would you expect a second scanf("%d", &foo); to be successful? *int x = scanf("%d", &foo); What do you suppose x will be if I run this code on Windows and press CTRL+Z to send EOF to stdin? *Would it be safe to use foo if x is less than 1? Why not? *int x = scanf("%d %d", &foo, &bar); What would you expect x to be if I enter "123 456\n" as input? *Do you suppose the '\n' will still be on stdin? What value would char_variable hold following scanf("%c", &char_variable);? EOF can be sent through stdin in Windows by CTRL+Z, and in Linux and friends by CTRL+D, in addition to using pipes and redirection to redirect input from other programs and files. By using code like int function; for (function = getchar(); function >= 0 && isspace(function); function = getchar()); assert(function >= 0); or char function; assert(scanf("%*[ \n]%c", &function) == 1); you can discard leading whitespace before assigning to function.
unknown
d4473
train
There is a package over on JSON.org called org.json.me which is a port of org.json to Java ME.
unknown
d4474
train
I have two get method on a controller for get a list and get info of 1 element I need to use this format GET:https://localhost:44309/api/department GET:https://localhost:44309/api/department?id=1 If you'd like to match request(s) to expected action(s) based on the query string, you can try to implement a custom ActionMethodSelectorAttribute and apply it to your actions, like below. [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class CheckQueryStingAttribute : ActionMethodSelectorAttribute { public string QueryStingName { get; set; } public bool CanPass { get; set; } public CheckQueryStingAttribute(string qname, bool canpass) { QueryStingName = qname; CanPass = canpass; } public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action) { StringValues value; routeContext.HttpContext.Request.Query.TryGetValue(QueryStingName, out value); if (QueryStingName == "" && CanPass) { return true; } else { if (CanPass) { return !StringValues.IsNullOrEmpty(value); } return StringValues.IsNullOrEmpty(value); } } } Apply it to actions [HttpGet] [CheckQuerySting("id", false)] [CheckQuerySting("", true)] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } [HttpGet] [CheckQuerySting("id", true)] [CheckQuerySting("", false)] public string GetDepartamento(int id) { return "value"; } Test Result
unknown
d4475
train
* *Remove a const qualifier from the Func parameter. template<typename Func, typename...Args> void addFunctionToQueue(int t , Func&& myFunc, Args&&... myArgs) // ~~~^ no const Rationale: When using a forwarding reference (or an lvalue reference) type with a template argument deduction, a const qualifier is automatically deduced (depending on the argument's qualifiers). Giving it explicitly prevents the compiler from adding it to the Func type itself, which results in an error when you try to std::forward<Func>. That said, you would need to write std::forward<const Func> instead to avoid the compiler error, but still, that would make no sense, as const T&& is not a forwarding reference. *Non-static member functions require an object for which they will be called, just like you write a.foo(), not foo(). newSystem.addFunctionToQueue(5, &System::doNonStaticFunction, &newSystem, 1); // ~~~~~~~~~^ context
unknown
d4476
train
First, using JavaScript you should be able to handle shadow roots: https://stackoverflow.com/a/60618233/143475 And the above answer links to advanced examples of executing JS in the context of the current page. I suggest you do some research into that, try to take the help of someone who knows JS, the DOM and HTML well - and you should be find a way to know if the XHR has been made successfully or not - for e.g. based on whether some element on the page has changed etc. Finally here is how you can do interception: https://stackoverflow.com/a/61372471/143475
unknown
d4477
train
Did you try to install the complete opencv package with all development dependencies? apt-get install libopencv-dev A: Okay, I was able to figure out what was going on. Apparently, if you don't install the prerequisites FIRST, Cmake will take into account not having them, and will disable the feature completely. I was able to figure this out during the Cmake process, it stated it was "looking" for the libav libraries, and in turn did not find them. So, I decided to completely reinstall the OS, (probably didn't have to, but wanted to save space) and reinstall the prereq's first, then made sure the cmake compiler was happy before the make process. I guess that's why they call them pre-requisites, huh?
unknown
d4478
train
I managed to find the reason. If anyone has a similar problem, this may help. Since I had a download manager in my system, it sent multiple requests to divide the file in order to expedite the download process.
unknown
d4479
train
Here is my setup for Flurl, which works with untrusted certificates: HttpClientHandler httpClientHandler = new HttpClientHandler(); httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; HttpClient httpClient = new HttpClient(httpClientHandler); httpClient.BaseAddress = new Uri("https://myaddress.com"); var flurlClient = new FlurlClient(httpClient); var apiInfo = await flurlClient.Request("apiInfo").GetJsonAsync<ApiInfoDto>(); I have created custom HttpClientHandler which accepts every certificate in ServerCertificateCustomValidationCallback. Of course, you can use other logic in this handler. Update: With this setup, you cannot use Flurl extensions for URL (you cannot write "http://myadress.com/apiInfo".GetJsonAsync<ApiInfoDto>(). You have to create Flurl client as seen above and use Flurl client for your calls as demonstrated also in mine code. The usage is the same as Flurl extensions for URL. A: An inline solution to accept any certificate is: var myString = await "https://some-server-with-an-invalid-cert.net" .AppendPathSegment("/some-file.txt") .WithClient(new FlurlClient(new HttpClient(new HttpClientHandler { ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true }))) .GetStringAsync(); With WithClient() you can pass a client configured different than the default client. In some cases you would not want to change the default client, but apply properties, e.g. the certificate validation only to this specific case. A: The most typical way to do this is to create a custom factory: public class UntrustedCertClientFactory : DefaultHttpClientFactory { public override HttpMessageHandler CreateMessageHandler() { return new HttpClientHandler { ServerCertificateCustomValidationCallback = (_, _, _, _) => true }; } } Then register it somewhere in your app startup: FlurlHttp.ConfigureClient("https://theapi.com", cli => cli.Settings.HttpClientFactory = new UntrustedCertClientFactory()); Flurl reuses the same HttpClient instance per host by default, so configuring this way means that every call to theapi.com will allow the use of the untrusted cert. The advantage of this over passing an HttpClient to a FlurlClient constructor is that it keeps this configuration "off to the side" and works when you use Flurl in the more typical/less verbose way: await "https://theapi.com/endpoint".GetJsonAsync();
unknown
d4480
train
well, a litle bit out-dated, but nevertheless here is what worked for me: * *unlock *place a 1x1 table object inside the Regions cell *place the regions name inside the table object (just drag it inside the table) *in the table's paginations properties deselect the option Allow row contents to break across pages you might also need to specify the height of the table object. A: You can use Page breaks to achieve this. In your example, click on Region data item. From Structure menu, click "Set Page Break using Master/Detail". That will do the trick. Please note, for crosstab and chart, report studio creates Page Break using Master/Detail relationship. If you were using List or repeater, then you could use the option of creating page break without Master/Detail relationship. Please refer to IBM Infocenter for more information on Page Breaks and Page Sets. http://publib.boulder.ibm.com/infocenter/c8bi/v8r4m0/index.jsp?topic=/com.ibm.swg.im.cognos.c8bi.doc/welcome.html
unknown
d4481
train
The standard library headers can include each other in unspecified ways, and headers can also contain extra declarations, so the error (if any) you get when you forget to include a header isn't necessarily what you'd expect. Here, for instance, one of the headers you included included the <__hash_table> internal header of libc++, which contains a forward declaration of unordered_map. This forward declaration contains no default template arguments (it can't have default arguments because the rules of the language prevents you from giving a template parameter default arguments in two declarations in the same scope, so if it did and then the user also included <unordered_map> - which must provide default arguments - the compiler would complain), so when the compiler sees you trying to use unordered_map with the default arguments, it complains that you have too few template arguments, rather than that unordered_map isn't declared. If you actually passed the requisite number of template arguments, the compiler will probably complain instead that you are attempting to instantiate a template that's declared but not defined. The fix is simple: include <unordered_map>. There's no need for a custom hasher or comparer either for unsigned - just use the default ones. A: Your problem probably comes from a bad copy-and-paste, as you are trying to get first and second fields from size_type variables, which are typedef to unsigned int. Replace your hash functors by these and your code will compile: struct size_type_hash { std::size_t operator()(const size_type& k) const { return std::hash<size_type>()(k); } }; struct size_type_equal { bool operator()(const size_type& lhs, const size_type& rhs) const { return lhs == rhs; } }; Just to be sure, do not forget to include the header in your file.
unknown
d4482
train
I think you should be able to do it with append. You can add the rows from df2 where the 'x' value isn't in df1 already. df1 = df1.append(df2[~df2['x'].isin(df1['x'])], ignore_index=True)
unknown
d4483
train
but I want use some String similarity algorithms. Take a look at Lucene. Allows you to index some text and look for works using a similarity algorithm. I would think you want to split each words and index them using lucene. Then for all the words you are interested for you can search the index. You can do things like Automobile~ which will do a fuzzy search. Here is a rough algo: for each word in STRING.split(' ') index word for each word in your list search for word and look for number of occurrences A: The inverted index that Denniss said is what you are looking for. You'll need to define your Document very well if you want a powerfull engine. For phrase matches, your Document should have the position of the word (the key of the Map) in this Document. Once you got all the words you were looking for, you can know if this words were together in the original document. For example: doc1: "Hello World" doc2: "Hello Beautiful World" inverted index { "Beautifull": [(doc2, 2)], "Hello": [(doc1, 1)(doc2, 1)], "World": [(doc1, 2)(doc2, 3)], } query: "Hello World" Both documents have the words "Hello" and "World", but doc1 has them together (position 1 and 2) and doc2 doesn't (position 1 and 3). If you want to find similar words, you'll need a new structure. First, you need to define what is similar. Levenshtein distance is what you need for that. To implement it, you'll need a whole new struture like an automata: Levenshtein automaton. Full-text search is a huge area. Implementing a search engine is hard and many libraries and applications already do it. (I work for Indextank.com a realtime full-text search engine. If you need a search engine running in a couple of minutes, try us out) A: What you are looking for is porbably an Inverted File data structure. I learned this in database class and here is a link to the lecture. http://dl.dropbox.com/u/8950924/16Sp11-Search.pdf Basically the idea is to have a Map data structure Map<String, List<Document>> invertedIndex; where string is the word and List<Document> is the documents containing that word. If you read more into that pdf, you can even find a way to rank the document.
unknown
d4484
train
You should place this line somewhere in the top cell in Jupyter to enable inline plotting: %matplotlib inline A: It's simply plt.show() you were close. No need for seaborn A: I was using PyCharm using a standard Python file and I had the best luck with the following: * *Move code to a Jupyter notebook (which can you do inside of PyCharm by right clicking on the project and choosing new - Jupyter Notebook) *If running a chart that takes a lot of processing time it might not have been obvious before, but in Jupyter mode you can easily see when the cell has finished processing.
unknown
d4485
train
There could be (1) client side routing and (2) server side routing create new page blog/index.tsx src -pages --blog ---[id].tsx ---index.tsx and redirect to /blog/1 in index.tsx(client side routing) import { useEffect } from 'react' import { useRouter } from 'next/router' export default function Blog() { useEffect(() => { router.push('/blog/1') }, []) return <p>Redirecting...</p> } server side route import { useEffect } from 'react' import { useRouter } from 'next/router' export default function Blog() { useEffect(() => { router.push('/blog/1') }, []) return <p>Redirecting...</p> } export const getServerSideProps = ({ req, res }) => { res.writeHead(302, { Location: "/blog/1" }); res.end(); return { props: {} } }
unknown
d4486
train
Hard to say without experimenting (any chance of creating a JSfiddle or similar?). I suspect the issue is that you are setting the width of all the rects in the brush. You only need to set the height, I believe. This is probably what is causing your extents to go all crazy. Once you get that straightened out, you'll need to filter your Crossfilter dimension based on the brush extent. Also, Crossfilter's group.reduceCount function doesn't take an argument, and if it is possible you are missing data you need to make sure to test/cast your data in your dimension accessors to make sure they always return naturally ordered numbers or strings.
unknown
d4487
train
There's a cool blog post on how to draw Waveforms by the author of the Capo audio editing software: http://supermegaultragroovy.com/2009/10/06/drawing-waveforms/ I wrote Cocoa (Mac) code based on that, and it's not too hard. You can find that code here: https://github.com/uliwitness/UKSoundWaveformView Though it's far from a finished, shippable editor, it's under a permissive license (zlib) and could easily be used as a basis for a full editor. A: Maibe this helps: Drawing waveform with AVAssetReader and if the issue is to draw, then this may help: Parametric acceleration curves in Core Animation A: This framework might help you out. From the examples it looks like its pretty easy to use and works well. It provides components to open an audio file, play it and draw the waveform. You might need to implement the cut/copy/paste features on your own.
unknown
d4488
train
The @KafkaListener comes with the: /** * Set an {@link org.springframework.kafka.listener.KafkaListenerErrorHandler} bean * name to invoke if the listener method throws an exception. * @return the error handler. * @since 1.3 */ String errorHandler() default ""; That one is used to catch and process all the downstream exceptions and if it returns a result, it is sent back to the replyTopic: public void onMessage(ConsumerRecord<K, V> record, Acknowledgment acknowledgment, Consumer<?, ?> consumer) { Message<?> message = toMessagingMessage(record, acknowledgment, consumer); logger.debug(() -> "Processing [" + message + "]"); try { Object result = invokeHandler(record, acknowledgment, message, consumer); if (result != null) { handleResult(result, record, message); } } catch (ListenerExecutionFailedException e) { // NOSONAR ex flow control if (this.errorHandler != null) { try { Object result = this.errorHandler.handleError(message, e, consumer); if (result != null) { handleResult(result, record, message); } } catch (Exception ex) { throw new ListenerExecutionFailedException(createMessagingErrorMessage(// NOSONAR stack trace loss "Listener error handler threw an exception for the incoming message", message.getPayload()), ex); } } else { throw e; } } See RecordMessagingMessageListenerAdapter source code for more info.
unknown
d4489
train
See the answer to this question for a suggestion on how to make your example work: You should change your INSERT to return that inserted ID to you right away (in an OUTPUT clause) A: You can only issue a single statement per batch in SQL Server Compact, and you cannot use Scope_identity, but must use @@IDENTITY (remember to keep the connection open betweeen the two calls)
unknown
d4490
train
1) You do not need to send 'ping' data to keep the connection alive, the TCP stack does this automatically; one reason for sending 'ping' data would be to detect a connection close on the client side - typically you only find out something has gone wrong when you try and read/write from the socket. There may be a way to change various time-outs so you can detect this condition faster. 2) In general while TCP provides a stream-oriented error free channel, it makes no guarantees about timeliness, if you are using it on the internet it is even more unpredictable. 3) For applications such as this (I hope you are making it for ethical purposes) - I would tend to use TCP, since you don't want a situation where the client receives a packet to raise an alarm but misses that one that turns it off again.
unknown
d4491
train
You can select which fields to export by defining the export block RailsAdmin.config do |config| config.model 'Highway' do export do field :number_of_lanes end end end Also you can configure the value of each field RailsAdmin.config do |config| config.model 'Lesson' do export do field :teacher, :string do export_value do value.name if value #value is an instance of Teacher end end end end end
unknown
d4492
train
You were pretty close! - (IBAction)myActionWithAnArbitraryName:(UIButton *)sender { if(playerTurn == YES) { [sender setBackgroundColor:[UIColor redColor]]; } } A: You can link all the 20 buttons of a single action. The sender knows which button was pressed, so directly channge the backgroundColor of sender. -(IBAction)changeColour:(id)sender { if (playerTurn == YES) sender.backgroundColor = [UIColor redColor]; } Note:This is not tested code. But i guess it should work, if wont they try do this way: UIButton *button=(UIButton *)sender; button.backgroundColor = [UIColor redColor]; A: You can actually use a single IBAction for all your buttons and just cast the sender as a UIButton: - (IBAction)buttonPressed:(id)sender { UIButton *button = (UIButton *)sender; if (playerTurn == YES) { button.backgroundColor = [UIColor redColor]; } }
unknown
d4493
train
Unless there's a very good reason that you specifically need NSValue, you should not add a class instance to an NSMutableArray that way. Just do: [myMutableArray addObject:myClassInstance]; This does all the right things with regards to memory management (and avoids ugly pointer value stuff), and should let you get at your class instance's array objects after retrieving the object. See the NSMutableArray docs for a quick starter on how to use the class properly.
unknown
d4494
train
In general, if you add folium.LayerControl().add_to(map) to the map then it provides functionality to display or hide your Geojson markers. Then you can hide or display markers using show=False or from 'Layers' icon on the top right of the map (see the image below) For example: # creating folium GeoJson objects from out GeoDataFrames pointgeo = folium.GeoJson(gdf,name='group on map', show=False, tooltip=folium.GeoJsonTooltip(fields=['Name', 'Relation', 'City'], aliases=['Name','Relation', 'City'], localize=True)).add_to(map) # To Add a LayerControl add below line folium.LayerControl().add_to(map) map Like in these images Marker are shown or hidden by controlling layer from top righ 'Layers' - 1) with markers 2) markers hidden you can refer to this link for more example: Folium_search Hope this helps!! A: I've found only this solution to make that. search = folium.FeatureGroup(name="Search", show=False).add_to(map) geojson_obj = folium.GeoJson(geo_json, zoom_on_click=True).add_to(search) Search( layer=geojson_obj, search_label="search_name", geom_type="Point", ).add_to(map) folium.LayerControl().add_to(map)
unknown
d4495
train
Change your styles to: body{ text-align: center; } input { width: 200px; } ul { text-align: left; margin: 0 auto; padding: 0; width: 200px; } #underbox li{ display: inline-block; text-decoration: underline; } input and ul => same width / ul => text-align: center; margin: 0 auto (for set position to center); padding: 0 (disable default style); jsfiddle A: something like this: #underbox { width: 200px; margin: 0 auto; padding: 0; list-style-type: none; } #underbox li { margin-right: 5px; text-decoration: underline; text-align: left; float: left; } A: Try to add style to the ul element like that: http://jsfiddle.net/csdtesting/j6f8L7Lp/ body { text-align: center; } #underbox li { display: inline-block; text-decoration: underline; } ul#underbox { padding: 0; list-style-type: none; margin: 0; } <input type="text" style="width: 200px;" /> <ul id="underbox"> <li>Test</li> <li>Next</li> </ul>
unknown
d4496
train
As array contains strings, you have to parse them back to integers when using them in the arithmetic. This is a possible solution: var roman = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" ]; function convertToRoman(num) { var result = []; var array = num.toString().split('').reverse(); for (i = 0, j = 0; i < array.length; i++, j += 10) { var location = parseInt(array[i]) + j; result.push(roman[location]); } return result.reverse().join(''); } console.log(convertToRoman(123)); Note that I made some changes regarding variable scope and use of array.push(). I also didn't try the method for multiple inputs. But getting the algorithm correct was not part of your question
unknown
d4497
train
you can use a list comprehension: [a for a, b in zip(l1, l2) if a > b] or you can use: from operator import gt, itemgetter list(map(itemgetter(1), filter(itemgetter(0), zip(map(gt, l1, l2), l1))))
unknown
d4498
train
Use $unwind and then $match to filter only answers to the question you are looking for: var steps = [ { $match: { 'path_id': ObjectId("560acae1904a29446a6d2610"), 'step_id': 'kids' } }, { $unwind : "$answers" }, { $match: { "answers.question": 'Do you have kids?' } }, { $group: { _id: '$answers.answer', count: { $sum: 1 } } } ]; Answer.aggregate(steps, function( err, results ) { //do whatever you want with the results } ); A: Really not sure if .aggregate() is really what you want for any of this. If I understand correctly you have these documents in your collection that has an array of answers to questions and that of course those answers are not in any set position within the array. But it also does not seem likely that any one document has more than one of the same answer type. So it seems to me is that all you really want is an $elemMatch on the array element values and determine the count of documents that contain it: Answer.count({ "path_id": "560acae1904a29446a6d2610", "answers": { "$elemMatch": { "question": "Do you have kids?", "answer": "Yes" } } },function(err,count) { }); The $elemMatch operator applies all of it's conditions just like another query to each element of the array. So multiple conditions of an "and" need to be met on the same element for it to be valid. No need to do this by index. If you wanted something broader, and then only really if it was possible for each document to contain more than one possible match in the array for those conditions, then you would use .aggregate() with a condition to filter and count the matches within the array. Answer.aggregate( [ { "$match": { "answers": { "$elemMatch": { "question": "Do you have kids?", "answer": "Yes" } } }}, { "$unwind": "$answers" }, { "$match": { "answers.question": "Do you have kids?", "answers.answer": "Yes" }}, { "$group": { "_id": "$path_id", "count": { "$sum": 1 } }} ], function(err,results) { } ); But I'd only be doing something like that if indeed you had multiple possible matches in the array and you needed multiple keys to group on within the results. So if it's just about matching documents that happen to have those details in one array entry, then just use $elemMatch for the query, and at most then just $group on the count for given keys and don't bother with filtering the array content via $unwind. Answer.aggregate( [ { "$match": { "answers": { "$elemMatch": { "question": "Do you have kids?", "answer": "Yes" } } }}, { "$group": { "_id": "$path_id", "count": { "$sum": 1 } }} ], function(err,results) { } ); So if there is really only one possible match within the array, then just count the documents instead
unknown
d4499
train
Try this: Private Sub ComboBox1_Change() Dim txt txt = ComboBox1.Text With Me 'assuming this is in the worksheet code module .Shapes("group_1").Visible = txt = "2021-2022" .Shapes("group_2").Visible = txt = "2022-2023" .Shapes("group_3").Visible = Len(txt) > 0 'any option selected End With End Sub
unknown
d4500
train
I found solution Append this script to admin panel This code adds a button for the ACF gallery field that fill the gallery with a predefined data. (function($){ setInterval(function() { let fields = acf.getFields({type:"gallery"}); for (let field of fields) { if (!field.dasupdated) { field.dasupdated = true; let control = $("<div><button class='button'>Append Attachment</button></div>"); control.find("button").click(()=>{ field.appendAttachment({attributes:{ id: 56060, url: "http://site.url/image.jpg" }}); }); $(field.$el[0]).find(".acf-gallery-main .acf-gallery-toolbar").append(control); } } }, 1000); })(jQuery);
unknown