id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_4700
sends user data with the GET parameter. I have a login and password for authorization, in return the server sends me a unique key. That is, after each successful authorization - the API key changes. Here is the instruction, but I don't understand how to set it up correctly in Postman to check. https://app.swaggerhub.com/apis-docs/pixel3655/democontent2.pi/1.0.0-oas3#/user/auth A: You need to send X-PI-EMAIL and X-PI-PASSWORD in the headers of the auth endpoint. Then in the Tests section of the auth endpoint you can inject the id into your environment variables. pm.environment.set("currentId", pm.response.json().result.id); and use it on the other API requests by adding a header of X-PI-KEY and a value of {{currentId}}.
doc_4701
My table has about 50 Million rows and I wish to sample 500,000 of those (i.e., 1%). It takes hours to do that. Do you have any idea how to make it more efficient, like using some C++ package (even though sample and [ already seems to both written in C)? The command I use so far: myTableSample <- myTable[sample(1:dim(myTable)[1], 500000, prob = prob_vector),] Thanks! A: Well, this would be much faster ind <- sample.int(dim(myTable)[1], 500000, prob = prob_vector) ind <- sort(ind) myTableSample <- myTable[ind, ] Before sorting you are doing completely random access. But after sorting it is much better in terms of cpu cache utility. Of course this is not yet the fastest. You can write this row subsetting in C, and it is (based on my previous experience) much faster than [?, ].
doc_4702
WebClient client = new WebClient(); String htmlCode = client.DownloadString("http://test.net"); I am able to use the agility pack to scan the html and get most of the tags that I need but its missing the html that is rendered by the javascript. My question is, how do I get the final rendered page source using c#. Is there something more to the WebClient to get the final rendered source after javascript is run? A: The HTML Agility Pack alone is not enough to do what you want, You need a javascript engine as well. To do that, you may want to check out something like Geckofx, which will allow you to embed a fully functional web browser into your application, and than allow you to programatically access the contents of the dom after the page has rendered. http://code.google.com/p/geckofx/ A: You need to wrap a browser in your application. You are in luck! There is a .NET wrapper for WebKit. http://webkitdotnet.sourceforge.net/ A: You can use the WebBrowser Class from System.Windows.Forms. using (WebBrowser wb = new WebBrowser()) { //Code here } https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser(v=vs.110).aspx
doc_4703
I was able to achieve the horizontal scroll in the website, but am struggling to add horizontal drag to scroll. If you're unsure of what that means, you simply drag the screen to move it horizontally. Here is an example. For some reason, the JS does not move the screen with dragging, but will move with screening as you can see in the reproducible example. My code: // script.js const slider = document.querySelector('.wrapper'); let isDown = false; let startX; let scrollLeft; slider.addEventListener('mousedown', (e) => { isDown = true; slider.classList.add('active'); startX = e.pageX - slider.offsetLeft; scrollLeft = slider.scrollLeft; }); slider.addEventListener('mouseleave', () => { isDown = false; slider.classList.remove('active'); }); slider.addEventListener('mouseup', () => { isDown = false; slider.classList.remove('active'); }); slider.addEventListener('mousemove', (e) => { if(!isDown) return; e.preventDefault(); const x = e.pageX - slider.offsetLeft; const walk = (x - startX) * 3; //scroll-fast slider.scrollLeft = scrollLeft - walk; console.log(walk); }); /* style.css */ .outer-wrapper { width: 100vh; height: 100vw; transform: rotate(-90deg) translateX(-100vh); transform-origin: top left; overflow-x: hidden; position: absolute; scrollbar-width: none; -ms-overflow-style: none; } .wrapper { display: flex; flex-direction: row; width: 400vw; transform: rotate(90deg) translateY(-100vh); transform-origin: top left; overflow: hidden; cursor: pointer; } .wrapper.active { cursor: grabbing; cursor: -webkit-grabbing; } .slide { width: 100vw; height: 100vh; } .one { background: #efdefe; } .two { background: #a3f3d3; } .three { background: #0bbaa0; } .four { background: #00dfdf; } ::-webkit-scrollbar { display:none; } <!-- index.html --> <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE-edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CodePen - GLTF Model Loading (.glb / .gltf)</title> <link rel="stylesheet" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body id="homePage"> <div class="outer-wrapper"> <div class="wrapper"> <div class="slide one"></div> <div class="slide two"></div> <div class="slide three"></div> <div class="slide four"></div> </div> </div> <script src="script.js"></script> </body> </html> A: Look like wrong variable you need select outer and scrollTop not scrollLeft You can follow this solition: var slider = document.querySelector('.wrapper'); var outer = document.querySelector('.outer-wrapper'); let isDown = false; let startX; let scrollLeft; slider.addEventListener('mousedown', (e) => { isDown = true; slider.classList.add('active'); startX = e.pageX - slider.offsetLeft; scrollLeft = slider.scrollLeft; outer.scrollTop = startX; }); slider.addEventListener('mouseleave', () => { isDown = false; slider.classList.remove('active'); }); slider.addEventListener('mouseup', () => { isDown = false; slider.classList.remove('active'); }); slider.addEventListener('mousemove', (e) => { if(!isDown) return; e.preventDefault(); const x = e.pageX - slider.offsetLeft; const walk = (x - startX) * 3; //scroll-fast slider.scrollLeft = scrollLeft - walk; slider.scrollLeft = startX; console.log(walk); outer.scrollTop = x; }); .outer-wrapper { width: 100vh; height: 100vw; transform: rotate(-90deg) translateX(-100vh); transform-origin: top left; overflow-x: hidden; position: absolute; } .wrapper { display: flex; flex-direction: row; width: 400vw; transform: rotate(90deg) translateY(-100vh); transform-origin: top left; overflow-x: hidden; cursor: pointer; } .wrapper.active { cursor: grabbing; cursor: -webkit-grabbing; } .slide { width: 100vw; height: 100vh; } .one { background: #efdefe; } .two { background: #a3f3d3; } .three { background: #0bbaa0; } .four { background: #00dfdf; } ::-webkit-scrollbar { display:none; } <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE-edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CodePen - GLTF Model Loading (.glb / .gltf)</title> <link rel="stylesheet" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body id="homePage"> <div class="outer-wrapper"> <div class="wrapper"> <div class="slide one"></div> <div class="slide two"></div> <div class="slide three"></div> <div class="slide four"></div> </div> </div> <script src="sliderScript.js"></script> </body> </html>
doc_4704
Here is my code. public interface IQueryExecuter { TReturn Execute<TReturn>(IQuery<TReturn> query); } public class QueryLoggingDecorator : IQueryExecuter { private ILogger _logger = NullLogger.Instance; public ILogger Logger { set { _logger = value; } } public TReturn Execute<TReturn>(IQuery<TReturn> query) { _logger.Info("Before query execute"); var queryResults = query.Execute(); _logger.Info("After query execute"); return queryResults; } } public class QueryTransactionDecorator : IQueryExecuter { public TReturn Execute<TReturn>(IQuery<TReturn> query) { try { Console.WriteLine("Beginning transaction"); var queryResults = query.Execute(); Console.WriteLine("Comitting transaction"); return queryResults; } catch (Exception) { Console.WriteLine("Rolling back transaction"); throw; } } } public interface IQuery<out TReturn> { TReturn Execute(); } public class Query : IQuery<string> { public string Execute() { Console.WriteLine("Executing query"); var queryResults = Path.GetRandomFileName(); return queryResults; } } And here is my Windsor registration code. public class DefaultInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Component .For<IQueryExecuter>() .ImplementedBy<QueryLoggingDecorator>() .LifestyleTransient()); container.Register(Component .For<IQueryExecuter>() .ImplementedBy<QueryTransactionDecorator>() .LifestyleTransient()); container.Register(Component .For<IQueryExecuter>() .ImplementedBy<QueryExecuter>() .LifestyleTransient()); } } And lastly, here is my calling code. var container = new WindsorContainer(); container.Install(FromAssembly.This()); var queryExecuter = container.Resolve<IQueryExecuter>(); var queryResults = queryExecuter.Execute(new Query()); What am I missing? I would expect that when I resolve IQueryExecuter that Windsor would decorate with QueryLoggingDecorator and then QueryTransactionDecorator. A: The problem is these aren't decorators; they're just different implementations of the same interface. Decorators need something to actually decorate, which is an instance of the same interface they're implementing, so they can call the next decorator in the chain. You need to set up an injectable reference to an IQueryExecuter. After that, Windsor handles the rest, injecting the decorator chain in the registered order (at least, according to the documentation). For example: public class QueryLoggingDecorator : IQueryExecuter { private ILogger _logger = NullLogger.Instance; private IQueryExecuter innerExecuter; public QueryLoggingDecorator(IQueryExecuter innerExecuter) { this.innerExecuter = innerExecuter; } public ILogger Logger { set { _logger = value; } } public TReturn Execute<TReturn>(IQuery<TReturn> query) { _logger.Info("Before query execute"); var queryResults = innerExecuter.Execute(query); _logger.Info("After query execute"); return queryResults; } } I will admit to not trying this out directly, but this blog indicated it would work.
doc_4705
A permission similar to this exists on Outlook, which has a permission called Non-editing author. Is the same available for Google Calendar? A: both the events.insert and the events.update / events.patch require the scope of https://www.googleapis.com/auth/calendar read/write access to Calendars Which technically gives a user access to read and write to any part of the calendar not just the events. Your application is going to have to limit access the calendar api does not give you this ability.
doc_4706
By reading a lot and going in to other stack overflow posts to check how pipe is supposed to work i have come up with this code that i will demonstrate for you guys. The function basically takes in a command that is should process. void runCommand(Command *cmd){ char **pl = cmd->pgm->pgmlist; int status; Pgm *p = cmd->pgm; //Count the number of pipes and create the right number of filedescriptors int numPipes = countPipes(cmd->pgm); int pipefds[2*numPipes]; //Pipe the file descriptors here and check if there was an error. for(int i = 0; i < (numPipes); i++){ if(pipe(pipefds + i*2) < 0) { perror("couldn't pipe"); exit(EXIT_FAILURE); } } pid_t pid, wpid; int fdr; int fd; int j = 0; while(p != NULL) { pid = fork(); if (pid == 0) { // Child process if (cmd->bakground == 1) // Check if it should be running in the background, if so, assign a new PID { setpgid(pid, 0); } // Check if RSTDOUT is on or not if(cmd->rstdout != NULL){ fd = open(cmd->rstdout, O_WRONLY | O_CREAT | O_TRUNC , S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR); //fclose(fopen(cmd->rstdout, "w")); printf("in first\n"); dup2(fd,1); close(fd); } // Check if RSTIN is on or not if(cmd->rstdin != NULL) { fdr = open(cmd->rstdin, O_RDONLY); printf("in second\n"); dup2(fdr, 0); close(fdr); } //if not last command if(p->next){ printf("in third\n"); if(dup2(pipefds[j + 1], 1) < 0){ perror("dup2"); exit(EXIT_FAILURE); } } //if not first command&& j!= 2*numPipes if(j != 0 ){ printf("in fourth: %d\n", j); if(dup2(pipefds[j-2], 0) < 0){ perror(" dup2");///j-2 0 j+1 1 exit(EXIT_FAILURE); } } for(int i = 0; i < 2*numPipes; i++){ printf("in fifth\n"); close(pipefds[i]); } j += 2; printf("%s\n",pl[0] ); if (execvp(pl[0], pl) == -1) { perror("lsh"); } exit(EXIT_FAILURE); } else if (pid < 0) { // Error forking perror("lsh"); } else if(cmd->bakground != 1){ // check in the parent process if it was running in background, if so dont call for wait() // Parent process j+=2; pl = p->pgmlist; p = p->next; for(int i = 0; i < 2 * numPipes; i++){ printf("in sixth\n"); close(pipefds[i]); } int returnStatus; waitpid(pid, &returnStatus, 0); // Parent process waits here for child to terminate. if (returnStatus == 0) // Verify child process terminated without error. { printf("The child process terminated normally."); } if (returnStatus == 1) { printf("The child process terminated with an error!."); } } else printf("Child process with ID %d is running in background\n",pid ); } } Normal commands still work fine however when i try to do this i get the following result. > ls | wc > dup2: Bad file descriptor As i read about it i think it means that i simply close to early or i am handling my file descriptors badly. I have tried to fix it but with no success i turn to you guys which might see something that i cant see. If you need any further information please just comment and i i will do my best to assist. ******EDIT 1****** I added printf to every dup2 or close that i used, naming them first, second , third etc just to know exactly in which dup or close that i get the error in . This was the result when i ran the command: > ls | wc in sixth in sixth in third in sixth in sixth in fourth: 2 dup2: Bad file descriptor So know we know where it fails at least. ******EDIT2****** i also added what filedescriptors we are writing or reading from or closing: In parent closing fd: 0 In parent closing fd: 1 in child third writing to fd: 1 In parent closing fd: 0 In parent closing fd: 1 in child fourth reading from fd: 0 dup2: Bad file descriptor A: I think that your problem with dup2 is here: if(cmd->rstdin != NULL) { fdr = open(cmd->rstdin, O_RDONLY); dup2(fd, 0); close(fdr); } you are opening "fdr" but then you use "fd" in dup2. "fd" is not open or already been closed inside a previous if {}. Moreover in both these conditionals you do not check the return value of dup2.
doc_4707
Is there any way we can lock the BB device with OS version 5.0 and later programmatically ? this qn here : How to programatically lock BLACKBERRY device(6.0)? is the same. But nobody has answered it yet; so Im posting it again. Thanks in advance.
doc_4708
<?php define('FACEBOOK_APP_ID', 'your_app_id'); define('FACEBOOK_SECRET', 'your_app_secret'); function parse_signed_request($signed_request, $secret) { list($encoded_sig, $payload) = explode('.', $signed_request, 2); // decode the data $sig = base64_url_decode($encoded_sig); $data = json_decode(base64_url_decode($payload), true); if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') { error_log('Unknown algorithm. Expected HMAC-SHA256'); return null; } // check sig $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true); if ($sig !== $expected_sig) { error_log('Bad Signed JSON signature!'); return null; } return $data; } function base64_url_decode($input) { return base64_decode(strtr($input, '-_', '+/')); } if ($_REQUEST) { echo '<p>signed_request contents:</p>'; $response = parse_signed_request($_REQUEST['signed_request'], FACEBOOK_SECRET); echo '<pre>'; print_r($response); echo '</pre>'; } else { echo '$_REQUEST is empty'; } ?> However, I got this error message Message: Undefined index: signed_request and I looked into $_REQUEST and I found only $_REQUEST['code'] rather than $_REQUEST['signed_request'], ref : facebookRegister/?code=AQBtVIDd-5MOklcFX0mRS_Pt1ht8svD6Soh_kNKiD8XG1QVPet6kVdVby7C8pDe1WwxBFIcqWDPVAEN1f4NBo_ZB5U1_19EV3bnYIGWv16Nok0IVWEXL4MYDB1p1VU2iEFq9NnH2TzFXXZQzEJWG5Jw9sTKAEK6GPpKdESaNiAkYBTZRl0qMv97O8HI1-Yu0PfI#= Anybody has idea whats wrong and highly appreciate for reply Thank you very much
doc_4709
Any idea what would be the proper selector for the following <!-- Get "Open Sans" font from Google --> ? Tried to match with Deface::Override.new(:virtual_path => 'spree/admin/shared/_head', :name => 'remove-googleapis', :remove => '!--') # this thows an exception Update (exception description): Nokogiri::CSS::SyntaxError unexpected '!' after '' A: Deface uses Nokogiri, which uses CSS selectors (with jQuery extensions). At the time of writing, there is no way to select a comment node using these selectors. There are several questions on SO looking for ways to select comment tags using jQuery, and most of them point to the comments plugin. So there is probably no way to do it through the Deface gem. If you really want to remove the comment nodes, you can look into using the sanitize gem, or using Nokogiri with xpath selectors. From an engineering POV, it's probably not worth the effort. Why are you trying to remove a harmless comment tag anyway?
doc_4710
My UserProfile model: class UserProfile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=255, null=True) profile_picture = models.CharField(max_length=1000, null=True) My Post model: class Post(models.Model): text = models.TextField(null=True) title = models.CharField(max_length=255, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ManyToManyField(User) My Post serializer: class PostSerializer(serializers.ModelSerializer): users = UserProfileSerializer(source='user.userprofile', many=True) class Meta: model = Post fields = ('id', 'text', 'title', 'users') With above serializer I am getting the following error: Got AttributeError when attempting to get a value for field `users` on serializer `WorkSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Work` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'userprofile'. EDIT: I created another serializer UserSerializerForPost which is used in PostSerializer: class UserSerializerForPost(serializers.ModelSerializer): user = UserProfileSerializer(source='userprofile') class Meta: model = User fields = ('user',) class PostSerializer(serializers.ModelSerializer): users = UserSerializerForPost(source='user', many=True) class Meta: model = Post fields = ('id', 'text', 'title', 'users') Though this works, but I am getting UserProfile response in a dictionary of user as users list: "users": [ { "user": { "id": 2, ... }, { "user": { "id": 4, ... } } ] But I want: "users": [ { "id": 2, ... }, { "id": 4, ... } } ], A: Following solution worked for me and it did not even require creating UserSerializerForPost: class PostSerializer(serializers.ModelSerializer): users = serializers.SerializerMethodField() class Meta: model = Post fields = ('id', 'text', 'title', 'users') def get_users(self, obj): response = [] for _user in obj.user.all(): user_profile = UserProfileSerializer( _user.userprofile, context={'request': self.context['request']}) response.append(user_profile.data) return response EDIT: Okay I found a even better approach than the above. First add a get_user_profiles to Post: class Post(models.Model): text = models.TextField(null=True) title = models.CharField(max_length=255, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ManyToManyField(User) def get_user_profiles(self): return UserProfile.objects.filter(user__post=self) Then I updated my PostSerializer with: class PostSerializer(serializers.ModelSerializer): users = UserProfileSerializer(source='get_user_profiles', many=True) class Meta: model = Post fields = ('id', 'text', 'title', 'users') This is way too cleaner version that earlier one.
doc_4711
* *How does it different from the PolicyRule we applied? *Should i keep ExistanceCondition almost same as PolicyRule? Policy rule i applied : "if":{ "allOf":[ { "field":"type", "equals":"Microsoft.Insights/metricalerts" }, { "field":"Microsoft.Insights/metricalerts/enabled", "equals":"true" }, { "field":"Microsoft.Insights/metricalerts/actions[*]", "less":"1" } ] } A: ExistenceCondition is the opposite of policyRule in terms of control direction. In policy rule you proceed only if the condition is true. in ExistenceCondition you proceed only if the condition is false. In the example below in policyRule you filter only the storageAccount then proceed. The deploy happens only if the condition is false (deleteRetentionPolicy.enabled ==false) so it proceeds and deploy. So once deploy is done, it will be deleteRetentionPolicy.enabled ==true "policyRule": { "if": { "allOf": [ { "field": "type", "equals": "Microsoft.Storage/storageAccounts" }, { "field": "kind", "in": [ "Storage", "StorageV2", "BlobStorage", "BlockBlobStorage" ] } ] }, "then": { "effect": "DeployIfNotExists", "details": { "type": "Microsoft.Storage/storageAccounts/blobServices", "existenceCondition": { "field": "Microsoft.Storage/storageAccounts/blobServices/default.deleteRetentionPolicy.enabled", "equals": true }, A: See this example: https://learn.microsoft.com/en-us/azure/governance/policy/samples/pattern-effect-details#sample-2-explanation "details": { "type": "Microsoft.Compute/virtualMachines/extensions", "existenceCondition": { "allOf": [{ "field": "Microsoft.Compute/virtualMachines/extensions/publisher", "equals": "[parameters('publisher')]" }, { "field": "Microsoft.Compute/virtualMachines/extensions/type", "equals": "[parameters('type')]" } ] } } The existenceCondition uses policy language elements, such as logical operators, to determine if a matching related resource exists. In this example, the values checked against each alias are defined in parameters. A: ExistenceCondition apply only to policy with effect AuditIfNotExists and DeployIfNotExists. In case of AuditIfNotExists "If any matching related resource evaluates to true, the effect is satisfied and doesn't trigger the audit." In case of DeployIfNotExists "If any matching related resource evaluates to true, the effect is satisfied and doesn't trigger the deployment." Existing resource which does not match ExistenceCondition will be marked as non-complaint. Resources filtered out by PolicyRule will not be marked as non-complaint.
doc_4712
A: CMS: Usually used when you are going to have multiple people editing content that know nothing about HTML and need a WYSIWYG to get things done. That being said, certain types of sites that are/need to be database driven for ease of organization usually run on some sort of CMS. FrameWork: Usually used for web applications as they usually have a ORM that makes managing data from a database very easy. Among many other reasons... (Built in security, user management, etc.) Custom Site: I usually do custom sites if I won't be getting any or very little data from a database and it isn't a traditional web application. I do this because it is usually faster. All that being said, you could use any of them for any purpose. It's the built in functionality that makes them better for different things. You question about building from ground up. I would say the more complex the more of a need for a framework. The simpler the site, the easier to write from scratch.
doc_4713
Thanks! A: A simple algorithm here isn't that complicated. Let's say you have a list of servers with the following weights: A 10 B 20 C 30 Where the higher weight represents it can handle more traffic. Just divide the amount of traffic sent to each server by the weight and sort smallest to largest. The server that comes out on top gets the user. for example, let's say each server starts at 10 users, then the order is going to be: C - 10 / 30 = 0.33 B - 10 / 20 = 0.50 A - 10 / 10 = 1.00 Which means the next 5 requests will go to server C. The 6th request will go to either C or B. The 7th will go to whichever one didn't handle the 6th. To complicate things, you might want the balancer to be more intelligent. In which case it needs to keep track of how many requests are currently being serviced by each of the servers and decrement them when the request is completely fulfilled. Further complications include adding stickiness to sessions. Which means the balancer has to inspect each request for the session id and keep track of where they went last time. On the whole, if you can just buy a product from a company that already does this. A: Tomcat's balancer app and the tutorial here serve as good starting points.
doc_4714
$acl->isAllowed("Guests", "Customers", "search"); This check if role called "Guest" can access "Customers" controller for action "search". In my scenario, we also have "Role Level", for example, Admin can access all modules and controllers, but, to modify the contents, an Admin should have minimum Role Level 2. To gain access to modifying website configuration, an Admin should have Role Level 3. In addition to role level, we also want to assign which models a role can have access to. For example, Mr. A and Mr. B both are Admins and have same levels. But, we decided only to allow Mr. A to access "Accounts" models while Mr. B can have access to "Accounts", "Personnel", etc. Here are my questions : * *Does phalcon ACL support roles and levels ? Or, should I just create the custom validation? *What is the benefit of using ACL compared to creating similar validation functions? *If I have to create custom validation, where should I put it ? In the controller, or in the dispatcher ? Thx A: At the moment Phalcon does not support Role based ACLs. You will have to do something yourself to cover this. The feature has however been asked for and it is in the long list of NFRs for the project :) The way I would go about it is use a combination of Phalcon functionality and custom programming. I would add everything to a base controller in the beforeExecuteRoute function so that whenever something is to be dispatched ACL is checked. In a similar project to yours, I created two tables in my database: Groups ------ group_id <- 2 group_name <- Admins and have an ACL table that maps all actions to a group like so ACL --- group_id <- 2 acl_controller <- Customers acl_action <- Search You can easily extend this to have a collection of controller/action pairs to map to a Role. From there you can just create a simple function that would load the role based resources. It is a bit of a workaround but it works.
doc_4715
minifyEnabled true shrinkResources true I have been trying various (failed attempts) at modifying the answers given in the link, but I have not had any luck. Given my object looks as follows: data class EmojiType( @SerializeNull var value: String? ) When I create a post request and pass null, I expect my object to look as follows: { "value":null } However, as mentioned, when minifyEnabled and shrinkResources are set to true, my object ends up looking like this: { "a":null } How can I avoid this and retain the field name of value? A: I faced a similar issue with Gson, where specifying the SerializedName got it to work: data class EmojiType( @SerializedName("value") var value: String? )
doc_4716
This works just fine during local testing. The appsettings.json is transformed and copied to the output directory. However, for deploying to Azure you don't want to publish any appsettings.json files (as the values will be read from the App Service's configuration), and seeing as the file is actually copied to the output directory it seems to follow that it would also be copied to Azure. How can I use the SlowCheetah transforms locally, while at the same time not deploying them to Azure?
doc_4717
class Owner(db.Model): name = db.StringProperty() age = db.IntegerProperty() class Pet(db.Model): name = db.StringProperty() owner = db.ReferenceProperty(Owner) and that some owners have no pets, how best to extract all owners who have a pet, ordered by owner age? I'm aware that JOINS are not possible, so it seems likely that there will be two queries. I have tried to extract all owner keys from Pets and then have done an 'IN' query with the keys but I hit the maximum 30 subqueries limitation. A: I would add an additional property or two to the Owner class. Define a boolean field owns_pets (or similiar) which you set to True when you add a pet, then select all Owners where owns_pets == True, ordered by Age, then fetch the pets for each Owner using the reverse set. Alternately add a ListProperty pets containing all the keys of the owned Pets. Then query for all owners (again easier with the boolean above) and then db.get(some_owner.pets) Without either of these you have a couple of less easy ways. loop through the set of owners in Age order, fetch reverse reference set (in your case pet_set) skipping owners where pet_set returns nothing. Other ways include fetching all pets, collecting the keys of the owners (in a set, removing duplicates) and then db.get(list of owner keys), then order them after the fact in code - not as efficient if you have a lot or possibly not doable (memory/time).) If you want to use this path, have a look at nick johnson prefetch reference set code http://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App-Engine Really the best bet is start storing redundant data at write time, that makes often used queries less expensive to perform.
doc_4718
( - open brace a - variable + - addition b - variable ) - close brace * - multiplication c - variable - - subtraction d - variable * - multiplication 0,5 - constant number Now, here is my class: class wz_formula(osv.osv_memory): """ Formula Wizard """ _name = "wz.formula" _inherit = "ir.wizard.screen" _description = "Formula Wizard" _columns = { 'name': fields.char('Formula name', required=True, size=64) , 'expression': fields.char('expression', required=True, size=64) , 'state': fields.selection([('init','init'),('done','done')], 'state', readonly=True) } _defaults = { 'state': 'init' } def next(self, cr, uid, ids, context=None): if context is None: context = {} formula_obj = self.browse(cr, uid, ids)[0] formula_name = formula_obj.name infix = formula_obj.expression if formula_name and expression: modobj = self.pool.get('ir.module.module') mids = modobj.search(cr, uid, [('state', '=', 'installed')]) modobj.update_translations(cr, uid, mids, [formula_name, expression], context or {}) self.write(cr, uid, ids, {'state': 'done'}, context=context) return { 'name': _('Formula') , 'view_type': 'form' , 'view_mode': 'form' , 'view_id': False , 'res_model': 'wz.formula' , 'domain': [] , 'context': dict(context, active_ids=ids) , 'type': 'ir.actions.act_window' , 'target': 'new' , 'res_id': ids and ids[0] or False } # create an object wz_formula() Here is my xml: <?xml version="1.0" encoding="utf-8"?> <openerp> <data> <record id="view_wz_formula" model="ir.ui.view"> <field name="name">Formula</field> <field name="model">wz.formula</field> <field name="type">form</field> <field name="arch" type="xml"> <form string="Formula"> <group colspan="8" col="8" states="init"> <separator string="Formula" colspan="8"/> <field name="state" invisible="1"/> <field name="name"/> <field name="expression" width="220"/> <button special="cancel" string="Cancel" icon="gtk-cancel" colspan="1"/> <button name="next" string="Next" type="object" icon="gtk-ok" colspan="1"/> </group> <group colspan="8" col="8" states="done"> <separator string="Done" colspan="8"/> <button special="cancel" string="Close" icon="gtk-cancel"/> </group> </form> </field> </record> <record id="action_view_wz_formula" model="ir.actions.act_window"> <field name="name">Formula</field> <field name="type">ir.actions.act_window</field> <field name="res_model">wz.formula</field> <field name="view_type">form</field> <field name="view_mode">form</field> <field name="target">new</field> </record> <menuitem name="Create a formula" action="action_view_wz_formula" id="menu_view_wz_formula" parent="menu_fs_root" sequence="2"/> </data> </openerp> So far, it just switches between Form1 and Form2. How can I extract the expression as I explained above? A: To add a dynamic view in openerp v6, override the function fields_view_get() def fields_view_get(self, cr, uid, view_id=None, view_type='form', context={}, toolbar=False): result = super(<your_class_name>, self).fields_view_get(cr, uid, view_id, view_type, context=context, toolbar=toolbar) # your modification in the view # result['fields'] will give you the fields. modify it if needed # result['arch'] will give you the xml architecture. modify it if needed return result result will be a dictionary which contain mainly two things, Xml architecture and fields. Provide the xml architecture in result['arch'] as string, provide the fields in result['fields'] as dictionary of dictionaries. Then return the result. Then you will get a view according to what you have given in the fields and architecure. A: a simpler way would be... first get the expression from first form (FORM 1),and evaluate it as per your choice, and keep a "TEXT" field in second form which has this data in as per your format in that field.. A: I'm not sure exactly what you're asking, but if you just want to parse the user's expression, then this question on Python expression parsers should be helpful.
doc_4719
Case #2 generates the same results of the code running on CPU only. Case #1 #pragma acc parallel loop for (j = jbeg; j <= jend; j++){ #pragma acc loop for (i = ibeg; i <= iend; i++){ double Rc[NFLX][NFLX]; double eta[NFLX], um[NFLX], dv[NFLX]; double lambda[NFLX], alambda[NFLX]; double fL[NFLX], fR[NFLX]; . . . } }} Case #2 #pragma acc parallel loop for (j = jbeg; j <= jend; j++){ double Rc[NFLX][NFLX]; double eta[NFLX], um[NFLX], dv[NFLX]; double lambda[NFLX], alambda[NFLX]; double fL[NFLX], fR[NFLX]; #pragma acc loop private(Rc[:NFLX][:NFLX], eta[:NFLX], \ um[:NFLX], lambda[:NFLX], alambda[:NFLX], \ dv[:NFLX], fL[:NFLX], fR[:NFLX]) for (i = ibeg; i <= iend; i++){ . . . } }} I have the following values: NFLX = 8; jbeg = 3, jend = 258; ibeg = 3, iend = 1026; In which cases the two techniques are equivalent and when it is better to choose one over the other? This is what I see with -Minfo=accel: case #1: 71, Local memory used for Rc,dv,fR,um,lambda,alambda,fL,eta case #2: 71, Local memory used for Rc,dv,fR,lambda,alambda,fL,eta CUDA shared memory used for Rc,eta Local memory used for um CUDA shared memory used for um,lambda,alambda,dv,fL,fR function: /* ********************************************************************* */ void Roe_Solver (Data *d, timeStep *Dts, Grid *grid, RBox *box) /* * Solve the Riemann problem between L/R states using a * Rusanov-Lax Friedrichs flux. *********************************************************************** */ { int i, j, k; int ibeg = *(box->nbeg)-1, iend = *(box->nend); int jbeg = *(box->tbeg), jend = *(box->tend); int kbeg = *(box->bbeg), kend = *(box->bend); int VXn = VX1, VXt = VX2, VXb = VX3; int MXn = MX1, MXt = MX2, MXb = MX3; int ni, nj; double gmm = GAMMA_EOS; double gmm1 = gmm - 1.0; double gmm1_inv = 1.0/gmm1; double delta = 1.e-7; double delta_inv = 1.0/delta; ARRAY_OFFSET (grid, ni, nj); INDEX_CYCLE (grid->dir, VXn, VXt, VXb); INDEX_CYCLE (grid->dir, MXn, MXt, MXb); #pragma acc parallel loop collapse(2) present(d, Dts, grid) for (k = kbeg; k <= kend; k++){ for (j = jbeg; j <= jend; j++){ long int offset = ni*(j + nj*k); double * __restrict__ cmax = &Dts->cmax [offset]; double * __restrict__ SL = &d->sweep.SL [offset]; double * __restrict__ SR = &d->sweep.SR [offset]; double um[NFLX]; double fL[NFLX], fR[NFLX]; #pragma acc loop private(um[:NFLX], fL[:NFLX], fR[:NFLX]) for (i = ibeg; i <= iend; i++){ int nv; double scrh, vel2; double a2, a, h; double alambda, lambda, eta; double s, c, hl, hr; double bmin, bmax, scrh1; double pL, pR; double * __restrict__ vL = d->sweep.vL [offset + i]; double * __restrict__ vR = d->sweep.vR [offset + i]; double * __restrict__ uL = d->sweep.uL [offset + i]; double * __restrict__ uR = d->sweep.uR [offset + i]; double * __restrict__ flux = d->sweep.flux[offset + i]; double a2L = SoundSpeed2 (vL); double a2R = SoundSpeed2 (vR); PrimToCons (vL, uL); PrimToCons (vR, uR); Flux (vL, uL, fL, grid->dir); Flux (vR, uR, fR, grid->dir); pL = vL[PRS]; pR = vR[PRS]; s = sqrt(vR[RHO]/vL[RHO]); um[RHO] = vL[RHO]*s; s = 1.0/(1.0 + s); c = 1.0 - s; um[VX1] = s*vL[VX1] + c*vR[VX1]; um[VX2] = s*vL[VX2] + c*vR[VX2]; um[VX3] = s*vL[VX3] + c*vR[VX3]; vel2 = um[VX1]*um[VX1] + um[VX2]*um[VX2] + um[VX3]*um[VX3]; hl = 0.5*(vL[VX1]*vL[VX1] + vL[VX2]*vL[VX2] + vL[VX3]*vL[VX3]); hl += a2L*gmm1_inv; hr = 0.5*(vR[VX1]*vR[VX1] + vR[VX2]*vR[VX2] + vR[VX3]*vR[VX3]); hr += a2R*gmm1_inv; h = s*hl + c*hr; /* ---------------------------------------------------- 1. the following should be equivalent to scrh = dv[VX1]*dv[VX1] + dv[VX2]*dv[VX2] + dv[VX3]*dv[VX3]; a2 = s*a2L + c*a2R + 0.5*gmm1*s*c*scrh; and therefore always positive. ---------------------------------------------------- */ a2 = gmm1*(h - 0.5*vel2); a = sqrt(a2); /* ---------------------------------------------------------------- 2. define non-zero components of conservative eigenvectors Rc, eigenvalues (lambda) and wave strenght eta = L.du ---------------------------------------------------------------- */ #pragma acc loop seq NFLX_LOOP(nv) flux[nv] = 0.5*(fL[nv] + fR[nv]); /* ---- (u - c_s) ---- */ SL[i] = um[VXn] - a; /* ---- (u + c_s) ---- */ SR[i] = um[VXn] + a; /* ---- get max eigenvalue ---- */ cmax[i] = fabs(um[VXn]) + a; NFLX_LOOP(nv) flux[nv] = 0.5*(fL[nv] + fR[nv]) - 0.5*cmax[i]*(uR[nv] - uL[nv]); #if DIMENSIONS > 1 /* --------------------------------------------- 3. use the HLL flux function if the interface lies within a strong shock. The effect of this switch is visible in the Mach reflection test. --------------------------------------------- */ scrh = fabs(vL[PRS] - vR[PRS]); scrh /= MIN(vL[PRS],vR[PRS]); if (scrh > 0.5 && (vR[VXn] < vL[VXn])){ /* -- tunable parameter -- */ bmin = MIN(0.0, SL[i]); bmax = MAX(0.0, SR[i]); scrh1 = 1.0/(bmax - bmin); #pragma acc loop seq for (nv = 0; nv < NFLX; nv++){ flux[nv] = bmin*bmax*(uR[nv] - uL[nv]) + bmax*fL[nv] - bmin*fR[nv]; flux[nv] *= scrh1; } } #endif /* DIMENSIONS > 1 */ } /* End loop on i */ }} /* End loop on j,k */ } A: Technically they are equivalent, but in practice different. What's happening is that the compiler will hoist the declaration of these arrays outside of the loops. This is standard practice for the compiler and happens before the OpenACC directives are applied. What should happen is that then these arrays are implicitly privatized within the scoping unit they are declared. However the compiler doesn't currently track this so the arrays are implicitly copied into the compute region as shared arrays. If you add the flag "-Minfo=accel", you'll see the compiler feedback messages indicating the implicit copies. I have an open issue report requesting this support, TPR #31360, however it's been a challenge to implement so not in a released compiler as of yet. Hence until/if we can fix the behavior, you'll need to manually hoist the declaration of these arrays and then add them to a "private" clause.
doc_4720
This never happened before. Could it be a bug ? A: Click on any field of the rows that were returned, then hit CTRL+END to retrieve the reset of the rows... that is how I have always done it. EDIT: could also be your preferences Tools -> Preferences Expand Database click on Advanced update the SQL Array Fetch Value (MAX = 500)
doc_4721
I have been working on a relatively simple cross platform python app. This app works correctly in Windows 10/11 and Linux Mint but not in MacOS, Big Sur. The app uses matplotlib + tkinter to display an animated chart, updated every 1 second, with live data yanked from the OS (wireless signal strength) I have used the following commands code to suppress any X-axis labeling- ax.tick_params(reset=True) ax.tick_params('y', left=False, right=False, bottom=False, labelsize=8) ax.tick_params('x', labelbottom=False, bottom=False, top=False) This code properly ensures no data is displayed on x-axis (as expected) on Windows 10, 11, Linux Mint, BUT on MacOS Big Sur (11.7) it displays the latest/newest x-axis, x value on the extreme rhs of the chart, basically only labeling the newest data value of the x-axis. See image below, the number in the red dashed rectangle shouldn't display. Interestingly I was able to recreate the same issue for all OS's by changing the above lines to the following code: ax.tick_params('x', labelbottom=False, bottom=False,reset=True) ax.tick_params('y', left=False, right=False, bottom=False, labelsize=8) PS I did see the issue with macos backends and using the framework version, my understanding is that I am using the Macos "framework version": pythonw on the macos installed thru anaconda A: It looks a lot like an offset rather than the newest value to me. Have you tried to ax.xaxis.get_major_formatter().set_useOffset(False) Just to see if it changes something (or even solve the problem)? Another thing you could try, in case it is really a label, not an offset, is to specify a formatter import matplotlib.ticker as ticker ax.xaxis.set_major_formatter(ticker.NullFormatter()) or ax.xaxis.set_major_formatter(ticker.FormatStrFormatter("tick")) This last one, is a test to check if this is really ticks. If you only see "tick", you can try to solve the problem (bypass it, rather) by ax.xaxis.set_major_formatter(ticker.FormatStrFormatter(" ")) (Tho, if this works, then NullFormatter should have work either. But, hard to say what works in a situation where none of that should have been necessary anyway)
doc_4722
But in my app setting, I'm having new option as "Send crash reports" switch. So if the user toggle off the switch in setting page, It should block the Crashlytics report from being send to its server. But i'm not seeing any option in the Crashlytics framework to block the reports or even stop the Crashlytics from running. Is there any way to block the reports or stop the Crashlytics from running? A: Once the setting changes, you can make sure Crashlytics is not enabled once the app restarts. In your app delegate, you can check for the setting and then enable Crashlytics. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //Crashlytics //Check setting if ([[NSUserDefaults standardUserDefaults] boolForKey: @"CanSendCrashReports"]) { [Fabric with:@[[Crashlytics class]]]; } }
doc_4723
Cache-control : private xxxx Cache-control : no-cache, no-store I am not clear on which value the browser will consider. I think browser will take the first Cache-control value or will it consolidate all Cache-control values? Even if it consolidate all Cache-control values then which one it will consider? Can anyone help in making this point clear
doc_4724
./ffmpeg -i ./clip11.mp4 -i ./clip21.mp4 -i ./clip31.mp4 -i ./clip41.mp4 -filter_complex "[0:v][1:v]hstack=inputs=2[top];[2:v][3:v]hstack=inputs=2[bottom];[top][bottom]vstack=inputs=2[v];amerge=inputs=4[a]" -map[v] -map[a] ./split21.mp4 I try tried and run the code, but it shows this as an error. zsh: no matches found: -map[v] I don't know whether my machine cannot configure the "map" because it happens the same thing when I tried to do "concat". I do not know what else to change about. I typed it out on the latest Mac, but surprisingly my friend that have an older version of Mac got the code working. Help. A: Looks like it's zsh that complains that a file pattern is not matching any file. Try to add a space and put quotes around the patterns like this -map "[v]" -map "[a]" to no expand them. A: You are missing some spaces to separate the option from the value. Use -map "[v]" -map "[a]". The quotes are not necessary in this case but will allow you to use spaces in your label names if desired.
doc_4725
values: [Number] }); SampleModelSchema.methods.addValue = function(value){ this.values.push(value); return this.save(); }; var SampleModel = mongoose.model('SampleModel', SampleModelSchema); I want to add a method addValue to my mongoose schema. I'm facing a dilemma here. I can either put 'this.save()' in the method itself, or I can let the caller of this method call save. If someone is using this model, I don't want them to have to remember to call save. But the implementation as is is really bad if this method is called in a loop. for(var k=0;k<10;k++){ mySampleModel.addValue(k); } This will call save 10 times, which is bad for performance. Is it best practice to never put save() in a method that can be called multiple times in a row and delegate the responsibility of saving to the caller? Thanks!
doc_4726
The name function returns a string containing a QName representing the expanded-name of the node in the argument node-set that is first in document order. The QName must represent the expanded-name with respect to the namespace declarations in effect on the node whose expanded-name is being represented. Typically, this will be the QName that occurred in the XML source. This need not be the case if there are namespace declarations in effect on the node that associate multiple prefixes with the same namespace. However, an implementation may include information about the original prefix in its representation of nodes; in this case, an implementation can ensure that the returned string is always the same as the QName used in the XML source. If the argument node-set is empty or the first node has no expanded-name, an empty string is returned. If the argument it omitted, it defaults to a node-set with the context node as its only member. But it's hard for me to understand what that is, and when clicking the links, it seems to give a "syntax/grammar" definition but not really one that would 'make sense' to me (i.e., be explainable to me and not just "Oh it represents those characters to a parser"). What would be a definition of these and an example for each? A: The need for NCName vs QName arises to support XML Namespaces. NCName A Non-Colonized NAME can contain any characters allowed in an XML Name except a colon, : : NCName ::= Name - (Char* ':' Char*) Example: p is an NCName, where <p> might be a paragraph start tag. The motivation for defining a name that cannot contain a : is to reserve : as a separator between XML namespace prefixes and the rest of the name, known as the local part. Which brings us to QName... QName A Qualified NAME may (but need not) have a namespace prefix separated from a local part by a :: QName ::= PrefixedName | UnprefixedName PrefixedName ::= Prefix ':' LocalPart UnprefixedName ::= LocalPart Prefix ::= NCName LocalPart ::= NCName Example: w:p is a QName, and <w:p> is a paragraph tag in OOXML, where w is a namespace prefix declared as xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main". See also * *What does the XML syntax with a colon mean? *Is it possible to have multiple namespace prefixes in XML? *Is a colon a legal first character in an XML tag name? *How does XPath deal with XML namespaces?
doc_4727
I understand that Simian and Munki are used to deploy and monitor software. What would building a deployment, for example, Google Chrome look like?
doc_4728
I assume my convention will consistently be <ResultName>Formatter. Is this a good case for Convention Over Configuration, and if so, what would that look like in Prism (if Prism matters to this question). Thanks. A: I'm not sure where Prism fits into this, unless the Result-Formatter pair are something Prism-specific. Beyond that, I think this is a fine case for convention-over-configuration, because you could create any number of result types and formatters without having to add them to any mapping or configuration classes/files. As the creator of this convention and API, however, the onus falls to you to implement and support the convention. Assuming that you will reflectively discover formatters capable of handling results, will this be done upon first request or application start? How will you cache the mappings? A big part of convention-over-configuration is taking decision-making off the shoulders of the end developer in favour of reasonable defaults and a standard to which they can adhere, but that means that the decisions fall to you and the level of override granularity that you provide must be determined. For example, can a consumer of this API have formatters defined in more than one assembly (this might be a Prism-relevant consideration)? If so, how are those assemblies specified? Can a consumer deviate from the convention and map differently-named formatters to result types? It sounds like this is an API that only you will consume, so much of this is moot, but these are just some considerations that would apply generally. A: Nope this looks more like consistent naming to me. This is important too to have a "discoverable API", where you can find things easily. Convention over configuration is where parts of your application hook up/work as expected if they follow a specific convention. e.g. Rails expects your Model, View and Controller to be in specific folder and with specific names. As long as you follow this convention, the framework auto-magically finds and wires them together. That doesn't mean that you "must" follow it always. There is also an option to override the default behavior but that would require you to add some stuff to some configuration/mapping file / write some code somewhere. Convention over configuration helps to keep the 80% scenario simple and quick.
doc_4729
A: UPDATE: Based on additional information this is not the correct answer!!! As pointed out, @Value can be private, but Micronaut advices against it. Short answer, it is because it is private. Wrong From the documentation: The @Value annotation accepts a string that can have embedded placeholder values (the default value can be provided by specifying a value after the colon : character). Also try to avoid setting the member visibility to private, since this requires Micronaut Framework to use reflection. Prefer to use protected. Also, consider using @Property instead of @Value. Still valid https://docs.micronaut.io/latest/guide/#valueAnnotation NOTE: The Micronaut framework does not inspect a manually created instance, even if it is instantiated in a @Factory, unlike other frameworks. A: In a comment the OP has indicated that they are doing new FeatureToggleService(). Creating your own instance of the object is the problem. Instead of using new, let the DI container create and manage the instance. If you do, then @Value will be relevant. See https://github.com/jeffbrown/filiard/blob/f6f704fb95d7821919748bb41968f87d11cee07b/src/main/java/filiard/DemoController.java and https://github.com/jeffbrown/filiard/blob/f6f704fb95d7821919748bb41968f87d11cee07b/src/main/java/filiard/FlagHelper.java for a working example.
doc_4730
A: The PostAuthenticateRequest occurs before the AcquireRequestState and the session state should only be available after this event is raised, so if you need to access session state for the request you need to wait for that event. See this page as a reference. * *... *Raise the PostAuthenticateRequest event. *... *Raise the AcquireRequestState event. *...
doc_4731
I have tried different versions of the code including: form.form p.submit input a:hover { background-color:E8E8E8; and form.form p.submit input:hover { background-color:E8E8E8; <style type="text/css"> form.form input.text, form.form textarea.standard, form.form select, form.form input.date { background-color:#FFFFFF; border:solid 1px #00BCF1; font-size:16px; color:#000000; width:550px; -moz-border-radius:px; -webkit-border-radius:px; border-radius:15px; padding-top:5px; padding-bottom:5px; padding-left:5px; padding-right:5px; } form.form p label { font-size:14px; color:#FFFFFF; font-weight:normal; padding-top:15px; padding-bottom:5px; } form.form p.submit input { background-color:#B2D235; border:solid 1px #00BCF1; font-size:16px; color:#003c71; font-weight:bold; padding-top:15px; padding-bottom:15px; padding-right:25px; padding-left:25px; -moz-border-radius:0px; -webkit-border-radius:0px; border-radius:30px; } form.form p.submit input a:hover { background-color:E8E8E8; } form.form p.submit { margin-top:40px; margin-bottom:0px; text-align:left; } form.form p.required label, form.form span.required label { background:none !important; font-weight:bold; } form.form p.required label.field-label:after { content:"*"; color: #FFFFFF; } </style> I would like to have the button change color but I can't seem to make that happen. A: One thing i immediately notice is that you didnt put a "#" in front of the hex code. So it should look something like this instead form.form p.submit input a:hover { background-color:#E8E8E8 } Aside from that, seeing your associated HTML could help A: You can try this, <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .btn { background-color: #ddd; border: none; color: black; padding: 16px 32px; text-align: center; font-size: 16px; margin: 4px 2px; transition: 0.3s; } .btn:hover { background-color: #3e8e41; color: white; } </style> </head> <body> <h2>Fading Buttons - "Fade in Effect"</h2> <button class="btn">Hover Over Me</button> </body> </html> A: By the Way you are missing # before the color code color:#E8E8E8 form.form p.submit input a:hover { background-color:E8E8E8; You can find the answer on the link: https://www.w3schools.com/css/css3_buttons.asp
doc_4732
sample dB b_id b_name 1 Huston 15 Berlin 06 Rio here when i enter the first b_id the output is Huston. the second one automatically calls Huston and third before i can enter the 2nd digit the code yells the else statement. private void textBox1_TextChanged(object sender, EventArgs e) { .........c#.... SqlDataReader reader; con.Open(); SqlCommand cmd = new SqlCommand("Select b_id,b_name from branches where b_id=@b_id", con); cmd.Parameters.AddWithValue("b_id", textBox1.Text); reader = cmd.ExecuteReader(); try { if(reader.Read()) { label2.Text = reader["b_name"].ToString(); } else { MessageBox.Show("No data was found in this ID"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } A: You can re-write your if-else like below : if(reader.Read()) label2.Text = reader["b_name"].ToString(); else label2.Text = "No data found!"; Hitting the database each time you type a char in the textbox is not a good idea. A better approach could be what @Oliver suggested or if the table branches is not so big, load all the data into a datatable and search in it from your textchange event.
doc_4733
train_data = LngDataset(zipfile.Path(archive, "train/train/")) test_data = LngDataset(zipfile.Path(archive, "test/test/")) train_loader = data.DataLoader(train_data, batch_size=32, shuffle=True) test_loader = data.DataLoader(test_data, batch_size=32, shuffle=True) archive is a zipfile which has two folders train and test. The LngDataset() function: class LngDataset(data.Dataset): def __init__(self, root): super().__init__() self.items = list(root.iterdir()) def __getitem__(self, index): item = self.items[index] if item.name.startswith("de_"): y = 0 elif item.name.startswith("en_"): y = 1 elif item.name.startswith("es_"): y = 2 else: raise ValueError(f"Unable to determine label for: {item.name}") signal, sample_rate = soundfile.read(item.open("r")) X = fbanks(signal, sample_rate).astype(np.float32) X = X[np.newaxis, ...] return X, y def __len__(self): return len(self.items) I checked the documentation of zipfile. The Path attribute exists. So I dont understand how I can solve this issue.
doc_4734
django.db.utils.ProgrammingError: relation "cms_cmsplugin" already exists Does anyone understand what is wrong and can help with that? Thanks. I have tried some solution propositions on other titles but none worked. did --fake-initial, tried migrating commenting out all other plugins of cms etc but none worked. A: I can only give little advice on your specific error: The table cms_cmsplugin" is already existing. But I guess you can read errors...starting with a fresh db could be a solution (restarting the upgrade process, with the orignal db from before the upgrade). I can give some general advice for upgrading django/django-cms projects. Key point for me always was: make it reproducable. So you can try things, but also start over again, without much of an effort. I for myself once made a tool for this purpose: project-updater. I normaly had scripts to automatically reset db and media files and git tag to the starting point of my upgrade, then execute steps required up to where I was currently stuck, and from there move on...wether using project updater, your own workflow, or another tool is not of that importance...
doc_4735
I need to study it but didnot find any example about it A: According to TDeBailleul's comment, this is a good place for you to start. I think that it's detailed enough: http://docs.sencha.com/touch/2-0/#!/api/Ext.data.proxy.Rest About REST vs JSONP. Essentially, REST is a specific type of Ajax. JSONP is actually Cross-domain AJAX. They are not the same in essence. A: Here's one for ExtJS - the data package is very similar between touch and extjs. http://try.sencha.com/extjs/4.0.7/examples/restful/restful/
doc_4736
'AAA' : [1, 2, 3], 'BBB' : [4, 5, 6] } I have an object that looks like this but I need to convert it into an array of array that looks like: arr = [['AAA', 'BBB'], [1, 4], [2, 5], [3, 6]] To be pass-able to the excel library that I am using. What is a good way to convert the format like that in Javascript? A: You could take the keys of the object and then take a nested approach for the outer iteration of the keys and for the inner iteration of the values. Then assign a new array, if not given and take the index of the outer array for assigning the value. Later concat the result with the keys as first array. var object = { AAA : [1, 2, 3], BBB : [4, 5, 6, 8] }, keys = Object.keys(object), array = [keys].concat(keys.reduce((r, k, j) => { object[k].forEach((v, i) => (r[i] = r[i] || [])[j] = v); return r; }, [])); console.log(array); .as-console-wrapper { max-height: 100% !important; top: 0; } A: Solution for given scenario: const objj = { 'AAA' : [1, 2, 3], 'BBB' : [4, 5, 6] } const getFormattedArray = (objJ) => { const formatted = [] const keys = Object.keys(objJ) const values = Object.values(objJ) const [val1, val2] = [...values] formatted.push(keys) getFormattedChild(val1, val2).forEach(item => { formatted.push(item) }) return formatted } const getFormattedChild = (a, b) => { let blob = [] for (let i = 0; i < a.length; i++){ let derp = [] derp.push(a[i]) derp.push(b[i]) blob.push(derp) } return blob } const result = getFormattedArray(objj) console.log('result: \n', result) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> Solution, If AAA and BBB have different array values: const objj = { 'AAA' : [1, 2, 3, null], 'BBB' : [4, 5, 6, 7, 8] } const getFormattedArray = (objJ) => { const formatted = [] const keys = Object.keys(objJ) const values = Object.values(objJ) const [val1, val2] = [...values] formatted.push(keys) getFormattedChild(val1, val2).forEach(item => { formatted.push(item) }) return formatted } const getFormattedChild = (a, b) => { let blob = [] const aLength = a.length const bLength = b.length const upperLimit = (aLength <= bLength) ? bLength : aLength for (let i = 0; i < upperLimit; i++){ let derp = [] derp.push(a[i]) derp.push(b[i]) blob.push(derp) } return blob } const result = getFormattedArray(objj) console.log('result: \n', result) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> A: Here's a way to do it succinctly in one line, based on a solution here: const arr = [Object.keys(object), Object.values(object)[0].map((col, i) => Object.values(object).map(row => row[i]))]; var object = { 'AAA' : [1, 2, 3], 'BBB' : [4, 5, 6] }; const arr = [Object.keys(object), Object.values(object)[0].map((col, i) => Object.values(object).map(row => row[i]))]; console.log(arr); A: var obj = { 'AAA' : [1, 2, 3], 'BBB' : [4, 5, 6] }; const result = [Object.keys(obj)]; result.concat(obj[Object.keys(obj)[0]].reduce((acc, ele, i)=>{ acc.push([ele,obj[Object.keys(obj)[1]][i]]); return acc; },[])); Output: [ [ 'AAA', 'BBB' ], [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
doc_4737
@Path("/api") @Api("My API") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class MyResource { public MyResource() { // assign some values in teh constructor } @POST @Timed @UnitOfWork @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation( value = "", response = Response.class) @ApiResponses( value = {@ApiResponse(code = 405, message = "Method not allowed"), @ApiResponse(code = 400, message = "some custom mesage")}) public Response createMyObject(MyObject o, @Context UriInfo uriInfo) throws JsonProcessingException { } And I am trying to unit test it using this @Test public void testCreate() throws JsonProcessingException { Entity<?> entity = Entity.entity(myObjInstance, MediaType.APPLICATION_JSON_TYPE); final Response response = resources.target("/api").request().post(entity); } This gives me a 404, I have verified that the resource is correctly registered. Also the GET methods in this resource work as expected. What am I doing wrong?
doc_4738
I have a express route, that needs to take in 2 values img_url, and image title. const img = new Image({ img_url:result.url, image_title:req.body.image_title }); Currently, i am able to post the img_url from react to express, however im having troubles posting the image_title. So to make it work for now, i'm making image_title:null I am using react-images-upload to pass in the file And doing this alone, passes in the img_url to the express route, handleUpload = file => { const data = new FormData() const image = file[0] console.log(this.state.image_title) // debugger; data.append('ourImage',image) data.append('image_title', this.state.image_title) Axios.post('/images/upload', data).then((response) => { console.log(response); this.setState({ image_url:response.data.img_url, // images: [...this.state.images, this.state.image_url ] }) }); console.log(this.state.image_url); } <ImageUploader withIcon={true} withPreview={true} onChange={this.handleUpload} buttonText='Upload an image' imgExtension={['.jpg', '.gif', '.png', '.gif']} maxFileSize={5242880} /> However i want to pass both values image title and the img_url itself. So in my attempt i make a form like this, but my attempt does not send the image title to the express route. My attempt gives me an error POST /images/upload 500 30.398 ms - 703 1 TypeError: Cannot read property 'path' of undefined 1 at path (/Users/eli/nodework/myexpressknex/routes/images.js:41:37) My attempt <form onSubmit={this.handleUpload}> <TextField id="outlined-name2" label="Image Title" fullWidth name="image_title" value={this.state.image_title} onChange={this.handleChange} margin="normal" /> <ImageUploader withIcon={true} withPreview={true} // onChange={this.handleUpload} buttonText='Upload an image' imgExtension={['.jpg', '.gif', '.png', '.gif']} maxFileSize={5242880} /> <Button variant="outlined" color="primary" type="submit"> Submit </Button> <br></br> <br></br> </form> So, How would i be able to pass in both values to express from react when doing file uploading ? express route import express from 'express'; import passport from 'passport'; import multer from 'multer'; import Image from '../models/Image' import cloudinary from 'cloudinary'; import multipart from 'connect-multiparty'; import var_dump from 'var_dump'; import dd from 'dump-die'; const multipartMiddleware = multipart(); const cloud = cloudinary.v2 const router = express.Router(); const storage = multer.memoryStorage(); const upload = multer({ storage }); cloudinary.config({ cloud_name: process.env.cloudinaryName, api_key: process.env.cloudinaryKey, api_secret: process.env.cloudinarySecret, }) router.get('/uploads', (req, res) => { Image.forge().fetchAll().then( (images) => { res.json(images.toJSON()); }) }) router.post('/upload', multipartMiddleware, upload.single('ourImage'), (req, res) => { if(!req.files){ return res.status(500).send("Please upload a file"); } console.log(req.files.ourImage.path) cloud.uploader.upload(req.files.ourImage.path, {crop: "thumb", folder: '/uploads'} , (err, result) => { if(err){ return res.status(500).send(err); } const img = new Image({ img_url:result.url, image_title:null }); // console.log(img); img.save().then( img => { return res.status(200).json(img); }); }); }); export default router; react side import React, { Component } from "react"; import Button from '@material-ui/core/Button'; import TextField from '@material-ui/core/TextField'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import ImageUploader from 'react-images-upload'; import Axios from '../Axios'; import Image from './Image'; class Dashboard extends Component{ constructor(props){ super(); this.state = { image_url: 'http://www.conservewildlifenj.org/images/artmax_1001.jpg', images: [], image_title:'' } } handleUpload = file => { const data = new FormData() const image = file[0] console.log(this.state.image_title) // debugger; data.append('ourImage',image) data.append('image_title', this.state.image_title) Axios.post('/images/upload', data).then((response) => { console.log(response); this.setState({ image_url:response.data.img_url, // images: [...this.state.images, this.state.image_url ] }) }); console.log(this.state.image_url); } handleChange = (e) => { // e.preventDefault(); this.setState({ [e.target.name]: e.target.value }) } // fileOnchange = (file) => { // this.setState({ // [file[0].target.name]: file[0].target.value // }) // } componentWillMount(){ Axios.get('/images/uploads').then( (response) => { let img; Object.keys(response.data).forEach( (key) => { img = response.data[key].img_url console.log(key, img); this.setState({ images: [...this.state.images, img] }) }); }) } componentDidUpdate(nextProps, prevState) { if (this.state.image_url !== prevState.image_url) { this.setState({ images: [ this.state.image_url, ...this.state.images] }); } } render(){ return( <div> <Grid container justify="center" spacing={16}> <Grid item sm={8} md={6} style={{ margin: '40px 0px', padding: '0px 30px'}}> <Typography align="center" variant="h6"> Welcome to the Dashboard </Typography> <form onSubmit={this.handleUpload}> <TextField id="outlined-name2" label="Image Title" fullWidth name="image_title" value={this.state.image_title} onChange={this.handleChange} margin="normal" /> <ImageUploader withIcon={true} withPreview={true} // onChange={this.handleUpload} buttonText='Upload an image' imgExtension={['.jpg', '.gif', '.png', '.gif']} maxFileSize={5242880} /> <Button variant="outlined" color="primary" type="submit"> Submit </Button> <br></br> <br></br> </form> {this.state.images.length > 0 ? ( this.state.images.map( (img, i) => ( <Grid item md={8} key={i}> {/* <Image image_url={this.state.image_url}/> */} <Image image_url={img} /> </Grid> )) ) : ( <div> <Grid item md={8}> <Typography>No Images yet</Typography> </Grid> </div> )} </Grid> {/* Images */} </Grid> </div> ) } } export default Dashboard;
doc_4739
https://fbcdn-profile-a.akamaihd.net/static-ak/rsrc.php/v1/yp/r/yDnr5YfbJCH.gif Is there an API call I can use to determine if the user has uploaded a custom photo? Thanks A: No. Don't know what else to tell you :) The only way I could think of doing it would be to pull the user's albums and look for the "Profile Pictures" album. There's a count element there. A: Maybe. Read http://developers.facebook.com/docs/api/realtime/ Your app can subscribe to changes to a user's properties. The profile picture is a property of the user object so you can be notified when it changes. The other photos are not properties of the user object, they are listed under Connections at http://developers.facebook.com/docs/reference/api/user/ so I don't know if you can access them from the real time notification api. Whatever, you need the user_photos permission to list them.
doc_4740
var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('youtube-player', { width: '100%', loadPlaylist:{ listType:'playlist', list: youtubeIdsArr, index:parseInt(0), suggestedQuality:'small' }, events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } function onPlayerReady(event) { event.target.cuePlaylist(youtubeIdsArr); } var done = false; function onPlayerStateChange(event) { if (event.data == YT.PlayerState.PLAYING && !done) { done = true; } } function stopVideo() { player.stopVideo(); } A: try adding this, title="Playlist: Kitchen Pilates Playlist"
doc_4741
Because google_map_location_picker 3.3.3 depends on intl >=0.16.0 <=0.16.1 and every version of flutter_localizations from sdk depends on intl 0.17.0, google_map_location_picker 3.3.3 is incompatible with flutter_localizations from sdk. So, because food_delivery_app depends on both flutter_localizations any from sdk and google_map_location_picker 3.3.3, version solving failed. pub get failed (1; So, because food_delivery_app depends on both flutter_localizations any from sdk and google_map_location_picker 3.3.3, version solving failed.) A: In the pubspec.yaml file set the version of google_map_location_picker to any (google_map_location_picker: any) then go to the pubspec.lock file and check the version of google_map_location_picker which solves the error.
doc_4742
What I want to do, from my mvc app, is to call an action in the controller on the keyup event of a textbox. I want to then pass back the contents of the textbox, do some stuff with the data and then pass back a list of items which can then be added to a dropdown. I'm completely new to json but [really] want to get stuck into it. A: Something like this?: $('input#textbox').keyup(function() { var textbox = $(this); $.ajax({ type: "POST", datatype = "json", data: textbox.serialize(), url: "<%= Url.Action("Action") %>", success : function(data) { textbox.val(data.TextBox); } }) }); public ActionResult Action(string TextBox) { return Json(new { TextBox = TextBox.ToUpper() }); } A: You can find a good example of using JsonResult in the Nerd Dinner project. Nerd Dinner source code
doc_4743
+--+-----+---+ |ID|value|cat| +--+-----+---+ |0 |1 |0 | +--+-----+---+ |1 |3 |0 | +--+-----+---+ |2 |2 |1 | +--+-----+---+ |3 |1.2 |1 | +--+-----+---+ |4 |1 |1 | +--+-----+---+ And I want to know, for each row, the ID of the row which matches the value most closely and belongs to the same category, and I also want to know the difference. So for row ID=0 the correct answer would be ID=1, and the difference value would be 2. The correct output would be this: +--+----------+----------+ |ID|difference|best match| +--+----------+----------+ |0 |2 |1 | +--+----------+----------+ |1 |2 |0 | +--+----------+----------+ |2 |0.8 |3 | +--+----------+----------+ |3 |0.2 |4 | +--+----------+----------+ |4 |0.2 |3 | +--+----------+----------+ I'm just learning about CROSS JOIN and while I'm sure this can be done I don't really know where to start. A: You can do this with a self-join and making use of the ROW_NUMBER() function in conjunction with MIN(): ;WITH cte AS (SELECT a.ID aID ,MIN(ABS(a.value - b.value)) diff ,ROW_NUMBER() OVER(PARTITION BY a.ID ORDER BY MIN(ABS(a.value - b.value)))RN ,b.ID bID FROM Table1 a JOIN Table1 b ON a.cat = b.cat AND a.ID <> b.ID GROUP BY a.ID,b.ID) SELECT aID ,diff ,bID Best_Match FROM cte WHERE RN = 1 Demo: SQL Fiddle If you want to return multiple rows in case of a tie, you'd want to use RANK() instead of ROW_NUMBER()
doc_4744
Is it possible to create a user expandable table that maintains the form controls in each column? A: I am on a Linux machine right now so I can't test and debug code for you, but I have made tables in Word before where the size is decided at runtime (in fact, I did it from Excel, but that is off topic). However, I can tell you the general form is: expression.Add(BeforeRow) where expression returns a rows object, such as ActiveDocument.Tables(1).Rows.Add(5) Please see microsoft documentation of dealing with tables: http://msdn.microsoft.com/en-us/library/office/aa212430%28v=office.11%29.aspx and rows: http://msdn.microsoft.com/en-us/library/office/aa223081%28v=office.11%29.aspx Also, from the VB editor in word, go to help and search "table object members," "row object members," etc. If this hasn't been closed by tomorrow I will write something up. I will admit, in my experience Word VBA is a bit more temperamental than Excel VBA.
doc_4745
Pyro wants to have its own event loop, which underneath probably uses epoll etc. I am having trouble reconciling the two. Help would be appreciated. A: I use gevent.spawn(daemon.requestLoop). I can't say more without knowing more about the specifics.
doc_4746
export default class ListTodo extends React.Component { constructor(props) { super(props); this.state = { data: {}, }; } componentDidMount() { //promise GetDataAsyncStorage('@TODOS').then((data) => { this.setState({ data: data, }); }); } render() { const {data} = this.state; console.log(data); // undifined return ( <> <Header /> <View> <FlatList data={data} renderItem={({item}) => <TodoItemComponent data={item} />} keyExtractor={(item) => item.id} /> </View> </> ); } } Here is my function to get data from asynStorage export const GetDataAsyncStorage = async (key) => { try { let data = await AsyncStorage.getItem(key); return {status: true, data: JSON.parse(data)}; } catch (error) { return {status: false}; } }; A: Add a state variable isLoading and toggle it after the data is got from AsyncStorage snack: https://snack.expo.io/@ashwith00/async code: export default class ListTodo extends React.Component { constructor(props) { super(props); this.state = { data: {}, isLoading: false, }; } componentDidMount() { this.getData(); } getData = () => { this.setState({ isLoading: true, }); //promise GetDataAsyncStorage('@TODOS').then((data) => { this.setState({ data: data, isLoading: false, }); }); }; render() { const { data, isLoading } = this.state; return ( <View style={styles.container}> {isLoading ? ( <ActivityIndicator /> ) : data.data ? ( <FlatList data={data} renderItem={({ item }) => <Text>{item}</Text>} keyExtractor={(item, i) => i.toString()} /> ) : ( <Text>No Data Available</Text> )} </View> ); } } A: Because AsyncStorage itself is asynchronous read and write, waiting is almost necessary, of course, another way to achieve, for example, to create a memory object, bind the memory object and AsyncStorage, so that you can read AsyncStorage synchronously. For example, using the following development library can assist you to easily achieve synchronous reading of AsyncStorage react-native-easy-app import { XStorage } from 'react-native-easy-app'; import { AsyncStorage } from 'react-native'; // or import AsyncStorage from '@react-native-community/async-storage'; export const RNStorage = { token: undefined, isShow: undefined, userInfo: undefined }; const initCallback = () => { // From now on, you can write or read the variables in RNStorage synchronously // equal to [console.log(await AsyncStorage.getItem('isShow'))] console.log(RNStorage.isShow); // equal to [ await AsyncStorage.setItem('token',TOKEN1343DN23IDD3PJ2DBF3==') ] RNStorage.token = 'TOKEN1343DN23IDD3PJ2DBF3=='; // equal to [ await AsyncStorage.setItem('userInfo',JSON.stringify({ name:'rufeng', age:30})) ] RNStorage.userInfo = {name: 'rufeng', age: 30}; }; XStorage.initStorage(RNStorage, AsyncStorage, initCallback);
doc_4747
Can someone help me determine why the following PDO MYSQL statement is only inserting a single row into the table when there are more than 1 value in the array? $availability array values = "1,2,4" for example. $stmt =$con -> prepare ("INSERT INTO Availability (Periods_P_ID, Users_user_id) VALUES (:period, $user_id)"); foreach($availability as $periods){ $stmt -> bindParam(':period', $periods, PDO::PARAM_INT); } $stmt -> execute(); A: You only need to bind the parameter once, outside the loop. But you need to call execute() in the loop to insert each row. $stmt =$con -> prepare ("INSERT INTO Availability (Periods_P_ID, Users_user_id) VALUES (:period, :user_id)"); $stmt->bindParam(':period', $periods, PDO::PARAM_INT); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); foreach($availability as $periods){ $stmt -> execute(); }
doc_4748
And I'm trying to retrieve "login" field iterating this result. I do next: for(key in result) { console.log(key); } and it prints only object indexes: 0, 1, 2... How can I retrieve object fields? I'm new in JS.
doc_4749
Out[178]: group value 0 A a 1 A b 2 A c 3 A d 4 B c 5 C d 6 C e 7 C a For this input, I want to create a combination for each group and create one DataFrame. How can I do it? The output I want to get: Out[180]: group 0 1 0 A a b 1 A a c 2 A a d 3 A b c 4 A b d 5 A c d 0 C d e 1 C d a 2 C e a A: Use groupby with lambda function and combinations: from itertools import combinations df = (df.groupby('group')['value'].apply(lambda x: pd.DataFrame(list(combinations(x,2)))) .reset_index(level=1, drop=True) .reset_index()) print (df) group 0 1 0 A a b 1 A a c 2 A a d 3 A b c 4 A b d 5 A c d 6 C d e 7 C d a 8 C e a A: Using combinations in a comprehension from itertools import combinations pd.DataFrame([ [n, x, y] for n, g in df.groupby('group').value for x, y in combinations(g, 2) ], columns=['group', 0, 1]) group 0 1 0 A a b 1 A a c 2 A a d 3 A b c 4 A b d 5 A c d 6 C d e 7 C d a 8 C e a A: This can be achieved with itertools and a list comprehension: from itertools import combinations, chain gen = ([(g,)+i for i in list(combinations(df.loc[df['group'] == g, 'value'], 2))] \ for g in df['group'].unique()) df_out = pd.DataFrame(list(chain.from_iterable(gen)), columns=['group', 0, 1]) Result group 0 1 0 A a b 1 A a c 2 A a d 3 A b c 4 A b d 5 A c d 6 C d e 7 C d a 8 C e a
doc_4750
#sortable li:hover:not(.ce){ background-color:#3f0; cursor:pointer; } does not work. The li changes color when my cursor is over the span as well. How can I make the li only change color when it --and not the span-- is hovered over? http://jsbin.com/alExeVO/16/edit A: As your <span> is part of the <li> your code behaves as expected. A hack would be to add a hover to your span so it changes to the original color. A: Give the span and the li their own hover features. Check it out. SEE DEMO HERE ul{ list-style-type:circle; text-align:center; } ul li{ display:inline-block; border:1px solid purple; padding:20px; } ul li span{ font-size:2em; } ul li:hover{ background:orange; } ul li span:hover{ background:white; color:black; }
doc_4751
service.html <ion-list> <ion-item ng-repeat="business in businessList track by $index" class="item-icon-right"> <h2>{{business.name}}</h2> {{business.distance}} miles <br> <div star-rating rating-value="{{business.rating}}" max="rating.max"></div> <i class="icon ion-chevron-right icon-accessory"></i> </ion-item> </ion-list> directives.js angular.module('starter.directives', []) .directive('starRating', function() { return { restrict: 'A', template: '<ul class="rating">' + '<li ng-repeat="star in stars" ng-class="star">' + '\u2605' + '</li>' + '</ul>', scope: { ratingValue: '=', max: '=' }, link: function(scope, elem, attrs) { scope.stars = []; for (var i = 0; i < scope.max; i++) { scope.stars.push({ filled: i < scope.rating }); } } } }); services.js .service("BusinessData", [function () { var businessData = [ { id: 1, serviceId: 1, name: 'World Center Garage', distance: 0.1, rating: 4 } ]; return { getAllBusinesses: function () { return businessData; }, getSelectedBusiness: function(serviceId) { var businessList = []; serviceId = parseInt(serviceId); for(i=0;i<businessData.length;i++) { if(businessData[i].serviceId === serviceId) { businessList.push(businessData[i]); } } return businessList; } } }]) controller.js .controller('ServiceCtrl', function($scope, ServicesData, BusinessData, $stateParams) { $scope.service = ServicesData.getSelectedService($stateParams.service); $scope.businessList = BusinessData.getSelectedBusiness($stateParams.service); }); A: controller.js .controller('ServiceCtrl', function($scope, ServicesData, BusinessData, $stateParams) { $scope.service = ServicesData.getSelectedService($stateParams.service); $scope.businessList = BusinessData.getSelectedBusiness($stateParams.service); $scope.ratings = { current: 5, max: 10 }; And also modify service.html <div star-rating rating-value="rating.current" max="rating.max"></div> Hope it will help you out.!!
doc_4752
$ sudo sysctl -w net.inet.ip.forwarding=1 Password: net.inet.ip.forwarding: 0 -> 1 $ sudo pfctl -f pf.conf No ALTQ support in kernel ALTQ related functions disabled $ sudo pfctl -e No ALTQ support in kernel ALTQ related functions disabled pf enabled But it doesn't seem to have had any effect. When I go to websites in my browser, it makes a direct request, and doesn't go through the port I specified. Here is the pf.conf file (en1 is my wifi): rdr on en1 inet proto tcp to any port 80 -> 127.0.0.1 port 4500 rdr on en1 inet proto tcp to any port 443 -> 127.0.0.1 port 4500 A: Thanks for stopping by the IRC channel today. I've tracked this down, and the basic issue is that the rdr rules apply to inbound traffic. This means that they will NOT redirect traffic coming from the box itself. If you think about it, this is inevitable: we can't distinguish between an outbound connection from a non-mitmproxy app, and an outbound connection from mitmproxy itself. We can use route-to to send the traffic to lo0 and then redirect it, but that causes an infinite loop where mitmproxy's own outbound connections are also redirected back to mitmproxy. Because I know a bit about your use case, I would suggest exploring ways to do this with VirtualBox. A plan of attack would be to set the VirtualBox network up in bridge mode, and then use a pf rule with a match on the source address to redirect traffic to mitmproxy. That should do what you want, and not cause singularities in time and space due to infinite redirection. Please drop by the IRC channel again if you need a further hand with this. A: Did you try net.inet.ip.scopedroute=0? From http://lucumr.pocoo.org/2013/1/6/osx-wifi-proxy/: Now currently if you finish that above setup you will notice that nothing actually works. The cause for this is a Bug in the OS X kernel that requires flipping the net.inet.ip.scopedroute flag to 0. I am not entirely sure what it does, but the internet reports that it breaks network sharing through the user preferences. In any case it fixes ipfw based forwarding so you can flip it with sysctl: $ sudo sysctl -w net.inet.ip.scopedroute=0 Unfortunately in OS X Lion this flag can actually not be flipped from userspace so you need to set it as boot parameter and then restart your computer. You can do this by editing the /Library/Preferences/SystemConfiguration/com.apple.Boot.plist file (continued...) A: You are using the port 4500 instead the default port 8080. Do you start mitmproxy with the port specification?: mitmproxy -T --host -p 4500 Did you follow the steps to set the certificate in the Android device? http://mitmproxy.org/doc/certinstall/android.html Another problem could be the gateway on your android phone: Preferences - Wifi - Hold on the network you are using - Edit network - Advanced options - Set as gateway the ip of your machine with mitmproxy. By the way I have the same warning with No ALTQ function but it works.
doc_4753
This is the code that I currently have: (main.c) #include <stdio.h> #include <stdlib.h> #include <unistd.h> typedef struct s_list { struct s_list *next; void *content; } t_list; typedef struct s_queue { t_list *first; t_list *last; } t_queue; typedef struct s_node { struct s_node *next; int vertex; } t_node; typedef struct s_graph { t_node **adj_lists; int *visited; int total_vertices; } t_graph; /*Graph functions*/ t_node *create_node(int vertex); t_graph *create_graph(int vertices); void add_edge(t_graph *graph, int src, int dst); void bfs(t_graph *graph, int start_vertex); /*Misc functions*/ void my_putstr(char *str); void *my_memalloc(size_t size); void *my_memset(void *ptr, int value, size_t num); void my_bzero(void *s, size_t n); /*Queue functions*/ t_queue *init_queue(void); void enqueue(t_queue *queue, void *content); void *dequeue(t_queue *queue); void *peek_queue(t_queue *queue); int is_empty(t_queue *queue); void my_print_queue(t_queue *queue); t_node *create_node(int val) { t_node *new_node; new_node = (t_node*)my_memalloc(sizeof(t_node)); new_node->vertex = val; new_node->next = NULL; return (new_node); } t_graph *create_graph(int vertices) { int i; t_graph *graph; i = 0; graph = my_memalloc(sizeof(t_graph)); graph->total_vertices = vertices; printf("graph->total_vertices: %d\n", vertices); graph->adj_lists = (t_node**)my_memalloc(sizeof(t_node)); graph->visited = my_memalloc(sizeof(int) * vertices); while (i < vertices) { graph->adj_lists[i] = NULL; graph->visited[i] = 0; i++; } return (graph); } void add_edge(t_graph *graph, int src, int dst) { t_node *new_node; new_node = create_node(dst); new_node->next = graph->adj_lists[src]; graph->adj_lists[src] = new_node; new_node = create_node(src); new_node->next = graph->adj_lists[dst]; graph->adj_lists[dst] = new_node; } void bfs(t_graph *graph, int start_vertex) { t_queue *queue; queue = init_queue(); graph->visited[start_vertex] = 1; printf("start_vertex before enqueue %d\n", start_vertex); my_print_queue(queue); enqueue(queue, &start_vertex); printf("start_vertex after enqueue %d\n", start_vertex); while (!is_empty(queue)) { my_print_queue(queue); int current_vertex; t_node *tmp; current_vertex = (int)dequeue(queue); printf("Visited %d nodes\n", current_vertex); tmp = graph->adj_lists[current_vertex]; while (tmp) { int adj_vertex; adj_vertex = tmp->vertex; if (graph->visited[adj_vertex] == 0) { graph->visited[adj_vertex] = 1; printf("%d\n", graph->visited[adj_vertex]); enqueue(queue, &adj_vertex); my_print_queue(queue); } tmp = tmp->next; } } } t_queue *init_queue(void) { t_queue *node; node = (t_queue *)my_memalloc(sizeof(t_queue)); node->first = NULL; node->last = NULL; return (node); } void enqueue(t_queue *queue, void *content) { t_list *node; node = (t_list *)my_memalloc(sizeof(t_list)); node->content = content; node->next = NULL; if (!queue->last) { queue->last = node; queue->first = node; } else { queue->last->next = node; queue->last = queue->last->next; } return ; } void *dequeue(t_queue *queue) { t_list *tmp; tmp = queue->first; if (!tmp) return (NULL); else { queue->first = tmp->next; return (tmp->content); } } void *peek_queue(t_queue *queue) { if (queue->first == NULL) return (NULL); return (queue->first->content); } int is_empty(t_queue *queue) { return (queue->first == NULL); } void my_print_queue(t_queue *queue) { if (is_empty(queue)) my_putstr("Empty queue\n"); else { while (!is_empty(queue)) { int val = *(int *)queue->first->content; printf("%d \n", val); dequeue(queue); } } } void my_putstr(char *str) { int i; i = 0; while (str[i]) write(1, &str[i++], 1); } void *my_memalloc(size_t size) { char *str; str = ((void*)malloc(size)); if (!str) return (NULL); my_bzero(str, size); return (str); } void *my_memset(void *ptr, int value, size_t num) { unsigned char *uptr; uptr = (unsigned char*)ptr; while (num--) *uptr++ = (unsigned char)value; return (ptr); } void my_bzero(void *s, size_t n) { my_memset(s, 0, n); } int main(void) { t_graph *graph; graph = create_graph(3); add_edge(graph, 0, 1); add_edge(graph, 0, 2); add_edge(graph, 2, 4); bfs(graph, 2); return (0); } I did some research like type-casting a void pointer to make it into a char or int, or any other data type. What happens is that the create graph does it's creation after calling it; but, when it comes to the bfs, it doesn't show the correct output after. It never prints the visited vertices. I'm getting a result of graph->total_vertices: 3 start_vertex before enqueue 2 Empty queue start_vertex after enqueue 2 2 Visited 0 nodes The expected output should be something like this: Queue contains 0 Resetting queueVisited 0 Queue contains 2 1 Visited 2 Queue contains 1 4 Visited 1 Queue contains 4 Resetting queueVisited 4 I've been trying to figure out by myself to the point that I'm burning out. What am I doing wrong in here? While posting this, I will keep debugging on my side and see what it does with a couple print statements. A: I can point out the following mistakes: * *my_print_queue destroys your queue. So anything after it's call works with empty queue. *You don't fill visited with to zeroes. By default their values is pretty much arbitrary. Since you compare their values with 0, it makes sense that comparison fails.
doc_4754
A: I am sorry for asking this question and I can promise that I was searching for an answer for a while, but now I came across the solution by random. You simply have to switch to Scripting Backend "Mono" and API Compatibility-Level ".NET 4.X" in Player Settings to get access to named Mutex. Thanks for anyone who wanted to help!
doc_4755
eventConstraint: { start: moment().format('YYYY-MM-DD'),/* This constrains it to today or later */ end: '2100-01-01' // hard coded goodness unfortunately }, I can prevent dragging to past dates with: eventDrop: function(info) { var eventObj = info.event; var check = moment(eventObj.start).format('YYYY-MM-DD'); var today = moment().format('YYYY-MM-DD'); if(check < today) { revertFunc(); //Put the Event back where it came from } else { //code } }, Full code: var calendar = new FullCalendar.Calendar(calendarEl, { firstDay: 0, //Sunday weekends: true, //Show the weekends businessHours: { // days of week. an array of zero-based day of week integers (0=Sunday) daysOfWeek: [ 1, 2, 3, 4, 5 ], // Monday - Friday startTime: '09:00', // a start time endTime: '17:00', // an end time }, initialView: 'dayGridMonth', headerToolbar: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth' }, locale: 'en-gb', selectable: true, // gives ability to select multiple days and then have a callback event when this occurs buttonIcons: false, // show the prev/next text weekNumbers: true, // show week numbers navLinks: true, // can click day/week names to navigate views editable: true, // can make changes and add changes dayMaxEvents: true, // allow "more" link when too many events displayEventEnd: true, // display the end time eventTimeFormat: { hour: '2-digit', minute: '2-digit', },// display time with minutes eventDisplay: 'block', //Changes an event with start and end times from a list-item to a block eventConstraint: { start: moment().format('YYYY-MM-DD'),/* This constrains it to today or later */ end: '2100-01-01', // hard coded goodness unfortunately }, events: responseJson1a,//Populate Event using JSON A: set key editable to false when you define your past events on fullCalendar events: [ { title: 'Business Lunch', start: '2021-11-03T13:00:00', constraint: 'businessHours', editable:false, }, ... ... ]
doc_4756
int main() { char s[20]="hello,world"; char d[20]; char *src=s; char *des=d; while(*src) *des++=*src++; return 0; } A: It has the same behavior as: *dest = *src; dest++; src++; That is copy the character pointed at by src to the character pointed at by dest. Then move each pointer to the next character element.
doc_4757
I have a Master Detail application for iPhone and have text fields and a date picker and an image in the detail view. All which are defined by the user. I need to know how to save all that information in the text fields(or labels) and in the image view. Will I need to save each text field individualy or can I just do that all at once. Also I realize that when I exit the simulator my new table view cell dissapears. Let me know if you need my code or more information. A: I had a similar problem in one of my apps. There is probably a way to do it all at once but I always did each one individually, it takes a while but it works. As for the table view cell disappearing, thats normal. The simulator always starts up as if you just downloaded the app. P.S. If you like my answer please click the checkmark
doc_4758
cat /proc/cpuinfo | grep 'model name\|Hardware\|Serial' | uniq I get the following output when I run the command directly on the Raspberry pi terminal : model name : ARMv7 Processor rev 4 (v7l) Hardware : BCM2835 Serial : 0000000083a747d7 which is what I expect as well. I want to get this into a Python list, so I used the subprocess.check_output() method and used a .split() and .splitlines() considering the way it is formatted. But invoking the same command by using subprocess.check_output() I do not get what I expect. Here's the code I ran in Python : import subprocess items = [s.split('\t: ') for s in subprocess.check_output(["cat /proc/cpuinfo | grep 'model name\|Hardware\|Serial' | uniq "], shell=True).splitlines()] The error I receive is as follows: TypeError: a bytes-like object is required, not 'str' Trying to debug issue: 1)On removing the .splitlines() at the end. ie: items = [s.split('\t: ') for s in subprocess.check_output(["cat /proc/cpuinfo | grep 'model name\|Hardware\|Serial' | uniq "], shell=True) Now the Output error is: AttributeError: 'int' object has no attribute 'split' 2)On removing .split: items = [s for s in subprocess.check_output(["cat /proc/cpuinfo | grep 'model name\|Hardware\|Serial' | uniq "], shell=True) Output items now holds the following: >>> items [109, 111, 100, 101, 108, 32, 110, 97, 109, 101, 9, 58, 32, 65, 82, 77, 118, 55, 32, 80, 114, 111, 99, 101, 115, 115, 111, 114, 32, 114, 101, 118, 32, 52, 32, 40, 118, 55, 108, 41, 10, 72, 97, 114, 100, 119, 97, 114, 101, 9, 58, 32, 66, 67, 77, 50, 56, 51, 53, 10, 83, 101, 114, 105, 97, 108, 9, 9, 58, 32, 48, 48, 48, 48, 48, 48, 48, 48, 56, 51, 97, 55, 52, 55, 100, 55, 10] Almost seems like grep is behaving differently than I expect it. but I'm not able to zero-in on what exactly is the problem. What are these numbers? Is it values that grep returns? Please help on how to resolve. Thanks A: In Python3 the subprocess.check_output() returns bytes which need to be decoded to the string before string functions could be used. Another option is to use the legacy subprocess.getoutput() function. The following code does the job for me: items = [s.split('\t: ') for s in subprocess.getoutput(["cat /proc/cpuinfo | grep 'model name\|Hardware\|Serial' | uniq "]).splitlines()] A: Compare with: items = dict(s.split('\t: ') for s in open('/proc/cpuinfo', 'r').read().splitlines() if s.startswith(('model name', 'Hardware', 'Serial')))
doc_4759
Here is my code for the above image: data = Data([ Bar( y=[x/float(114767406) for x in yp_views], x=[x for x in yp_views], name='Relative Frequency')]) layout = Layout(xaxis=XAxis(type='log',title = "Number of Premium Highlight Views") ,yaxis=YAxis(title = "Frequency")) fig = Figure(data = data, layout = layout) py.iplot(fig) Here is what I tried: I tried solving this problem by using histogram and the xbins. However, this doesn't allow me the freedom of using a custom x and y axis to plot. I don't see a xbins property for bar charts. Is there another name for it? Here is trying to plot using the range: data = Data([ Bar( y=[x/float(114767406) for x in yp_views], x=[x for x in yp_views], name='Relative Frequency')]) layout = Layout(xaxis=XAxis(type='log', range = [3000,10000], title = "Number of Premium Highlight Views") ,yaxis=YAxis(title = "Frequency")) fig = Figure(data = data, layout = layout) py.iplot(fig) A: You can use range=[min, max] in your xaxis / yaxix to define your desired range. For example, your layout would look like something like this: layout = Layout(xaxis=XAxis(type='log', range=[np.log10(3000), np.log10(10000)], title = "Number of Premium Highlight Views"), yaxis=YAxis(title = "Frequency"))
doc_4760
void func(int a, int b, int c, int d, int e); where b & d are default parameters. The types are obviously not int, I have created them here for understanding purpose. Currently I can use that function by passing NULL for the default args. But I was thinking in the case of above function func, if the default value for b & d was non-zero say 1 & the user did not know this & if he used NULL (which is = 0) then a different result would be arrived. So I would like to know how should I create such functions that have default args between non-default ones & I should not be needed to pass anything for that arg i.e. func(23, , 34, , 45); Currently VS2010 is giving me compile error for similar implementation for our company's API call. I hope I made the question pretty clear to understand. I tried searching similar question elsewhere too but could not find solution for my query. Thank You. A: You can't do that, you have to put all non-optional parameters first, followed by optional parameters after. You can read a bit more about optional parameters here. Microsoft says: Default arguments are used only in function calls where trailing arguments are omitted — they must be the last argument(s). Therefore, the following code is illegal: int print( double dvalue = 0.0, int prec ); A: void func(int a, int c, int e) { int default_b = 1; int default_d = 1; func(a, default_b, c, default_d, e); } Otherwise you simply can't, as there is no named parameters in C++. (Though another solution would be to use boost::bind or a similar functor). If you can modify the original function, you can simply use default value at the condition the defaulted parameter are at the end : void func(int a, int c, int e, int b = 1, int d = 1); A: How do you expect the compiler to know that you mean to pass a,c and e and not some other triplet? In a function declaration all parameters after a parameter with default value should have default values. So you can never have default b and d - whenever you pass only three parameters to this function it would mean you want to use the default values for the last 2 parameters and these are d and e. Move your optional parameters as last in the function. A: There is no direct way to achieve what you are looking for. The first alternative would be the use of boost::optional<T> for the parameters. Another alternative might be named parameters, as implemented in the Boost Parameter Library. If you think that this might be something for you and you want further elaboration on how these could be used for your use case, let me know and I'll edit this answer. A: There is a boost library for this boost::parameter http://www.boost.org/doc/libs/1_53_0/libs/parameter/doc/html/index.html It supports named parameters in arbitrary order with default values for non used parameters.
doc_4761
I have a button function. How can call the onUpdate callback from button? $("#range").ionRangeSlider({ min: +moment().subtract(3, "days").format("X"), max: +moment().add(1, "days").format("X"), from: +moment().format("X"), step: 10800, grid: true, grid_num: 16, force_edges: true, onUpdate: function (data){ alert ("Update value"); } }); function buttonClick(){ // here i want to call onUpdate; } Thanks in advance!
doc_4762
P/s: Sorry for my poor English :D A: Yes, you are right. And quoted from wiki: Time domain is the analysis of mathematical functions, physical signals or time series of economic or environmental data, with respect to time. In the time domain, the signal or function's value is known for all real numbers, for the case of continuous time, or at various separate instants in the case of discrete time.
doc_4763
Collision Event: void OnTriggerExit2D(Collider2D other) { if (other.GetComponent<Rigidbody2D>() == projectile) { Respawn(); Ammo -= 1; SetAmmoCount(); Destroy(GO); UpdateReferences(); } } UpdateReferences Method: void UpdateReferences() { projectile = GameObject.FindGameObjectWithTag("Damager").GetComponent<Rigidbody2D>(); tran = GameObject.FindGameObjectWithTag("Damager").GetComponent<Transform>(); GO = GameObject.FindGameObjectWithTag("Damager"); } Everytime I run the game it doesn't seem to be able to find the new object. However I have used this method of updating object references in other script for the same object and it has worked fine. Not sure what I am doing wrong. Respawn Method: void Respawn() { GameObject.Instantiate(player, Vector3.zero, Quaternion.identity); projectile.isKinematic = true; isSpawned = true; } It compiles I used some bad names to reference objects and things. Yes the object I am instantiating is a prefab. A: Replace your Respawn function with : void Respawn() { GameObject obj = GameObject.Instantiate(player, Vector3.zero, Quaternion.identity) as GameObject; obj.tag = "Damager"; projectile.isKinematic = true; isSpawned = true; } A: So after reading into Destroy() a little more it occurred to me about a problem I had before. When using Destroy(), you actually destroy the references to that object as well. Thus creating an issue when trying to create a new copy and move the references to that instead. What you should use is GameObject.SetActive() and then the references will all update to the new Object with Instantiate and the reference updates in my question above.
doc_4764
So this is the part which has an issue (when I launch the app it crashes) - (void)viewDidLoad { [super viewDidLoad]; _scheduleList = [[NSMutableArray alloc] init]; _futurScheduleList = [[NSMutableArray alloc] init]; _currentScheduleList = [[NSMutableArray alloc] init]; _pastScheduleList = [[NSMutableArray alloc] init]; for (id item in self.endpoints) { NSString *url = [NSString stringWithFormat: @"https://apis.is%@", item]; NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]]; // Parse JSON NSError *error; if (JSONData) { NSDictionary *json = [NSJSONSerialization JSONObjectWithData:JSONData //1 options:kNilOptions error:&error]; NSArray *jsonResult = [json objectForKey:@"results"]; for (id item in jsonResult) { TVShow *tvs = [[TVShow alloc] init]; tvs.title = [item objectForKey:@"title"]; tvs.startTime = [item objectForKey:@"startTime"]; tvs.duration = [item objectForKey:@"duration"]; tvs.episode = [item valueForKeyPath:@"series.episode"]; tvs.serie = [item valueForKeyPath:@"series.series"]; tvs.theDescription = [item objectForKey:@"description"]; if ([self isItAFuturShow:tvs]) { [_futurScheduleList addObject:tvs]; } if ([self isItAPastShow:tvs]) { [_pastScheduleList addObject:tvs]; } if ([self isTimeForAShow:tvs]) { [_currentScheduleList addObject:tvs]; } [_scheduleList addObject:tvs]; } } } } When I look at the error I have that : *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSTaggedPointerString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xa00f048fc1508fc8' When I check 0xa00f048fc1508fc8, I have something inside The error pop at this line for (id item in self.endpoints) Thanks for your help
doc_4765
[End Url]/api/customers/1/venues/55/abcfiles/sasfordownload?licenseid=01234567890&ispreproduction=true Headers: authorization -> Bearer someToken Body: { "some_field" : {"55" : "29"}} -- Response: "Some String Value" POST request: @POST("customers/{customers}/venues/{venues}/abcfiles/sasfordownload") fun makeRequestForfileUrl( @HeaderMap token: Map<String, String>, @Path("customers") customers: Int, @Path("venues") venues: Int, @Query("licenseid") licenceId: String, @Query("ispreproduction") ispreproduction: Boolean, @Body body: JSONObject ): Call<String> Retrofit Builder: fun requestApi(mContext: Context): ApiInterface { return Retrofit.Builder() .baseUrl(apiUrl) .addConverterFactory(GsonConverterFactory.create()) .client( OkHttpClient.Builder() .addInterceptor(NetworkConnectionInterceptor(mContext)) .addInterceptor(httpLoggingInterceptor) .build() ) .build() .create(ApiInterface::class.java) } Retrofit API request: val headerMap = HashMap<String, String>() headerMap["Authorization"] = "Bearer $fetchedToken" headerMap["Content-Type"] = "application/json" val apiInterface = ServiceGenerator.requestApi().makeRequestForfileUrl( headerMap, customerId, venueId, licenceId, true, JSONObject("{\"some_field\" : { \"55\" : \"29\" }}") ) Getting response code 500 for the above request. Response{protocol=h2, code=500, message=, url=[End Url]/api/customers/1/venues/55/abcfiles/sasfordownload?licenseid=0123456789&ispreproduction=true} Response body -> null The API request is working on Postman. A: Working after Changing from org.json.JSONObject to com.google.gson.JsonObject @POST("customers/{customers}/venues/{venues}/abcfiles/sasfordownload") fun makeRequestForfileUrl( @HeaderMap token: Map<String, String>, @Path("customers") customers: Int, @Path("venues") venues: Int, @Query("licenseid") licenceId: String, @Query("ispreproduction") ispreproduction: Boolean, @Body body: JsonObject //<- here changed org.json.JSONObject to com.google.gson.JsonObject ): Call<String> And val apiInterface = ServiceGenerator.requestApi().makeRequestForfileUrl( headerMap, customerId, venueId, licenceId, true, JsonObject) //<- "{\"some_field\" : { \"55\" : \"29\" }}" in this format ) Don't know what is the difference between org.json.JSONObject and com.google.gson.JsonObject But working with com.google.gson.JsonObject. If anyone know the differences please add it here.
doc_4766
I tried to (hard) code a Script Task to create just one folder but I'm getting this error: http://img856.imageshack.us/img856/1386/helpel.png After running only a part of this script: Microsoft.Sharepoint.Client.dll Microsoft.Sharepoint.Client.Runtime.dll public void Main() { ClientContext clientContext = new ClientContext("http://spdemo.example.com/"); clientContext.Credentials = new System.Net.NetworkCredential("admin", "password", "SPDEMO"); Web rootWeb = clientContext.Web; Dts.TaskResult = (int)ScriptResults.Success; } I've scoured the internet for solutions, but haven't found something that works for me. So basically i need to find out how to: * *create a folder *populate it with sub-folders *Copy files in bitestreams from SQL to Sharepoint, all in SSIS Thanks in advance! Regards, Vlad Ardelean A: After some research I found out that in order to reference a DLL in a SSIS Script Task it first has to be strong named Instead, I have found an easier way to create folders and upload files: public void CreateFolder(string url) { HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url); request.Credentials = new NetworkCredential(user, pass); request.Method = "MKCOL"; HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); } public void UploadDocument(byte[] file, string destinationName) { byte[] buffer = file; WebRequest request = WebRequest.Create(destinationName); request.Credentials = new System.Net.NetworkCredential(user, pass); request.Method = "PUT"; request.ContentLength = buffer.Length; BinaryWriter writer = new BinaryWriter(request.GetRequestStream()); writer.Write(buffer, 0, buffer.Length); writer.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); response.Close(); } url : represents the url path of the folder you want to create http://spsite.host.com/DocLib/FolderToCreate destinationName: path + document name http://spsite.host.com/DocLib/FolderToCreate/DocToCreate.docx A: Did you try running your code from a stand-alone windows application written in C# in Visual Studio? If I get errors in SSIS, my preference is to test that code thoroughly in Visual Studio and then port it to a script task in SSIS. If you haven't done folder creation and file copy to SharePoint, the below links might help. * *Create a folder - http://thingsthatshouldbeeasy.blogspot.in/2009/09/how-to-add-folder-to-sharepoint-list.html *You can do the create folder step recursively untill you have created the destination tree structure. *Copy Files - http://msdn.microsoft.com/en-us/library/ms454491.aspx, http://msdn.microsoft.com/en-us/library/ms470176.aspx I dont understand what you mean by copy file in bitestreams from SQL. If you want to read binary data from SQLServer via ADO.Net use System.Data.SqlDbType.VarBinary Read the data from SQL server to a stream and write to a temp file, copy that temp file from local to SP. Or you may even write the data in a stream to SP directly without a temp file.
doc_4767
The below code works, but the problem is it's not at all efficient in terms of speed. Creating/updating 500 records takes approx. 1 minute and generates 6500+ db queries! def add_details(shop, shopify_orders) shopify_orders.each do |shopify_order| order = Order.where(:order_id => shopify_order.id.to_s, :shop_id => shop.id).first_or_create order.update_details(order,shopify_order,shop) #This calls update_attributes for the Order ShippingLine.add_details(order, shopify_order.shipping_lines) LineItem.add_details(order, shopify_order.line_items) Taxline.add_details(order, shopify_order.tax_lines) Fulfillment.add_details(order, shopify_order.fulfillments) Note.add_details(order, shopify_order.note_attributes) Discount.add_details(order, shopify_order.discount_codes) billing_address = shopify_order.billing_address rescue nil if !billing_address.blank? BillingAddress.add_details(order, billing_address) end shipping_address = shopify_order.shipping_address rescue nil if !shipping_address.blank? ShippingAddress.add_details(order, shipping_address) end payment_details = shopify_order.payment_details rescue nil if !payment_details.blank? PaymentDetail.add_details(order, payment_details) end end end def update_details(order,shopify_order,shop) order.update_attributes( :order_name => shopify_order.name, :order_created_at => shopify_order.created_at, :order_updated_at => shopify_order.updated_at, :status => Order.get_status(shopify_order), :payment_status => shopify_order.financial_status, :fulfillment_status => Order.get_fulfillment_status(shopify_order), :payment_method => shopify_order.processing_method, :gateway => shopify_order.gateway, :currency => shopify_order.currency, :subtotal_price => shopify_order.subtotal_price, :subtotal_tax => shopify_order.total_tax, :total_discounts => shopify_order.total_discounts, :total_line_items_price => shopify_order.total_line_items_price, :total_price => shopify_order.total_price, :total_tax => shopify_order.total_tax, :total_weight => shopify_order.total_weight, :taxes_included => shopify_order.taxes_included, :shop_id => shop.id, :email => shopify_order.email, :order_note => shopify_order.note ) end So as you can see, we are looping through each order, finding out if it exists or not (then either loading the existing Order or creating the new Order), and then calling update_attributes to pass in the details for the Order. After that we create or update each of the associations. Each associated model looks very similar to this: class << self def add_details(order, tax_lines) tax_lines.each do |shopify_tax_line| taxline = Taxline.find_or_create_by_order_id(:order_id => order.id) taxline.update_details(shopify_tax_line) end end end def update_details(tax_line) self.update_attributes(:price => tax_line.price, :rate => tax_line.rate, :title => tax_line.title) end I've looked into the activerecord-import gem but unfortunately it seems to be more geared towards creation of records in bulk and not update as we also require. What is the best way that this can be improved for performance? Many many thanks in advance. UPDATE: I came up with this slight improvement, which essentialy removes the call to update the newly created Orders (one query less per order). def add_details(shop, shopify_orders) shopify_orders.each do |shopify_order| values = {:order_id => shopify_order.id.to_s, :shop_id => shop.id, :order_name => shopify_order.name, :order_created_at => shopify_order.created_at, :order_updated_at => shopify_order.updated_at, :status => Order.get_status(shopify_order), :payment_status => shopify_order.financial_status, :fulfillment_status => Order.get_fulfillment_status(shopify_order), :payment_method => shopify_order.processing_method, :gateway => shopify_order.gateway, :currency => shopify_order.currency, :subtotal_price => shopify_order.subtotal_price, :subtotal_tax => shopify_order.total_tax, :total_discounts => shopify_order.total_discounts, :total_line_items_price => shopify_order.total_line_items_price, :total_price => shopify_order.total_price, :total_tax => shopify_order.total_tax, :total_weight => shopify_order.total_weight, :taxes_included => shopify_order.taxes_included, :email => shopify_order.email, :order_note => shopify_order.note} get_order = Order.where(:order_id => shopify_order.id.to_s, :shop_id => shop.id) if get_order.blank? order = Order.create(values) else order = get_order.first order.update_attributes(values) end ShippingLine.add_details(order, shopify_order.shipping_lines) LineItem.add_details(order, shopify_order.line_items) Taxline.add_details(order, shopify_order.tax_lines) Fulfillment.add_details(order, shopify_order.fulfillments) Note.add_details(order, shopify_order.note_attributes) Discount.add_details(order, shopify_order.discount_codes) billing_address = shopify_order.billing_address rescue nil if !billing_address.blank? BillingAddress.add_details(order, billing_address) end shipping_address = shopify_order.shipping_address rescue nil if !shipping_address.blank? ShippingAddress.add_details(order, shipping_address) end payment_details = shopify_order.payment_details rescue nil if !payment_details.blank? PaymentDetail.add_details(order, payment_details) end end end and for the associated objects: class << self def add_details(order, tax_lines) tax_lines.each do |shopify_tax_line| values = {:order_id => order.id, :price => tax_line.price, :rate => tax_line.rate, :title => tax_line.title} get_taxline = Taxline.where(:order_id => order.id) if get_taxline.blank? taxline = Taxline.create(values) else taxline = get_taxline.first taxline.update_attributes(values) end end end end Any better suggestions? A: Try wrapping your entire code into a single database transaction. Since you're on Heroku it'll be a Postgres bottom-end. With that many update statements, you can probably benefit greatly by transacting them all at once, so your code executes quicker and basically just leaves a "queue" of 6500 statements to run on Postgres side as the server is able to dequeue them. Depending on the bottom end, you might have to transact into smaller chunks - but even transacting 100 at a time (and then close and re-open the transaction) would greatly improve throughput into Pg. http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html http://www.postgresql.org/docs/9.2/static/sql-set-transaction.html So before line 2 you'd add something like: def add_details(shop, shopify_orders) Order.transaction do shopify_orders.each do |shopify_order| And then at the very end of your method add another end: if !payment_details.blank? PaymentDetail.add_details(order, payment_details) end end //shopify_orders.each.. end //Order.transaction.. end //method A: You can monkey-patch ActiveRecord like this: class ActiveRecord::Base #http://stackoverflow.com/questions/15317837/bulk-insert-records-into-active-record-table?lq=1 #https://gist.github.com/jackrg/76ade1724bd816292e4e # "UPDATE THIS SET <list_of_column_assignments> FROM <table_name> THIS JOIN (VALUES (<csv1>, <csv2>,...) VALS ( <column_names> ) ON <list_of_primary_keys_comparison>" def self.bulk_update(record_list) pk = self.primary_key raise "primary_key not found" unless pk.present? raise "record_list not an Array of Hashes" unless record_list.is_a?(Array) && record_list.all? {|rec| rec.is_a? Hash } return nil if record_list.empty? result = nil #test if every hash has primary keys, so we can JOIN record_list.each { |r| raise "Primary Keys '#{self.primary_key.to_s}' not found on record: #{r}" unless hasAllPKs?(r) } #list of primary keys comparison pk_comparison_array = [] if (pk).is_a?(Array) pk.each {|thiskey| pk_comparison_array << "THIS.#{thiskey} = VALS.#{thiskey}" } else pk_comparison_array << "THIS.#{pk} = VALS.#{pk}" end pk_comparison = pk_comparison_array.join(' AND ') #SQL (1..record_list.count).step(1000).each do |start| key_list, value_list = convert_record_list(record_list[start-1..start+999]) #csv values csv_vals = value_list.map {|v| "(#{v.join(", ")})" }.join(", ") #column names column_names = key_list.join(", ") #list of columns assignments columns_assign_array = [] key_list.each {|col| unless inPK?(col) columns_assign_array << "THIS.#{col} = VALS.#{col}" end } columns_assign = columns_assign_array.join(', ') sql = "UPDATE THIS SET #{columns_assign} FROM #{self.table_name} THIS JOIN ( VALUES #{csv_vals} ) VALS ( #{column_names} ) ON ( #{pk_comparison} )" result = self.connection.execute(sql) return result if result<0 end return result end def self.inPK?(str) pk = self.primary_key test = str.to_s if pk.is_a?(Array) (pk.include?(test)) else (pk==test) end end #test if given hash has primary keys included as hash keys and those keys are not empty def self.hasAllPKs?(hash) h = hash.stringify_keys pk = self.primary_key if pk.is_a?(Array) (pk.all? {|k| h.key?(k) and h[k].present? }) else h.key?(pk) and h[pk].present? end end def self.convert_record_list(record_list) # Build the list of keys key_list = record_list.map(&:keys).flatten.map(&:to_s).uniq.sort value_list = record_list.map do |rec| list = [] key_list.each {|key| list << ActiveRecord::Base.connection.quote(rec[key] || rec[key.to_sym]) } list end # If table has standard timestamps and they're not in the record list then add them to the record list time = ActiveRecord::Base.connection.quote(Time.now) for field_name in %w(created_at updated_at) if self.column_names.include?(field_name) && !(key_list.include?(field_name)) key_list << field_name value_list.each {|rec| rec << time } end end return [key_list, value_list] end end Then, you can generate a array of hashes containing your models attributes (including theirs primary keys) and do something like: ActiveRecord::Base.transaction do Model.bulk_update [ {attr1: val1, attr2: val2,...}, {attr1: val1, attr2: val2,...}, ... ] end It will be a single SQL command without Rails callbacks and validations. A: For PostgreSQL, there are several issues that the above approach does not address: * *You must specify an actual table, not just an alias, in the update target table. *You cannot repeat the target table in the FROM phrase. Since you are joining the target table to a VALUES table (hence there is only one table in the FROM phrase, you won't be able to use JOIN, you must instead use "WHERE ". *You don't get the same "free" casts in a VALUES table that you do in a simple "UPDATE" command, so you must cast date/timestamp values as such (#val_cast does this). class ActiveRecord::Base def self.update!(record_list) raise ArgumentError "record_list not an Array of Hashes" unless record_list.is_a?(Array) && record_list.all? {|rec| rec.is_a? Hash } return record_list if record_list.empty? (1..record_list.count).step(1000).each do |start| field_list, value_list = convert_record_list(record_list[start-1..start+999]) key_field = self.primary_key non_key_fields = field_list - [%Q["#{self.primary_key}"], %Q["created_at"]] columns_assign = non_key_fields.map {|field| "#{field} = #{val_cast(field)}"}.join(",") value_table = value_list.map {|row| "(#{row.join(", ")})" }.join(", ") sql = "UPDATE #{table_name} AS this SET #{columns_assign} FROM (VALUES #{value_table}) vals (#{field_list.join(", ")}) WHERE this.#{key_field} = vals.#{key_field}" self.connection.update_sql(sql) end return record_list end def self.val_cast(field) field = field.gsub('"', '') if (column = columns.find{|c| c.name == field }).sql_type =~ /time|date/ "cast (vals.#{field} as #{column.sql_type})" else "vals.#{field}" end end def self.convert_record_list(record_list) # Build the list of fields field_list = record_list.map(&:keys).flatten.map(&:to_s).uniq.sort value_list = record_list.map do |rec| list = [] field_list.each {|field| list << ActiveRecord::Base.connection.quote(rec[field] || rec[field.to_sym]) } list end # If table has standard timestamps and they're not in the record list then add them to the record list time = ActiveRecord::Base.connection.quote(Time.now) for field_name in %w(created_at updated_at) if self.column_names.include?(field_name) && !(field_list.include?(field_name)) field_list << field_name value_list.each {|rec| rec << time } end end field_list.map! {|field| %Q["#{field}"] } return [field_list, value_list] end end
doc_4768
A: In Alfresco, to create a new version, just get the Private Working Copy that is returned to you after a checkout, update the PWC's content stream, then check it back in. Alfresco will manage the versions for you. Here is an example. Folder folder = (Folder) getSession().getObjectByPath("/cmis-demo"); String timeStamp = new Long(System.currentTimeMillis()).toString(); String filename = "cmis-demo-doc (" + timeStamp + ")"; // Create a doc Map <String, Object> properties = new HashMap<String, Object>(); properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document"); properties.put(PropertyIds.NAME, filename); String docText = "This is a sample document"; byte[] content = docText.getBytes(); InputStream stream = new ByteArrayInputStream(content); ContentStream contentStream = getSession().getObjectFactory().createContentStream(filename, Long.valueOf(content.length), "text/plain", stream); Document doc = folder.createDocument( properties, contentStream, VersioningState.MAJOR); System.out.println("Created: " + doc.getId()); System.out.println("Content Length: " + doc.getContentStreamLength()); System.out.println("Version label:" + doc.getVersionLabel()); // Now update it with a new version if (doc.getAllowableActions().getAllowableActions().contains(org.apache.chemistry.opencmis.commons.enums.Action.CAN_CHECK_OUT)) { doc.refresh(); String testName = doc.getContentStream().getFileName(); ObjectId idOfCheckedOutDocument = doc.checkOut(); Document pwc = (Document) session.getObject(idOfCheckedOutDocument); docText = "This is a sample document with an UPDATE"; content = docText.getBytes(); stream = new ByteArrayInputStream(content); contentStream = getSession().getObjectFactory().createContentStream(filename, Long.valueOf(content.length), "text/plain", stream); ObjectId objectId = pwc.checkIn(false, null, contentStream, "just a minor change"); doc = (Document) session.getObject(objectId); System.out.println("Version label is now:" + doc.getVersionLabel()); } When run, it outputs this: Created: workspace://SpacesStore/d6f3fca2-bf9c-4a0e-8141-088d07d45359;1.0 Content Length: 25 Version label:1.0 Version label is now:1.1 Done
doc_4769
But now I need to use a different approach. In my app the user doesn't have limitation of the type of file (can be an image, a pdf, or something else), so, according to the documentation I'm using the following approach: val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "*/*" } requireActivity().startActivityForResult(intent, REQUEST_CODE_PICK_ID) It works, and after the file selection, I obtain the content uri of the file in the onActivityResult. I'm able to query the content provider to obtain a small amount of information (filename for example), and I can convert the content uri in a filedescriptor or an inputstream using the content resolver. But I don't have the file instance, that I need to use to convert the file into a RequestBody. I can obtain a bytearray from the inputstream and I could use it (there is another extension function in the request body), but is it the right approach? If the file is big, could it be bad in terms of performance? I could create a copy of the file using the inputstream, but I don't like this approach, the official documentation says to use open_document instead of get_content as action of the intent to avoid copy creation of the file. So, how can I use the filedescriptor or the inputstream with retrofit? There is a way to obtain a File instance from the content uri? A: You can get Input stream Object from content provider by passing your Uri once u gets it convert input stream to byte array by following below code You can use Apache Commons IO to handle this and similar tasks. The IOUtils type has a static method to read an InputStream and return a byte[]. InputStream is; byte[] bytes = IOUtils.toByteArray(is); In Retrofit 2.7.1 There is an Extension class named Request body There is an extension method to convert byte array into request body @JvmOverloads @JvmStatic @JvmName("create") fun ByteArray.toRequestBody( contentType: MediaType? = null, offset: Int = 0, byteCount: Int = size ): RequestBody { checkOffsetAndCount(size.toLong(), offset.toLong(), byteCount.toLong()) return object : RequestBody() { override fun contentType() = contentType override fun contentLength() = byteCount.toLong() override fun writeTo(sink: BufferedSink) { sink.write(this@toRequestBody, offset, byteCount) } } }
doc_4770
s1 = "this is a foo bar sentence ." s2 = "what the foo bar blah blah black sheep is doing ?" def longest_common_substring(s1, s2): m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))] longest, x_longest = 0, 0 for x in xrange(1, 1 + len(s1)): for y in xrange(1, 1 + len(s2)): if s1[x - 1] == s2[y - 1]: m[x][y] = m[x - 1][y - 1] + 1 if m[x][y] > longest: longest = m[x][y] x_longest = x else: m[x][y] = 0 return s1[x_longest - longest: x_longest] print longest_common_substring(s1, s2) [out]: foo bar But how do i ensure that the longest common substring respect English word boundary and don't cut up a word? For example, the following sentences: s1 = "this is a foo bar sentence ." s2 = "what a kappa foo bar black sheep ?" print longest_common_substring(s1, s2) outputs the follow which is NOT desired since it breaks up the word kappa from s2: a foo bar The desired output is still: foo bar I've tried also an ngram way of getting the longest common substring respecting word boundary but is there other way that deals with strings without calculating ngrams? (see answer) A: This is too simple to understand. I used your code to do 75% of the job. I first split the sentence into words, then pass it to your function to get the largest common substring(in this case it will be longest consecutive words), so your function gives me ['foo', 'bar'], I join the elements of that array to produce the desired result. Here is the online working copy for you to test and verify and fiddle with it. http://repl.it/RU0/1 def longest_common_substring(s1, s2): m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))] longest, x_longest = 0, 0 for x in xrange(1, 1 + len(s1)): for y in xrange(1, 1 + len(s2)): if s1[x - 1] == s2[y - 1]: m[x][y] = m[x - 1][y - 1] + 1 if m[x][y] > longest: longest = m[x][y] x_longest = x else: m[x][y] = 0 return s1[x_longest - longest: x_longest] def longest_common_sentence(s1, s2): s1_words = s1.split(' ') s2_words = s2.split(' ') return ' '.join(longest_common_substring(s1_words, s2_words)) s1 = 'this is a foo bar sentence .' s2 = 'what a kappa foo bar black sheep ?' common_sentence = longest_common_sentence(s1, s2) print common_sentence >> 'foo bar' Edge cases * *'.' and '?' are also treated as valid words as in your case if there is a space between last word and the punctuation mark. If you don't leave a space they will be counted as part of last word. In that case 'sheep' and 'sheep?' would not be same words anymore. Its up to you decide what to do with such characters, before calling such function. In that case import re s1 = re.sub('[.?]','', s1) s2 = re.sub('[.?]','', s2) and then continue as usual. A: My answer does not draw from any official sources, but just a simple observation: at least in my installation, there is a difference between the output of your LCS function as it is on the pair (s1, s2) and (s1, s3): In [1]: s1 = "this is a foo bar sentence ." In [3]: s2 = "what the foo bar blah blah black sheep is doing ?" In [4]: s3 = "what a kappa foo bar black sheep ?" In [12]: longest_common_substring(s1, s3) Out[12]: 'a foo bar ' In [13]: longest_common_substring(s1, s2) Out[13]: ' foo bar ' As you may notice, if complete words are matched, then also the surrounding whitespace is matched. You can then modify the function before its output is returned, like this: answer = s1[x_longest - longest: x_longest] if not (answer.startswith(" ") and answer.endswith(" ")): return longest_common_substring(s1, answer[1:]) else: return answer I am sure there are other edge cases, like the substring appearing at the end of the string, recursively calling the function either with s1 or s2, whether to trim the answer front or back, and others -- but at least in the cases you show, this simple modification does what you want: In [20]: longest_common_substring(s1, s3) Out[20]: ' foo bar ' Do you think this direction is worth exploring? A: Just add an acceptance condition in your code: s1 = "this is a foo bar sentence ." s2 = "what the foo bar blah blah black sheep is doing ?" def longest_common_substring(s1, s2): m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))] longest, x_longest = 0, 0 for x in xrange(1, 1 + len(s1)): for y in xrange(1, 1 + len(s2)): if s1[x - 1] == s2[y - 1]: m[x][y] = m[x - 1][y - 1] + 1 if m[x][y] > longest and word_aligned(x, y, m[x][y]): # acceptance condition longest = m[x][y] x_longest = x else: m[x][y] = 0 return s1[x_longest - longest: x_longest] def word_aligned(x, y, length): """check that a match starting at s1[x - 1] and s2[y - 1] is aligned on a word boundary""" # check start of match in s1 if s1[x - 1].isspace(): # match doesn't start with a character, reject return False if x - 2 > 0 and not s1[x - 2].isspace(): # char before match is not start of line or space, reject return False # check start of match in s2 ... same as above ... # check end of match in s1 ... your code is a bit hard for me follow, what is end of match? ... # check end of match in s2 ... same as above ... return True print longest_common_substring(s1, s2) A: This is more of an interesting problem then I initially gave it credit for. When you think about it there are 4 possible outcomes. * *The trivial case, the whole string is matched no boundaries (your first example) *Cross a word boundary at the beginning (your second example) *Cross a word boundary at the end *Have a word boundary at each end Now your code takes care of the trivial case so we can leverage that; all that's left is to wrap your results in a few checks for the other cases. So what should these checks look like? Let's take your failure case: string 1 = "this is a foo bar sentence ." string 2 = "what a kappa foo bar black sheep ?" output string = "a foo bar" So from a string find perspective we can find all those letters in that order in both string1 and string2, but if we separate everything around spaces into lists, and look for the lists in order only string1 will match. Now I'm primarily a C guy, so I want to write that in a function: def full_string(str1, str2, chkstr): l1 = str1.split() l2 = str2.split() chkl = chkstr.split() return (any(l1[i:i+len(chkl)]==chkl for i in xrange(len(l1)-len(chkl)+1)) and any(l2[i:i+len(chkl)]==chkl for i in xrange(len(l2)-len(chkl)+1))) With this function we can check if either of the two strings do not contain all of the words of our result from longest_common_substring(s1, s2) in order. Perfect. So the last step is to combine these two functions and check for each of the 4 cases listed above: def longest_whole_substring(s1, s2): subs = longest_common_substring(s1, s2) if not full_string(s1, s2, subs): if full_string(s1, s2, ' '.join(subs.split()[1:])): subs = ' '.join(subs.split()[1:]) elif full_string(s1, s2, ' '.join(subs.split()[:-1])): subs = ' '.join(subs.split()[:-1]) else: subs = ' '.join(subs.split()[1:-1]) return subs Now the function longest_whole_substring(s1, s2) will provide the longest whole substring not chopping off any words. Let’s just test it out in each of the cases: Trivial: >>> a = 'this is a foo bar bar foo string' >>> b = 'foo bar' >>> >>> longest_whole_substring(a,b) 'foo bar' Word boundary at the beginning: >>> b = 's a foo bar' >>> >>> longest_whole_substring(a,b) 'a foo bar ' Word boundry at the end: >>> b = 'foo bar f' >>> >>> longest_whole_substring(a,b) 'foo bar' And a Word boundry at both ends: >>> b = 's a foo bar f' >>> >>> longest_whole_substring(a,b) 'a foo bar' Lookin' Good! A: All you need to do is add checks for beginning and end of a word. You then update m only for valid match ends. Like so: def longest_common_substring(s1, s2): m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))] longest, x_longest = 0, 0 for x in xrange(1, 1 + len(s1)): # current character in s1 x_char = s1[x - 1] # we are at the beginning of a word in s1 if # (we are at the beginning of s1) or # (previous character is a space) x_word_begin = (x == 1) or (s1[x - 2] == " ") # we are at the end of a word in s1 if # (we are at the end of s1) or # (next character is a space) x_word_end = (x == len(s1)) or (s1[x] == " ") for y in xrange(1, 1 + len(s2)): # current character in s2 y_char = s2[y - 1] # we are at the beginning of a word in s2 if # (we are at the beginning of s2) or # (previous character is a space) y_word_begin = (y == 1) or (s2[y - 2] == " ") # we are at the end of a word in s2 if # (we are at the end of s2) or # (next character is a space) y_word_end = (y == len(s2)) or (s2[y] == " ") if x_char == y_char: # no match starting with x_char if m[x - 1][y - 1] == 0: # a match can start only with a space # or at the beginning of a word if x_char == " " or (x_word_begin and y_word_begin): m[x][y] = m[x - 1][y - 1] + 1 else: m[x][y] = m[x - 1][y - 1] + 1 if m[x][y] > longest: # the match can end only with a space # or at the end of a word if x_char == " " or (x_word_end and y_word_end): longest = m[x][y] x_longest = x else: m[x][y] = 0 return s1[x_longest - longest: x_longest] A: I did it recursively: def common_phrase(self, longer, shorter): """ recursively find longest common substring, consists of whole words only and in the same order """ if shorter in longer: return shorter elif len(shorter.split()) > 1: common_phrase_without_last_word = common_phrase(shorter.rsplit(' ', 1)[0], longer) common_phrase_without_first_word = common_phrase(shorter.split(' ', 1)[1], longer) without_first_is_longer = len(common_phrase_without_last_word) < len(common_phrase_without_first_word) return ((not without_first_is_longer) * common_phrase_without_last_word + without_first_is_longer * common_phrase_without_first_word) else: return '' Just classify the two strings to 'shorter' and 'longer' before applying: if len(str1) > len(str2): longer, shorter = str1, str2 else: longer, shorter = str2, str1 A: Here's an ngram way: def ngrams(text, n): return [text[i:i+n] for i in xrange(len(text)-n)] def longest_common_ngram(s1, s2): s1ngrams = list(chain(*[[" ".join(j) for j in ngrams(s1.split(), i)] for i in range(1, len(s1.split()))])) s2ngrams = list(chain(*[[" ".join(j) for j in ngrams(s2.split(), i)] for i in range(1, len(s2.split()))])) return set(s1ngrams).intersection(set(s2ngrams)) A: One efficient method for finding longest common substrings is a suffix tree (see http://en.wikipedia.org/wiki/Suffix_tree and http://en.wikipedia.org/wiki/Longest_common_substring_problem). I don't see any reason you couldn't create a suffix tree using words instead of characters, in which case the longest-common-subsequence extracted from the tree would respect token boundaries. This approach would be particularly efficient if you want to find common substrings between one fixed string and a large number of other strings. See the accepted answer to python: library for generalized suffix trees for a list of Python suffix tree implementations. A: from difflib import SequenceMatcher def longest_substring(str1, str2): # initialize SequenceMatcher object with # input string # below logic is to make sure word does not get cut str1 = " " + str1.strip() + " " str2 = " " + str2.strip() + " " seq_match = SequenceMatcher(None, str1, str2) # find match of longest sub-string # output will be like Match(a=0, b=0, size=5) match = seq_match.find_longest_match(0, len(str1), 0, len(str2)) # return longest substring if match.size != 0: lm = str1[match.a: match.a + match.size] # below logic is to make sure word does not get cut if not lm.startswith(" "): while not (lm.startswith(" ") or len(lm) == 0): lm = lm[1:] if not lm.endswith(" "): while not (lm.endswith(" ") or len(lm) == 0): lm = lm[:-1] return lm.strip() else: return ""
doc_4771
HTML <div class="gif"> </div> <button class="stop">Stop</button> CSS .gif { background-image: url('https://img06.deviantart.net/4ba2/i/2012/053/c/c/stacey_run_sprite_sheet_by_django90-d4qo9pi.jpg'); width: 140px; height: 220px; } Javascript var $image = document.querySelector('.gif'); var $button = document.querySelector('.stop'); var id = setInterval(function () { $image.style.backgroundPosition = '-140px'; }, 60); $button.addEventListener('click', function () { clearInterval(id); }); Somehow the image animates only once. How can I keep it animated (loop the animation) ? Here is JSFIDDLE A: You have 2 problems here, where one is to increment moving horizontal and vertical (every 4:th step), and the other is that the images aren't easily divided as they differ in size. One way would be to recreate the image, another is like this. var $image = document.querySelector('.gif'); var $button = document.querySelector('.start'); var $button2 = document.querySelector('.stop'); var $positionx = [0,-230,-515,-770,0,-230,-515,-770]; var $positiony = [0,0,0,0,-220,-220,-220,-220]; var $positioncounter = 0; var id; $button.addEventListener('click', function () { if (id) return; id = setInterval(function () { $positioncounter++; if ($positioncounter >= $positionx.length) {$positioncounter = 2} $image.style.backgroundPosition = $positionx[$positioncounter] + 'px ' + $positiony[$positioncounter] + 'px'; }, 100); }); $button2.addEventListener('click', function () { clearInterval(id); id = null; $positioncounter = 0; $image.style.backgroundPosition = '0px 0px'; }); .gif { background-image: url('https://img06.deviantart.net/4ba2/i/2012/053/c/c/stacey_run_sprite_sheet_by_django90-d4qo9pi.jpg'); width: 180px; height: 220px; background-repeat: no-repeat; } button { margin-top: 20px; } .stop { margin-left: 90px; } <div class="gif"></div> <button class="start">Start</button> <button class="stop">Stop</button> A: Your problem is that you get the backgroundPosition values which return a String , not a number ,so you have to do some manipulation to make the annimation work : edit: Another probeleme is that your Images isn't correctly divided ( for sprite use ) : so I used another images that can work correctly : JS var $image = document.querySelector('.gif'); var $button = document.querySelector('.stop'); //get the img width var imgWidth = window.getComputedStyle($image,null).width.replace("px", ""); var id = setInterval(function () { // get backround style axis (x y) style=window.getComputedStyle($image,null).backgroundPosition.trim().split(/\s+/); // replace px by nothing to get number string var position = style[0].replace("px", ""); $image.style.backgroundPosition = parseInt(position)-parseInt(imgWidth)+"px 0px"; }, 100); $button.addEventListener('click', function () { clearInterval(id); }); try this : Fiddle (Updated Fiddle) A: I think the problem is with your background position value. the interval works fine but the background position is not changing! its always set to -140px. if you want it to decrease by 140 each time. you have to use variables. try this: var $position = 0; var id = setInterval(function () { $position = $position - 140; $image.style.backgroundPosition = $position + 'px'; }, 60); and this changes the position both vertically and horizontally. I tries using it on fiddle it should be: $image.style.backgroundPosition = $position + 'px 0'; this worked just fine.
doc_4772
createElement() { this.input = document.createElement('input'); this.input.setAttribute('matInput', ''); this.input.setAttribute('placeholder', 'Tema'); this.input.setAttribute('[(ngModel)]', 'module.theme'); this.input.setAttribute('name', 'theme'); return (<HTMLDivElement>(document.getElementById('ejemplo').appendChild(this.input))); } A: Something like this.input.setAttribute('[(ngModel)]', 'module.theme'); is not supposed to work. Property/attribute bindings and component/directive instantiation only happens for markup added to a components template statically. If it is added dynamically it won't have any effect. If you need this, you can create and compile a component at runtime and add that component dynamically (to a statically defined ViewContainerRef). Alternatively you can use imperative code to update the DOM.
doc_4773
The Display Attribute does not work on classes and the DisplayName Attribute does not support localization. [MetadataTypeAttribute(typeof(ServiceType.ServiceTypeMetadata))] // Compile Error: Attribute 'Display' is not valid on this declaration type. It is only valid on 'method, property, indexer, field, param' declarations. // [Display(ResourceType = typeof(Resources.DisplayNames), Name = "ServiceType")] [System.ComponentModel.DisplayName("Service Type")] public partial class ServiceType : ILookupEntity<EdmBilingualStringVarCharSingleLine>, ISelectListEntity, IUpdateableEntity { #region Metadata internal sealed class ServiceTypeMetadata { [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] [Display(ResourceType = typeof(Resources.DisplayNames), Name = "InactiveDate")] public DateTime? InactiveDate { get; set; } [Display(ResourceType = typeof(Resources.DisplayNames), Name = "ModifiedBy")] [Required] public string ModifiedBy { get; set; } [Display(ResourceType = typeof(Resources.DisplayNames), Name = "ModifiedDate")] [Required] public System.DateTime ModifiedDate { get; set; } } #endregion // ... the rest of the class .... } A: The solution is to create your own Display Name attribute. The following worked for me and could be made more generic by passing the Resource file name which in my case I simply hardcoded. using System.ComponentModel; using System.Resources; namespace SCC.Case.Entities { /// <summary> /// Provides a class attribute that lets you specify the localizable string for the entity class /// </summary> class DisplayNameForClassAttribute : DisplayNameAttribute { public string Name { get; set; } public override string DisplayName { get { ResourceManager resourceManager = new ResourceManager("SCC.Case.Entities.DisplayNames", typeof(DisplayNameForClassAttribute).Assembly); return resourceManager.GetString(this.Name); } } } }
doc_4774
The title as as generic as possible to extend to a broad audience, and the question is as specific to my problem as possible identical to my issue as possible so I can get maximum audience coverage but get a specific solution. Summary I have missing records that should display in my desired query but are not showing up, because they are not present in one table of a join. I want to accomplish addition of the missing records without using a second join. My question follows, along with a Minimal Complete Verifiable Example, with a desired result. See below for details. Question How do I select two columns from a result of a join query, then use a where clause to display those results from the join also displaying the non matching rows from the set of my in clause that have a column not in the set in the most time efficient manner as possible? What I want? 10 rows columna columnb columnc val01 (null) (null) val02 2020-01-01 2020-01-01 val03 2020-01-01 2020-01-01 val04 2020-01-01 2020-01-01 val05 2020-01-01 2020-01-01 val06 2020-01-01 2020-01-01 val07 2020-01-01 2020-01-01 val08 2020-01-01 2020-01-01 val09 2020-01-01 2020-01-01 val10 2020-01-01 2020-01-01 num rows returned: 10 What I get? 9 rows - one less row from 10 row expectation columna columnb columnc val02 2020-01-01 2020-01-01 val03 2020-01-01 2020-01-01 val04 2020-01-01 2020-01-01 val05 2020-01-01 2020-01-01 val06 2020-01-01 2020-01-01 val07 2020-01-01 2020-01-01 val08 2020-01-01 2020-01-01 val09 2020-01-01 2020-01-01 val10 2020-01-01 2020-01-01 num rows returned: 9 What I have tried? I have tried union (not shown below, but if desired can be added to question details), leading to much more records than necessary. But on analysis, the primary issue lies in the misuse of my filter on join, which does not include the missing record on columnA. Schema CREATE TABLE IF NOT EXISTS `tableb` ( `col1` char NOT NULL, `columna` char(5) NOT NULL, `columnb` date, `columnc` date ) DEFAULT CHARSET=utf8; INSERT INTO `tableb` (`col1`, `columna`, `columnb`, `columnc`) VALUES ('a', 'val01', '2020-01-01', '2020-01-01'), ('b', 'val02', '2020-01-01', '2020-01-01'), ('c', 'val03', '2020-01-01', '2020-01-01'), ('d', 'val04', '2020-01-01', '2020-01-01'), ('e', 'val05', '2020-01-01', '2020-01-01'), ('f', 'val06', '2020-01-01', '2020-01-01'), ('g', 'val07', '2020-01-01', '2020-01-01'), ('h', 'val08', '2020-01-01', '2020-01-01'), ('i', 'val09', '2020-01-01', '2020-01-01'), ('j', 'val10', '2020-01-01', '2020-01-01'); CREATE TABLE IF NOT EXISTS `tablea` ( `col1` char(2) NOT NULL ) DEFAULT CHARSET=utf8; INSERT INTO `tablea` (`col1`) VALUES ('b'), ('c'), ('d'), ('e'), ('f'), ('g'), ('h'), ('i'), ('j'); Expected Result Query: select desired.columna, desired.columnb, desired.columnc from (select * from (select 'val01' as columna, null as columnb, null as columnc) `t1` union select * from (select 'val02' as columna, '2020-01-01' as columnb, '2020-01-01' as columnc) `t2` union select * from (select 'val03' as columna, '2020-01-01' as columnb, '2020-01-01' as columnc) `t3` union select * from (select 'val04' as columna, '2020-01-01' as columnb, '2020-01-01' as columnc) `t4` union select * from (select 'val05' as columna, '2020-01-01' as columnb, '2020-01-01' as columnc) `t5` union select * from (select 'val06' as columna, '2020-01-01' as columnb, '2020-01-01' as columnc) `t6` union select * from (select 'val07' as columna, '2020-01-01' as columnb, '2020-01-01' as columnc) `t7` union select * from (select 'val08' as columna, '2020-01-01' as columnb, '2020-01-01' as columnc) `t8` union select * from (select 'val09' as columna, '2020-01-01' as columnb, '2020-01-01' as columnc) `t9` union select * from (select 'val10' as columna, '2020-01-01' as columnb, '2020-01-01' as columnc) `t10`) desired; Actual Query: #Actual Result /*Goal: Basically, alongside the join results, I want to also display the rows from the set of the NOT IN clause based upon the column, that are not in the result set of the join, which would show columnb, columnc as null*/ SELECT columna, columnb, columnc FROM tablea a, tableb b # inner join WHERE a.col1 = b.col1 # on a.col1 = b.col1 AND b.columna IN ('val01', 'val02', 'val03', 'val04', 'val05', 'val06', 'val07', 'val08', 'val09', 'val10') /* Presently: Using IN returns 9 rows in this query */ UNION SELECT columna, columnb, columnc FROM tablea a, tableb b # inner join WHERE a.col1 = b.col1 # on a.col1 = b.col1 AND b.columna NOT IN ('val01', 'val02', 'val03', 'val04', 'val05', 'val06', 'val07', 'val08', 'val09', 'val10') /* Presently: Using NOT IN returns 0 rows in this query because my join is returning result of that join BUT not adding the values not present in the join from the "not in" set to the set of results. */ GROUP BY b.columna ,find_in_set("b.columna", "val01, val02, val03, val04, val05, val06, val07, val08, val09, val10") # find_in_set is here to adhere to original order of a.col1 SQL Fiddle http://sqlfiddle.com/#!9/2c98a7/28 A: Using LEFT JOIN and condition in SELECT list: SELECT tb.columnA, IF(ta.col1 IS NULL, NULL, tb.columnb) AS columnb, IF(ta.col1 IS NULL, NULL, tb.columnc) AS columnc FROM tableb tb LEFT JOIN tablea ta ON tb.col1 = ta.col1; db<>fiddle demo Using CASE expression(more generic): SELECT tb.columnA, CASE WHEN ta.col1 IS NOT NULL THEN tb.columnb END AS columnb, CASE WHEN ta.col1 IS NOT NULL THEN tb.columnc END AS columnc FROM tableb tb LEFT JOIN tablea ta ON tb.col1 = ta.col1 If column we are joining is unique then double LEFT JOIN could be used: SELECT tb.columnA, tb2.columnb, tb2.columnc FROM tableb tb LEFT JOIN tablea ta ON tb.col1 = ta.col1 LEFT JOIN tableb tb2 ON ta.col1 = tb2.col1; db<>fiddle demo 2 EDIT: can you help answer if there is any other way to accomplish this other than the join Using correlated subquery: SELECT tb.columnA, CASE WHEN EXISTS (SELECT 1 FROM tablea ta WHERE tb.col1 = ta.col1) THEN tb.columnb END AS columnb, CASE WHEN EXISTS (SELECT 1 FROM tablea ta WHERE tb.col1 = ta.col1) THEN tb.columnc END AS columnc FROM tableb tb db<>fiddle demo3 And LATERAL JOIN but no real advantages over regular LEFT JOIN: SELECT tb.columnA, CASE WHEN s.c IS NOT NULL THEN tb.columnb END AS columnb, CASE WHEN s.c IS NOT NULL THEN tb.columnc END AS columnc FROM tableb tb LEFT JOIN LATERAL (SELECT 1 c FROM tablea ta WHERE tb.col1 = ta.col1 LIMIT 1) s ON TRUE And using mutually exclusive UNION ALL: SELECT tb.columnA, tb.columnB, tb.columnC FROM tableb tb WHERE EXISTS (SELECT 1 FROM tablea ta WHERE ta.col1 = tb.col1) UNION ALL SELECT tb.columnA, NULL AS columnB, NULL AS columnC FROM tableb tb WHERE NOT EXISTS (SELECT 1 FROM tablea ta WHERE ta.col1 = tb.col1) db<>fiddle demo4
doc_4775
The web service calls are asynchronous. But why do the controllers still exists to deal with the response? This is the web service call: [NSURLConnection connectionWithRequest:NSMutableURLRequestObject delegate:self]; This is the code in the controller which is a delegate to the web service: -(void)connectionDidFinishLoading:(NSURLConnection *)connection { // do something with response object [self performSegueWithIdentifier:@"XXsearch" sender:self]; } A: According to the documentation for connectionWithRequest:delegate: During the download the connection maintains a strong reference to the delegate. It releases that strong reference when the connection finishes loading, fails, or is canceled. This means that even though you are removing the view controller, the NSURLConnection is forcing it to stay around. First of all, you'll want to save the connection in property in your view controller. self.connection = [NSURLConnection connectionWithRequest:NSMutableURLRequestObject delegate:self]; Then you'll need to make sure you cancel the connection and set it to nil when your view controller is removed from its parent view controller. - (void)didMoveToParentViewController:(UIViewController *)parent { [super didMoveToParentViewController:parent]; if (!parent && self.connection) { [self.connection cancel]; [self setConnection:nil]; } } Also, you'll want to make sure you set the connection to nil when the connection finished or fails.
doc_4776
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'sql_user_name'@'172.45.678.910' (using password: YES) here is my code import mysql.connector import sshtunnel with sshtunnel.SSHTunnelForwarder( (ssh_host,ssh_port), ssh_username = ssh_username, ssh_pkey = ssh_pkey_path, remote_bind_address=(sql_host, sql_port), local_bind_address=("127.0.0.1",8080)) as server: mydb = mysql.connector.connect(host=sql_host,user=sql_user_name,password=sql_pwd,db=db_name) myCursor = mydb.cursor() my user_name and password is correct, I can successfully connect via sequal_pro using same credential and same ssh host, so why it is throwing an error here? and in error message which ssh_host('172.45.678.910') it is showing is also different, I never use this ssh_host in code,in variable "ssh_host" the ip is different, I tried all the solution available on the internet, but could not solve this issue
doc_4777
addEventListener(Event.EnterFrame,loop); I have to do varible = onEnterFrame() { } that type of code, I've only seen in AS2. my question is what documents do I read so I know what to use when working from the actions panel. also would like to start a loop in the actions panel. I've saw it a few time's but I can't think of any resources that demonstrate it at the moment. also, I am using as3 [edit] If I add the following code inside the Actionscript panel. I get an error addEventListener(Event.ENTER_FRAME, loop); public function loop(e:Event):void { } error 1114: The public attribute can only be used inside a package. If you must know why, I am just curious in case I want to try some simple code out without setting up a document class. Thanks A: If you are using CS4 you should use AS3. So the example you posted would look like: addEventListener(Event.ENTER_FRAME, loop); Good luck! A: I'm not totally sure this is what you're asking for but: addEventListener(Event.ENTER_FRAME, loop); function loop(event:Event):void { //whatever code you want to happen each frame }
doc_4778
val myList: List<Int>? = listOf() if(!myList.isNullOrEmpty()){ // myList manipulations } Which smartcasts myList to no non null. The below do not give any smartcast: if(!myList.orEmpty().isNotEmpty()){ // Compiler thinks myList can be null here // But this is not what I want either, I want the extension fun below } if(myList.isNotEmptyExtension()){ // Compiler thinks myList can be null here } private fun <T> Collection<T>?.isNotEmptyExtension() : Boolean { return !this.isNullOrEmpty() } Is there a way to get smartCasts for custom extensions? A: This is solved by contracts introduced in Kotlin 1.3. Contracts are a way to inform the compiler certain properties of your function, so that it can perform some static analysis, in this case enable smart casts. import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract @ExperimentalContracts private fun <T> Collection<T>?.isNotEmptyExtension() : Boolean { contract { returns(true) implies (this@isNotEmptyExtension != null) } return !this.isNullOrEmpty() } You can refer to the source of isNullOrEmpty and see a similar contract. contract { returns(false) implies (this@isNullOrEmpty != null) }
doc_4779
I created a SIGNAL/SLOT, the method is called: void MyWidget::slot( bool bChecked ) { myLayout->setEnabled(bChecked); std::cout << "OnAllToggled: " << bChecked << ", isEnabled: " << myLayout->isEnabled() << std::endl; } everything is great except that the layout is still accessible. Apparently I don't understand the meaning of setEnabled method. Question: what does setEnabled mean and how can I make the layout inaccessible? Thanks! A: I'd like to make widgets in some layout inaccessible, so a user would not be able to change a state of any layout's widgets (I want everything grayed out). And you try to disable the layout object. Of course, enabling or disabling layout affects the way widgets aligned against each other: void QLayout::setEnabled(bool enable) Enables this layout if enable is true, otherwise disables it. An enabled layout adjusts dynamically to changes; a disabled layout acts as if it did not exist. By default all layouts are enabled. Instead you can attempt to disable all the children for some parent widget: Disabling a widget implicitly disables all its children. Enabling respectively enables all child widgets unless they have been explicitly disabled. It it not possible to explicitly enable a child widget which is not a window while its parent widget remains disabled. For that you can create some 'container' widget that occupies the layout you are talking about and add the nested layout to that widget to accommodate all the widgets. QWidget* container = new QWidget; myLayout->addWidget(container); // put container widget in myLayout QHBoxLayout* hboxLayout = new QHBoxLayout(container); hBoxLayout->addWidget(widget1); hBoxLayout->addWidget(widget2); hBoxLayout->addWidget(widget3); container->setEnabled(false); // disable all nested widgets A: I had got problem, that relates to this question: QTCreator in design mode disables widgets on layout, when i disable layout. Every child has property "Enabled":false. And enabling layout programmably didn't enables all child. Way to disable/enable all widgets on layout (or just all child widgets): for(auto&& child:ui->parentLayout->findChildren<QWidget *>()){ child->setEnabled(false); }
doc_4780
Here is the code. The function UserExists() is returning false I'm not entirely sure if my LDAP query is even hitting my directory service. (Active Directory) using System.DirectoryServices; namespace UserManagement { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (UserExists("abc")) lblUserExists.Text = "Found Username"; } public static DirectoryEntry GetDirectoryEntry() { DirectoryEntry de = new DirectoryEntry(); de.Path = "LDAP://OU=Users,OU=Network Users,DC=domain,DC=org"; de.AuthenticationType = AuthenticationTypes.Secure; return de; } public bool UserExists(String UserName) { DirectoryEntry de = GetDirectoryEntry(); DirectorySearcher deSearch = new DirectorySearcher(); deSearch.SearchRoot = de; deSearch.Filter = "(&(objectClass=user) (cn=" + UserName + "))"; SearchResultCollection results = deSearch.FindAll(); return results.Count > 0; } } } A: I'm no guru, but some ideas: * *LDAP connection string doesn't look right - I would have thought it would look more like LDAP://MyADServer:389/CN=SomeStore,OU=Users,OU=Network Users,DC=domain,DC=org *You might need some properties to load, e.g. string[] propertiesToLoad = new string[] { "DistinguishedName", "mail" } ; ... deSearch.PropertiesToLoad = propertiesToLoad; *Possibly try fetch data without the username filter first to see if the connection works, i.e. deSearch.Filter = "(&(objectClass=user))" And add the user filter back later. A: If you are having issues searching for entities in Active Directory, consider tools like ldp. You can use it to check your paths are correct, the object exists and so on.
doc_4781
My Fragment class public class student extends Fragment { public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View view= inflater.inflate(R.layout.layout_main, container, false); return view; } public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); edittext.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub showDatePicker(); } }); } private void showDatePicker() { DatePickerFragment date = new DatePickerFragment(); /** * Set Up Current Date Into dialog */ Calendar calender = Calendar.getInstance(); Bundle args = new Bundle(); args.putInt("year", calender.get(Calendar.YEAR)); args.putInt("month", calender.get(Calendar.MONTH)); args.putInt("day", calender.get(Calendar.DAY_OF_MONTH)); date.setArguments(args); /** * Set Call back to capture selected date */ date.setCallBack(ondate); date.show(getFragmentManager(), "Date Picker"); } OnDateSetListener ondate = new OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { edittext.setText(String.valueOf(dayOfMonth) + "-" + String.valueOf(monthOfYear+1) + "-" + String.valueOf(year)); } }; } other class DatePickerFragment.java public class DatePickerFragment extends DialogFragment { OnDateSetListener ondateSet; private int year, month, day; public DatePickerFragment() {} public void setCallBack(OnDateSetListener ondate) { ondateSet = ondate; } @SuppressLint("NewApi") @Override public void setArguments(Bundle args) { super.setArguments(args); year = args.getInt("year"); month = args.getInt("month"); day = args.getInt("day"); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new DatePickerDialog(getActivity(), ondateSet, year, month, day); } } tentei outro forama com ou design de material mais na função dentro do fragmet... Please help me I accept another suggestion but it has to be within a frament
doc_4782
* *Site A has a sale category with a running 15% off. *Both sites have a coupon code that takes 10% off, they use the same code *The coupon excluded anything in the sale category. The problem is the coupon refuses to apply to products in this category, regardless of the site. So if I use the coupon on Site B, and the product is in Site A's sale section, it won't apply. I tried resolving this by setting the Catalog rule to stop processing further rules and setting up the priorities. However, this doesn't appear to have worked, as the coupon can still apply regardless. Since both sites use the same code for their coupon, I can't recreate it as a separate rule on the other site. So I'm left with trying to make the rules stop stacking. Does anyone know of some way to do this? A: It's kind of a hack, but I did figure out how to make this work. I basically just created a dummy cart rule using the same conditions as the catalog rule with a higher priority.
doc_4783
So to make anything compile in ghc, I have to use the -dynamic flag, otherwise it doesn't even discover the libraries. However, I would like to produce statically linked binaries that I can distribute to other systems. Is there any way to produce a statically linked binary from dynamic/shared libraries with ghc? I tried -optl-static from this related post but that led to countless "undefined reference" errors. A: Libraries compiled for dynamic linking are missing information needed for static linking (and vice versa). For details, see: * *Static link of shared library function in gcc This is intrinsic in the design of the OS linker, and beyond any limitation of cabal or GHC. For example, this cannot be simply done in C either. To achieve single-file redistributable binaries, you could try bundling the dynamic libs into the executable, using a format such as AppImage on Linux, or the windres resource scheme on Windows, but you would have to manually set up your code and cabal to find the libraries in the right place. A: If you use The Stack build system, it will automatically download and manage a fixed version of GHC and all libraries per project (and store them in a hidden folder in your project directory), so if you get it set up right, the whole lot will be static. Stack doesn't have amazing static support right now, but it can be made to work. Some resources: * *Static compilation with Stack *Adding --static flag for building static executables with stack? *Is there an easy way to compile static binaries?
doc_4784
The grid is much larger than the example and the numbers are arbitrary for the example. I'd like to compare the numbers in the odd columns, i.e. Col1 and Col3, with their adjacent columns, i.e. Col2 and Col4. I want to see if the values in Col1 cells are more than 2x the adjacent cell value in Col2 and if Col2 values are more than 2x the adjacent values in Col1. The same criteria applies to Col3 and Col4. If the values are out of variance I want to change the color of both cells to light red. I'd like to apply the same algorithm to all the cells in the grid, or have 2 algorithms, one for the odd number columns, another for the even number columns. I tried using "Conditional Formatting". Comparing Col1 to Col2 works correctly with =((B6 * 2) <= C6) but comparing Col2 to Col1 with =((C6 * 2) <= B6) does not produce the expected results. In fact it looks like it's actually comparing Col2 to its right hand neighbor Col3, which is no good. Questions: Is there a way using "Conditional Formatting" to compare a right hand cell with its left hand neighbor? Is there a better approach, maybe using a VBA macro or something similar? A: This can be done with conditional formatting. Taken from context, your column labeled "Col 1" is Column B, and your first row of data is row 2 * *Select the data range: B2:E4 in the example *Enter a CF rule formula (this will colour Col 1, Col 3 etc) =AND(ISEVEN(COLUMN()),OR(B2>C2*2,C2>B2*2)) *Enter another rule (this will colour Col 2, Col 4 etc) =AND(ISODD(COLUMN()),OR(A2>B2*2,B2>A2*2)) Notes: * *The Formulas assume that the data range starts in B2. If yours starts somewhere else, adjust the references accodingly. *The Formulas assume your data starts on an Even numbered column. If it in fact starts on an Odd numbered column, swap the ISEVEN and ISODD functions *I've used two different colours to show the effect of the two rules. You can of course use the same colour for both *I've used two rules as I think this is clearer. You could combine them into one rule if you want =OR(AND(ISEVEN(COLUMN()),OR(B2>C2*2,C2>B2*2)),AND(ISODD(COLUMN()),OR(A2>B2*2,B2>A2*2))) A: Try this (Suppose the numbers start at row 2) Sub Test() Dim r As Long, c As Long For r = 2 To Cells(Rows.Count, 1).End(xlUp).Row For c = 1 To 4 Step 2 If Cells(r, c).Value * 2 <= Cells(r, c + 1).Value Or Cells(r, c + 1).Value * 2 <= Cells(r, c).Value Then Cells(r, c).Resize(1, 2).Interior.Color = RGB(255, 153, 153) End If Next c Next r End Sub A: If I put my upper left data point in cell B6, then a conditional formatting formula like this =IF(MOD(COLUMN(),2),OR(B6*2<=A6,A6*2<=B6),OR(B6*2<=C6,C6*2<=B6)) over cells B6 onwards seems to do the trick. The logical test of the IF statement checks whether the column is even or odd. Based on that, it either looks backwards one cell (TRUE case here) or forwards one cell (FALSE case here). Good luck!
doc_4785
* *I cross checked the working directory using: import pandas as pd import numpy as np import os os.chdir("/Users/madan/Desktop/ML/Datasets/AutomobileDataset") os.getcwd() Output: '/Users/madan/Desktop/ML/Datasets/AutomobileDataset' *Then I tried reading the file using pandas: import pandas as pd import numpy as np import os os.chdir("/Users/madan/Desktop/ML/Datasets/AutomobileDataset") os.getcwd() automobile_data = pd.read_csv("AutomobileDataset.txt", sep = ',', header = None, na_values = '?') automobile_data.head() Output: --------------------------------------------------------------------------- ParserError: Error tokenizing data. C error: Expected 1 fields in line 2, saw 26 Someone please help me with this, I don't know where I am making a mistake. A: Can try this! import os # Read in a plain text file with open(os.path.join("c:user/xxx/xx", "xxx.txt"), "r") as f: text = f.read() print(text)
doc_4786
Similarly, I don't want my 'Previous' button going from the first back to the last. I've hit a wall! This is my code behind the 'Next' button } public void nextButtonPressed(ActionEvent e) { currentEntryIndex++; if (currentEntryIndex >= numberOfEntries){ currentEntryIndex = 0; } Any advice? Thanks, C A: You could test that it is less than the numberOfEntries before you increment. Something like, public void nextButtonPressed(ActionEvent e) { if (currentEntryIndex < numberOfEntries) { currentEntryIndex++; } } And similarly with "Previous" test that you are > 0 before subtracting one.
doc_4787
import SwiftUI struct ContentView: View { @State private var isAnimating = false var animation: Animation { Animation.linear(duration: 1) .repeatForever(autoreverses: false) } var body: some View { HStack { Text("Hello, world!") .padding() Spacer() Rectangle() .frame(width: 20, height: 20) .foregroundColor(.red) .rotationEffect(Angle.degrees(isAnimating ? 360 : 0)) .animation(animation) .onAppear { isAnimating = true } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } A: You just need to join animation with value, like Rectangle() .frame(width: 20, height: 20) .foregroundColor(.red) .rotationEffect(Angle.degrees(isAnimating ? 360 : 0)) .animation(animation, value: isAnimating) // << here !! .onAppear { isAnimating = true }
doc_4788
import sys import random from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import Qt class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.label = QtWidgets.QLabel() self.setCentralWidget(self.label) self.Clock_pixmap = QtGui.QPixmap("clock.png") self.Arm_pixmap = QtGui.QPixmap("clockarm.png") self.painter = QtGui.QPainter(self.Clock_pixmap) self.painter.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform) self.painter.drawPixmap(QtCore.QPoint(), self.Arm_pixmap) self.painter.end() self.label.setPixmap(self.Clock_pixmap.scaled(self.label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) self.label.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.label.setMinimumSize(150, 150) self.w1 = self.Arm_pixmap.width()/2 self.h1 = self.Arm_pixmap.height()/2 self.rotationData = random.sample(range(100), 100) timer = QtCore.QTimer(self, timeout=self.rotateArm, interval=100) timer.start() self.n=0 def rotateArm(self): self.n+=1 self.painter.translate(self.w1,self.h1) self.painter.rotate(self.rotationData[self.n]) self.painter.translate(-self.w1,-self.h1) self.update() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_()) A: You are painting on a QPainter where you indicated that it was finished painting since you used the end() method. So it is not necessary to make a class attribute to QPainter but only a local variable. Considering the above, the solution is: import sys import random from PyQt5 import QtCore, QtGui, QtWidgets class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self._angle = 0 self.label = QtWidgets.QLabel() self.setCentralWidget(self.label) self.clock_pixmap = QtGui.QPixmap("clock.png") self.arm_pixmap = QtGui.QPixmap("clockarm.png") rotation_data = random.sample(range(100), 100) self.data_iter = iter(rotation_data) timer = QtCore.QTimer(self, timeout=self.rotate_arm, interval=100) timer.start() def rotate_arm(self): try: angle = next(self.data_iter) except StopIteration: pass else: self.draw(angle) def draw(self, angle): pixmap = self.clock_pixmap.copy() painter = QtGui.QPainter(pixmap) painter.setRenderHints( QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform ) painter.translate(pixmap.rect().center()) painter.rotate(angle) painter.translate(-pixmap.rect().center()) painter.drawPixmap(QtCore.QPoint(), self.arm_pixmap) painter.end() self.label.setPixmap(pixmap) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_())
doc_4789
I am building a custom Gallery app where the first thumbnail is an album cover displaying album details. Here's the flow: getView() { //inflate cover.xml which includes two textviews and an imageview. if(position == 0) //set some album-specific text else //set image-specific text } Here's the actual getView() code: public View getView(int position, View convertView, ViewGroup parent) { //TODO: Recycle view convertView = mInflater.inflate(R.layout.cover, null); TextView tvTxt1 = (TextView)convertView.findViewById(R.cover.tvCoverText1); TextView tvTxt2 = (TextView)convertView.findViewById(R.cover.tvCoverText2); //ImageView imgView = (ImageView)convertView.findViewById(R.cover.imgImage); if(position == 0) { tvTxt1.setText("AlbumText1"); tvTxt2.setText("AlbumText2"); return convertView; } else { tvTxt1.setText("ImageText1"); tvTxt2.setText("ImageText2"); ImageView imgView = new ImageView(mContext); imgView.setImageResource(mImageIds[position]); imgView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); imgView.setScaleType(ImageView.ScaleType.FIT_XY); imgView.setBackgroundResource(mGalleryItemBackground); return imgView; //return convertView; } } The cover.xml contains an ImageView and two TextViews. when I return convertView in the else block, I get a ClassCastException. I am certainly doing something wrong. I have spent almost two days on this now :( Please help! A: Here's what it looks like to me. When position == 0 you are returning convertView, which is a View. When you return "else", you are returning a ImageView. Your method is set to return a View. Try casting your ImageView to a View before returning it. Try: return (View) imgView; Never tried it myself though... A: Add this imageview into your layout xml, and then retrieve it from convertview and at the end return the convert view. This may solve the problem. I have worked a lot on Gallery widget, if there is more problem do let me know. A: After trying all the suggestions given by helpful people here,I still wasn't able to get across the ClassCastException. So, as a workaround - I sort of "overlayed" the Gallery with other views that I wanted to enable/disable. This is a workaround, so if someone comes up with a better answer - do post it here so I can accept it. So here's what worked for me: public View getView(int position, View convertView, ViewGroup parent) { //TODO: Recycle view //onvertView = mInflater.inflate(R.layout.cover, null); //ImageView imgView = (ImageView)convertView.findViewById(R.cover.imgImage); ImageView imgView = new ImageView(mContext); imgView.setImageResource(mImageIds[position]); imgView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); imgView.setScaleType(ImageView.ScaleType.FIT_XY); imgView.setBackgroundResource(mGalleryItemBackground); if(position == 0) { tvText1.setText("AlbumText1"); tvText2.setText("AlbumText2"); tvText3.setVisibility(View.VISIBLE); bottomBar.setVisibility(View.VISIBLE); } else { tvText1.setText("ImageText1"); tvText2.setText("ImageText2"); tvText3.setVisibility(View.GONE); bottomBar.setVisibility(View.GONE); } return imgView; } Here's my layout main.xml file: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Gallery android:id="@+main/gallery" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <!-- <ImageView android:id="@+main/imgImage" --> <!-- android:layout_width="fill_parent" android:layout_height="fill_parent" --> <!-- android:adjustViewBounds="true"> --> <!-- </ImageView> --> <TextView android:id="@+main/tvText2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true" android:maxLines="1" android:text="Text2" android:layout_alignParentBottom="true" /> <TextView android:id="@+main/tvText1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:maxLines="2" android:text="Text1" android:layout_above="@main/tvText2" /> <RelativeLayout android:id="@+main/bottomBar" android:layout_alignParentBottom="true" android:layout_width="fill_parent" android:layout_height="40dip" android:background="#A3A1A1"> <TextView android:id="@+main/tvBottomText" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="BottomBarText"/> </RelativeLayout> </RelativeLayout> The rest of the code in Main.java (whose getView method I modified) is almost verbatim from here Thanks again for helping out!
doc_4790
Apache error log: [Fri Jun 19 07:39:53.574508 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] mod_wsgi (pid=14184): Failed to exec Python script file '/var/www/fplstats/python-django-fplstats/fplstats/wsgi.py'. [Fri Jun 19 07:39:53.574573 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] mod_wsgi (pid=14184): Exception occurred processing WSGI script '/var/www/fplstats/python-django-fplstats/fplstats/wsgi.py'. [Fri Jun 19 07:39:53.575320 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] Traceback (most recent call last): [Fri Jun 19 07:39:53.575367 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] File "/var/www/fplstats/python-django-fplstats/fplstats/wsgi.py", line 16, in <module> [Fri Jun 19 07:39:53.575374 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] application = get_wsgi_application() [Fri Jun 19 07:39:53.575381 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] File "/var/www/fplstats/fplstatsenv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Fri Jun 19 07:39:53.575386 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] django.setup(set_prefix=False) [Fri Jun 19 07:39:53.575392 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] File "/var/www/fplstats/fplstatsenv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup [Fri Jun 19 07:39:53.575397 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] apps.populate(settings.INSTALLED_APPS) [Fri Jun 19 07:39:53.575403 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] File "/var/www/fplstats/fplstatsenv/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate [Fri Jun 19 07:39:53.575407 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] app_config = AppConfig.create(entry) [Fri Jun 19 07:39:53.575413 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] File "/var/www/fplstats/fplstatsenv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create [Fri Jun 19 07:39:53.575418 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] module = import_module(entry) [Fri Jun 19 07:39:53.575424 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module [Fri Jun 19 07:39:53.575428 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] return _bootstrap._gcd_import(name[level:], package, level) [Fri Jun 19 07:39:53.575434 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] File "<frozen importlib._bootstrap>", line 994, in _gcd_import [Fri Jun 19 07:39:53.575441 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] File "<frozen importlib._bootstrap>", line 971, in _find_and_load [Fri Jun 19 07:39:53.575448 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked [Fri Jun 19 07:39:53.575467 2020] [wsgi:error] [pid 14184] [remote 79.160.57.239:48226] ModuleNotFoundError: No module named 'channels' Channels is installed in the virtual environement. pip3 show channels: Name: channels Version: 2.4.0 Summary: Brings async, event-driven capabilities to Django. Django 2.2 and up only. Home-page: http://github.com/django/channels Author: Django Software Foundation Author-email: foundation@djangoproject.com License: BSD Location: /home/marcus/.local/lib/python3.6/site-packages Requires: daphne, Django, asgiref Why isn't the channels module found?
doc_4791
List1 - The first list contains email addresses. List2 - The second list contains only domains in the format "@domain.com" etc I would like to delete objects (e-mails) from the first list which is NOT on the second list (List2 - domains). For example: If List1 contains the email address "email@domain.com" and the second List2 does NOT contain "@domain.com" - then I want to delete this email address (from list 1) I know it may be duplicated post: Remove objects from list - contains strings - Comparing the List But I don't know how to create a negation (!) of these answers... I will be grateful for your quick help A: Based on the accepted answer in your other question, you'll just have to change the anyMatch to noneMatch: list1.removeIf(email -> list2.stream().noneMatch(email::endsWith));
doc_4792
employee.py: class Employee: def __init__(self, name, emplpoyeeid, department, job_title): self.__name = "" self.__employeeid = "" self.__department = "" self.__job_title = "" def set_name(self, name): self.__name = name def set_id(self, employeeid): self.__employeeid = employeeid def set_department(self, department): self.__department = department def set_job_title(self, job_title): self.__job_title = job_title def get_name(self): return self.__name def get_employeeid(self): return self.__employeeid def get_department(self): return self.__department def get_job_title(self): return self.__job_title The actual program file: import pickle from Employee import Employee try: filename=open('Employee.dat','rb') dictionary=pickle.load(filename) except: dictionary={} while True: print('\n1. Look up an employee in the dictionary') print('2. Add a new employee in the dictionary') print("3. Change an existing employee's name,department and job title in the dictionary") print('4. Delete an employee from the dicionary') print('5. Quit the program\n') choice=input('\nEnter a choice: ') if choice == '1': while True: employeeid=input('\nEnter the ID of the employee: ') if employeeid in dictionary: ob=dictionary[employeeid] print('Employee Name: ',ob.get_name()) print('Employee ID: ',ob.get_employeeid()) print('Employee department: ',ob.get_department()) print('Employee job title: ',ob.get_job_title()) break else: print('\nEmployee not found \n') break elif choice== '2': while True: name=input('\nEnter the name of the employee: ') employeeid=input('\nEnter the employee id: ') dept=input('\nEnter the employee department: ') title=input('\nEnter the employee job title: ') ob=Employee(name,employeeid,dept,title) dictionary[employeeid]=ob print("employee has been added") break elif choice== '3': while True: employeeid=input('\nEnter the employee ID to change the details: ') if employeeid in dictionary: ob=dictionary[employeeid] while True: name=input('\nEnter the new name of the employee: ') ob.set_name(name) dept=input('\nEnter the new department of the employee: ') ob.set_department(dept) title=input('\nEnter the new job title of the employee: ') ob.set_job_title(title) break else: print('\nID not found \n') elif choice == '4': while True: employeeid=input('\nEnter the ID of the employee to delete: ') if employeeid in dictionary: del dictionary[employeeid] print('\nEmployee data removed \n ') else: print("Employee data not found") elif choice == '5': filename=open('Employee.dat','wb') pickle.dump(dictionary,filename) filename.close() else: print('\nPlease enter a valid choice ') * *Look up an employee in the dictionary *Add a new employee in the dictionary *Change an existing employee's name,department and job title in the dictionary *Delete an employee from the dicionary *Quit the program Enter a choice: 2 Enter the name of the employee: sam Enter the employee id: 1 Enter the employee department: 2 Enter the employee job title: 3 employee has been added * *Look up an employee in the dictionary *Add a new employee in the dictionary *Change an existing employee's name,department and job title in the dictionary *Delete an employee from the dicionary *Quit the program 4 Enter a choice: 1 Enter the ID of the employee: 1 Employee Name: Employee ID: Employee department: Employee job title: * *Look up an employee in the dictionary *Add a new employee in the dictionary *Change an existing employee's name,department and job title in the dictionary *Delete an employee from the dicionary *Quit the program Enter a choice: I expected the values that i put initially to be in the second output but it is only displaying blanks A: First: Your Employee import is incorrect. If your filename is employee.py, you should write: from employee import Employee because your program can't find the file named Employee.py. Second: Try not to use while True. It can easily throw your program in the infinite loop. For example: If you will select the fourth choice - Delete an employee from the dicionary - you will never return to the main menu because you can't break your infinite loop. Third: Your Employee.__init__ creates empty fields: class Employee: def __init__(self, name, emplpoyeeid, department, job_title): self.__name = "" self.__employeeid = "" self.__department = "" self.__job_title = "" and you use no setters in the main module. Of course it will return empty strings for every field. Add setters to the main module or change employee.py to this: class Employee: def __init__(self, name, emplpoyeeid, department, job_title): self.__name = name self.__employeeid = emplpoyeeid self.__department = department self.__job_title = job_title
doc_4793
const blacklistedCities = { [NATION_ID_USA]: [ 'New York', ], [NATION_ID_JAPAN]: [ 'Tokio', 'Kyoto', ] } export function isBlacklistedCity(city, nationId) { if(blacklistedCities.indexOf(nationId) !== -1 && blacklistedCities. ??WHAT SHOULD I PUT HERE??) { return false; } return true; } NATION_ID_USA and NATION_ID_JAPAN are constants imported from another file this function should return false when the element is found because I am using it from a filter() function somewhere else but I am open to any suggestion thanks A: You can use the nation name as a property name to index directly into the object, and then use .includes() on the array (if present): export function isBlacklistedCity(city, nationId) { return (nationId in blacklistedCitites) && blacklistedCities[nationId].includes(city); } A: I'd think of the input object as describing a much simpler array of scalar values that will be queried. // Convert the input to a set containing [ 'nationId-cityId', ...] // const blacklistedCities = { NATION_ID_USA: [ 'New York', ], NATION_ID_JAPAN: [ 'Tokio', 'Kyoto', ] } const keys = Object.entries(blacklistedCities).reduce((acc, [nationId, cityIdArray]) => { let nationIds = cityIdArray.map(cityId => `${nationId}-${cityId}`) acc = acc.concat(nationIds) return acc }, []) // keep this set around for queries const queryMe = new Set(keys) // and query with nation, key pair function queryFor(nationId, cityId) { return queryMe.has(`${nationId}-${cityId}`) } console.log(queryFor('NATION_ID_USA', 'New York')) // -> true console.log(queryFor('NATION_ID_FRANCE', 'Paris')) // -> false A: You can do something like this const blacklistedCities = { NATION_ID_USA: [ 'New York', ], NATION_ID_JAPAN: [ 'Tokio', 'Kyoto', ] } function isBlacklistedCity(city, nationId) { if(blacklistedCities[nationId] && blacklistedCities[nationId].length > 0 && blacklistedCities[nationId].find((cityInObj) => cityInObj==city)) { return true; } else { return false; } } console.log(isBlacklistedCity("Tokio", "NATION_ID_JAPAN"));
doc_4794
I want to convert a string of paths (where each path may contain escaped spaces) into a printed list of paths. I'm mainly using echo and sed, and the problem lies therein (see below). For example, I want these three files: one two three\ two\ one To be printed on three lines: one two three two one Problem with "sed" and "echo" (1) These are three sample files: "one", "two", and "three two one". echo "one two three\ two\ one" # one two three\ two\ one (2) I replace the whitespace that separates files with a newline. echo "one two three\ two\ one" | sed 's/\([^\]\) /\1$'"'"'\\n'"'"'/g' # one$'\n'two$'\n'three\ two\ one (3) I test that indeed, "echoing" the output of the above results in the output I want. echo one$'\n'two$'\n'three\ two\ one # one # two # three two one Combining (2) and (3), the functionality breaks using "xargs echo": echo "one two three\ two\ one" | sed 's/\([^\]\) /\1$'"'"'\\n'"'"'/g' | xargs echo # one$\ntwo$\nthree two one How to fix the sed substitution? How can the sed substitution be fixed so that echoing the output gives: one two three two one I'm looking for a solution that uses primarily "echo" and "sed" (not looking for other solutions). I also can't use "echo -e" to interpret escaped characters. A: Here's how you show your filenames on screen separated by linefeeds: find "$PWD" -maxdepth 1 -print If you wanted to process them in some way, you should pass them \0 separated (using -print0) or use find -exec. Trying to format them as shell words is not the way to go. The reason why echo doesn't show the value you expect is because $'\n' is Bash syntax meaning literal linefeed. It is not echo syntax, and echo is not involved in interpreting it. For dash, xargs and other more traditional tools, $'\n' is just a weird way of formatting the literal characters dollar-backslash-n ($\n). Since you're using xargs echo, bash is not involved, so you get $\n out instead. The solution is not to try to format data into code in such a way that the code will evaluate back to the original data. The solution is to skip that step entirely and just let data be data, such as in the initial example. A: This command works for me: echo "one two three\ two\ one" | sed 's/\([^\]\) /\1\n/g' | sed 's/\\ / /g' | xargs -L1 -I {} echo -{}- The trick was * *replace \\n with \n *use -L1 in xargs parameters *I used {} and -I{} just to demonstrate that echo is called for each line A: Not a solution but an answer to the comment you made on your own post "on why xargs echo" isn't working, see this answer regarding what $'\n' is: https://stackoverflow.com/a/4128305/4092051
doc_4795
Here are my current thoughts, but doesn't seem ideal: 1) Vote model: entity_id, contest_id, user_id (optional), created_at, ip_address * *search for ip in db on new vote and see if time diff greater than allowed vote time limit between user votes *use CAPTCHA every variable number of votes to ensure human *calculate current vote count by counting all the entries for an entity for a contest 2) Contest model: start and end datetime * *have a weekly or monthly cron job create the newest instance *votes find current contest if current date in between these 2 dates *individual model allows to create attributes to the contest(for example, special kinds of contests) 3) Winner model: contest_id, entity_id * *allows for users to comments on past contest winners A: Without knowing more details, I would go with something along the lines of: class User has_many :votes has_many :comments has_many :contests, :through => :votes class Vote belongs_to :user belongs_to :contest class Contest has_many :votes has_many :users, :through => :votes class Comment belongs_to :user This way, you can have @user.votes, @contest.votes, @contest.users, etc. I don't see the need for a Winners model, since that can just be a boolean in Users. If you needed to, you could always have a Winnings model that belonged to both Users and Contests to link the two. Hope that helps.
doc_4796
This is my code: $(document).ready(function() { var button = document.querySelector('.container a'), list = document.getElementById('list'), li = list.children; $(button).on('click', function() { var li = document.createElement('LI'); var word = prompt('Enter a word'); var text = document.createTextNode(word); li.appendChild(text); list.appendChild(li); console.log(list.children); }); // click event $(li).on('click', function() { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { $(this).addClass('selected'); } }); // click event // console.log(li); }); actually code is pretty simple, i'm little bit confused why it does not work. A: You're using jQuery, so this is pretty easy: $("#list").on("click", "> li", function() { $(this).toggleClass("selected"); }); The code above creates a delegated event handler. The handler is attached to the list container, so it will catch all events that bubble up from within. That means that you can add <li> elements freely, and the events from new ones will be handled exactly like events from old ones. A: It's not working, because you are creating new DOM elements and these elements have no listeners attached to them. Replace your code with this. $("body").on('click', "li", function() { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { $(this).addClass('selected'); } }); // click event Edit: In case you need this. I have created a vanilla event handler, which will attach event handlers to all elements. fakejQuery == jQuery's $ but a simpler version of it :). The code works in IE8+, where in IE8 you can use only CSS2 selectors window.fakejQuery = document.querySelectorAll.bind(document) eventHandler: function (element, eventType, fn) { if (document.addEventListener) { for (var i = fakejQuery(element).length - 1; i >= 0; i--) { fakejQuery(element)[i].addEventListener(eventType, fn, false) } } else if (document.attachEvent) { for (var i = fakejQuery(element).length - 1; i >= 0; i--) { fakejQuery(element)[i].attachEvent("on" + eventType, fn) } } else { alert("Ooops, no event listener methods found!"); } }
doc_4797
#include <stdio.h> #include <time.h> int main(void) { struct timespec ts; timespec_get(&ts, TIME_UTC); char buff[100]; strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec)); printf("Current time: %s.%09ld UTC\n", buff, ts.tv_nsec); } However, if I look at the sources of glibc here, the code is the following: #include <time.h> /* Set TS to calendar time based in time base BASE. */ int timespec_get (struct timespec *ts, int base) { switch (base) { case TIME_UTC: /* Not supported. */ return 0; default: return 0; } return base; } stub_warning (timespec_get) Which... should not work... Which leads to the question: where is the source code of timespec_get that is actually called? A: The timespec_get function's implementation depends on the system the library is running on, so it appears both as a stub in time/timespec_get.c (in case no implementation is available) and as various system-dependent implementations elsewhere. You can see the Linux implementation in sysdeps/unix/sysv/linux/timespec_get.c, /* Set TS to calendar time based in time base BASE. */ int timespec_get (struct timespec *ts, int base) { switch (base) { int res; INTERNAL_SYSCALL_DECL (err); case TIME_UTC: res = INTERNAL_VSYSCALL (clock_gettime, err, 2, CLOCK_REALTIME, ts); if (INTERNAL_SYSCALL_ERROR_P (res, err)) return 0; break; default: return 0; } return base; } This is is just a thin wrapper around a vDSO call, and the vDSO is part of the Linux kernel itself. If you are curious, look for the definition of clock_gettime there. It's unusual that clock_gettime is in the vDSO, only a small number of syscalls are implemented this way. Here is the x86 implementation for CLOCK_REALTIME, found in arch/x86/entry/vdso/vclock_gettime.c: /* Code size doesn't matter (vdso is 4k anyway) and this is faster. */ notrace static int __always_inline do_realtime(struct timespec *ts) { unsigned long seq; u64 ns; int mode; do { seq = gtod_read_begin(gtod); mode = gtod->vclock_mode; ts->tv_sec = gtod->wall_time_sec; ns = gtod->wall_time_snsec; ns += vgetsns(&mode); ns >>= gtod->shift; } while (unlikely(gtod_read_retry(gtod, seq))); ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns); ts->tv_nsec = ns; return mode; } Basically, there is some memory in your process which is updated by the kernel, and some registers in your CPU which track the passage of time (or something provided by your hypervisor). The memory in your process is used to translate the value of these CPU registers into the wall clock time. You have to read these in a loop because they can change while you are reading them... the loop logic detects the case when you get a bad read, and tries again. A: The timespec_get definition you linked to is a stub (see the stub_warning). The actual implementation will be under sysdeps for your platform. For example, here is the version for sysv: https://github.com/lattera/glibc/blob/a2f34833b1042d5d8eeb263b4cf4caaea138c4ad/sysdeps/unix/sysv/linux/timespec_get.c int timespec_get (ts, base) struct timespec *ts; int base; { switch (base) { int res; INTERNAL_SYSCALL_DECL (err); case TIME_UTC: res = INTERNAL_GETTIME (CLOCK_REALTIME, ts); if (INTERNAL_SYSCALL_ERROR_P (res, err)) return 0; break; default: return 0; } return base; }
doc_4798
Now, I tried using segue unwinding, so that when C closes, B's return method gets called to dismiss the destination controller: - (IBAction)returnFromC:(UIStoryboardSegue*)segue { [segue.destinationViewController dismissViewControllerAnimated:YES completion:nil]; } I put a breakpoint in this method - it is called. I have verified that the destinationController is indeed B. However, I noticed when the break point hits, C is still visible. After playing from the break point, C does exit as expected, but B is still visible. Any ideas? Many thanks in advance. A: When C closes, I want it to always return to A, i.e. it automatically closes B upon closing C, if opened from B The simplest solution is: in C's viewDidAppear:, secretly remove B as a child of the navigation controller. In other words, you've got this: A > B > C Now you rearrange things so that you've got this: A > C Thus, the only thing to go back to from C is A. It's easy to manipulate the navigation controller's set of children in this way. Just call setViewControllers:animated: (with a second argument of NO). [But if I've understood your setup properly, another easy way would be to implement the unwind method in A and not B. Then do an unwind segue. We always unwind to the first view controller that contains the unwind method, so that would always be A.] A: dismissViewControllerAnimated:completion: is used to dismiss a Modal segue and has no effect for Push segues As @matt suggested you could just remove B (the middle) view controller from self.navigationController.viewControllers and here's a sample code that you can put in B view controller: - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; // No need to process if the viewController is already being removed if (!self.isMovingFromParentViewController) { // Getting a mutable copy of the viewControllers (can't directly modify) NSMutableArray *temp = [self.navigationController.viewControllers mutableCopy]; // Removing 'self' -> so A > B > C will become A > C [temp removeObject:self]; // Setting the new array of viewControllers self.navigationController.viewControllers = [temp copy]; // getting an immutable copy } } P.S. You could use popViewControllerAnimated: instead of Unwind segue if you're not planning to send the data back.
doc_4799
public class Doc1 { public Doc1() { Docs = new List<Doc2>(); } private IList<Doc2> Docs{get;set;} } public Class Doc2 { //whatever } The Problem is when I try to Use it like this var provider = new LuceneDataProvider(directory, Version.LUCENE_30); using (var session = provider.OpenSession<Doc1>()) { var m = new Doc1(); session.Add(m); } The Problem is when I execute this code, I get the following error Property Event of type System.Collections.Generic.IList`1[Doc1] cannot be converted from System.String Please is there another way of doing this Thanks in advance Here goes the Full Stack Trace [NotSupportedException: Property Event of type System.Collections.Generic.IList`1[Doc2] cannot be converted from System.String] Lucene.Net.Linq.Mapping.FieldMappingInfoBuilder.GetConverter(PropertyInfo p, Type type, FieldAttribute metadata) +487 Lucene.Net.Linq.Mapping.FieldMappingInfoBuilder.BuildPrimitive(PropertyInfo p, Type type, FieldAttribute metadata, Version version, Analyzer externalAnalyzer) +63 Lucene.Net.Linq.Mapping.FieldMappingInfoBuilder.Build(PropertyInfo p, Version version, Analyzer externalAnalyzer) +364 Lucene.Net.Linq.Mapping.ReflectionDocumentMapper`1.BuildFieldMap(IEnumerable`1 props) +184 Lucene.Net.Linq.Mapping.ReflectionDocumentMapper`1..ctor(Version version, Analyzer externalAnalyzer) +77 Lucene.Net.Linq.LuceneDataProvider.OpenSession(ObjectLookup`1 lookup) +67 Lucene.Net.Linq.LuceneDataProvider.OpenSession(ObjectFactory`1 factory) +142 Lucene.Net.Linq.LuceneDataProvider.OpenSession() +114