text
stringlengths
14
21.4M
Q: Model Placement It is necessary to place posts on the site so that they can be created and edited, but in the site design the posts are separated by sliders and other elements, how is it possible to implement this in such a way that the other layout elements are, so to speak, ignored? I tried to solve this problem by creating additional models, that is, the posts before the separating elements (sliders in this case) should be taken in one class, and the subsequent ones in another and further edited in such a way. Of course this is a crutch, but I don't know how to configure it, because together these models are not displayed for me, that is, either one or the other. I also created a separate class for the Main Post, because it has a different design and, as a matter of fact, always hangs in the top, but of course it's ideal to implement such that the model has such an attribute that you can indicate to a specific post that it is the main and most located at the beginning of the site. Here is my code (let's say that we added Posts_one, Posts_two, if we talk about the case of using a crutch, which I also failed): models.py: from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Toppost(models.Model): title = models.CharField(max_length=200) caption = models.CharField(max_length=150, default='краткое описание поста') text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=200) caption = models.CharField(max_length=150, default='краткое описание поста') text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title views.py: from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post, Toppost def posts_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/posts_list.html', {'posts': posts}) topposts = Toppost.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/posts_list.html', {'topposts': topposts}) I also attach a screenshot with a diagram of how it should look. Ideally, of course, it's interesting to know how this can be implemented so that all this is one Post model and does not destroy the layout of the site and that you can select any post as Main_Post. A: I'd simply add an attribute for a post to define whether it's a top post or not. class Post(models.Model): # ... all the other stuff ... is_top_post = models.BooleanField(default=False) # ... all the other stuff ... # ... def posts_list(request): all_posts = Post.objects.filter(published_date__lte=timezone.now()).order_by("published_date") non_top_posts = [] top_posts = [] for post in all_posts: (top_posts if post.is_top_post else non_top_posts).append(post) return render(request, "blog/posts_list.html", {"posts": non_top_posts, "top_posts": top_posts}) You can also ensure that there is exactly one top post by adding a save override like class Post(models.Model): # ... all the other stuff ... is_top_post = models.BooleanField(default=False) # ... all the other stuff ... def save(self, **kwargs): if self.is_top_post: # Un-top every other post Post.objects.exclude(id=self.id).update(is_top_post=False) return super().save(**kwargs)
Q: Cannot find module '../assets/json/example.json' enter image description herestrong text Consider using '--resolveJsonModule' to import module with '.json' extension A: open File tsconfig.json and change resolveJsonModule : to true. { resolveJsonModule:true, } A: Try to solve it this way. Its work for me. Create file called json-typings.d.ts in src/app folder. and typing file as follows: declare module "*.json" { const value: any; export default value; } Then you can import Json files just like TypeScript 2.9+. import * as info from "info.json"; A: Please add in your tslint.json file { "linterOptions": { "exclude": [ "*.json", "**/*.json" ] } } **/*.json to be recursive A: Copy this in your tsconfig.json file , inside compilerOptions: "resolveJsonModule": true, "esModuleInterop": true
Q: Do I place the cursor 'in a cell' or 'on a cell' when working on a spreadsheet? This is about Microsoft Excel: I don't know, if I should say: Place the cursor in cell A5 or Place the cursor on cell A5 or maybe something completely different? I'd say "on" simply because Excel won't be in edit mode yet, so the cursor isn't flashing inside the cell. Does that make sense? A: Since, as John Burger said, the cursor is the flashing thing, it goes in the cell: Place the cursor in cell A5. To achieve that, though, you click on the cell: Click on cell A5 to select it. A: I'd agree with you - except that "cursor" actually means the flashing thing. The bold border around the cell is called the "selection". So you should actually say "Select cell A5" - so that you can (for instance) say "Select cells A5:B7"
Q: SQL update multiple rows with different values Edit: I've re-written my question to include more details: Here's a snapshot of the code that produces the page of results from the database of users: userdetails.php $currenttechnicians = "SELECT * FROM ahsinfo ORDER BY FirstName"; $currenttechniciansresults = sqlsrv_query($conn,$currenttechnicians) or die("Couldn't execut query"); while ($techniciandata=sqlsrv_fetch_array($currenttechniciansresults)){ echo "<tr align=center>"; echo "<td height=35 background=largebg.gif style=text-align: center valign=center>"; echo "<input type=hidden name=\"ID\" value="; echo $techniciandata['ID']; echo ">"; echo "<input type=textbox name=\"FirstName\" value="; echo $techniciandata['FirstName']; echo "> "; echo "</td><td height=35 background=largebg.gif style=text-align: center valign=center>"; echo "<input type=textbox name=\"LastName\" value="; echo $techniciandata['LastName']; echo "> "; echo "</td><td height=35 background=largebg.gif style=text-align: center valign=center>"; echo "<input type=textbox size=40 name=\"SIPAddress\" value="; echo $techniciandata['SIPAddress']; echo "> "; echo "</td><td height=35 background=largebg.gif style=text-align: center valign=center>"; echo "<input type=textbox name=\"MobileNumber\" value="; echo $techniciandata['MobileNumber']; echo "> "; echo "</td><td height=35 background=largebg.gif style=text-align: center valign=center>"; ?> Here's the code that handles the form submission: (again, just the SQL query that updates the database. I've removed the database connection string). edituserdetails.php <?PHP //Add the new users details to the database $edituser = " UPDATE ahsinfo SET FirstName='{$_POST['FirstName']}', LastName='{$_POST['LastName']}', SIPAddress='{$_POST['SIPAddress']}', MobileNumber='{$_POST['MobileNumber']}' WHERE ID='{$_POST['ID']}' "; $editresult = sqlsrv_query($conn,$edituser) or die("Couldn't execute query to update database"); ?> I'm trying to update the entire database (it's a small database) with any changes that a user makes on the userdetails.php page. A: You're missing quotes around your string values and used a curly brace instead of a bracket on one of your POST variables: UPDATE ahsinfo SET FirstName="{$_POST['FirstName']}", LastName="{$_POST['LastName']}", EmailAddress="{$_POST['EmailAddress']}", MobileNumber="{$_POST['MobileNumber']}" WHERE ID={$_POST['ID']} You would have caught this if you checked for errors in your code. FYI, you are wide open to SQL injections
Q: Filling the missing values in the specified formate we can't use numpy or pandas , can anyone help me in finding approach for it You will be given a string with digits and '_'(missing value) symbols you have to replace the '_' symbols as explained Ex 1: _, _, _, 24 ==> 24/4, 24/4, 24/4, 24/4 i.e we. have distributed the 24 equally to all 4 places Ex 2: 40, _, _, _, 60 ==> (60+40)/5,(60+40)/5,(60+40)/5,(60+40)/5,(60+40)/5 ==> 20, 20, 20, 20, 20 i.e. the sum of (60+40) is distributed qually to all 5 places Ex 3: 80, _, _, _, _ ==> 80/5,80/5,80/5,80/5,80/5 ==> 16, 16, 16, 16, 16 i.e. the 80 is distributed qually to all 5 missing values that are right to it Ex 4: _, _, 30, _, _, _, 50, _, _ ==> we will fill the missing values from left to right a. first we will distribute the 30 to left two missing values (10, 10, 10, _, _, _, 50, _, _) b. now distribute the sum (10+50) missing values in between (10, 10, 12, 12, 12, 12, 12, _, ) c. now we will distribute 12 to right side missing values (10, 10, 12, 12, 12, 12, 4, 4, 4) for a given string with comma seprate values, which will have both missing values numbers like ex: ", _, x, _, _, " you need fill the missing values Q: your program reads a string like ex: ", _, x, _, _, _" and returns the filled sequence A: Tried to cover as many edge cases as possible: inp = "80, _, _, _, _" inp=inp.split(", ") start=-1 end=-1 new_arr=inp.copy() for i in range(len(inp)): if (inp[i]=='_')&(i!=len(inp)-1): continue elif start==-1: if i==0: ## 0th position element has non blank value # print("cond1") start=0 end=0 new_arr[i]=int(inp[i]) else: # print("cond2") start=i end=i avg=int(inp[start])/(i+1) for k in range(0, start+1): new_arr[k]=avg elif i==len(inp)-1: ## reached last element # print("cond3") avg=int(new_arr[start])/(i+1-start) for k in range(start, i+1): new_arr[k]=avg else: # print("cond4") end=i if end-start>1: ## blank are present avg=(int(new_arr[start])+int(new_arr[end]))/(end-start+1) for k in range(start, end+1): new_arr[k]=avg start=end print(new_arr) The complexity of this is ~ O(n), space complexity ~ O(n) A: Based only on what you've given, This is a dumb implementation of what is being asked for. def fill_in(s : str): l = s.split(',') last = -1 for e, i in enumerate(l): if i.strip() != '_': if last==-1: filler = float(i) / (e+1) l = [filler]*(e+1) + l[e+1:] last = e else: filler = (l[last] + float(i)) / (e - last +1) l = l[0:last] + [filler]*(e - last +1) + l[e+1:] last = e elif e==len(l)-1: if last==-1: last = 0 filler = l[last] / (len(l) - last) l = l[:last] + [filler]*(len(l) - last) return l Usage: fill_in('_, _, 30, _, _, _, 50, _, _') Returns: [10.0, 10.0, 12.0, 12.0, 12.0, 12.0, 4.0, 4.0, 4.0]
Q: IN a greasemonkey userscript append text to a form when submitted with ajax So, in this question I explained my whole situation and to save space I am not going to repost my whole situation But here is the answer to the question that I am having problems with function form_submit (event) { var form, bClickNotSubmit; if (event && event.type == 'click') { bClickNotSubmit = true; form = document.getElementById ('quick_reply_form'); } else { bClickNotSubmit = false; form = event ? event.target : this; } var arTextareas = form.getElementsByTagName ('textarea'); for (var i = arTextareas.length - 1; i >= 0; i--) { var elmTextarea = arTextareas[i]; elmTextarea.value = "[font=Tahoma][color=white]" + elmTextarea.value + "[/color][/font]"; } if ( ! bClickNotSubmit ) { form._submit(); } } window.addEventListener ('submit', form_submit, true); document.getElementById ('quick_reply_submit').addEventListener ('click', form_submit, true); HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit; HTMLFormElement.prototype.submit = form_submit; So this works all fine and dandy in firefox, but I have now realized that there is a issue in chrome. When it quick reply form is submitted on the page, the function seems to run, in the sense that you can see the stuff get added to the beginning and the end of the text, but it seems to not do it fast enough because the form gets submitted to the server before the text is added does anyone know how to remedy this? A: Not tested, but try changing this: if ( ! bClickNotSubmit ) { form._submit(); } To this: if ( ! bClickNotSubmit ) { form._submit(); } else { event.preventDefault (); event.stopPropagation (); return false; }
Q: how to print a category with sub-list (courses). java I have two classes One Category and one Course they have a common identifier int categoryId. Each category has one course. I want to print each category with its related course. the category object contains course list as a parameter so when i print out the category for each element all elements of courses are printed repeatedly which not suppose to. public class Category { private int categoryId; private String name; private String description; private List<Course> courseList; public Category(int categoryId, String name, String description,List<Course> courseList) { this.categoryId = categoryId; this.name = name; this.description = description; this.courseList = courseList; } public int getCategoryId() { return categoryId; } public void setCategoryId(int categoryId) { this.categoryId = categoryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<Course> getCourseList() { return courseList; } public void setCourseList(List<Course> courseList) { this.courseList = courseList; } @Override public String toString() { return "Category{" + "categoryId=" + categoryId + ", name='" + name + '\'' + ", description='" + description + '\'' + ", courseList=" + courseList + '}'; } } public class Course { private int courseId; private int categoryId; private String name; private int duration; private int miles; public int getCourseId() { return courseId; } public void setCourseId(int courseId) { this.courseId = courseId; } public int getCategoryId() { return categoryId; } public void setCategoryId(int categoryId) { this.categoryId = categoryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public int getMiles() { return miles; } public void setMiles(int miles) { this.miles = miles; } @Override public String toString() { return "Course{" + "courseId=" + courseId + ", categoryId=" + categoryId + ", name='" + name + '\'' + ", duration=" + duration + ", miles=" + miles + '}'; } } public class Main { public static void main(String[] args){ List<Course> courses = new ArrayList<>(Arrays.asList( new Course(2001, 1001, "Cloud Computing",180, 200), new Course(2002, 1002, "Web servers Computing",200, 250)) ); List<Category> categories = new ArrayList<>(Arrays.asList( new Category(1001, "AWS", "cloud courses", courses), new Category(1002, "LMS", "English courses", courses)) ); for(Category c : categories){ for(Course cr: courses){ if(c.getCategoryId() == cr.getCategoryId()){ System.out.println(c); } } } } The output: Category{categoryId=1001, name='AWS', description='cloud courses', courseList=[courseId=2001, name='Cloud Computing', duration=180, miles=200}, courseId=2002, name='Web servers Computing', duration=200, miles=250}]} Category{categoryId=1002, name='LMS', description='engish courses', courseList=[courseId=2001, name='Cloud Computing', duration=180, miles=200}, courseId=2002, name='Web servers Computing', duration=200, miles=250}]}
Q: How to change disk name from /dev/sda1 to /dev/sd127 in ubuntu How do I change the name of the disk in ubuntu 14.04 LTS server from /dev/sda1 to something else like /dev/sd127? This is a regular EXT4 striped disk attached to the system.
Q: Bigquery Select from table where any column contains 'FINISHED' I have table in bigquery which has over 100 columns and has more than 70 Million row. I want to find out if I can write a query to extract rows where any of the column contains a value 'FINISHED'. A: Below is for BigQuery Standard SQL Should be good start for you :) #standardSQL SELECT <columns to output> FROM yourTable AS t WHERE REGEXP_CONTAINS(LOWER(TO_JSON_STRING(t)), 'finished') You can test/play with it with below dummy data #standardSQL WITH yourTable AS ( SELECT 'a' AS x, 'b' AS y, 'c' AS z UNION ALL SELECT 'finished', '', '' UNION ALL SELECT '', 'Bigquery Select from table where any column contains "FINISHED"','' UNION ALL SELECT '', '', 'aaa' UNION ALL SELECT 'finished', 'bbb', 'finished' ) SELECT * FROM yourTable AS t WHERE REGEXP_CONTAINS(LOWER(TO_JSON_STRING(t)), 'finished') Update Note: if you have your search word as a part of at least one column name - above will return all rows! To address this - you would need to invest a little bit more coding For example, for simple schema (with no record or repeated) this would be a #standardSQL SELECT <columns to output> FROM yourTable AS t WHERE (SELECT COUNTIF(SPLIT(zzz, ':')[SAFE_OFFSET(1)] LIKE '%finished%') FROM UNNEST(SPLIT(SUBSTR(LOWER(TO_JSON_STRING(t)),2,LENGTH(TO_JSON_STRING(t))-2))) AS zzz ) > 0 You can test this with below #standardSQL WITH yourTable AS ( SELECT 'a' AS x, 'b' AS y, 'c' AS col_finished UNION ALL SELECT 'finished', '', '' UNION ALL SELECT '', 'Bigquery Select from table where any column contains "FINISHED"','' UNION ALL SELECT '', '', 'aaa' UNION ALL SELECT 'finished', 'bbb', 'finished' ) SELECT * FROM yourTable AS t WHERE (SELECT COUNTIF(SPLIT(zzz, ':')[SAFE_OFFSET(1)] LIKE '%finished%') FROM UNNEST(SPLIT(SUBSTR(LOWER(TO_JSON_STRING(t)),2,LENGTH(TO_JSON_STRING(t))-2))) AS zzz ) > 0
Q: How to make Common code and vars in React We have created a GeneralForm in React which accepts a json of fields with their properties: name, type, min/max values etc.) the GeneralForm have created a form with all relevant inputs. The GeneralForm also managed the state with map for all the fields. And did other logic as well: disable/enable fields according to the definitions in the json and the values the user input. Now, we have some more complicated forms, with variant designs, so we want to create the form, as static form, without using the GeneralForm. We are also afraid building complicated forms on runtime will cause slowness in the application. The thing is, we still want to reuse the state management of the GeneralForms and the logic of enabled/disabled. Any ideas how we can implment this? In OOP the GeneralForm would have been Abstract to all forms, but since React is functional oriented, we can't do it. Another option is to leave the GeneralForm and make support this different variant forms somehow - but we are not sure it worth the work. A: Continuing from my comment above, I suggested that you could use a common component accross several other components, as such: import React from 'react' const commonFields = { field1: { id: 1, name: "e-mail", type: "email" }, field2: { id: 2, name: "password", type: "password" } } export default function App() { function submitHandleExtended(formData) { // handle form data } function submitHandleAlternative(formData) { // handle form data } return <div> <ExtendedForm formId="extended" fields={commonFields} submitHandler={submitHandleExtended}/> <AlternativeForm formId="alternative" fields={commonFields} submitHandler={submitHandleAlternative}/> </div> } function CommonForm({formId, fields, submitHandler}) { return <form id={formId} onSubmit={submitHandler}> {Object.keys(fields).map(key => { const field = fields[key] return <div key={field.id}> <label htmlFor={field.id}>{`${field.name}`}</label> <br /> <input type={field.type} id={field.id} name={field.name} /><br /> </div> })} </form> } function ExtendedForm({formId, fields, submitHandler}) { return <div> <CommonForm formId={formId} fields={fields} submitHandler={submitHandler} /> <input type="submit" value={"Submit"} form={formId}/> </div> } function AlternativeForm({formId, fields, submitHandler}) { return <div> <CommonForm formId={formId} fields={fields} submitHandler={submitHandler} /> <label htmlFor="fileId">Add file</label> <input id="fileId" type="file" form={formId}/> <br /> <input type="submit" value={"Submit"} form={formId}/> </div> } Here you can use CommonForm inside all other forms, which would work similar to an abstract/open class.
Q: Move built dll file to specific folder by BAT script? I am using Qt Creator to built a shared library on windows 7. Hence it generates a myLib.dll and a myLib.lib Is there a way such that the myLib.dll file is automatically moved, after creation, to a specific directory? A: This could be done automatically as post link job after a completely successful compilation according to Qt Documentation - Variables. Add to .pro file of your project a line like: QMAKE_POST_LINK += $(COPY_FILE) "$${DESTDIR_TARGET}$${TARGET_EXT}" "C:\Destination\Directory\For Created DLL" Or with following if DESTDIR was not defined in project before or DESTDIR_TARGET does not exist when QMAKE parses the line for creating the MakeFile. QMAKE_POST_LINK += $(COPY_FILE) "$${OUT_PWD}/$${TARGET}$${TARGET_EXT}" "C:\Destination\Directory\For Created DLL" And if $${TARGET_EXT} is replaced by an empty string, use fixed .dll instead of $${TARGET_EXT} in the line above. It is of course also possible to move the DLL instead of copying it using one of the following 3 lines: QMAKE_POST_LINK += $(MOVE) "$${DESTDIR_TARGET}$${TARGET_EXT}" "C:\Destination\Directory\For Created DLL" QMAKE_POST_LINK += $(MOVE) "$${OUT_PWD}/$${TARGET}$${TARGET_EXT}" "C:\Destination\Directory\For Created DLL" QMAKE_POST_LINK += $(MOVE) "$${OUT_PWD}/$${TARGET}.dll" "C:\Destination\Directory\For Created DLL" But on Windows there is also the QMAKE variable DLLDESTDIR to specify directly in .pro file a directory into which the created DLL should be copied after linking. DLLDESTDIR="C:\Destination\Directory\For Created DLL" Note: I could not testing anything written here for Windows. I can only confirm that everything written above does not work for Linux as library management is on Linux completely different in comparison to Windows.
Q: when i was trying to cretae modules locally and refer the vpc name in creation of ec2 instances and security group i was not able to proceed further below is the code in ec2, security group module. data "aws_ami" "ubuntu" { owners = ["373042721571"] most_recent = true filter { name = "name" values = ["image-test"] } } # data "template_file" "user_data" { # template = file("userdata.sh") # } resource "aws_instance" "web-1" { count = 1 ami = "${data.aws_ami.ubuntu.id}" instance_type = "t2.micro" key_name = var.key_name subnet_id = var.subnetid vpc_security_group_ids = var.securitygroupid associate_public_ip_address = true # user_data = data.template_file.user_data.rendered tags = { Name = "Server-1" Owner = "Terraform" } } resource "aws_security_group" "allow_all" { name = var.sg_name description = "allowing all traffic to the servers in piblic " vpc_id = var.vpcid ingress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] } tags = { Name = "allow_all_trafic" } } module "vpc" { source = "./module/vpc" vpc_cidr = var.vpc_cidr vpc_name = var.vpc_name IGW_name = var.IGW_name routing_table_public_name = var.routing_table_public_name } module "securitygroup" { source = "./module/securitygroup" sg_name = var.sg_name vpcid = module.vpc.vpc_id } module "ec2" { source = "./module/ec2" key_name = var.key_name securitygroupid = module.securitygroup.aws_security_group.allow_all.id subnetid = module.vpcmodule.public[0] } this is the terrafrom modules i created locally when i refer to vpc-id and subnet ids i was getting as │ Error: Unsupported attribute │ │ on output.tf line 3, in output "vpc_id": │ 3: value = module.vpc.vpc_id │ ├──────────────── │ │ module.vpc is a object, known only after apply │ │ This object does not have an attribute named "vpc_id".
Q: Screen Bash Scripting for Cronjob Hi I am trying to use screen as part of a cronjob. Currently I have the following command: screen -fa -d -m -S mapper /home/user/cron Is there anyway I can make this command do nothing if the screen mapper already exists? The mapper is set on a half an hour cronjob, but sometimes the mapping takes more than half an hour to complete and so they and up overlapping, slowing each other down and sometimes even causing the next one to be slow and so I end up with lots of mapper screens running. Thanks for your time, A: ls /var/run/screen/S-"$USER"/*.mapper >/dev/null 2>&1 || screen -S mapper ... This will check if any screen sessions named mapper exist for the current user, and only if none do, will launch the new one. A: Why would you want a job run by cron, which (by definition) does not have a terminal attached to it, to do anything with the screen? According to Wikipedia, 'GNU Screen is a software application which can be used to multiplex several virtual consoles, allowing a user to access multiple separate terminal sessions'. However, assuming there is some reason for doing it, then you probably need to create a lock file which the process checks before proceeding. At this point, you need to run a shell script from the cron entry (which is usually a good technique anyway), and the shell script can check whether the previous run of the task has completed, exiting if not. If the previous incarnation is complete, then the current incarnation creates a lock file containing its PID and runs the job. When it completes, it removes the lock file. You should review the shell trap command, and make sure that the lock file is removed if the shell script exits as a result of a trappable signal (you can't trap KILL and some process-control signals). Judging from another answer, the screen program already creates lock files; you may not have to do anything special to create them - but will need to detect whether they exist. Also check the GNU manual for screen.
Q: Can we install the UFT 11.53 patch on trail version of UFT 11.50? I tried to install the UFT 11.53 patch on trail version of the UFT as I have 11 days left for trail to expire. But after installing the patch UFT asking the license and giving the following error. Can somebody tell me the solution. A: Whenever you 1)Install Patches or 2)Repair UFT or 3)Modify UFT finally the setup wizard will prompt to run UFT license wizard ,Debugger, DCOM Settings.. Here try to cancel license wizard stuff,(If you want u can proceed with DCOM and Debugger) then restart your system and Launch UFT(Hope UFT will continue in trail mode). Download patches here http://www.learnqtp.com/patches/ Please let me know if you need any clarification..
Q: Need to run .jar from console for it to work I have a java application. I'm using eclipse to write, compile and create a runnable .jar. The program is used to discover OCF devices. It uses UDP and multicast. Multicast code public static void sendMulticast(byte[] data) throws Exception{ DatagramPacket pack = new DatagramPacket(data, data.length, mgroup, mport); msocket.send(pack); } public static byte[] recieveMulticast(int timeout) throws Exception{ DatagramPacket packet; byte[] data = new byte[AppConfig.ocf_buffer_size]; packet = new DatagramPacket(data, data.length); msocket.setSoTimeout(timeout); msocket.receive(packet); return data; } The code works when I start it from eclipse. It also works when I run the .jar from console on Linux. But when I start it with a double click, it doesn't work. When started from console, it finds my test device in less then a second. When started with a double click it doesn't find it ever. I haven't tested it on Windows yet, but the problem remains on Linux all the same. What is the difference when you start .jar from console or by double clicking? Why is it effecting messages on multicast? I'm using "Package required libraries into generated JAR". I'm using java 1.7 in eclipse, and 1.8 on Linux, maybe thats the problem? But why does running it from console work? I would understand if I used sudo, but I didn't. A: When you are running any jar from console, Console/Terminal knows which program responsible to run the any jar i.e java -jar example.jar but when double-clicking environment, OS/GUI manager doesn't know default responsible program to run the jar. ( Same way when you try to open some unknown extension file, Operating system will ask you open with which program/application) To make Java open .jar files per default (i.e. double click) right click on any .jar file to select Properties. In the following window select the "Open With" tab to see e.g. the follwing choice: A: The problem was in current location, system property user.dir This is the first function I call in my main. It doesn't work from eclipse, so I'll put an argument for disabling it (it will be disabled only during development). static void setCurrentDir() throws URISyntaxException{ String s; s = ESP8266_Configurator.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); s = s.substring(0, s.lastIndexOf('/')); System.setProperty("user.dir",s); } I hope this helps someone. Code should be exported with extracted libraries, not packaged, otherwise it doesn't work.
Q: Sending a jquery array through AJAX to a c# ObservableCollection I need to create an Array in jquery and pass it to an MVC controller which is accepting an Object with an ObseverableCollection inside of it. I am having an issue with getting the Observable to accept my array. I am having an issue with creating the array, but also passing it through AJAX to an ObservableCollection. Member: is the observable and Name: is just a string inside the Object. Any Ideas? Here is my jquery code: var memberCollection = new kendo.data.ObservableObject({ Members: [] }); click: function (e) { var myId = e.dataItem.AdId; memberCollection.Members.push(myId) } AJAX: $.ajax({ url: MobileHomePath + "AddGroup", contentType: 'application/json', data: { Name: this.get("groupName"), Members: memberCollection }, }).success(function (data) { if (data != "fail") { alert("Awesome"); } else { app.hideLoading(); alert(data); } }); Controller: public ActionResult AddGroup(GroupObj obj) { return Content(""); } Object: public class GroupObj { public string Id { get; set; } public string Name { get; set; } public ObservableCollection<string> Members { get; set; } }
Q: issues installing selenium and chromedriver in the Anaconda Spyder environment I am trying ti setup selenium and chromedriver in the Ananconda spyder environment but keep hitting this following error: dir_path = os,path.dirname(os.path.realpath(_file_)) Traceback (most recent call last): File "<ipython-input-23-fdfb1f77b9dd>", line 1, in <module> dir_path = os,path.dirname(os.path.realpath(_file_)) NameError: name 'path' is not defined The trouble is I am following a YouTube video step by step and it works with no issues on the demo, so not sure why I am getting this error. Any help much appreciated.
Q: Can open react-bootstrap modal but closing I am trying to let modal screen to disappear when I click close or save & close button. But I cannot find which line prevent close feature to work. What could be wrong? I really want to let modal to disappear when I click button inside of it. note: I use latest react-bootstrap (bootstrap 5) function MemberMgt() { const [showModal, setShowModal] = useState(false); const handleCloseClick = () => { setShowModal(false); }; const handleEditClick = () => { setShowModal(true); }; ... <tr onClick={handleEditClick}> <Modal show={showModal} onHide={handleCloseClick}> <Modal.Header closeButton> <Modal.Title>Edit Screen</Modal.Title> </Modal.Header> <Modal.Body> <li>ID</li> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={handleCloseClick}> Close </Button> <Button variant="primary" onClick={handleCloseClick}> Save & Close </Button> </Modal.Footer> </Modal> ...
Q: Is it possible to PUT JSP Code inside HTML Page? I have a sample HTML File as shown below <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> Hi How are you </body> </html> I have tried to put JSP code inside the aboev HTML File as shown below , which i will be using for Authentication purpose <%! System.out.println("Hi How are you 22222222"); session.setAttribute("LOGIN_USER", "user"); %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> Hi How are you </body> </html> But this is not working ( I mean it is not setting that value and Hi How are you 22222222 is not getting printed also ) Could you please let me know hpw to put JSP Code inside HTML File ?? A: The tag <%! allows only to declare variable and methods. Change it to <%. So your code should look like: <% System.out.println("Hi How are you 22222222"); session.setAttribute("LOGIN_USER", "user"); %>
Q: How to get the Name and DeptId of the employees whose salary is greater than average of his department? I am newbie to Hadoop and pig.As per the question i able to drill down till the below script but how can i compare salary of person to his average salary of his dept. Following is the script written to get average salary of each department A = LOAD 'Assignment_1_Input.log' USING PigStorage('\t') as (id:int,name:chararray,age:int,salary:int,deptid:int); B = GROUP A by deptid; STORE B INTO 'Assign1GrpByNew'; C = FOREACH B GENERATE group as grpId,AVG(A.salary) as grpAvgSal; DUMP C; Input File: 15878 mohan 24 8000 1 19173 ramya 27 10000 1 9527 krishna 35 40000 2 9528 raj 36 60000 2 16884 ravi 50 70000 2 Expected Output ramya 1 raj 2 ravi 2 Help me out,Thanks A: JOIN A and C by deptid,grpId and FILTER where salary > grpAvgSal A = LOAD 'Assignment_1_Input.log' USING PigStorage('\t') as (id:int,name:chararray,age:int,salary:int,deptid:int); B = GROUP A by deptid; STORE B INTO 'Assign1GrpByNew'; C = FOREACH B GENERATE group as grpId,AVG(A.salary) as grpAvgSal; D = JOIN A BY deptid,C BY grpId; E = FILTER D BY (A::salary > C::grpAvgSal); DUMP E; A: GROUP BY dept_id and compute the avg salary for each employee record and select those employees who salary is greater than avg. Snippet : inp_data = LOAD 'Assignment_1_Input.log' USING PigStorage('\t') as (id:int,name:chararray,age:int,salary:int,deptid:int); inp_data_fmt = FOREACH(GROUP inp_data BY deptid) GENERATE FLATTEN(inp_data), AVG(inp_data.salary) AS avg_salary; req_data = FILTER inp_data_fmt BY salary > avg_salary; DUMP req_data;
Q: SPARQL INSERT with ARC2 PHP library I am trying to execute an INSERT on a SPARQL endpoint in PHP using the ARC2 library. This fails with the error "Could not properly handle " PREFIX dc:" The SPARQL UPDATE query is taken from the W3C specification and works just fine on my Jena-Fuseki control panel: $query = ' PREFIX dc: <http://purl.org/dc/elements/1.1/> INSERT DATA { <http://example/book007> dc:title "A new book" ; dc:creator "A.N.Other" . } '; But even variations of the query without a PREFIX statement just result in a similar error "Could not properly handle " INSERT DATA {" in my PHP code. My PHP code is as follows: include_once('./lib/arc2/ARC2.php'); $config = array( //db 'db_name' => 'arc2', 'db_user' => 'root', 'db_pwd' => '-', //store 'store_name' => 'arc_tests' ); $store = ARC2::getStore($config); if (!$store->isSetUp()) $store->setUp(); $res = $store->query($query); echo var_dump($store->getErrors()); echo "<br><br>executed INSERT, returned: "; echo var_dump($res); This version is using a native ARC2 store to reduce potential error sources. I am actually trying to interact with a remote store: $config = array( 'remote_store_endpoint' => 'http://localhost:3030/data/update', ); $store = ARC2::getRemoteStore($config); Both give me the same error, however. In the end I want to connect to the remote SPARQL endpoint of my Jena Fuseki server and interactively insert and retrieve data with that in PHP. If you have any other libraries or clean solutions how to interact through the SPARQL protocol in PHP, I am happy to change my approach. A: It seems, ARC2 does not support SPARQL 1.1 parsing. Instead it only supports a simplified SPARQL+ for UPDATE queries. The following query successfully inserts a new triple into the ARC2 store: $query = 'INSERT DATA { <http://example/book1> dc:title "A new book" ; dc:creator "A.N.Other" . }'; Unfortunately, with this limited SPARQL+ it seems impossible to do UPDATEs through a remote store on my Jena Fuseki instance. Either ARC2 is complaining about the SPARQL 1.1 conform query syntax as given in the question, or Jena Fuseki is complaining about the SPARQL+ query syntax that seems specific to ARC2. Any advice? I posted a new question about this: https://stackoverflow.com/questions/26858594/php-sparql-1-1-library-for-semantic-web-stack-php-sparql-jena-fuseki
Q: Making math operations in setText? Why I'm getting error on this line ? textView1.setText((editText1.getText() + editText2.getText() + (editText3.getText)) / 3); Can we do math operations in setText method ? A: Replace textView1.setText((editText1.getText() + editText2.getText() + editText3.getText) / 3); with textView1.setText(""+(Integer.parseInt(editText1.getText().toString()) + Integer.parseInt(editText2.getText().toString()) + Integer.parseInt(editText3.getText().toString())) / 3); A: editText1.getText() is returning a string. Adding the other getText's is performing string concatenation. You need to convert the values to integer (or float) and then divide: textView1.setText(String.valueOf((Integer.valueOf(editText1.getText()) + Integer.valueOf(editText2.getText()) + Integer.valueOf(editText3.getText)) / 3)); A: editText1.getText() returns Editable which implements CharSequence. So you cannot directly perform arithmetic operations on such data types until you convert them into correct ones. For example: int, double... A: These methods will return String editText1.getText() editText2.getText() editText3.getText() You need to cast to Integer or double. eg Integer.pargeInt(editText1.getText()) for illustration try this one String s="2"; System.out.println(s/3); A: Try this : float result = (Integer.parseInt(editText1.getText().toString()) +Integer.parseInt(editText2.getText().toString())+Integer.parseInt(editText3.getText().toString()))/ 3; textView1.setText(""+result );
Q: Equivalent to Interfaces in Embedded C / Code organization I'm developing embedded C code on EFM32 Cortex M3 processors, and after a few months the code is beginning to get crazy... By this I mean that we changed the hardware so we get different versions, on which we changed some components, moved some IOs, have different states for theses at start up... So I'm trying to clean it up a bit: Where I had some very big files organised like this: /*============================================================================*/ /* File : BSP_gpio.h */ /* Processor : EFM32GG980F1024 */ /*----------------------------------------------------------------------------*/ /* Description : gpio driver */ /*----------------------------------------------------------------------------*/ #ifndef BSP_GPIO_H #define BSP_GPIO_H #ifdef EXTERN #undef EXTERN #endif #ifdef BSP_GPIO_C #define EXTERN #else #define EXTERN extern #endif typedef enum { GPIO_INIT = 0, GPIO_WAKEUP = 1, GPIO_SLEEP = 2, } GPIO_MODE; /* Definition / conts */ #define PIO_PIN_HIGH 1 #define PIO_PIN_LOW 0 #ifdef HW_v1 ... hundreds of lines... #elif defined HW_v2 ... hundreds of lines... #endif #endif I try to separate the different versions in separated files and try something like this: #ifdef HW_v1 #include "BSP_gpio_HW1.h" #elif defined HW_v2 #include "BSP_gpio_HW2.h" #endif With the same type of header for each "subfile" (until the enum). The aim is that in every other ".c" file we include the "BSP_gpio.h" and it automatically includes the file corresponding to the hardware used. The first problem is that the compilation depends on where I include the subfile. For example, I have a function "void BSP_GPIO_set(GPIO_MODE mode)" which uses the enum "GPIO_MODE" and is different in the two hardware versions (because the state of the IOs is not the same on the two hardwares). If I include the subfile before the declaration, it doesn't know the type "GPIO_MODE" and makes a compilation error, even if I #include "BSP_gpio.h" in the subfiles. So I just put this at the end of the file and it works, even if I don't really like it... The second problem appears when I have a variable declared as extern which I want to use in both subfiles and in others C files. Lets say I put this line just before "#ifdef HW_v1": EXTERN int numberOfToggles; The "EXTERN" word is nothing in my "BSP_gpio.c" file as I define BSP_GPIO_C at the beginning of it, and is the keyword extern in every other file where I include "BSP_gpio.h". When I build my project, it compiles but I have a linker error : "Duplicate definitions for numberOfToggles in BSP_gpio.o and BSP_gpio_HW2.o" and I can't find a solution for that. I'm ready to change the architecture of my project if anyone has a proper solution for that! A: The first problem is that the compilation depends on where I include the subfile. For example, I have a function "void BSP_GPIO_set(GPIO_MODE mode)" which uses the enum "GPIO_MODE" and is different in the two hardware versions [...]. If I include the subfile before the declaration, it doesn't know the type "GPIO_MODE" and makes a compilation error, even if I #include "BSP_gpio.h" in the subfiles. So I just put this at the end of the file and it works, even if I don't really like it... I'm not sure how "The first problem is [...]" goes together with "it works". I guess your complaint is about coding style that is falling out from your refactoring. Anyway, yes, C is sensitive to the order in which declarations appear, thus it matters where you put your #include directives. Personally, I prefer to take the approach that each header file H should #include all the other headers providing macros and declarations that H needs and does not itself provide. With standard guards against multiple inclusion, that eases many (but not all) of the issues around header order and position. It may be that factoring out even more or finer pieces of your headers is necessary to be able to put #include directives only at the top of each one. The second problem appears when I have a variable declared as extern which I want to use in both subfiles and in others c files. [...] When I build my project, it compiles but I have a linker error : "Duplicate definitions for numberOfToggles in BSP_gpio.o and BSP_gpio_HW2.o" and I can't find a solution for that. A global variable may have any number of compatible declarations in any number of compilation units, but it must have exactly one definition. The extern declarations in your header(s) are perfectly fine as long as they do not have initializers for the globals. Each global should then have a non-extern declaration in exactly one .c source file to serve as a definition. Bonus points for using an initializer in the definition. A: To me it looks like you don't make a clear distinction between interface and implementation. Is there a good reason to have hardware dependencies in your header file? Is there a good reason to have a GPIO driver as opposed to a function specific driver? In my opinion, hardware-dependencies should be hidden in the implementation (i.e. .c file) and not made public via header file. For example a Signalisation driver for LEDs. There, the header file could look something like this: #ifndef DRIVER_SIGNAL_H #define DRIVER_SIGNAL_H typedef enum { SIGNAL_STARTED, SIGNAL_ERROR, SIGNAL_WARNING, } signal_id_t; void signal_show(signal_id_t signal_id); #endif If you follow this approach you will mostly only have to change the implementations of driver code and not the header files between different hardware versions. Apart from that, I agree with the answers of Ludin and John Bollinger. A: The problem seems to be 100% related to lack of version control and not really to programming. Instead of going out of your mind with compiler switches, simply change the code as it should be for the latest version of the hardware. As you go, create a "tag" in your version control system for each hardware revision change. Should you ever need to use old hardware, simply go back to the version you used then. Or create a branch of your current up-to-date files, take the "hardware routing" file from the old tag and dump it among the up-to-date files. A: I modified my code so it get clearer, based on your answer. I have now only one BSP_gpio.h file where I have my definitions and all the prototypes: /*============================================================================*/ /* File : BSP_gpio.h */ /* Processor : EFM32GG980F1024 */ /*----------------------------------------------------------------------------*/ /* Description : gpio driver */ /*----------------------------------------------------------------------------*/ #ifndef BSP_GPIO_H #define BSP_GPIO_H #ifdef EXTERN #undef EXTERN #endif #ifdef BSP_GPIO_C #define EXTERN #else #define EXTERN extern #endif typedef enum { GPIO_INIT = 0, GPIO_WAKEUP = 1, GPIO_SLEEP = 2, } GPIO_MODE; /* Definition / conts */ #define PIO_PIN_HIGH 1 #define PIO_PIN_LOW 0 /* Variables */ EXTERN UINT8 numberOfToggles; /* Functions */ void BSP_GPIO_set_interupt(UINT8 port, UINT8 pin, BOOL falling); void BSP_GPIO_set(GPIO_MODE mode) #endif And I have now three .c files, BSP_gpio.c where I implement everything which is common to both hardwares: /*============================================================================*/ /* File : BSP_gpio.c */ /* Processor : EFM32GG980F1024 */ /*----------------------------------------------------------------------------*/ #define BSP_GPIO_C /*----------------------------------------------------------------------------*/ /* Includes */ /*----------------------------------------------------------------------------*/ #include "BSP_type.h" #include "BSP_gpio.h" void BSP_GPIO_set_interupt(UINT8 port, UINT8 pin, BOOL falling) { //implementation } , and BSP_gpio_HW1(/2).c files where I implement the void BSP_GPIO_set(GPIO_MODE mode) function surrounded by preprocessor instructions so it is implemented only once: #ifdef HW_v1(/2) #include "BSP_gpio.h" /*============================================================================*/ /* BSP_gpio_set */ /*============================================================================*/ void BSP_GPIO_set(GPIO_MODE mode) { //Implementation which depends on the hardware } #endif So this answers my first remark/question where I wasn't really satisfied of my code, but I still have the duplicate definitions problem which I don't understand because BSP_GPIO_Cis only defined in the BSP_gpio.c file and not in the BSP_gpio_HW1(/2).c files. Any idea on that? Again thank you for your help!
Q: I want to pushback and change but my code first changes Hello everyone Im working on a project but Im stuck in a point. I am trying to write a code that stores a char into a string then change the char to '_'. But my code changes the char first and gets that char to my string how can I fix it? Sincerely word.push_back(puzzle[x++][y]); puzzle[x++][y] = '_'; puzzle[x--][y]; In this part of code puzzle is the main matrix that I want to use and word is the vector that stores my characters. Sorry if I couldn't explain myself. Thanks in advance. A: Like this word.push_back(puzzle[x][y]); puzzle[x++][y] = '_'; The problem with your code was that it incremented x before you changed the char to '_'. Obviously you should only do that afterwards.
Q: .net JavaScript minification breaks jQuery plugin I have a jQuery plugin that works fine when JS minification is turned off. As soon as you switch it on though a specific part of the plugin no longer works. The plugin: Is a password strength indicator plugin, which checks the input runs through some logic then highlights 1 - 5 indicator blocks depending on the number of conditions the user input has met. The plugin (minus large parts of the logic for brevity): $(function () { (function ($) { $.fn.strongPassword = function () { var updatePasswordStrengthIndicator = function (indicators, $context) { console.log("indicators ", indicators); //prints out correct value console.log("$context ", $context); //prints out object reference for (var i = 0; i <= indicators; i++) { //problem lies here then $context.siblings(".strong-password").children('.strong-password-indicator:nth-child(' + (i + 1) + ')').removeClass('normal').removeClass('pass').addClass('pass'); } } return this.each(function () { var $this = $(this); //code to insert HTML elements for password strength indicators $("<div class='strong-password'><div class='clear-fix'><div class='float-left'>Password Strength</div><div class='float-right strong-password-status'>Too Short</div></div><span class='strong-password-indicator normal'></span><span class='strong-password-indicator normal'></span><span class='strong-password-indicator normal'></span><span class='strong-password-indicator normal'></span><span class='strong-password-indicator normal'></span></div>") .insertAfter($this); $this.keyup(function () { //create required variables //logic to work out password strength //call to update indicators updatePasswordStrengthIndicator(blocksToLight, $(this)); }); }); } }(jQuery)); }); Problem Area: The problem is with the function 'updatePasswordStrengthIndicator'. I traced out the values from the two arguments 'indicators' renders out the number of blocks and '$context' renders out the HTML input both of which are correct. Turn on minification and the updatePasswordStrengthIndicator fails, no blocks light up even though the arguments are correct Here is the minified output: $(function () { (function (n) { n.fn.strongPassword = function () { var t = function (n, t) { console.log('indicators ', n), console.log('$context ', t); for (var i = 0; i <= n; i++) t.siblings('.strong-password').children('.strong-password-indicator:nth-child(' + (i + 1) + ')').removeClass('normal').removeClass('pass').addClass('pass') }; return this.each(function () { var r = n(this); //code to insert HTML elements for password strength indicators n('<div class=\'strong-password\'><div class=\'clear-fix\'><div class=\'float-left\'>Password Strength</div><div class=\'float-right strong-password-status\'>Too Short</div></div><span class=\'strong-password-indicator normal\'></span><span class=\'strong-password-indicator normal\'></span><span class=\'strong-password-indicator normal\'></span><span class=\'strong-password-indicator normal\'></span><span class=\'strong-password-indicator normal\'></span></div>').insertAfter(r), r.keyup(function () { //create required variables //logic to work out password strength //call to update indicators t(h, n(this)), }) }) } }) (jQuery) }) EDIT Note - If I change the updatePasswordStrengthIndicator, for loop, children selector from nth-child to 'eq' it works when minified. Not sure why nth-child would be an issue EDIT - Here's the code that works Without Minification $(function () { (function ($) { $.fn.strongPassword = function () { var updatePasswordStrengthIndicator = function (indicators, $context) { console.log("indicators ", indicators); //prints out correct value console.log("$context ", $context; //prints out empty string which is incorrect for (var i = 0; i <= indicators; i++) { $context.siblings(".strong-password").children('.strong-password-indicator:eq(' + i + ')').removeClass('normal').removeClass('pass').addClass('pass'); } } return this.each(function () { var $this = $(this); //code to insert HTML elements for password strength indicators $("<div class='strong-password'><div class='clear-fix'><div class='float-left'>Password Strength</div><div class='float-right strong-password-status'>Too Short</div></div><span class='strong-password-indicator normal'></span><span class='strong-password-indicator normal'></span><span class='strong-password-indicator normal'></span><span class='strong-password-indicator normal'></span><span class='strong-password-indicator normal'></span></div>") .insertAfter($this); $this.keyup(function () { //create required variables //logic to work out password strength //call to update indicators updatePasswordStrengthIndicator(blocksToLight, $(this)); }); }); } }(jQuery)); }); With Minification $(function () { (function (n) { n.fn.strongPassword = function () { var t = function (n, t) { console.log('indicators ', n), console.log('$context ', t); for (var i = 0; i <= n; i++) t.siblings('.strong-password').children('.strong-password-indicator:eq(' + i + ')').removeClass('normal').removeClass('pass').addClass('pass') }; return this.each(function () { var r = n(this); //code to insert HTML elements for password strength indicators n('<div class=\'strong-password\'><div class=\'clear-fix\'><div class=\'float-left\'>Password Strength</div><div class=\'float-right strong-password-status\'>Too Short</div></div><span class=\'strong-password-indicator normal\'></span><span class=\'strong-password-indicator normal\'></span><span class=\'strong-password-indicator normal\'></span><span class=\'strong-password-indicator normal\'></span><span class=\'strong-password-indicator normal\'></span></div>').insertAfter(r), r.keyup(function () { //create required variables //logic to work out password strength //call to update indicators t(h, n(this)), }) }) } }) (jQuery) })
Q: "Not only one of the most talented actors of our age but kind." -- what does 'kind' mean here? I was searching for information about the original novel "House of Cards" and from following site, in the middile of the page, there's sentence which compliment Kevin Spicey as shown below(http://www.michaeldobbs.com/house-of-cards/): He's not only one of the most talented actors of our age but kind, too. I don't think the "Kind" here means Spacey's a nice guy, I guess it might imply that he's a good actor of "man kind" (our kind)? I couldn't find any sentence with similar structure as an example to support my guess, so please anyone can explan to me the real meaning of the word "kind" here, better with some example, thanks. A: It does mean that he's a nice guy. Look at the context. The piece is on an author's website, and is talking about an adaptation of one of his books. In the previous sentence, Spacey has paid the author a compliment with, "'this wouldn't have been possible without the brilliant material it was based on". Calling him "kind" is acknowledging that fact.
Q: Getting user's ip address in model I have an ip_address field for all my tables that I'd like to popular automatically using the models. How could I set that in the models? I'm guessing I'd have to use the before_save filter for this? A: There is no reason to use a filter. The ip_address column is a column like every other. Depending on your intention you must find an matching model instance and change its ip_address column or create a new entry including the columnm. And when you say you have the column in every table its bad style. The ip_address is assigned to a user, not to every single model. I would suggest you to create a new model called Login which includes the ip_address, user_id and the created_at and updated_at fields. The last one are generated automaticly. Then you can save the ip_address each time the user logs in. Like this in your controller: login=Login.new login.user=current_user login.ip_address=request.remote_ip login.save
Q: How do you compute with decimal numbers on a computer? I came across something this morning which made me think... If you store a variable in Python, and I assume most languages, as x = 0.1, and then you display this value to 30 decimal places you get: '0.100000000000000005551115123126' I read an article online which explained that the number is stored in binary on the computer and the discrepancy is due to base conversion. My question is how do physicists and nano-scientists get around this problem when they do computation? I always thought that if I input data into my calculator using scientific-notation it will give me a reliable accurate result but now I am wondering if this is really the case? There must be a simple solution? Thanks. A: Well, as a physicist I say these decimals are redundant in most cases.. it really doesn't matter what's on the 16th decimal place. The precision of measurements doesn't reach that level (not even in QED). Take a look at here, the highest precision measurements are around 10^13 - 10^14. Applying to this to your example: With 14 decimal places 0.100000000000000005551115123126 becomes 0.100000000000000, which doesn't introduce any errors at all. A: There is the decimal class in python that can help you deals with this problem. But personally, when I work with money transactions, I don't want to have extra cents like 1€99000012. I convert amounts to cents. So I just have to manipulate and store integers. A: As always, it depends on the context (sorry for all the "normally" and "usually" words below). Also depends on definition of "scientific". Below is en example of "physical", not "purely mathematical" modeling. Normally, using computer for scientific / engineering calculations: * *you have reality *you have an analytical mathematical model of the reality *to solve the analytical model, usually you have to use some numerical approximation (e.g. finite element method, some numerical scheme for time integration, ...) *you solve 3. using floating point arithmetics Now, in the "model chain": * *you loose accuracy from 1) reality to 2) analytical mathematical model * *most theories does some assumptions (neglecting relativity theory and using classical Newtonian mechanics, neglecting effect of gravity, neglecting ...) *you don't know exactly all the boundary and initial conditions *you don't know exactly all the material properties *you don't know ... and have to do some assumption *you loose accuracy from 2) analytical to 3) numerical model * *from definition. Analytical solution is accurate, but usually practically unachievable. *in the limit case of infinite computational resources, the numerical methods usually converges to the analytical solution, which is somehow limited by the limited floating point accuracy, but usually the resources are limiting. *you loose some accuracy using floating point arithmetics * *in some cases it influences the numerical solution *there are approaches using exact numbers, but they are (usually much) more computationally expensive You have a lot of trade-offs in the "model chain" (between accuracy, computational costs, amount and quality of input data, ...). From "practical" point of view, floating point arithmetics is not fully negligible, but usually is one of the least problems in the "model chain".
Q: Issue with calling multiple labels/functions in assembly I've been learning assembly programming recently and am trying to make a program for an assignment. I have a function/label that draws a line on the screen. The problem is that after calling the function the first time it doesn't get called the second time. I'm using 'bl label' to call the function and 'bx lr' to return to the entry point. The compiler I'm using is FASM v1.43, running on a Raspberry Pi 2 part of the main file responsible for calling drawline: mov r4, #309 ;x mov r5, #219 ;y ;draw veritcal line push{r11,r10,r5,r4} ;vertical or horizontal mov r10,#1 ;length mov r11,$0100 orr r11,$0003 bl drawline pop{r4,r5,r10,r11} ;draw second vertical line push{r11,r10,r5,r4} mov r10,#1 mov r4, #349 ;x mov r11,$0100 orr r11,$0003 bl drawline pop{r4,r5,r10,r11} code in drawline that gets called: rect_vloop: push {r0-r3} mov r0,r7 ;screen address mov r1,r4 ;x mov r2,r5 ;y mov r3,r6 ;colour ;assume BITS_PER_PIXEL, SCREEN_X are shared constants bl drawpixel pop {r0-r3} ;increment and test add r5,#1 mov r8,r11 cmp r5,r8 bls rect_vloop dl_end: bx lr I didn't write drawpixel and I already know that it works. The first line draws onto the screen like it should but the second doesn't draw, removing the first call makes the second draw, so I'd say I've messed up returning the function but I can't tell what i did wrong. Thanks in advance. A: Well, not all of your code is present in the question, but the main thing that stands out is that you are not preserving the correct registers within and between your functions. The ARM Application Binary Interface designates r0-r3 for passing parameters and return values, so preserving the values of r0-r3 in your function is not correct. Indeed the ABI states that A subroutine must preserve the contents of the registers r4-r8, r10, r11 and SP (and r9 in PCS variants that designate r9 as v6) and if you're not sure what the status of r9 is on your platform, play safe and preserve it too. So you need to preserve anything important in r0-r3 and r12 before calling a function, and preserve r4-r11 inside it. You will also need to ensure that the function's stack usage is balanced, hence preserving sp (r13). You must also preserve the link register (lr, r14) if your function calls any other functions, otherwise you lose your return address (this step is also missing in drawline as written). Of course if the only functions you ever call are your own, and your functions are only called by your own code, you can violate the ABI - but I don't know why you'd want to, and the preservation of lr will still be required. FYI the order of registers in your push and pop instructions (actually STMDB and LDMIA) doesn't matter; the instructions are encoded with bitfields describing the registers to be saved or loaded, and the order in which they are stored and retrieved is with ascending register numbers occupying ascending memory locations. Most ARM assemblers will warn you if you try to specify the register list in anything other than ascending order because they assume that you're trying to obtain some specific load or store ordering which you won't get. Finally note that you should make it a habit to push and pop even numbers of registers to maintain 8-byte stack alignment - perhaps you already know this, because you're doing it in the code you presented. This helps your code to be compatible with existing code that requires 8-byte stack alignment, of which there is plenty.
Q: Unable to enter the for loop in test class public class StdQuoteSummaryCreationHandler{ public static void createICMQuoteSummaryRecords(Set<Id> quoteIds) { Map<String,List<QuoteLineItem>> quotelineMap=new Map<String,List<QuoteLineItem>>(); Map<String,List<Quote_Summary__c>> quoteICMSummaryMap=new Map<String,List<Quote_Summary__c>>(); List<QuoteLineItem> qlineList; List<Quote_Summary__c> qlistICMSummary; List<Quote_Summary__c> qlistICMSummarytodelete; List<Quote_Summary__c> qlistICMSummaryAll=new List<Quote_Summary__c>(); Set<String> quoteToUpdate=new Set<String>(); List<Quote> quotelist=[SELECT Id,Currency__c,ICM_Summary_Created__c,DH_StartDate__c,DH_EndDate__c,DH_SubscriptionTerm__c,DH_Ramp__c FROM Quote WHERE Id IN:quoteIds]; for(QuoteLineItem sbqlineItem : [SELECT Id,QuoteId,ACVLicensePS__c,Product2.Global_Local__c,Product2.Family,DH_Period__c,DH_Start_date__c,DH_End_Date__c,DH_Net_Price__c,ProductFamily__c,Term_Type__c,DealHub_QuoteLine_Ramp__c FROM QuoteLineItem WHERE QuoteId IN:quoteIds]) { if(quotelineMap.ContainsKey(sbqlineItem.QuoteId)) { quotelineMap.get(sbqlineItem.QuoteId).add(sbqlineItem); } else { quotelineMap.put(sbqlineItem.QuoteId,new List<QuoteLineItem>()); quotelineMap.get(sbqlineItem.QuoteId).add(sbqlineItem); } } for(Quote sbq:quotelist) { system.debug('quotelist:::::::::' +quotelist); if(quotelineMap.ContainsKey(sbq.Id)) { qlineList=new List<QuoteLineItem>(); qlistICMSummary=new List<Quote_Summary__c>(); qlistICMSummarytodelete=new List<Quote_Summary__c>([select id from Quote_Summary__c where DH_Quote__c =:sbq.id]); if(qlistICMSummarytodelete.size()>0){ Database.delete(qlistICMSummarytodelete, false); } for(QuoteLineItem lineItem:quotelineMap.get(sbq.ID)) { qlineList.add(lineItem); } system.debug('qlineList' +qlineList); if(qlineList.size()>0){ qlistICMSummary=U4_GetICMRecordsForQuote.createICMQuoteSummary(sbq.Id,sbq.DH_StartDate__c,sbq.DH_EndDate__c,sbq.DH_SubscriptionTerm__c,sbq.DH_Ramp__c,qlineList,sbq.Currency__c); system.debug('qlistICMSummary@@@@@' +qlistICMSummary); } if(qlistICMSummary.size()>0) { for(Quote_Summary__c qsummary:qlistICMSummary) { qlistICMSummaryAll.add(qsummary); } quoteToUpdate.add(sbq.id); } } } if(qlistICMSummaryAll.size()>0) try{ insert qlistICMSummaryAll; } catch(Exception ex) { U4_ServiceCloud_Utility.CreateSCLog('Quote_Summary__c','', System.UserInfo.getUserId(),'Info','U4_ICMQuoteStdSummaryCreationHandler.insertquoteSummaryList',ex.getMessage().substring(0, 254)); } } public static void sendICMQuoteSummaryToICMAzure(Set<Id> quoteIds) { AzureServiceBusConfigDetails__mdt asbconfigDetail = [SELECT MasterLabel, Namespace__c, Topic__c ,SASKeyName__c,SASKeyValue__c FROM AzureServiceBusConfigDetails__mdt WHERE MasterLabel ='ICM ASB Configuration' LIMIT 1]; Set<String> oppIds= new Set<String>(); List<Quote> quoteToProcess=[SELECT Id,OpportunityId FROM Quote WHERE ID IN:quoteIds]; for(Quote sbq : quoteToProcess) { oppIds.add(sbq.OpportunityId); } Map<String,List<Quote>> oppquoteMap =new Map<String,List<Quote>>(); for(Quote oppQuoteInfo : [SELECT Id,OpportunityId, DH_SubscriptionTerm__c, Unit4_Company_Name__c, Unit4_street__c, Unit4_country__c, BillingCountry, AccountId,Account.Name,DH_CSR_First_Name__c,DH_CSRLastName__c, DH_CSR_Email__c, CurrencyIsoCode, LastModifiedDate,Aggregated_TCV_SaaS_non_ramped__c,Aggregate_TCV_License_Maintenece_Supp__c, Aggregated_TCV_Summary__c,TCV_Professional_Services__c,DH_Ramp__c, ICM_Min_Indexation_Rate__c,ICM_Indexation_Rate_Increase__c,ICM_ExpiryDate__c,DH_StartDate__c,DH_BillingFrequency__c, Email,ExpirationDate,DH_PONumber__c,DH_Quote_Id__c,Status,ICM_DeliveryMethod__c, ICM_EffectiveDate__c,ICM_ProductType__c,BillingStreet,BillingName, Unit4_Postal_Code__c,BillingCity,BillingState,BillingPostalCode, DH_PaymentTerms__c,ICM_SysID__c, (SELECT Id, DH_HeadProduct__c,ProductName__c,ProductFamily__c, ProductCode__c,DH_Quantity__c,DH_Unit_OfMeasure__c,DH_List_Price__c, Discount,currencyisocode,DealHub_QuoteLine_Ramp__c,DH_Period__c FROM QuoteLineItems), (SELECT Id,Aggregate_for_PF__c,Component__c,End_Date__c,Product_Family__c, PS_Scope__c,DH_Quote__c,Segment__c,Start_Date__c,TCV__c, Term_type__c,Year__c,CurrencyIsoCode FROM Quote_Summarys__r) from Quote where OpportunityId IN:oppIds AND Status=:System.Label.Approval_Status_Approved order by LastModifiedDate DESC]) { if(oppquoteMap.ContainsKey(oppQuoteInfo.OpportunityId)) { oppquoteMap.get(oppQuoteInfo.OpportunityId).add(oppQuoteInfo); } else { oppquoteMap.put(oppQuoteInfo.OpportunityId,new List<Quote>()); oppquoteMap.get(oppQuoteInfo.OpportunityId).add(oppQuoteInfo); } } for(Quote sbq : quoteToProcess) { if(oppquoteMap.ContainsKey(sbq.OpportunityId)) { PrepareAndSendMessageToAzure(sbq.Id,oppquoteMap.get(sbq.OpportunityId),asbconfigDetail); } } } @TestVisible private static void PrepareAndSendMessageToAzure(String quoteId,List<Quote> oppquoteinfo,AzureServiceBusConfigDetails__mdt asbConfigDetail) { String oldquoteId; String action='add'; Quote quote; Integer oppquoteinfoSize=oppQuoteinfo.size(); if(oppquoteinfoSize>1) { oldquoteId=oppQuoteinfo[1].Id; action='update'; } for(Quote quoteInfo:oppquoteinfo) { if(quoteInfo.Id==quoteId) { quote=quoteInfo; break; } } JSONGenerator gen = JSON.createGenerator(true); gen.writeStartObject(); gen.writeStringField('EventType','QuoteToAgreementSync'); gen.writeStringField('Action',action); gen.writeStringField('User',userInfo.getUserId()); gen.writeFieldName('Data'); gen.writeStartObject(); gen.writeFieldName('sfEntityInfo'); gen.writeStartObject(); gen.writeStringField('OpportunityId',(quote.OpportunityId!=null)?quote.OpportunityId:''); //gen.writeStringField('OldQuoteId', (oldquoteId!=null)?oldquoteId:''); if(oldquoteId!=null) gen.writeStringField('OldQuoteId',oldquoteId); else gen.writeNullField('OldQuoteId'); gen.writeStringField('NewQuoteId',(quote.id!=null)?quote.id:''); if(quote.Aggregated_TCV_SaaS_non_ramped__c!=null) gen.writeNumberField('Aggregated_tcv_saas_non_ramped__c',quote.Aggregated_TCV_SaaS_non_ramped__c); else gen.writeNullField('Aggregated_tcv_saas_non_ramped__c'); if(quote.Aggregate_TCV_License_Maintenece_Supp__c!=null) gen.writeNumberField('Aggregate_tcv_license_maintenece_supp__c',quote.Aggregate_TCV_License_Maintenece_Supp__c); else gen.writeNullField('Aggregate_tcv_license_maintenece_supp__c'); if(quote.TCV_Professional_Services__c!=null) gen.writeNumberField('Tcv_professional_services__c',quote.TCV_Professional_Services__c); else gen.writeNullField('Tcv_professional_services__c'); gen.writeStringField('AccountId', (quote.AccountId!=null)?quote.AccountId:''); gen.writeBooleanField('DH_Ramp__c',(quote.DH_Ramp__c!=null)?quote.DH_Ramp__c:false); if(quote.ICM_Min_Indexation_Rate__c!=null) gen.writeStringField('ICM_Min_Indexation_Rate__c',quote.ICM_Min_Indexation_Rate__c); else gen.writeNullField('ICM_Min_Indexation_Rate__c'); if(quote.ICM_Indexation_Rate_Increase__c!=null) gen.writeStringField('ICM_Indexation_Rate_Increase__c',quote.ICM_Indexation_Rate_Increase__c); else gen.writeNullField('ICM_Indexation_Rate_Increase__c'); if(quote.DH_StartDate__c!=null) gen.writeDateField('DH_StartDate__c',quote.DH_StartDate__c); else gen.writeStringField('DH_StartDate__c',''); gen.writeStringField('DH_BillingFrequency__c', (quote.DH_BillingFrequency__c!=null)?quote.DH_BillingFrequency__c:''); // gen.writeStringField('Unit4_taxid__c', (quote.Unit4_TaxId__c!=null)?quote.Unit4_TaxId__c:''); gen.writeStringField('Email', (quote.Email!=null)?quote.Email:''); if(quote.ExpirationDate!=null) gen.writeDateField('ExpirationDate',quote.ExpirationDate); else gen.writeStringField('ExpirationDate',''); gen.writeStringField('DH_PONumber__c', (quote.DH_PONumber__c!=null)?quote.DH_PONumber__c:''); gen.writeStringField('DH_Quote_Id__c', (quote.DH_Quote_Id__c!=null)?quote.DH_Quote_Id__c:''); gen.writeStringField('Status', (quote.Status!=null)?quote.Status:''); gen.writeStringField('Icm_deliverymethod__c', (quote.ICM_DeliveryMethod__c!=null)?quote.ICM_DeliveryMethod__c:''); if(quote.ICM_ExpiryDate__c!=null) gen.writeDateField('Icm_expirydate__c',quote.ICM_ExpiryDate__c); else gen.writeStringField('Icm_expirydate__c',''); if(quote.ICM_EffectiveDate__c!=null) gen.writeDateField('Icm_effectivedate__c',quote.ICM_EffectiveDate__c); else gen.writeStringField('Icm_effectivedate__c',''); // gen.writeStringField('Icm_contractdocumentname__c', (quote.ICM_ContractDocumentName__c!=null)?quote.ICM_ContractDocumentName__c:''); gen.writeStringField('Icm_producttype__c', (quote.ICM_ProductType__c!=null)?quote.ICM_ProductType__c:''); gen.writeStringField('BillingStreet', (quote.BillingStreet!=null)?quote.BillingStreet:''); gen.writeStringField('BillingName', (quote.BillingName!=null)?quote.BillingName:''); gen.writeStringField('Unit4_Postal_Code__c', (quote.Unit4_Postal_Code__c!=null)?quote.Unit4_Postal_Code__c:''); gen.writeStringField('BillingCity', (quote.BillingCity!=null)?quote.BillingCity:''); gen.writeStringField('BillingState', (quote.BillingState!=null)?quote.BillingState:''); gen.writeStringField('BillingPostalCode', (quote.BillingPostalCode!=null)?quote.BillingPostalCode:''); gen.writeStringField('DH_PaymentTerms__c', (quote.DH_PaymentTerms__c!=null)?quote.DH_PaymentTerms__c:''); gen.writeStringField('Unit4_Company_Name__c', (quote.Unit4_Company_Name__c!=null)?quote.Unit4_Company_Name__c:''); gen.writeStringField('ICM_SysID__c', (quote.ICM_SysID__c!=null)?quote.ICM_SysID__c:''); // gen.writeStringField('Region__c', (quote.Region__c!=null)?quote.Region__c:''); if(quote.Aggregated_TCV_Summary__c!=null) gen.writeNumberField('Aggregated_TCV_Summary__c',quote.Aggregated_TCV_Summary__c); else gen.writeNullField('Aggregated_TCV_Summary__c'); if(quote.DH_SubscriptionTerm__c!=null) gen.writeNumberField('DH_SubscriptionTerm__c', quote.DH_SubscriptionTerm__c); gen.writeStringField('Unit4_Company_Name__c',(quote.Unit4_Company_Name__c!=null)?quote.Unit4_Company_Name__c:''); gen.writeStringField('Unit4_street__c', (quote.Unit4_street__c!=null)?quote.Unit4_street__c:''); gen.writeStringField('Unit4_country__c', (quote.Unit4_country__c!=null)?quote.Unit4_country__c:''); gen.writeStringField('BillingCountry', (quote.BillingCountry!=null)?quote.BillingCountry:''); gen.writeStringField('Account.Name', (quote.Account.Name!=null)?quote.Account.Name:''); gen.writeStringField('DH_CSR_Email__c', (quote.DH_CSR_Email__c!=null)?quote.DH_CSR_Email__c:''); gen.writeStringField('DH_CSR_First_Name__c', (quote.DH_CSR_First_Name__c!=null)?quote.DH_CSR_First_Name__c:''); gen.writeStringField('DH_CSRLastName__c', (quote.DH_CSRLastName__c!=null)?quote.DH_CSRLastName__c:''); gen.writeStringField('CurrencyIsoCode',(quote.CurrencyIsoCode!=null)?quote.CurrencyIsoCode:''); gen.writeFieldName('QuoteLineItems'); gen.writeStartArray(); for(QuoteLineItem lineItem:quote.QuoteLineItems) { system.debug('lineItem'+lineItem); gen.writeStartObject(); gen.writeStringField('QuoteLineItems.DH_HeadProduct__c',(lineItem.DH_HeadProduct__c!=null)?lineItem.DH_HeadProduct__c:''); gen.writeStringField('QuoteLineItems.ProductName__c',(lineItem.ProductName__c!=null)?lineItem.ProductName__c:''); gen.writeStringField('QuoteLineItems.ProductFamily__c',(lineItem.ProductFamily__c!=null)?lineItem.ProductFamily__c:''); gen.writeStringField('QuoteLineItems.ProductCode__c',(lineItem.ProductCode__c!=null)?lineItem.ProductCode__c:''); gen.writeBooleanField('QuoteLineItems.DealHub_QuoteLine_Ramp__c',(lineItem.DealHub_QuoteLine_Ramp__c!=null)?lineItem.DealHub_QuoteLine_Ramp__c:false); gen.writeStringField('QuoteLineItems.DH_Period__c',(lineItem.DH_Period__c!=null)?lineItem.DH_Period__c:''); if(lineItem.DH_Quantity__c!=null) gen.writeNumberField('QuoteLineItems.DH_Quantity__c',lineItem.DH_Quantity__c); gen.writeStringField('QuoteLineItems.DH_Unit_OfMeasure__c',(lineItem.DH_Unit_OfMeasure__c!=null)?lineItem.DH_Unit_OfMeasure__c:''); if(lineItem.DH_List_Price__c!=null) gen.writeNumberField('QuoteLineItems.DH_List_Price__c',lineItem.DH_List_Price__c); if(lineItem.Discount!=null) gen.writeNumberField('QuoteLineItems.Discount',lineItem.Discount); gen.writeStringField('QuoteLineItems.currencyisocode',(lineItem.CurrencyIsoCode!=null)?lineItem.CurrencyIsoCode:''); gen.writeStringField('QuoteLineItems.id', (lineItem.Id!=null)?lineItem.Id:''); gen.writeEndObject(); } gen.writeEndArray(); gen.writeFieldName('Quote_Summarys__r'); gen.writeStartArray(); for(Quote_Summary__c qsummry:quote.Quote_Summarys__r) { system.debug('qsummry'+qsummry); gen.writeStartObject(); gen.writeBooleanField('Quote_Summarys__r.Aggregate_for_PF__c',(qsummry.Aggregate_for_PF__c!=null)?qsummry.Aggregate_for_PF__c:false); gen.writeStringField('Quote_Summarys__r.Component__c',(qsummry.Component__c!=null)?qsummry.Component__c:''); if(qsummry.End_Date__c!=null) gen.writeDateField('Quote_Summarys__r.End_Date__c',qsummry.End_Date__c); else gen.writeStringField('Quote_Summarys__r.End_Date__c',''); gen.writeStringField('Quote_Summarys__r.Product_Family__c',(qsummry.Product_Family__c!=null)?qsummry.Product_Family__c:''); gen.writeStringField('Quote_Summarys__r.PS_Scope__c',(qsummry.PS_Scope__c!=null)?qsummry.PS_Scope__c:''); gen.writeStringField('Quote_Summarys__r.Segment__c',(qsummry.Segment__c!=null)?qsummry.Segment__c:''); if(qsummry.Start_Date__c!=null) gen.writeDateField('Quote_Summarys__r.Start_Date__c',qsummry.Start_Date__c); else gen.writeStringField('Quote_Summarys__r.Start_Date__c',''); if(qsummry.TCV__c!=null) gen.writeNumberField('Quote_Summarys__r.TCV__c',qsummry.TCV__c); else gen.writeStringField('Quote_Summarys__r.TCV__c',''); gen.writeStringField('Quote_Summarys__r.Term_type__c',(qsummry.Term_type__c!=null)?qsummry.Term_type__c:''); gen.writeStringField('Quote_Summarys__r.Year__c',(qsummry.Year__c!=null)?qsummry.Year__c:''); gen.writeStringField('Quote_Summarys__r.id', (qsummry.Id!=null)?qsummry.Id:''); gen.writeStringField('Quote_Summarys__r.currencyisocode',(qsummry.CurrencyIsoCode!=null)?qsummry.CurrencyIsoCode:''); gen.writeEndObject(); } gen.writeEndArray(); gen.writeEndObject(); gen.writeEndObject(); gen.writeEndObject(); String jsonData = gen.getAsString(); U4_AzureManagement u4Azr=new U4_AzureManagement(asbconfigDetail.Namespace__c,asbconfigDetail.Topic__c,asbconfigDetail.SASKeyName__c,asbconfigDetail.SASKeyValue__c); u4Azr.sendMessageToQueue(jsonData); } } The test class doesn't cover : for(Quote_Summary__c qsummary:qlistICMSummary) { qlistICMSummaryAll.add(qsummary); } part of the code. Test class:: @isTest static void quoteCreationAndApprove(){ CPQ_TriggerSwitches__c cts = new CPQ_TriggerSwitches__c(); cts.Quote_onBeforeInsert__c = true; cts.Quote_onBeforeUpdate__c = true; cts.Quote_onAfterInsert__c = true; insert cts; Id pricebookId = Test.getStandardPricebookId(); Id PBcustom = Id.valueOf(System.Label.PB2020ID); TriggerSupport__c triggerSupport = U4_NewTestDataFactory.TEST_CreateTriggerSupport(true); SCMC__Currency_Master__c SCM = U4_NewTestDataFactory.TEST_CreateSCMCurrency(False); SCM.Name = 'EUR'; insert SCM; //Creating U4 Account Account account = U4_NewTestDataFactory.TEST_CreateSingleAccount(False); account.Name = 'Business Software Ltd.'; account.BillingCountry = 'North America'; insert account; Opportunity opportunity = CPQTestFactory.createOpportunity(account.Id, 'Opty1', PBcustom); opportunity.Require_DH_Quote__c = 'Yes'; opportunity.ACV_License__c = 12; opportunity.Pricebook2Id = pricebookId; opportunity.accountid = account.id; update opportunity; Quote qt = new Quote(); qt.Name = 'test'; qt.Status = 'Draft'; qt.opportunityid = opportunity.id; qt.DH_StartDate__c = System.today(); qt.DH_EndDate__c = system.today()+2; qt.ExpirationDate = system.today()+1; qt.DH_SubscriptionTerm__c = 36; qt.DH_Ramp__c = TRUE; qt.ExpirationDate = system.today()+1; insert qt; opportunity.SyncedQuoteId = qt.id; update opportunity; User approver = U4_NewTestDataFactory.TEST_CreateSystemAdminitrator(true); Product2 product1 = new Product2(); product1.Name = 'testProduct'; product1.productCode = '1234'; product1.isActive = true; product1.CurrencyIsoCode = 'EUR'; product1.U4_Product_Family__c = 'testFamily'; product1.ProductCode = 'PCode'; product1.Unit_of_Measure__c = 'number of FTE employees'; product1.SBQQ__Component__c = true; product1.SbQQ__hidden__c = false; insert product1; // 1. Insert a price book entry for the standard price book. // Standard price book entries require the standard price book ID we got earlier. PricebookEntry standardPrice = new PricebookEntry( Pricebook2Id = pricebookId, Product2Id = product1.Id, UnitPrice = 1000, IsActive = true); insert standardPrice; PriceBook2 pb2=new PriceBook2(); pb2.Name = 'test'; pb2.IsActive = true; pb2.CurrencyIsoCode='EUR'; insert pb2; PricebookEntry pbe = New PricebookEntry (); pbe = new PricebookEntry(Pricebook2Id = pb2.Id, Product2Id = product1.Id, UnitPrice = 10000, IsActive = true, UseStandardPrice = false); insert pbe; QuoteLineItem testQuoteline = new QuoteLineItem ( Quoteid = qt.id, Product2id = product1.id, Quantity = 22, PricebookEntryId = standardPrice.id, UnitPrice = 200, DH_Quantity__c = 10, DH_List_Price__c = 10.0, Discount= 2); insert testQuoteline; //qt.Status = 'In Approval Process'; // update qt; Quote_Summary__c qs = new Quote_Summary__c(); qs.Aggregate_for_PF__c = false; qs.Component__c = 'non ramped'; qs.Start_Date__c = system.today(); qs.End_Date__c = system.today() + 5; qs.TCV__c = 4400; qs.DH_Quote__c = qt.id; insert qs; qt.Status = 'Approved'; qt.ICM_EffectiveDate__c = system.today(); qt.ICM_ExpiryDate__c = system.today()+2; update qt; List<Quote> quoteList=new List<Quote>(); quoteList.add(qt); Set<Id> quoteIds = new Set<Id>(); quoteIds.add(qt.id); AzureServiceBusConfigDetails__mdt asbconfigDetail = [SELECT MasterLabel, Namespace__c, Topic__c ,SASKeyName__c,SASKeyValue__c FROM AzureServiceBusConfigDetails__mdt WHERE MasterLabel ='ICM ASB Configuration' LIMIT 1]; Test.setMock(HttpCalloutMock.class, new U4_AzureManagementCallOutMock()); Test.startTest(); U4_ICMStdQuoteToAzurePBHandler.sendQuoteToASB(quoteList); StdQuoteSummaryCreationHandler.createICMQuoteSummaryRecords(quoteIds); QuoteSummaryCreationHandler.sendICMQuoteSummaryToICMAzure(quoteIds); test.stopTest(); }
Q: Need advice on my Update Query I'm trying create an update query which supposed to change the field value (Default value is "Delhivery") to "IndiaPost" when the corresponding Pin code is not found in the table "Pin code Whitelist". It always gives me an "Unknown" error while running the query, even though no syntax errors were displayed. I hope these attached pictures will give you enough clarity on this. Screenshot-Main Database fields Screenshot-Query Window with error Screenshot-Table " Pincode Whitelist" Correction- On the "Screenshot-Query Window with error]", criteria is as given bellow: DCount("*", "[Delhivery Pincode List]", "[pin]=[MainDb]![Pincode]") Sorry for the mistake. Expecting your valuable advice to identifying the mistake and fixing it. Thank you very much in anticipation. A: I would recommend a Not In statement in your update query: UPDATE MainDb SET [shipping choice] = "IndiaPost" WHERE (((pincode) Not In (select pincode from [Delhivery Pincode List])));
Q: Android DAO adding a query "'@Query not applicable for field" Here is a DAO i have created for a rooms library with a list of participants. The data is very simple. package com.example.tag; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import java.util.List; @Dao public interface ParticipantDAO { @Query("SELECT * FROM Participants ORDER BY Name") LiveData<List<Participant>> getAllParticipants(); @Query("SELECT * FROM Participants LIMIT 1") Participant[] getAnyParticipant; @Insert void insert(Participant participant); @Update void update(Participant participant); @Delete void delete(Participant participant); @Query("DELETE FROM Participants") void deleteAll(); } The problem is with the second @Query statement (getAnyParticipant). I receive the error: "'@Query' not applicable to field". I am attempting to modify the android tutorials for my needs (using participants instead of words) located here: https://codelabs.developers.google.com/codelabs/android-training-room-delete-data/index.html?index=..%2F..android-training#2 What am I doing wrong? A: Only method can be annotated with @Query. Here, you are trying to annotate a class field with @Query. You missed a pair of parentheses.
Q: Jenkins Running xUnit Tests Code 58 This has me completely stumped. I have a Jenkins build configured to run some xUnit tests in my solution via an MSBuild script. When it gets to the task to run the tests I get a failure message: error MSB3073: The command .... exited with code 58. I can't even find any info on what error code 58 is. If I copy the command to a CMD window and run it it runs perfectly so the command itself is definitely correct. Any ideas what error code 58 is? Or has anyone seen this problem before and have a solution?
Q: Why are Mac OS X alias files so large? On Mac OS X, I have two aliases in my Applications folder, each points to another folder. They are 1 MB each. Why so large? I've found other sources on the Internet to say that yes, alias files can be large, but no explanation why. Even if they store a lot of redundant information to find the target file in case it moves, I can't imagine why an entire megabyte would be needed. A: First of all, I wonder if the 1 MB is correct: true, Finder's Show Info tells you this, but in Terminal the file sizes are always just half of that. Odd. The size is due to embedded icons. Note that an alias to an application (more precisely: an application bundle) might be much smaller than an alias to a plain folder. Hence, I guess plain folders use a higher definition icon than, for example, iTunes does. And indeed, if you change the icon of the source, the icon of the alias is not changed. In Terminal you'll see: ls -l@ drwxr-xr-x 2 arjan staff 68 Nov 14 09:20 MyFolder -rw-r--r--@ 1 arjan staff 519012 Nov 14 09:20 MyFolder alias com.apple.FinderInfo 32 com.apple.ResourceFork 518659 drwxr-xr-x 2 arjan staff 68 Nov 14 09:26 MyOtherFolder -rw-r--r--@ 1 arjan staff 519040 Nov 14 09:26 MyOtherFolder alias com.apple.FinderInfo 32 com.apple.ResourceFork 518679 So: 4 bytes more in the "Resource Fork" for each letter in the file name, and on the file system things are padded a bit. That same Resource Fork also includes the icons. If you have the Apple Developer Tools installed: DeRez "MyFolder alias" > MyFolderAlias.txt That text file then shows you more than 32,000 lines of text that represents the icon. (See also Ars Technica about HFS+. Without the Developer Tools, your can use xattr -l to kind of see what's in those extended attributes.) A: In High Sierra, the following works: just select the alias and run Finder command "Show Original" (command-R). This trims the alias size down to a minimum. This brought an alias that was previously 24 Mb down to 8 Kb.
Q: One-liner shoulda syntax using braces In the book Rails Test Prescriptions (b10.0, page 176), there are examples of one-liner assertions like the following: should "be successful" { assert_response :success } This doesn't appear to be valid ruby syntax to me, and ruby reports that the left curly brace is unexpected. In order for it to be parsed, I have to change it to should "be successful"; do assert_response :success end What's wrong with the syntax of the first example? A: This is valid Ruby syntax. Well, sort of. It just doesn't make sense! Since the precedence of a literal block using curly braces is higher than passing an argument without parentheses, the block gets bound to the argument instead of the method call. If the argument is itself a method call, then you won't even get a syntax error. You'll just scratch your head wondering why your block doesn't get called. To fix this, you either put parentheses around the argument, since parentheses have higher precedence than curly braces, or use the do / end form, which is lower precedence than an argument list without parentheses. def foo; yield if block_given?; 'foo' end puts foo { puts 'block' } # block # foo puts(foo) { puts 'block' } # foo puts foo do puts 'block' end # foo puts foo { puts 'block' }, foo { puts 'block' } # block # block # foo # foo puts 'foo' { puts 'block' } # SyntaxError: (irb):19: syntax error, unexpected '{', expecting $end A: This may be a mistake on my part in trying to get the example to take up fewer lines. The block is probably binding to the argument and not the method call, as Jorg said. I think that the proper way to rewrite this as a one-liner is: should("be successful") { assert_response :success } But really, the way to go is to use the shoulda macro: should respond_with(:success) Thanks, Noel
Q: Sending email with different domain name While sending the mail it showing Mailer Error: SMTP connect() failed It was not working properly.Please check the code and give me valuable answer. require 'PHPMailerAutoload.php'; if(isset($_POST['send'])) { $email = $_POST['email']; $password = $_POST['password']; $to_id = $_POST['toid']; $message = $_POST['message']; $subject = $_POST['subject']; $mail = new PHPMailer; $mail->isSMTP(); $mail->Host = 'smtp.domain.com'; $mail->Port = 465; $mail->SMTPSecure = 'ssl'; $mail->SMTPAuth = true; $mail->Username = $email; $mail->Password = $password; $mail->addAddress($to_id); $mail->Subject = $subject; $mail->msgHTML($message); var_dump($mail->send()); if (!$mail->send()) { $error = "Mailer Error: " . $mail->ErrorInfo; echo '<p id="para">'.$error.'</p>'; } else { echo '<p id="para">Successfully sent mail</p>'; } } ?> A: It looks like an authentication problem. control your host, port, username and password.
Q: How do you make 4 2x2 buttons having the same dimensions I want to create a group of 2by2 buttons aligned to each other like this: A B C D each having the same width and height regardless of the length of their content. I try using the following setup with nested LinearLayouts, it meets my requirement, however I have received a warning saying that nested layout_weight has great(exponential) impact on performance. <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:baselineAligned="false"> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="50" android:orientation="vertical"> <Button android:id="@+id/buttonA" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="50" android:text="aaa"/> <Button android:id="@+id/buttonC" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="50" android:text="cccccccccccccccccccccccccccc"/> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="50" android:orientation="vertical"> <Button android:id="@+id/buttonB" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="50" android:text="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" /> <Button android:id="@+id/buttonD" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="50" android:text="ddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"/> </LinearLayout> </LinearLayout> I wonder if there is a better way to do this? Thank you! A: Use a LinearLayout with 2 TableRows and insert 2 Buttons in each TableRow. Assign width and height accordingly to your needs. Assign a weight of 1 to each item including the TableRows and you should be good to go. EDIT: Ok after playing a bit around I found this was working good ;-) This is basically a mix of your own layout and mine ;-) <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="0dip" android:layout_weight="1" > <Button android:id="@+id/button1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="cccccccccccccccccccccccccccc" /> <Button android:id="@+id/button2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="Button" /> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="match_parent" android:layout_height="0dip" android:layout_weight="1" > <Button android:id="@+id/button3" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" /> <Button android:id="@+id/button4" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="ddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" /> </TableRow> </LinearLayout> A: I haven't tested it, but you could use button.getWidth() to get the width of the 4 buttons. Find the max of the 4 and then set all the buttons to that width. If the content of the buttons are going to be dynamic.
Q: no layout in login page in angular 4 project I am working on angular 4 project I want to create login page in which I don't want the layout that is given for other pages.I don't want the header, footer and sidebar in it. I have seen on stack overflow but I didn't understood it Best method to set different layout for different pages in angular 4 how can i do that any help my code on git hub is https://github.com/s2pedutech/imsui1
Q: How to sum and group data for template For simplicity, assume a database with the following columns: Table: Tickets Columns: Gender, Quantity, Date where Gender can be M or F. A row is inserted for every purchase. Ultimately I want a stacked bar chart that shows the quantity purchased by males and females each month. I can't seem to find a way to do this that doesn't require 2 queries, one that sums for M per month and one for F per month. The problem is that the query sets may not have the same number of objects and may not be in the same order by date. I've tried: set = Model.objects.filter(date__month = month).values('gender').aggregate(Sum('quantity')) This sorts by date but doesn't separate M from F. Adding M or F as a filter yields the correct quantity for one of the groups. Using two queries(one for each of M, F) yields the correct quantities and date ranges but doesn't necessarily yield an identical number of sets. (eg. if in some months there are no purchases by M). Thanks in advance for guidance. A: You can use the following Statement : Model.objects.filter(date__month = month).values('gender'). \ annotate(total=Sum('quantity')) in order to sum the quantity per gender per month
Q: SvelteKit + Supabase - get data onMount, keep pre-fetch working I am building the site which seems fairly simple show data on page from database. I want it to be as fast as possible. It already works/partially works in 3 ways: #Approach 1 +page.server.js -> gets data from Supabase +page.svelte -> gets data and creates a website Advantages: - works - pre-fetch (hovering over links) works Disadvantages: - wasting a lot of time (100-600ms) waiting for document. I don't know what is the reason for waiting. Just render site (logo, menu, header etc.) and when data is retrieved show it on page. Don't make user wait with blank site for document to get downloaded. As stated in here: https://kit.svelte.dev/docs/load "Once all load functions have returned, the page is rendered." As said, it seems to be a waste of time to wait #Approach 2 As stated in here: https://languageimperfect.com/2021/02/17/data-fetching-in-svelte.html I only use +page.svelte with onMount Advantages: - works - there is no wasted time waiting for document to retrieve data Disadvantages: - pre-fetch does not work So in general this approach is faster for 1-st time user, however is much slower for desktop users (as there is no pre-fetch on hover) #Approach 3 Only use +page.svelte, in <script context="module"> import data from Supabase and show it as: {#await getDataFromSupabase} <p>Loading ...</p> {:then data} {:catch error} <p style="color: red">{error.message}</p> {/await} Advantages: - there is no wasted time waiting for document to retrieve data - pre-fetch works Disadvantages: - does not work with any additional parameters. For example I am not able to user page path to retrieve only selected data based on my URL So those are my 3 ways already tested. How to improve it? My goal seems fairly simple: 1)Load data as soon as possible, without waiting for document (Approach #1 does not do it) 2)Pre-fetch should work, so if user hoover over link on desktop it should already start building webpage (Approach #2 does not do it) 3)I should be able to use parameters from URL (Approach #3 does not do it) Any idea how to achieve it? I've tried 3 methods described above. All 3 have some disadvantages. I am looking for creating blazing fast webpage A: Have you tried leveraging a prop + reactivity? For example, In your page.ts (or page.server.ts in my case) return a user and a table return { user: session.user, tableData }; Then in your +page.svelte access it with export let data; $: ({ user, tableData } = data); A: I'm still reading about it and found half-solution Adding: export const prerender = true; in all +page.svelte.js files My page is on vercel and it seems as when anyone visits page (for example /product/123) it creates it's prerendered version, and when anybody visits the same url again it will be loaded much faster Pre-render still works I though I will be able to provide list of pages (as i have dynamic ones like /product/[slug]) in prerender: prerender: { entries: [ '/product/1', '/product/2', '/product/3' ], }, However, I do not know why it does not work for me. Furthermore it would not be the full solution, as I have a lot of (really a lot of) links, so Vercel would need to visit each one during build to save html. It would kill my database... So in summary: For now I implemented prerender. It is still worse than having js in +page.svelte inside as with this one page would have document load ~100 ms. Now (on second visit) it has ~400 ms, which is still much better than 800 ms without prerender I do not use js in to load data from database, as with this approach prefetch does not work. So if I hover over link nothing happens. And page is loaded only after click This is not the best solution. For 2000 url's (which Vercel gets automatically) build process lasts 50 minutes. Looking for another solution
Q: Type not assignable to type MenuTheme I'm still new on TS. I define ThemeSwitcher using hooks from package react-css-theme-switcher But when i try to assign its object into attribute theme from component Menu Ant Design. This error pop up. It is working fine in react but using TypeScript i dont even know how to do Please enlight me regarding this. Thank you
Q: While "!b.equals(x) || !b.equals(y)" is an infinite loop? Hey guys this is my code and what it is doing is going in an loop but what its suppose to do is if the user types in borrow then it will ask the user how much which it does but then they type in a number and it will ask them again would you like to borrow or sell and it is in an infinite loop. case 3: do{ System.out.println("What would you like to do? Please type borrow to borrow money or sell to sell assets: "); b = scan.nextLine().toLowerCase(); if(b.equals("borrow")){ System.out.print("how much would you like to borrow Remmber if you go over 50000 debt its game over."); try { input = scan.nextInt(); } catch (Exception e) { System.err.println("That is not a number!!"); } account.setdebt(account.getDebt() + input); account.setBalance(account.getBalance() + input); System.out.println("Your new Balance is " + account.getBalance()); } else if(b.equals("sell")){ sellA(); }else{ System.out.println("You didn't input 'borrow' or 'sell'. Reinput please"); } }while(!b.equals("borrow") || !b.equals("sell")); break; A: You need to change || to && inside while, otherwise the condition is always true. There'll always be at least one of those two values that b is not equal to.
Q: Java Swing: combine effects of CardLayout and JLayeredPane I am trying to place some JPanels one on top of the other, completely overlapping. I use JLayeredPane to have them in different "depth" so I can change the depth and opacity to see a certain panel "under" another. Here is a small test I did which is working properly: public class LayeredCardPanel extends JPanel { private static final String BLUE_PANEL = "blue "; private static final String RED_PANEL = "red "; private static final String GREEN_PANEL = "green"; private String[] panelNames = { BLUE_PANEL, RED_PANEL, GREEN_PANEL }; private Color[] panelColors = { Color.BLUE, Color.RED, Color.GREEN }; private List<JPanel> panels = new ArrayList<>(); private final int TOP_POSITION = 30; private static final int PANELS_FIRST_POS = 10; private JLayeredPane layeredPane; public LayeredCardPanel() { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(createControlPanel()); layeredPane = new JLayeredPane(); //////////////////////////////////////////////////////////////// //setting layout here results in all grey, non functioning panel. //layeredPane.setLayout(new CardLayout(0, 0)); ////////////////////////////////////////////////////////////// add(layeredPane); //adding 3 panel for (int i = 0; i < panelNames.length; i++) { JPanel panel = new JPanel(); panel.setBackground(panelColors[i]); layeredPane.add(panel); layeredPane.setLayer(panel, PANELS_FIRST_POS + i); panels.add(panel); } //////////////////////////////////////////////////////////// //setting the card here, after adding panels, works fine layeredPane.setLayout(new CardLayout(0, 0)); ////////////////////////////////////////////////////////// } The test result looks like this: As you can see in between the ////// commented line, this test works fine only if I set CardLayout to the JLayeredPane after I add the JPanels to it. It seems to me that the JPanels are added to the JLayeredPane using the default layout manager. The layout (setting and changing bounds to fill the JLayeredPane) is done by the later-applied CardLayout. My question is: although this is working as I need, the solution (using one layout manager to add, and then replacing it to achieve the layout I want) does not look an elegant solution. I am looking for better ways to do it. Here is the whole SSCE : public class LayeredCardPanel extends JPanel { private static final String BLUE_PANEL = "blue "; private static final String RED_PANEL = "red "; private static final String GREEN_PANEL = "green"; private String[] panelNames = { BLUE_PANEL, RED_PANEL, GREEN_PANEL }; private Color[] panelColors = { Color.BLUE, Color.RED, Color.GREEN }; private List<JPanel> panels = new ArrayList<>(); private final int TOP_POSITION = 30; private static final int PANELS_FIRST_POS = 10; private JLayeredPane layeredPane; public LayeredCardPanel() { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(createControlPanel()); layeredPane = new JLayeredPane(); add(layeredPane); //add 3 panel for (int i = 0; i < panelNames.length; i++) { JPanel panel = new JPanel(); panel.setBackground(panelColors[i]); layeredPane.add(panel); layeredPane.setLayer(panel, PANELS_FIRST_POS + i); panels.add(panel); } layeredPane.setLayout(new CardLayout()); } private JPanel createControlPanel() { ActionListener aListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(e.getSource() instanceof JButton ) { moveToTop(((JButton) e.getSource()).getActionCommand() ); } } }; JPanel controls = new JPanel(); controls.setLayout(new BoxLayout(controls, BoxLayout.Y_AXIS)); JButton blueViewBtn = new JButton(BLUE_PANEL); blueViewBtn.setActionCommand(BLUE_PANEL); blueViewBtn.addActionListener(aListener); controls.add(blueViewBtn); JButton redViewBtn = new JButton(RED_PANEL); redViewBtn.setActionCommand(RED_PANEL); redViewBtn.addActionListener(aListener); controls.add(redViewBtn); JButton greenViewBtn = new JButton(GREEN_PANEL); greenViewBtn.setActionCommand(GREEN_PANEL); greenViewBtn.addActionListener(aListener); controls.add(greenViewBtn); return controls; } private void moveToTop(String panelName) { for(int i = 0; i < panelNames.length; i++) { if(panelNames[i].equals(panelName)) { layeredPane.setLayer(panels.get(i),TOP_POSITION); } else { layeredPane.setLayer(panels.get(i), PANELS_FIRST_POS + i); } } } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("Layered Card Panel Simulation"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComponent newContentPane = new LayeredCardPanel(); newContentPane.setPreferredSize(new Dimension(300,100)); frame.setContentPane(newContentPane); frame.pack(); frame.setVisible(true); } }); } } A: Basically you are NOT using a CardLayout. Your code would work even if you don't have the setLayout(...) statement. When you use a CardLayout: * *The layout manager can only track the cards added after you have set the layout manager. *only one component is ever displayed at a time, which you don't want since you want to play with panel transparency Edit: When you set the CardLayout AFTER the panels are added to the layered pane they are NOT handled by the CardLayout. As a result all panel remain visible. Apparently all that happens is that the CardLayout will set the size of each panel to fill the space available so painting appears to work correctly. When I modify your SSCCE to set the CardLayout BEFORE adding the panels then the CardLayout does manage the panels. So the CardLayout invokes setVisible(false) on all the panels except the first panel added, which in the SSCCE is the blue panel. So you will only ever see the blue panel even though you try to move different panels to the front. This is easily verified by the following change to the SSCCE: layeredPane.setLayer(panel, PANELS_FIRST_POS + i); System.out.println(panel.isVisible()); So yes, using a CardLayout is really a hack and is not the way the CardLayout was intended to be used or the way a JLayeredPane was intended to be used. A JLayeredPane is really meant to be used with a null layout meaning you are responsible for setting the size of each component. For a better solution I would suggest that you need to add a ComponentListener to the layered pane. Then you should handle the componentResized(...) event. Then you would iterate through all the components added to the layered pane and set the size of each component equal to the size of the layered pane. A: The solution I applied is the following: I changed the contractor so layeredPane uses custom layout manager Layout() : public LayeredCardPanel() { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(createControlPanel()); layeredPane = new JLayeredPane(); layeredPane.setLayout(new Layout()); add(layeredPane); //add 3 panel for (int i = 0; i < panelNames.length; i++) { JPanel panel = new JPanel(); panel.setBackground(panelColors[i]); layeredPane.add(panel); layeredPane.setLayer(panel, PANELS_FIRST_POS + i); panels.add(panel); } } Layout() extends CardLayout overriding addLayoutComponent to do nothing: class Layout extends CardLayout{ @Override public void addLayoutComponent(String name, Component comp) { // override to do nothing } }
Q: Как удалить из List Частично повторяющиеся объекты Есть класс для десериализации: class ActorRow { public long idP { get; set; } public string fio { get; set; } public int idt { get; set; } public string tyt { get; set; } public string ExpT { get; set; } public string Verificated { get; set; } } в ходе получения часть объектов этого класса может совпадать. Часть объектов может совпадать по всем свойствам кроме Verificated, а часть объектов вообще может не совпадать. Полученные объекты хранятся в var RowA = new List<ActorRow>() Вопрос: Как удалить из листа все повторяющиеся и частично повторяющиеся записи? Под удалением понимаю, что если записи совпадают или частично совпадают, то все повторения и оригинал надо удалить. Глядя на эту задачу решил пройти циклично по записям и найти дубли, но такой подход меня не устраивает, хотелось бы сделать что-нибудь по проще, например LINQ, но опыта не хватает. Я даже не знаю с какой стороны начать. A: Как правильно подметил @AK вы получите те же циклы при написании linq-запросов. Сделал 2 способами- циклом и Linq'ом. void Main() { var a = new List<ActorRow>{ new ActorRow { idP = 1, fio = "abc", idt = 1, tyt = "a", ExpT = "b", Verificated = "true" }, new ActorRow { idP = 2, fio = "abc", idt = 1, tyt = "a", ExpT = "b", Verificated = "false" }, new ActorRow { idP = 3, fio = "bca", idt = 1, tyt = "a", ExpT = "b", Verificated = "true" }, new ActorRow { idP = 4, fio = "bas", idt = 1, tyt = "a", ExpT = "b", Verificated = "false" }, new ActorRow { idP = 1, fio = "abc", idt = 1, tyt = "a", ExpT = "b", Verificated = "true" }, new ActorRow { idP = 1, fio = "das", idt = 1, tyt = "a", ExpT = "b", Verificated = "false" }, new ActorRow { idP = 1, fio = "abc", idt = 1, tyt = "a", ExpT = "b", Verificated = "true" }, new ActorRow { idP = 1, fio = "abc", idt = 1, tyt = "a", ExpT = "b", Verificated = "true" }, }; var b = new List<ActorRow>(); foreach(var el in a){ var item = b.FirstOrDefault(x => x.idP == el.idP && x.fio == el.fio && x.idt == el.idt && x.tyt == el.tyt && x.ExpT == el.ExpT); if(item == null){ b.Add(el); } else{ b.Remove(item); } } Console.WriteLine(b); var c = a.Where(x => !a.Any(el => a.IndexOf(el) != a.IndexOf(x) && x.idP == el.idP && x.fio == el.fio && x.idt == el.idt && x.tyt == el.tyt && x.ExpT == el.ExpT )).Select(x => x).ToList(); Console.WriteLine(c); } // Define other methods and classes here class ActorRow { public long idP { get; set; } public string fio { get; set; } public int idt { get; set; } public string tyt { get; set; } public string ExpT { get; set; } public string Verificated { get; set; } } Вывод: idP fio idt tyt ExpT Verificated 2 abc 1 a b false 3 bca 1 a b true 4 bas 1 a b false 1 das 1 a b false Можно еще попробовать способ который предложил @tym32167 в комментариях: var d = a.GroupBy(x => new { x.idP, x.fio, x.idt, x.tyt, x.ExpT }).Where(x => x.Count() == 1).Select(x => x.First()).ToList(); Console.WriteLine(d); Вывод: idP fio idt tyt ExpT Verificated 2 abc 1 a b false 3 bca 1 a b true 4 bas 1 a b false 1 das 1 a b false A: То же самое, что и в ответе @Anamnian просто код почистил: void Main() { var source = new List<ActorRow>{ new ActorRow { idP = 1, fio = "abc", idt = 1, tyt = "a", ExpT = "b", Verificated = "true" }, new ActorRow { idP = 2, fio = "abc", idt = 1, tyt = "a", ExpT = "b", Verificated = "false" }, new ActorRow { idP = 3, fio = "bca", idt = 1, tyt = "a", ExpT = "b", Verificated = "true" }, new ActorRow { idP = 4, fio = "bas", idt = 1, tyt = "a", ExpT = "b", Verificated = "false" }, new ActorRow { idP = 1, fio = "abc", idt = 1, tyt = "a", ExpT = "b", Verificated = "true" }, new ActorRow { idP = 1, fio = "das", idt = 1, tyt = "a", ExpT = "b", Verificated = "false" }, new ActorRow { idP = 1, fio = "abc", idt = 1, tyt = "a", ExpT = "b", Verificated = "true" }, new ActorRow { idP = 1, fio = "abc", idt = 1, tyt = "a", ExpT = "b", Verificated = "true" }, }; var result = new List<ActorRow>(); foreach (var el in source) { if (!result.Any(x => this.IsSemiDup(x, el))) result.Add(el); } result.Dump(); } // Define other methods and classes here public bool IsSemiDup(ActorRow a, ActorRow b) { if (a.idP != b.idP) return false; if (a.fio != b.fio) return false; if (a.idt != b.idt) return false; if (a.tyt != b.tyt) return false; if (a.ExpT != b.ExpT) return false; return true; } Публикую код лишь для того, чтобы было видно, что есть варианты более читаемые, чем первый предложенный. PS И да. Тут можно легко зарыться в тему сравнения по ссылке/значению и более правильно написать процедуру поиска дубликата. A: Переопределим GetHashCode. class ActorRow { public long idP { get; set; } public string fio { get; set; } public int idt { get; set; } public string tyt { get; set; } public string ExpT { get; set; } public string Verificated { get; set; } public override int GetHashCode() { unchecked { var hashCode = 675286467; hashCode = hashCode * idP.GetHashCode(); hashCode = hashCode * fio.GetHashCode(); hashCode = hashCode * idt.GetHashCode(); hashCode = hashCode * tyt.GetHashCode(); hashCode = hashCode * ExpT.GetHashCode(); return hashCode; } } } Далее просто группируем по хешкоду и фильтруем те которое уникальные, т.е. в 1 экземпляре. Собираем в плоскую коллекцию, старую забываем. var rows = new List<ActorRow>(); rows = rows.GroupBy(r => r.GetHashCode()) .Where(g => g.Count() == 1) .SelectMany(g => g) .ToList();
Q: Make First Sheet Display in Excel of Sharepoint in Browser I have a Excel Web part and make an excel appear in browser throught this web part. There is 4 sheets in excel but when I open the page , firstly the third sheet appears but not he first sheet. How can I make the first sheet appear?
Q: Parallelize A Batch Application I am currently working on an application that parses huge XML files. For each file, there will be different processes but all of them will be parsed into a single object model. Currently, the objects parsed from each XML file will go into a single collection. This collection is also used during parsing, e.g. if a similar object already exists, it will modify the object's property instead, such as adding count. Looking at the CPU graph when this application is running, it is clear that it only uses part of the CPU (one core at a time on 100%), so I assume that running it on parallel will help shave running time. I am new into parallel programming, so any help is appreciated. A: I suggest that you look at using threads instead of parallel programming. Threading Tutorial A: Instead of trying to managed threading yourself (which can be a daunting task), I suggest using a parallel library. Look at PLINQ/TPL for what is coming in .Net. CTPs can be downloaded here. A: I would suggest you the following technique: construct a queue of objects that wait to be processed and dequeue them from multiple threads: * *Create an XmlReader and start reading the file node by node while not EOF. *Once you encounter a closing tag you can serialize the contents it into an object. *Put the serialized object into a Queue. *Verify the number of objects in the Queue and if it is bigger than N, kick a new thread from the ThreadPool which will dequeue <= N objects from the queue and process them. The access to the queue needs to be synchronized because you will enqueue and dequeue objects from multiple threads. The difficulty consists in finding N such that all the CPU cores work at the same time.
Q: Why do node modules have an `@` in the name? With the release of material-ui version 1, I noticed they have added an @ symbol to the front of the library name @material-ui/core. After digging into my node modules, I see that they aren't the only one - I have @babel and @types as well. Is the @ significant for some reason, or is it just for the purposes of clarity and avoiding conflicts with previous versions of the library? A: @ indicates that the package is a scoped package. It is a way of grouping similar projects under single scope. A scoped package can be published as private as well as public. For more info check out the following link npm-scope
Q: Dojo 1.8 dnd modify data state of dnd items I have a dnd.source and a dnd.target. So user drags an item from the source and drops it on the target. I use custom creators because their view is different. Its dnd item is backed by a data object like this {alpha:"alphaVal", beta:"betaVal", charlie:"charlieVal", delta:"deltaVal"} The dnd items on the source are displayed as a list but when dropped onto the target the custom creator creates a div with three input fields so that user can alter the state of alpha, beta, charlie. I then use dojo on so that when the value changes on any of the fields to update the item's data state. For instance, function( item, hint ) { var node = domConstruct.create( 'div' ); var alphaVal = new TextBox( { name : 'filterBy', value : item.filterBy, placeHolder : 'type in a value', } ); domConstruct.place( alphaVal.domNode, node ); on( filterValue, 'change', function() { item.alphaVal = alphaVal.get( 'value' ); targetDnd.setItem( itemId , item); } ); return { 'node' : node, 'data' : item, 'type' : hint }; }; As you can see I am changing the data state that is backing that dnd item. My problem is that the dnd source is set to copyOnly so items still remain in the source when dragged onto the target. So when I change the underlying data state of the dnd item in the target it also changes the data state of the dnd item which is on the source. Hence any subsequent drags 'n' drops of the same item carries that state with it. How can I stop this from happening? Regards, G A: The only way I found so far is to use dojo/_base/lang to clone the item and then modify and return that. var clonedItem = lang.clone(item); on( inputTextBox, 'change', function() { // update clonedItem // target.setItem(itemId, clonedItem); }); return { "node" : node, "data" : clonedItem, "type" : hint }; I was wondering if there is a way to set the source to pass a clone of the data item rather than the reference of item.
Q: How can I validate two date fields against each other and current day? I am trying to validate an HTML form field: * *The start date must be before the end date *Both dates must be not in the past. Here is my form inputs: $(document).ready(function() { var dateIsBefore = false; var dateInPast = false; $('#end_date').on('keyup', function() { if ($('#start_date').val() < $('#end_date').val()) { dateIsBefore = true; } else { $('#message').html('Start date must not be after end date').css('color', 'red'); dateIsBefore = false; } }); $('#submitRequest').click(function(e) { if (!dateIsBefore) { e.preventDefault(); } }) }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <input class="form-control" id="start_date" name="start_date" placeholder="DD/MM/YYYY" required="required" /> <input class="form-control" id="end_date" name="end_date" placeholder="DD/MM/YYYY" required="required" /> <br/> <button type="submit" id="submitRequest" class="btn btn-primary">Submit Request</button> <span id='message'></span> I use type Date, so not sure if I need to replace / before comparing. Also I am not sure how I would be able to check if the dates are in the past. A: You can use momentjs library, this library is popular for handle date time. In your code, you need set $('#message').html(''); in case valid $(document).ready(function() { var dateIsBefore = false; var dateInPast = false; $('#end_date').on('keyup', function() { var start_date = moment($('#start_date').val(), "DD/MM/YYYY"); var end_date = moment($('#end_date').val(), "DD/MM/YYYY"); if ( start_date < end_date) { dateIsBefore = true; $('#message').html(''); } else { $('#message').html('Start date must not be after end date').css('color', 'red'); dateIsBefore = false; } }); $('#submitRequest').click(function(e) { if (!dateIsBefore) { e.preventDefault(); } }) }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <input class="form-control" id="start_date" name="start_date" placeholder="DD/MM/YYYY" required="required" /> <input class="form-control" id="end_date" name="end_date" placeholder="DD/MM/YYYY" required="required" /> <br/> <button type="submit" id="submitRequest" class="btn btn-primary">Submit Request</button> <span id='message'></span> A: You are trying to compare the input's values directly in your condition. These values are Strings and as string they get compared lexographical. To compare the values as Dates you have to simply create a new Date Object from the inputs value String and compare those: if(new Date($('#start_date').val()) > new Date($('#end_date').val())) { alert('End has to be after start'); } To take it a step further, you could reset the inputs value to null if the condition returns true, that way your input has no value, and since it has the required Attribute, the additional check in your submit gets redundant and can be deleted. if(new Date($('#start_date').val()) > new Date($('#end_date').val())) { alert('End has to be after start'); $(this).val(null); } Side note: I would rather use the change event instead of the keyup event, to validate your input. You have alot of unnessecary runs and probably even errors when you use the keyupevent and check before a valid date string is entered.
Q: How to use GAMs to test whether a prediction model is properly calibrated in R Suppose we wish to test whether there is an identity relationship between some observed values and the predicted values from some model, and allow for non-linear deviations from this hypothesis. This is a test for model calibration, or whether predicted values resemble the observed values. Thus we test $$H_0 : \text{model is calibrated}$$ against $$H_A : \text{model is not calibrated}.$$ I am using mgcv to conduct such a test; under the null hypothesis, the best-fitting model for the relationship between the observed and predicted data is the identity relationship (the line $\text{observed} = \text{predicted}$). If a fit other than the identity line better describes the relationship between observed and predicted values, we should reject the null hypothesis. This other relationship is allowed to be any (smooth) relationship, hence the use of generalized additive models. Thus, one should compare a GAM with an intercept and a smooth function of the predicted values to a "model" with a linear identity relationship, which can be done using something resembling ANOVA for GAMs. Below is R code demonstrating this idea. First is the data. # NECESSARY DATA -------------------------------------------------------------- # CONTINUOUS ------------------------------------------------------------------ func_train <- structure(list(t = c(0.0303030303030303, 0.0404040404040404, 0.0505050505050505, 0.0606060606060606, 0.0707070707070707, 0.0808080808080808, 0.121212121212121, 0.131313131313131, 0.151515151515152, 0.171717171717172, 0.181818181818182, 0.212121212121212, 0.222222222222222, 0.232323232323232, 0.242424242424242, 0.252525252525253, 0.272727272727273, 0.282828282828283, 0.292929292929293, 0.313131313131313, 0.323232323232323, 0.333333333333333, 0.343434343434343, 0.383838383838384, 0.414141414141414, 0.434343434343434, 0.444444444444444, 0.464646464646465, 0.474747474747475, 0.494949494949495, 0.525252525252525, 0.535353535353535, 0.585858585858586, 0.636363636363636, 0.656565656565657, 0.666666666666667, 0.686868686868687, 0.707070707070707, 0.737373737373737, 0.747474747474748, 0.757575757575758, 0.767676767676768, 0.787878787878788, 0.797979797979798, 0.808080808080808, 0.838383838383838, 0.858585858585859, 0.878787878787879, 0.939393939393939, 0.94949494949495, 0.95959595959596, 0.97979797979798), xt = c(3.63646184859767, 2.04366285020827, 2.40217293175171, 1.92764066195575, 2.09648921296279, 1.83178201173648, 2.59777911981743, 1.70198152297048, 3.1380721870924, 2.71868172485417, 3.38388214151374, 2.42085094978724, 2.56497719313567, 3.44671977084476, 2.39025018974132, 1.48377974658384, 3.18324259582037, 2.67374271529648, 2.43479989087673, 2.94967229684157, 3.72188635380589, 1.96556247970551, 2.51248175746488, 2.30538233637176, 2.53759710325252, 0.929349103723103, 1.06886278854257, 1.61838423274164, 0.671269406607747, 1.43763814664885, 1.9223411940236, 1.3614459122771, 1.38318561351847, 1.69640947189312, 1.5065339734596, 1.98566063977038, 0.666709569418715, 0.98379114909344, 1.57865628080262, 2.07604740761617, 2.24889414005422, 3.55793900242699, 2.42813714143812, 3.47050731227238, 2.09330094819542, 2.88930885347281, 4.12094951149849, 3.3426038340013, 3.89767608248133, 4.04384524659107, 4.39797282760465, 3.95885899856536)), row.names = c(4L, 5L, 6L, 7L, 8L, 9L, 13L, 14L, 16L, 18L, 19L, 22L, 23L, 24L, 25L, 26L, 28L, 29L, 30L, 32L, 33L, 34L, 35L, 39L, 42L, 44L, 45L, 47L, 48L, 50L, 53L, 54L, 59L, 64L, 66L, 67L, 69L, 71L, 74L, 75L, 76L, 77L, 79L, 80L, 81L, 84L, 86L, 88L, 94L, 95L, 96L, 98L), class = "data.frame") # BINARY ---------------------------------------------------------------------- inv_logit <- \(z) exp(z)/(1 + exp(z)) new_t <- seq(-2, 2, length = 100) train_bin_t <- tibble(t = new_t, pass = inv_logit(new_t ^ 2 - 2) %>% map_int(~ rbinom(1, size = 1, prob = .x))) test_bin_t <- tibble(t = new_t, pass = inv_logit(new_t ^ 2 - 2) %>% map_int(~ rbinom(1, size = 1, prob = .x))) Next, the procedure: library(mgcv) library(ggplot2) library(patchwork) func_gam_cont_overfit <- gam(xt ~ s(t), data = func_train, family = gaussian, sp = 1e-4) func_gam_bin <- gam(pass ~ s(t), data = train_bin_t, family = binomial) calib_fit <- function(observed, predicted, ...) { calib_df <- tibble(observed = observed, predicted = predicted) calib_gam <- gam(observed ~ offset(predicted) + s(predicted, m = c(2, 0)), data = calib_df, ...) null_fit <- gam(observed ~ offset(predicted) - a, data = calib_df, ...) make_fit_df <- function(d) { pred <- seq(min(d$predicted), max(d$predicted), length = 100) tibble(predicted = pred) %>% cbind(as_tibble(predict(calib_gam, ., type = "response", se.fit = TRUE))) %>% rename(observed = fit)} list(calib_gam = calib_gam, null_fit = null_fit, calib_viz = ggplot(calib_df, aes(x = predicted, y = observed)) + geom_point() + geom_line(data = make_fit_df, aes(x = predicted, y = observed), color = "red") + geom_ribbon(data = make_fit_df, aes(x = predicted, ymin = observed - 2 * se.fit, ymax = observed + 2 * se.fit), fill = "pink", alpha = 0.5) + geom_abline(slope = 1, intercept = 0, color = "blue")) } # INITIAL CALIBRATION FIT AND PLOTS ------------------------------------------- axis_lim <- c(0.5, 5) is_cont_obs_calib <- calib_fit(func_train$xt, predict(func_gam_cont_overfit, func_train["t"], type = "response")) is_cont_obs_calib_plot <- is_cont_obs_calib$calib_viz + coord_cartesian(axis_lim, axis_lim) + theme_bw() + ggtitle("Continuous") is_bin_obs_calib <- calib_fit(train_bin_t$pass, predict(func_gam_bin, test_bin_t["t"], type = "response"), family = binomial) is_bin_obs_calib_plot <- is_bin_obs_calib$calib_viz + coord_cartesian(0:1, 0:1) + theme_bw() + ggtitle("Binary") is_cont_obs_calib_plot | is_bin_obs_calib_plot # TESTS FOR CALIBRATION ------------------------------------------------------- summary(is_cont_obs_calib$calib_gam) # Note p-value for intercept and smooth summary(is_bin_obs_calib$calib_gam) with(is_cont_obs_calib, anova(calib_gam, null_fit, test = "Chisq")) # Note p-value with(is_bin_obs_calib, anova(calib_gam, null_fit, test = "Chisq")) Output is below. Family: gaussian Link function: identity Formula: observed ~ offset(predicted) + s(predicted, m = c(2, 0)) Parametric coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 2.990e-14 7.691e-02 0 1 Approximate significance of smooth terms: edf Ref.df F p-value s(predicted) 2.648e-10 8 0 0.957 R-sq.(adj) = 0.655 Deviance explained = 5.66e-11% GCV = 0.31364 Scale est. = 0.30761 n = 52 Family: binomial Link function: logit Formula: observed ~ offset(predicted) + s(predicted, m = c(2, 0)) Parametric coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -0.8927 0.2375 -3.759 0.000171 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 Approximate significance of smooth terms: edf Ref.df Chi.sq p-value s(predicted) 1.522 8 15.28 4.44e-05 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 R-sq.(adj) = 0.28 Deviance explained = 16% UBRE = 0.086762 Scale est. = 1 n = 100 Analysis of Deviance Table Model 1: observed ~ offset(predicted) + s(predicted, m = c(2, 0)) Model 2: observed ~ offset(predicted) - a Resid. Df Resid. Dev Df Deviance Pr(>Chi) 1 51 15.688 2 51 15.688 -5.297e-10 -8.8871e-12 6.458e-09 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 Analysis of Deviance Table Model 1: observed ~ offset(predicted) + s(predicted, m = c(2, 0)) Model 2: observed ~ offset(predicted) - a Resid. Df Resid. Dev Df Deviance Pr(>Chi) 1 96.998 103.63 2 99.000 123.44 -2.0021 -19.808 5.013e-05 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 In particular, notice the result for the continuous case in the example. Why does the ANOVA test reject when neither the smooth nor the slope are anywhere near significant? I know these tests are allowed to disagree, but the difference here is so stark that I'm suspicious that I'm doing the ANOVA procedure wrong. Is using ANOVA this way allowed? A: I solved my own problem. Remove the null space requirements from the fit. As described in the documentation of mgcv (man, it's so good), p-value approximations are terrible with there being no null space. So in the function, change the computation of calib_gam. calib_gam <- gam(observed ~ s(predicted), data = calib_df, ...)
Q: Select from 2 tables (Kohana framework) I've got 2 tables with the same datastructure. Ex: table 1 (id, pay_amount, package, date) table 2 (id, pay_amount, package, date) How can I get with Kohana framework data from both tables and sum the results by days? also how can I substr a string and sum the rest of the string (which is a number? look at the package_credit_ row in the example). For example if I have this data: Table1: (1, 200, "package_credit_300", "12.12.12 12:02:34"), (2, 50, "package_credit_50", "12.12.12 15:17:02"), (2, 50, "package_credit_50", "13.12.12 16:12:12") Table2: (1, 50, "package_credit_50", "13.12.12 12:02:34"), (2, 50, "package_credit_50", "13.12.12 15:17:02"), (2, 200, "package_credit_300", "14.12.12 16:12:12") I want to get something liket that: Date: 12.12.12 - Credit: 350 - Paid: 250 Date: 13.12.12 - Credit: 150 - Paid: 150 Date: 14.12.12 - Credit: 300 - Paid: 200 A: This can not be done using ORM or ActiveRecord in Kohana. You need to execute this custom sql. SELECT Date(t.`date`) AS `Date`, Sum(Cast(Substring(t.`package`, 16) AS UNSIGNED)) AS `Credit`, Sum(t.pay_amount) AS `Paid` FROM (SELECT * FROM table1 UNION SELECT * FROM table2) AS `t` GROUP BY `Date` ORDER BY `Date` ASC A: try this SELECT Substring(t.`date`,1,8) AS dates, Sum(Cast(Substring(t.`package`, 16) AS UNSIGNED)) AS `Credit`, Sum(t.pay_amount) AS `Paid` FROM (SELECT * FROM table1 UNION SELECT * FROM table2) AS `t` GROUP BY dates ORDER BY dates ASC LOOK DEMO HERE
Q: og images not showing in linkedIn ím using webp for my images, but it seems that linkedin doesn't support this format for og images. Is there a way I can convert all images as once to png? (maybe via database)
Q: Generating Excel file from database using Blazor page so I just recently started working in Blazor. I have my page set-up and I have successfully connected it with a database, in which I am gonna store some data. Now I am trying to generate an Excel file from these data, but I really struggle to find any information on how to properly do it. For now I load all the data from database to list, when the page loads. The goal is to add a button that will generate .xlsx or .csv file from this list and fire a download. Any suggestions how to do it? All help is appreciated.
Q: Move SurfaceView across Activities I'm working on a video app where user can watch a video, open it il fullscreen if needed and come back to default view and so on. I was using ExoPlayer and recently switch to default MediaPlayer due to the upcoming explanation. I need to change "on the fly" the Surface of the player. I need to use the same player to display video among activities, with no delay to display the image. Using Exoplayer, the decoder wait for the next keyframe to draw pixels on the empty Surface. So I need to use the same Surface so I don't need to push a new surface each time, just attachign the surface to a View parent. The Surface can stay the same but if I detach the SurfaceView to retrieve it from another activity and reattach it, the inner Surface is destroyed. So is there a way to keep the same Surface across different activities ? With a Service ? I know the question is a bit weird to understand, I will explain specified part is request in comment. A: The Surface associated with a SurfaceView or TextureView will generally be destroyed when the Activity stops. It is possible to work around this behavior. One approach is built into TextureView, and is described in the architecture doc, and demonstrated in the "double decode" activity in Grafika. The goal of the activity is to continue playing a pair of videos while the activity restarts due to screen rotation, not pausing at all. If you follow the code you can see how the return value from onSurfaceTextureDestroyed() is used to keep the SurfaceTexture alive, and how TextureView#setSurfaceTexture() attaches the SurfaceTexture to the new View. There's a bit of a trick to it -- the setSurfaceTexture() needs to happen in onCreate(), not onSurfaceTextureAvailable() -- but it's reasonably straightforward. The example uses MediaCodec output for video playback, but it'll work equally well with anything that takes a Surface for output -- just create a Surface from the SurfaceTexture. If you don't mind getting ankle-deep into OpenGL ES, you can just create your own SurfaceTexture, independent of Views and Activities, and render it yourself to the current SurfaceView. Grafika's "texture from camera" activity does this with live video from the camera (though it doesn't try to preserve it across Activity restarts).
Q: HTML/CSS - How to autofit/scale multiple images onto 1 row I cut a flowchart drawn in Photoshop into various "parts" that I want to "reassemble" onto a webpage. All of the "parts" have the same height but different widths. To fully reassemble the flowchart, I'd need 4 rows and each row would have anywhere from 4 to 5 images. I would like the "flowchart" to automatically scale with the window size. How would I do about doing this in HTML/CSS? A: use this display:flex;flex-wrap:wrap; <div class="images-row"> <div><img src="" class="images"/></div> <div><img src="" class="images"/></div> <div><img src="" class="images"/></div> <div><img src="" class="images"/></div> <div><img src="" class="images"/></div> <div><img src="" class="images"/></div> <div><img src="" class="images"/></div> <div><img src="" class="images"/></div> </div> **style of CSS** .images-row{display:flex;flex-wrap:wrap;} .images-row div{width:17%;padding:5px;} .images{ width:100%; height:150px;background:#ccc;} A: You can use responsiveimages for them to scale with the windows size: width: 100%; max-width: 400px; height: auto;
Q: CouchDB db-per-user with shared data scalability I have an application with the following architecture: The master couchdb is required to share data between the users. EG: If user-1 writes data to the cloud, this replicates to the master and back to user-2 and user-3. However, as the user base increases so do the number of cloud user couchDBs, which results in a large number of replication links between the cloud user couchDBs and the master couchDB. I believe this can lead to a huge bottleneck. Is there a better way to approach this problem? A: You're right: the db-per-user pattern for CouchDB can run into scalability issues. This is to do with the fact that the CouchDB replicator will struggle to service the number of simultaneous replication jobs it is asked to handle. If you know that your user numbers will grow over time it's worth considering architectures that multiplex many users' data into a single (or a handful) database. This makes authentication and replication trickier, as CouchDB authenticates per database only, and you may end up with another layer in between to resolve this. One approach is to use a replication proxy such as Cloudant Envoy, which lets your PouchDB applications remain unchanged — the model on the client side is still "db-per-user", but the actual writes go to a single DB server side. This also means that you may be able to avoid the server side replication into a single master DB as you already have that in the main Envoy DB. Disclaimer: I'm one of the authors of Envoy.
Q: Absolute imports issue in react with typescript I've been wandering through posts and posts about this and haven't been able to fix it. They all state pretty much the same: take notice of tsconfig.json's nesting, correctly set the baseUrl and explicitely mention filenames if were using index files. But I can't get my path aliases to work. As I'm refactoring this project, this is getting necessary as the previous developer's dot-dot-dash hell is driving me crazy. An excerpt from my project's structure: . +-- tsconfig.js +-- package.json +-- src | +-- ui | | +-- hooks | | | +-- useProfessionalOnboarding | | | | +-- index.tsx | | +-- components | | | +-- professional | | | | +-- onboarding | | | | | +-- availability | | | | | | +-- ProOboardingServicesAvailability.tsx | | +-- pages | | | +-- ProfessionalOnBoarding | | | | +-- ... | | +-- types | | | +-- ... | +-- index.tsx | +-- App.tsx Now in ProOboardingServicesAvailability.tsx I'm trying to import the useProfessionalOnboarding hook as import useProfessionalOnboarding from '@hooks/useProfessionalOnboarding/index'; My tsconfig.json being { "compilerOptions": { "baseUrl": "src", "paths": { "@hooks/*": [ "ui/hooks*" ], }, "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": [ "src" ] } However I keep getting "Cannot find module or its correspondent type declarations". I tried some other paths mappings as "@hooks/*": [ "./ui/hooks*" ], "@hooks/*": [ "src/ui/hooks*" ] "@hooks/*": [ "./src/ui/hooks*" ], none worked. Tried with and without the at-symbol, no difference. There's a ton of work ahead and a small hideous chance of having to do the ant work of going through each file re-counting the '../'s. I crave for help. At least some way of tweaking or debugging. btw I'm using Atom for text editor. Thanks! A: I noticed that a message flashed between the run startup and the compiling step. I says compilerOptions.paths must not be set (aliased imports are not supported)! It was flashing fast and I had to take a screen capture to read it. Looking up, I found this comment which states create-react-app doesn't support path aliasing and probably won't for the near future. I'll settle with baseUrl
Q: using .each to execute array of functions on .resize In the an object called Response this works to trigger a function on .ready and .resize simultaneously... Response.action = function ( func ) { if ( typeof func !== 'function' ) { return false; } // If func is not a function, return false. $(function () { func(); $(window).resize( func ); }); // return func; }; // Response.action ...using this to call it: Response.action( myfunc ); function myfunc() { //do stuff } (We worked that out in this thread.) I'd like to make another version that can do the same thing for an array of functions, with usage like this: Response.actionSet( [myfunc1, myfunc2] ); function myfunc1() { //do stuff } function myfunc2() { //do stuff } I tried it as below and every other incantation I could imagine, but I haven't got it to work. No error messages either. Can anyone recommend how to get this working: Response.actionSet = function ( arr ) { if ( arr.isArray !== true ) { return false; } // If arr is not an array, return false. $.each(arr, Response.action(this)); // iterate over arr array return arr; }; // Response.actionSet A: You have a small error; it should be $.each(arr, function() { Response.action(this); }); Response.actionSet = function(arr) { if(!$.isArray(arr)) return false; $.each(arr, function() { Response.action(this); }); return arr; };
Q: Increase the sizes of Unicode Character 'BULLET OPERATOR' (U+2219) I am trying to increase the sizes of the bullet operator using font-sizebut it turned out that it is becoming square-ish instead of circle. Can anyone suggest: * *Why is it happened? Is it possible to increase the sizes of unicode character while maintaining the shape? I replicate the problem with the following snippets: .first { width:30%; min-height: 40px; background-color: grey; text-align: center; } .first:after { content: "\2219"; font-size:70px; } <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery.min.js"></script> <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" /> <script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="first"> <p>This is test</p> </div> </div> </div> </div> </body> </html> A: The character you may be looking for is .first::after { content: "\2022"; } Look in the hex column, this looks like a useful reference site. http://www.ascii.cl/htmlcodes.htm A: the type of font can also affect this character..to illustrate ,I use monospace font and got a rounded circle snippet here .first { width:30%; min-height: 40px; background-color: grey; text-align: center; } .first:after { font-family:monospace; content: "\2219"; font-size:70px; border-radius:5px; } <script src="https://code.jquery.com/jquery.min.js"></script> <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" /> <script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="first"> <p>This is test</p> </div> </div> </div> </div> </body> </html>
Q: Get the value of 'specific Times' array (IIS) from powershell I am trying to retrieve the specific times values from IIS. But I get back some sort of reference to a configuration element. This is for a Microsoft Internet Information Services (version 10.0.14393.0). I tried $itemsInIis = Get-ItemProperty -Path IIS:\AppPools\DefaultAppPool -Name recycling.periodicRestart.schedule.collection Write-Host "Times present in IIS: [$itemsInIis]." I get back Microsoft.IIs.PowerShell.Framework.ConfigurationElement instead of the actual values. How Should I do this to retrieve the times such as 00:00:00 NOt sure what I am missing here to retrieve the actual times inside the array. A: You are getting back an array of ConfigurationElements, each of which has value of type TimeSpan. Try something like this: $itemsInIis = (Get-ItemProperty -Path IIS:\AppPools\DefaultAppPool -Name recycling.periodicRestart.schedule.collection).value -F 'hhmmsss' Write-Host "Times present in IIS: [$itemsInIis]."
Q: How to add custom, but not-required, method to jQuery Validation plugin? I am adding in a custom method for the jQuery Validation plugin to check for a valid phone number. However, I want this field to be optional, and not required. For some reason, when I add the following code in, it is making fields with the class "phone" required too. Any ideas what I'm doing wrong? $.validator.addMethod("phone", function(ph, element) { var stripped = ph.replace(/[\s()+-]|ext\.?/gi, ""); // 10 is the minimum number of numbers required return ((/\d{10,}/i).test(stripped)); }); $('#custom').validate({ errorPlacement: function(error, element) { return true; } }); <input type="text" class="phone" name="phone_1" id="phone_1"> A: You'll want to update your method so it returns true if the phone field is empty. Something like: $.validator.addMethod("phone", function(ph, element) { if(ph=='') return true; var stripped = ph.replace(/[\s()+-]|ext\.?/gi, ""); // 10 is the minimum number of numbers required return ((/\d{10,}/i).test(stripped)); }); It's going to run the method on all of the phone fields, so this way you allow them to pass on untested unless they actually contain content.
Q: How I can check whether 2 databases despite being in different postgresql servers of versions are the same? I copied an existing posttgresql database from one server to another. The source of my data is a postgresql 9.6 whilst the newer server is in postgresql 11. So I want to know how I can check that both databases have the same schema and data in a fast and easy way? A: You cannot do that in a fast way. The best you can do is to dump both databases using pg_dump from v11 and compare the files with diff. If you want to do that just to ensure that the migration was successful, don't. If you don't trust PostgreSQL's upgrade process, why should you trust pg_dump?
Q: GridLayout (Support Version) - Android 2.3.3 I am developing for Android 2.3.3 and attempting to use the support GridLayout. After SetContentView is run on onCreate in a class I am using, my app crashes. I have the following GridLayout in a view: <android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/chaptergrid" android:layout_width="match_parent" android:layout_height="match_parent" app:columnCount="4"> </android.support.v7.widget.GridLayout> And I get the following in the Log Cat: 01-04 08:43:05.648: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed 55K, 53% free 2566K/5379K, external 716K/1038K, paused 56ms 01-04 08:43:05.708: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed 1K, 53% free 2565K/5379K, external 1382K/1894K, paused 26ms 01-04 08:43:05.768: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed <1K, 53% free 2565K/5379K, external 1902K/2568K, paused 27ms 01-04 08:43:05.848: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed <1K, 53% free 2565K/5379K, external 2944K/3677K, paused 36ms 01-04 08:43:05.937: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed <1K, 53% free 2566K/5379K, external 4160K/4795K, paused 25ms 01-04 08:43:05.987: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed <1K, 53% free 2566K/5379K, external 4883K/5590K, paused 25ms 01-04 08:43:06.107: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed 1K, 53% free 2567K/5379K, external 6330K/6493K, paused 33ms 01-04 08:43:06.207: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed 1K, 53% free 2568K/5379K, external 7776K/8299K, paused 32ms 01-04 08:43:36.217: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed 14K, 52% free 2595K/5379K, external 2163K/2886K, paused 24ms 01-04 08:43:36.277: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed 1K, 52% free 2594K/5379K, external 2481K/3205K, paused 24ms 01-04 08:43:36.347: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed <1K, 52% free 2595K/5379K, external 3697K/4332K, paused 23ms 01-04 08:43:36.777: D/dalvikvm(346): GC_CONCURRENT freed 189K, 48% free 3036K/5831K, external 4181K/5012K, paused 4ms+4ms 01-04 08:43:36.998: D/szipinf(346): Initializing inflate state 01-04 08:43:38.547: I/dalvikvm(346): Jit: resizing JitTable from 512 to 1024 01-04 08:43:38.598: W/dalvikvm(346): VFY: unable to resolve static field 1174 (default_gap) in Landroid/support/v7/gridlayout/R$dimen; 01-04 08:43:38.598: D/dalvikvm(346): VFY: replacing opcode 0x60 at 0x0024 01-04 08:43:38.598: D/dalvikvm(346): VFY: dead code 0x0026-007b in Landroid/support/v7/widget/GridLayout;.<init> (Landroid/content/Context;Landroid/util/AttributeSet;I)V 01-04 08:43:38.618: I/dalvikvm(346): Could not find method android.support.v4.view.ViewCompat.resolveSizeAndState, referenced from method android.support.v7.widget.GridLayout.onMeasure 01-04 08:43:38.618: W/dalvikvm(346): VFY: unable to resolve static method 2483: Landroid/support/v4/view/ViewCompat;.resolveSizeAndState (III)I 01-04 08:43:38.618: D/dalvikvm(346): VFY: replacing opcode 0x71 at 0x0050 01-04 08:43:38.618: D/dalvikvm(346): VFY: dead code 0x0053-005b in Landroid/support/v7/widget/GridLayout;.onMeasure (II)V 01-04 08:43:38.618: D/AndroidRuntime(346): Shutting down VM 01-04 08:43:38.618: W/dalvikvm(346): threadid=1: thread exiting with uncaught exception (group=0x40015560) 01-04 08:43:38.627: E/AndroidRuntime(346): FATAL EXCEPTION: main 01-04 08:43:38.627: E/AndroidRuntime(346): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.turbo/com.example.turbo.Chapter}: android.view.InflateException: Binary XML file line #28: Error inflating class android.support.v7.widget.GridLayout 01-04 08:43:38.627: E/AndroidRuntime(346): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.os.Handler.dispatchMessage(Handler.java:99) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.os.Looper.loop(Looper.java:123) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.app.ActivityThread.main(ActivityThread.java:3683) 01-04 08:43:38.627: E/AndroidRuntime(346): at java.lang.reflect.Method.invokeNative(Native Method) 01-04 08:43:38.627: E/AndroidRuntime(346): at java.lang.reflect.Method.invoke(Method.java:507) 01-04 08:43:38.627: E/AndroidRuntime(346): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 01-04 08:43:38.627: E/AndroidRuntime(346): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 01-04 08:43:38.627: E/AndroidRuntime(346): at dalvik.system.NativeStart.main(Native Method) 01-04 08:43:38.627: E/AndroidRuntime(346): Caused by: android.view.InflateException: Binary XML file line #28: Error inflating class android.support.v7.widget.GridLayout 01-04 08:43:38.627: E/AndroidRuntime(346): at android.view.LayoutInflater.createView(LayoutInflater.java:518) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.view.LayoutInflater.inflate(LayoutInflater.java:408) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 01-04 08:43:38.627: E/AndroidRuntime(346): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.app.Activity.setContentView(Activity.java:1657) 01-04 08:43:38.627: E/AndroidRuntime(346): at com.example.turbo.Chapter.onCreate(Chapter.java:21) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 01-04 08:43:38.627: E/AndroidRuntime(346): ... 11 more 01-04 08:43:38.627: E/AndroidRuntime(346): Caused by: java.lang.reflect.InvocationTargetException 01-04 08:43:38.627: E/AndroidRuntime(346): at java.lang.reflect.Constructor.constructNative(Native Method) 01-04 08:43:38.627: E/AndroidRuntime(346): at java.lang.reflect.Constructor.newInstance(Constructor.java:415) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.view.LayoutInflater.createView(LayoutInflater.java:505) 01-04 08:43:38.627: E/AndroidRuntime(346): ... 21 more 01-04 08:43:38.627: E/AndroidRuntime(346): Caused by: java.lang.NoClassDefFoundError: android.support.v7.gridlayout.R$dimen 01-04 08:43:38.627: E/AndroidRuntime(346): at android.support.v7.widget.GridLayout.<init>(GridLayout.java:270) 01-04 08:43:38.627: E/AndroidRuntime(346): at android.support.v7.widget.GridLayout.<init>(GridLayout.java:289) 01-04 08:43:38.627: E/AndroidRuntime(346): ... 24 more
Q: how to override react-bootstrap with custom css file I use react-bootstrap, but I want to modify some of the elements, so I wrote my own custom.css. However it doesn't make any changes (only when I put !important, but the file is so large so it's not a good option). import {MenuItem, Nav, Navbar, NavBrand, NavDropdown, NavItem} from "react-bootstrap"; import {LinkContainer, MenuItemLink} from "react-router-bootstrap"; import '../assets/css/custom.css'; This is what I did so far. A: When are you importing the Bootstrap CSS? I have an app which successfully uses Bootstrap with some overrides, which does this at the top of its index.js: require('bootstrap/dist/css/bootstrap.min.css') require('./bootstrap-overrides.css')
Q: Localizing iPhone App I'm using xCode 4.3.2, For my new iPhone project, I've added strings files for Arabic and English, which work well with iPhone language change. But i need to load/change the App language with UIButton click. Is it possible? A: How to change iPhone app language during runtime? This may help you.
Q: SBT how to create custom command Given I have build.sbt name := """app""" version := "1.0-SNAPSHOT" lazy val root = (project in file(".")).enablePlugins(PlayScala) scalaVersion := "2.11.7" // <-- some other code --> import Fixtures._ lazy val fixtures = inputKey[Unit]("Generating Cassandra fixtures") fixtures := { Fixtures.generate() } and Fixtures.scala in project directory object Fixtures { def generate (): Unit = { println("generating fixtures") } } I am able to run command ./activator fixtures and I am getting "generating fixtures" But how can I call some service, let say GenerateUserFixtureService.scala but from app/scala/com/MyProject/Service directory. Import package does not work, because project directory belongs to different package. I am not able to import anything to Fixtures.scala from Play | |___app | |__scala | |__com | |__MyProject | |__Service | |--GenerateUserFixtureService.scala |___project | |--Fixtures.scala |___ |--build.sbt Actually the question is, why I am able to import to build.sbt only files from project directory. Or how can I call another files from app dir? Or maybe the way I am thinking is completely wrong. I just want to create some command upload:fixtures send:emails etc, and call some scala class. How can I achieve this? A: For creating a custom command you must specify a function which corresponds to the logic of your command. Let's consider a few examples: first just print hello message: def helloSbt = Command.command("hello") { state => println("Hello, SBT") state } commands += helloSbt just put this code into build.sbt, commands is project key which is present into sbt.Keys as val commands = SettingKey[Seq[Command]] Of course, you can manage the statement of your command like success or fail: def failJustForFun = Command.single("fail-condidtion") { case (state, "true") => state.fail case (state, _) => state } You can change the color in console for specific part of your command or output of this command via leveraging of DefaultParsers: lazy val color = token( Space ~> ("blue" ^^^ "4" | "green" ^^^ "2") ) lazy val select = token( "fg" ^^^ "3" | "bg" ^^^ "4" ) lazy val setColor = (select ~ color) map { case (g, c) => "\033[" + g + c + "m" } And like alternative, you can extend xsbti.AppMain and implement - your own logic
Q: How do I test that there's a main effect and no interaction with one contrast? Suppose there's a treatment applied to a cell culture to see if there's an effect on gene expression. The measurements are performed at two time points: 10 and 20 days after treatment. For the sake of simplicity, suppose that I work with the following model: $$ log y_{s, g} = \beta_{0} + \beta_{t}x_{t} + \beta_{20d}x_{20d} + \beta_{int}x_{t}x_{20d} $$ where $x_{t}$ is 0 for control and 1 for treatment and $x_{20d}$ is 0 for 10 days after treatment and 1 for 20 days. $s$ and $g$ are sample and gene index, respectively. I want to select all genes where effect of treatment is the same between two time points. I can do it like so: * *Use the full model and select genes where $\beta_{int}$ is not significant *For those genes I use the simpler model $log y_{s, g} = \beta_{0} + \beta_{t}x_{t}$ to select genes for which treatment $\beta_{t}$. However, is there a way to write a single contrast that I can use to select genes with stable treatment effect over time and avoid doing multiple tests for a gene? Thanks! A: There are some misconceptions here. If you want to select genes where the effect is the same, then your step * *Use the full model and select genes where $\beta_{int}$ is not significant is not that. A non-significant test does not mean that the effect is the same. For example, consider a case where there is a difference but you have very little data and thus not enough power to detect it: the test will be not significant but there still is a difference. Perhaps a better question to ask is whether the difference in gene expression after the 10th and the 20th day is significantly affected by treatment? To this end you could compute a new variable, which for each gene is the difference between the effect on the 10th and 20th day, i.e. $$ y_{new} = y_{10d} - y_{20d}$$, and then check whether there is a significant effect of treatment: $$ y_{new} = \beta_0 + \beta_t x_t + \epsilon$$,
Q: ENTER_FRAME Event not working correctly with MouseEvent As3 I know I am missing something very simple but I just can't seem to figure it out. So I have my buttons that control a log on the stage like so: //buttons for main screen left and right mainScreen.leftBtn.addEventListener(MouseEvent.CLICK, leftButtonClicked); mainScreen.rightBtn.addEventListener(MouseEvent.CLICK, rightButtonClicked); private function leftButtonClicked(e:MouseEvent):void { if (e.type == MouseEvent.CLICK) { clickLeft = true; trace("LEFT_TRUE"); } } private function rightButtonClicked(e:MouseEvent):void { if (e.type == MouseEvent.CLICK) { clickRight = true; trace("RIGHT_TRUE"); } } Now these control the logs rotation that I have setup in an ENTER_FRAME event listener function called logControls(); like so: private function logControls():void { if (clickRight) { log.rotation += 20; }else if (clickLeft) { log.rotation -= 20; } } What I want to do is when the user presses left or right the log rotates each frame left or right. But what is happening is it only rotates one way and doesnt respond to the other mouse events. What could I be doing wrong? A: Likely you just need to set opposite var to false when you set a rotation. So if you're rotating left, you want to set the clickRight var to false. mainScreen.leftBtn.addEventListener(MouseEvent.CLICK, rotationBtnClicked); mainScreen.rightBtn.addEventListener(MouseEvent.CLICK, rotationBtnClicked); private function rotationBtnClicked(e:MouseEvent):void { clickLeft = e.currentTarget == mainScreen.leftBtn; //if it was left button clicked, this will true, otherwise false clickRight = e.currentTarge == mainScreen.rightBtn; //if it wasn't right button, this will now be false } private function logControls():void { if (clickRight){ log.rotation += 20; } if (clickLeft){ log.rotation -= 20; } }
Q: How to update the style of an element on state change I have a button that changes state when clicked. I would like a style (resultInfo) to show up on another element when the button state is false. I tried to use useEffect [checkAnswer] to update the other element's inline style, but upon the button's state change, the other element's style is not updated. How come the following doesn't work? Thanks. // the Continue button that also shows the user if they are correct or wrong import React, { useEffect, useContext, useState } from 'react'; import { PracticeContext } from '../contexts/PracticeContext'; import ModuleFinished from './ModuleFinished'; // Enables the user to check their answer, shows the result, and provides an element to proceed to the next question const ModulePracticeAnswerResult = ( {questionNumber, answer, attempt} ) => { const { setShowModuleFinished } = useContext(PracticeContext); const { questionIndex, setQuestionIndex } = useContext(PracticeContext); const { selectedPracticeEnd } = useContext(PracticeContext); const [checkAnswer, setCheckAnswer] = useState(false); // create the user selected module for practice useEffect(() => { setCheckAnswer(false); // answer state is reverted when question state is updated }, [questionIndex]); // navigate to the next question function progress(e) { e.preventDefault(); if (checkAnswer === false) { setCheckAnswer(true); return; } if (selectedPracticeEnd === true) { // there are no more questions - don't progress any further if (checkAnswer) { setShowModuleFinished(true); } return; } // if checkAnswer is true, user has already answers and received feedback. progress to next question setQuestionIndex(questionNumber + 1); } let resultInfo = { display: 'none' }; useEffect(() => { // when check answer button has been pressed, its state changes to false until the continue button is pressed if (checkAnswer === false) { // display the result of the answer if (answer === attempt) { resultInfo = { display: 'block', background: '#4CAF50' } } else { resultInfo = { display: 'block', background: 'rgb(255, 52, 86)' } } return; } resultInfo = { display: 'none' }; // user hasn't checked the answer yet }, [checkAnswer]); return ( <div className="module-practice-answer-result"> <div className="result-info-container"> <div style={resultInfo}> <p>{ 'result message here...' }</p> </div> <button className={ checkAnswer === false ? 'answer-button answer-button-default' : 'answer-button answer-button-continue' } onClick={progress} disabled={attempt.length < 1 ? 'disabled' : ''}> { checkAnswer === false ? 'Check' : 'Continue' } </button> </div> <ModuleFinished /> </div> ); } export default ModulePracticeAnswerResult;
Q: SQL developer refine connections view I searched about this on google and so, but could not find a solution: I am working on Oracle SQL developer using multiple schemas and database connections. Lets say i have connection 1 which has schema 1 and table 1. Then i have connection 2, which has schema 2 and table 2, and so on... Every now and then i have to lookup information in table 1 then table2, .... and so on... which means a lot of navigation, scrolling etc. on my small laptop screen. it would make the life much easier if there was a way to hide the unwanted schema objects. For example, i only need to work with tables, don't need views, procedures, Indexes, Triggers etc. to be visible (on the left hand menu-> under connections) - that will reduce the scrolling a lot and hopefully i would be able to see tables under connection 1 and tables under connection 2 in single view(without scrolling). Is there a way to remove these unwanted objects from the view? Sorry if this sounds like a dumb question, but i am not SQL-developer-savvy, so any help is greatly appreciated. thanks! A: Open the Preferences dialog Go to the Database page find, navigation filtering enable the feature on the right bottom, then uncheck what you don't want to browse A: When You have connections to different systems, eg. DEV, TEST, INTEGRATION, PRODUCTION it may additionally be helpful to organize each of these target systems into different folders. Just context-click (for me it's a left click, as my mouse is lefthanded) to the connection, then choose ADD TO FOLDER. As I guess you will have the same schemata in all those connections, this help you to avoid to connection to the wrong system by accident. A: Maybe another alternative method to work with, is to use the "Schema_Browser" in SQL-Developer. It opens a separate Tab for each connection, where you can select just the objects from the connected schema. Instead of scrolling between different schemas, it means, working only within the Tab of each connection. To open it, just go to "Connections", and right-click on the wanted schema. Then select "Schema Browser". You will see just one kind of objects. Since "Tables" are already the default object, it might be a good alternative for you.
Q: iOS: Button to access next Tableview cell I have a main view controller which is a tableview, after selecting a cell from the table view, another view is displayed. How can I create buttons to access and display the next and previous cell's view? I have the toolbar and buttons set, I just need help with the code to access and push the next view. A: If you pass the data for the tableView (presumably an array containing info for the cells) to your detailViewController, then you can navigate through the items that way. When you select a row, send the indexPath.row to the detailViewController as a property, e.g. int selectedRow. Then wire up two buttons, one that decrements this parameter and another that increments it. A: You are just looking at basic NavigationController and TableViewcontroller properties. If you want to navigate between two views then you need a Navigation Controller, and for choosing cells you need to work with the tableView. You just need to go to the didSelectRowAtIndexPath method of your table view controller, and after selecting a row, you need to push your view controller to your next view [self.navigationController pushViewController: nextController animated:YES];. This will take control to your nextView, and you will have a back button which will bring you back to the previous view. If you want to pass data between the views, you will need to * *Set them as properties and reference the classes to access them. *Use NSUserDefaults.
Q: Continuous bijection between open simply connected subsets of $\mathbb{C}$ Suppose $U,V \subseteq \mathbb{C}$ are open sets. I did a proof saying if $U$ and $V$ were conformally equivalent then $U$ simply connected implies $V$ is as well. I did this by showing the conformal map between the two was a homeomorphism. However, the problem has a side note saying that it would have been enough to have a continuous bijection rather than holomorphic bijection between the two sets. I don't see why this is the case. Can someone explain why this was enough as I used the holomorphicity in my proof? A: You can use the invariance of domain http://en.wikipedia.org/wiki/Invariance_of_domain to show that the continuous bijection is a homeo into the image, so that the image is simply-connected.
Q: Ruby - How to take two arrays of strings and return an array with all of the combinations of the items in them, listing the first items first My goal is to go from this: first = ["on","in"] second = ["to","set"] to this: ["onto", "onset", "into", "inset"] I want to achieve this using a method, so far this is the closest I can get: def combinations(array_one,array_two) results = [] array_one.each do |x| array_two.each do |y| results << ["#{x}#{y}"] end end results end This returns: [["onto"], ["onset"], ["into"], ["inset"]] Is there a better way to do this? A: This should work: def combinations(first, second) first.product(second).map(&:join) end combinations(%w(on in), %w(to set)) # => ["onto", "onset", "into", "inset"] A: Have you tried Array#product? first = ["on","in"] second = ["to","set"] first.product(second).map(&:join) #=> ["onto", "onset", "into", "inset"]
Q: Reassigning the value of variables in Ruby? I'm trying to write a program to use the Babylonian Method for square roots, and this requires reassigning the values of variables radicand=gets.to_f A=rand(1..radicand) B = A+1 while B != A C = radicand/A B = A A = (A+C)/2 end print"The square root of #{radicand} is #{A}" When I run this, I'll get an answer among an insane number of error messages. The answer is always correct, so why does this code cause so many problems? Console with error messages A: Try something like this where you use lower case variable names rather than upper case constant names: def square_root(radicand) a, b = radicand, 1 tolerance = 0.00000000000000000001 while (a - b).abs > tolerance a = (a + b) / 2 b = radicand / a end a end print "Enter the radicand:" radicand = gets.to_f puts "The square root of #{radicand} is #{square_root(radicand)}" Example Usage: Enter the radicand: 256 The square root of 256.0 is 16.0
Q: Why $\operatorname{dim}X < \infty$ in the proof of the Gortz's Algebraic Geometry. Theorem 14.114? I'm reading the Gortz's Algebraic Geometry, Theorme 14.114 and some question arises. : Why the underlined statement is true? In our situation, is there an irreducible component $X_0$ of $X$ such that $$\operatorname{dim}(f|_{X_0}^{-1}(\eta)) = \operatorname{dim}(f^{-1}(\eta) \cap X_0) = \operatorname{dim}_{\theta_0}f^{-1}(\eta) < \infty $$ ? ($\theta_0$ is the generic point of the $X_0$) If so, how to prove.. A: Let's assume that $X$ equidimensional means that all irreducible components of $X$ have finite dimension $d$ (Görtz is not entirely clear in his definition on page 120, but otherwise the statement $\dim X < \infty$ clearly false). Then any chain of irreducible subsets $$X_0 \supsetneq X_1 \supsetneq \dots \supsetneq X_k$$ is contained in one irreducible component $X'$ (which contains $X_0$). Hence $k \leq \dim X' = d$, so $\dim X = d$. Tbh that proof is quite confusing, because in the equation above he already writes $\dim X' = \dim X$... Also I think he confused $X$ and $Y$ i the statement of the theorem, it should be $$\dim Y + \dim f^{-1}(y) = \dim X.$$ This is corrected in the second edition from 2020, see the errata.
Q: How can I animate Label.Content with a DoubleAnimation? A DoubleAnimation changes a double value over time. I would like to set the Content property of a Label to this value. However, this fails because WPF does not convert the double to a string. Do I have to subclass the Label and add a new double propery, which is bound to the Content, and let the DoubleAnimation change this new property? Or is there an easier way? The double value in question is not limited to certain values, i.e. fixed StringKeyframes cannot be used. Example use case: A countdown timer with extended precision, which displays the remaining time in a Label. A: Set the Label ContentStringFormat="{}{0}", or use a TextBox and set StringFormat in the Text binding.
Q: usb not detected it's my first post and I am new to ubuntu. My pc is an Hp pavilion x2 and I am trying to build a live Kubuntu 20.04 and a complete install on usb, before deciding to install it on computer. I used Sandisk Flair, Transcend and Samsung usb and sd cards. What happens is that sd cards work (a live with persistence working and booting perfectly and a full install very slow and freezing at times), while usb are not detected at all by computer bios (I changed boot order of course). Is there a reason I cannot understand? Thank you
Q: unexpected 'public' (T_PUBLIC) I had a helper class conflict with two of my modules. I have resolved this issue by doing following: if (Mage::helper('core')->isModuleEnabled('Amasty_Methods')) { class Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp extends Amasty_Methods_Helper_Payment_Data {} } else { class Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp extends Mage_Payment_Helper_Data {} } class Ebizmarts_SagePaySuite_Helper_Payment_Data extends Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp { } /** * Retrieve all payment methods * * @param mixed $store * @return array */ public function getPaymentMethods($store = null) { $_methods = parent::getPaymentMethods($store); if (isset($_methods['sagepaysuite'])) { unset($_methods['sagepaysuite']); } return $_methods; } } Now, I get the error: Parse error: syntax error, unexpected 'public' (T_PUBLIC) in /domains/dev.domain.co.uk/http/app/code/local/Ebizmarts/SagePaySuite/Helper/Payment/Data.php on line 26 Do I just delete the public from my function? Also what are the consequences of doing so? A: There is one } to much ... replace class Ebizmarts_SagePaySuite_Helper_Payment_Data extends Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp { } with class Ebizmarts_SagePaySuite_Helper_Payment_Data extends Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp { A: I had the closing curly bracket after class Ebizmarts_SagePaySuite_Helper_Payment_Data extends Ebizmarts_SagePaySuite_Helper_Payment_Data_Temp { } Deleting the } solved my issue. Now, it works fine with the Public declarations in the function. Sorry to bother you all.
Q: Google Analytics Event Tracking - How to track an auto-popup We have a popup that appears after a certain number of pageviews on our site and I would like to track this as an event. I currently have <script> ga('send', { 'hitType': 'pageview', 'page': '/signupPopup' }); </script> In my popup but I'm having trouble determining if this is the correct format. The main GA script is located at the footer of the entire site (on every page), but this is a jquery pop up div with this script included. Do I need to include anything else to track a simple page hit/view? A: I ended up having to post the entire tracking code inside the popup (I am using an iframe, as it turns out) then used ga('create', 'UA-XXXXXXX-X', 'domain.com'); ga('send', 'event', 'popup', 'popup');
Q: How to decode a nested JSON struct with Swift Decodable? Here is my JSON { "myItems": { "item1name": [{ "url": "google.com", "isMobile": true, "webIdString": "572392" }, { "url": "hulu.com", "isMobile": false, "webIdString": "sad1228" }], "item2name": [{ "url": "apple.com", "isMobile": true, "webIdString": "dsy38ds" }, { "url": "Facebook.com", "isMobile": true, "webIdString": "326dsigd1" }, { "url": "YouTube.com", "isMobile": true, "webIdString": "sd3dsg4k" }] } } The json can have multiple items (such as item1name, item2name, item3name,...) and each item can have multiple objects (the example has 2 objects for the first item and 3 objects for the second item). Here is the structure I want it saved to (incomplete): struct ServerResponse: Decodable { let items: [MyItem]? } struct MyItem: Decodable { let itemName: String? let url: String? let isMobile: Bool? let webIdString: String? } In the example above, it would mean that the items list should have five MyItem objects. For example, these would be the MyItem objects: #1: itemName: item1name, url: google.com, isMobile: true, webIdString: 572392 #2: itemName: item1name, url: hulu.com, isMobile: false, webIdString: sad1228 #3: itemName: item2name, url: apple.com, isMobile: true, webIdString: dsy38ds #4: itemName: item2name, url: Facebook.com, isMobile: true, webIdString: 326dsigd1 #5: itemName: item2name, url: YouTube.com, isMobile: true, webIdString: sd3dsg4k What would be the best way for me to do this using Decodable? Any help would be appreciated. I think this may be similar to this problem: How to decode a nested JSON struct with Swift Decodable protocol? A: Use below code to decode nested JSON for your requirement: import Foundation // MARK: - Websites struct Websites: Codable { var myItems: MyItems } // MARK: - MyItems struct MyItems: Codable { var item1Name, item2Name: [ItemName] enum CodingKeys: String, CodingKey { case item1Name = "item1name" case item2Name = "item2name" } } // MARK: - ItemName struct ItemName: Codable { var url: String var isMobile: Bool var webIDString: String enum CodingKeys: String, CodingKey { case url, isMobile case webIDString = "webIdString" } } NOTE: change the name of the variables according to your need. EDIT If you're still facing issue, use this app to convert your JSON to Struct: Quick Type A: Here is the structure you are after: struct Websites: Decodable { let items: [Item] init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Key.self) items = try container.decode([String: [Item]].self, forKey: .myItems).values.flatMap { $0 } } private enum Key: String, CodingKey { case myItems } } struct Item: Decodable { let url: String let isMobile: Bool let webIdString: String }
Q: Is there a py2exe version that's compatible with python 3.5? I am trying to compile my python 3.5 file with the latest py2exe version 0.9.2.2 with the following command: py -3.5 -m py2exe.build_exe myscript.py But it reports this: "run-py3.5-win-amd64.exe" file is not found in the ...lib\site-packages\py2exe\ folder. Does this mean that py2exe 0.9.2.2 is only compatible up to python 3.4? A: There are significant changes in Python 3.5 regarding the MSVCR dll dependency. py2exe 0.9.2.2 supports Python 3.3 and 3.4 Article describing these changes - BUILDING EXTENSIONS FOR PYTHON 3.5 A: I came here looking for a 3.5 exe generator. I've found that using "pyinstaller" version 3.2 works perfectly with python 35. I found the easiest way to use it is from the command window when on Windows. To make things a little easier you can create a command window from the directory your scripts are stored. Here's how: From the directory your scripts are saved you can launch a command window by holding 'Alt' + 'Shift' and clicking on the window. In the drop down menu you will see "Open Command Window Here". In that command window you will write 'pyinstaller --onefile script.py' where "script.py" is the name of the script you want to generate the .exe for. I hope this helps someone else as much as it helped me. A: Unfortunately as of November 2016 there is still no Python 3.5 support in sight for py2exe. However, I've had great success using cx_Freeze 5.0 with Python 3.5 and since both projects use a very similar configuration I've migrated away from py2exe to cx_Freeze without much work. Binary Wheels of cx_Freeze 5.0 for Python 3.5 are now available officially on PyPi: https://pypi.python.org/pypi/cx_Freeze A: Install pyinstaller through Command Prompt (Microsoft Windows) : * *search cmd on windows to open Command Prompt with black screen *type and enter: pip install pyinstaller *Again at Command Prompt type and enter: cd c:\....(the Folder where your file example.py is located) *Finally type and enter: pyinstaller --onefile example.py *Now after some minutes your example.exe is ready A: Py2Exe just released Py2Exe for Python 3! To install on windows do this: cd C:\Python34\Scripts Then run: pip install py2exe And your done you can now run the normal commands, and if your having trouble here are the docs. A: I note that the original question was asked just shy of 4 years ago. Visiting https://pypi.org/project/py2exe/ the version offered is still at 0.9.2.2 Using the command pip install py2exe and checking the py2exe directory created on my system, I only see options for Python 3.3 and 3.4 installed. Given that the last time py2exe was updated was in 2014, my guess is that it is no longer being developed so folks wanting to create executables using versions of Python more recent than 3.4 should look elsewhere for a solution. A: There is py2exe for python versions that can be downloaded at https://pypi.python.org/pypi/py2exe/0.9.2.0#downloads A: ** #I use pyinstaller #pip install pyinstaller #command line: #pyinstaller --onedir --onefile --name=what you call it --console myscript.py #pyinstaller --onedir --onefile --name=what you call it --windowed myscript.py #pyinstaller -h help file #pyinstaller -d -f -n=file name -c or -w myscript.py **
Q: Why does the page go to the address of the php file when closing the alert? On my page when we click on the STOP button of the java script alert we are immediately directed to the address of the php file. But I want to direct to another page, how do I go to another page? <input id="sendMessageButton" type="submit" value="Enviar" onclick="functionAlert();"> var el = document.getElementById('contactForm'); el.addEventListener('submit', function(){ return confirm('your message?'); }, true);
Q: How to publish binary Python wheels for linux on a local machine I have a package containing C extensions that I would like to upload to pypi: https://github.com/Erotemic/netharn I built a wheel on Ubuntu 18.04 using the command python setup.py bdist_wheel --py-limited-api=cp36, but when I went to upload with twine upload --skip-existing dist/*, but then I get the error that it has an unsupported platform tag: HTTPError: 400 Client Error: Binary wheel 'netharn-0.0.4-cp36-abi3-linux_x86_64.whl' has an unsupported platform tag 'linux_x86_64'. for url: https://upload.pypi.org/legacy/ After a bit of searching I found that PEP 513 requires building a wheel to support manylinux (aka Centos5): https://github.com/pypa/manylinux They provide an example here: https://github.com/pypa/python-manylinux-demo/blob/master/travis/build-wheels.sh However, all examples I can find always build their binaries using some sort of CI server. If possible I would like to be able to build them locally. I thought that it should be simple to just replicate the docker commands and built it in a docker container on my own machine. However, I'm having issues. (I ensured any existing build and dist directories in the repo were removed) The first thing I did was to dump myself in an interactive docker session so I could play with things. I chose the x8_64 image and mounted the local directory to my code repository on /io in the docker machine. I then started an interactive bash session. REPO_DPATH=$HOME/code/netharn DOCKER_IMAGE=quay.io/pypa/manylinux1_x86_64 PRE_CMD="" # Interactive test docker run -it --rm -v $REPO_DPATH:/io $DOCKER_IMAGE $PRE_CMD bash Inside docker, I first wanted to build a wheel for python36 (really this is the only Python I'm interested in supporting at the moment). PYBIN=/opt/python/cp36-cp36m/bin/ Simply installing my requirements.txt didn't seem to work, so I manually installed a few packages first. After doing that (imgaug was the culprit because it relies on a specific master build), installing requirements.txt seemed to work. cd /io "${PYBIN}/pip" install opencv_python "${PYBIN}/pip" install Cython "${PYBIN}/pip" install pytest "${PYBIN}/pip" install -e git+https://github.com/aleju/imgaug.git@master#egg=imgaug "${PYBIN}/pip" install torch # this is in the requirements.txt, but will cause problems later "${PYBIN}/pip" install -r requirements.txt I then run the wheel command and bundle external shared libraries into wheels "${PYBIN}/pip" wheel /io/ -w wheelhouse/ for whl in wheelhouse/*.whl; do auditwheel repair "$whl" -w /io/wheelhouse/ done The last step is to install the package and test "${PYBIN}/pip" install netharn --no-index -f /io/wheelhouse (cd "$HOME"; "${PYBIN}/python" -m xdoctest netharn all) However, when I got to test it I get ImportError: /opt/python/cp36-cp36m/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so: ELF file OS ABI invalid I guess this is because torch does not support Centos5. What I don't get is how torch gets away with uploading a cpython-36m-x86_64-linux-gnu.so shared library to pypi, but I'm having issues? A: A solution that works with caveats explained below. pip install auditwheel twine apt install patchelf python setup.py bdist_wheel auditwheel repair [[lib]]-linux_x86_64.whl -w . --plat manylinux_2_24_x86_64 twine upload [[lib]]-manylinux_2_24_x86_64.whl Context I have a C library w/ python wrapper I don't own directly (making CI difficult) with a very small user base (don't need true manylinux support) and an official conda binary that doesn't include the wrapper (don't want to make a competing conda channel). The above solves my specific needs on Ubuntu 20.04 but please read below before using. Caveats * *If you have control of your repo, you really should be using CI. If this is set up, then there's no need for command-line uploads. *This doesn't support the older/broader manylinux_1 distro as Ubuntu 20.04 is too new for it. This should still support the bulk of Linux distros but might not run on older hardware (ex. university HPC clusters). *It would likely be better to build directly from a docker container. The build + repair workflow is ugly. I'm guessing this is not much more than a file rename with some .so cleanup.
Q: Huge speed difference in numpy between similar code Why is there such a large speed difference between the following L2 norm calculations: a = np.arange(1200.0).reshape((-1,3)) %timeit [np.sqrt((a*a).sum(axis=1))] 100000 loops, best of 3: 12 µs per loop %timeit [np.sqrt(np.dot(x,x)) for x in a] 1000 loops, best of 3: 814 µs per loop %timeit [np.linalg.norm(x) for x in a] 100 loops, best of 3: 2 ms per loop All three produce identical results as far as I can see. Here's the source code for numpy.linalg.norm function: x = asarray(x) # Check the default case first and handle it immediately. if ord is None and axis is None: x = x.ravel(order='K') if isComplexType(x.dtype.type): sqnorm = dot(x.real, x.real) + dot(x.imag, x.imag) else: sqnorm = dot(x, x) return sqrt(sqnorm) EDIT: Someone suggested that one version could be parallelized, but I checked and it's not the case. All three versions consume 12.5% of CPU (as is usually the case with Python code on my 4 physical / 8 virtual core Xeon CPU. A: np.dot will usually call a BLAS library function - its speed will thus depend on which BLAS library your version of numpy is linked against. In general I would expect it to have a greater constant overhead, but to scale much better as the array size increases. However, the fact that you are calling it from within a list comprehension (effectively a normal Python for loop) will likely negate any performance benefits of using BLAS. If you get rid of the list comprehension and use the axis= kwarg, np.linalg.norm is comparable to your first example, but np.einsum is much faster than both: In [1]: %timeit np.sqrt((a*a).sum(axis=1)) The slowest run took 10.12 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 11.1 µs per loop In [2]: %timeit np.linalg.norm(a, axis=1) The slowest run took 14.63 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 13.5 µs per loop # this is what np.linalg.norm does internally In [3]: %timeit np.sqrt(np.add.reduce(a * a, axis=1)) The slowest run took 34.05 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 10.7 µs per loop In [4]: %timeit np.sqrt(np.einsum('ij,ij->i',a,a)) The slowest run took 5.55 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 5.42 µs per loop
Q: Android equivalent of Nibs? I am an iOS developer who is new to Android dev. I'm wondering if there is an equivalent to nibs in Android dev. For example: * *I subclass Button to programmatically define behaviors like having the button spin on touchdown (similar to creating a .swift file and subclassing UIButton) *I can design the look of the button in XML once (similar to editing the xib file) *I can drag my new custom button from Android Studio's Layout Editor onto other views I already know that subclassing views will make them appear in the palette, I just don't know how to design the look of a subclassed view using XML. When I try to drag additional things into my button, it doesn't work (probably because I'm subclassing Button and not ViewGroup). A: In android studio You can create some reusable.xml file in resource's layout directory, then create a new reusable.java java class and in constructor of this class use layout inflater of android studio to inflate reusable.xml view. Then you can do with inflated view what you want.
Q: mySQL ORDER based on multiple criteria My actual table is much more in-depth than this but let's assume I have a table that looks like this... Record_ID Due_Date Style ========= ========== ===== 100 2018-01-01 10 101 2018-01-02 20 102 2018-01-03 12 103 2018-01-04 10 104 2018-01-05 20 105 2018-01-06 12 106 2018-01-02 10 What I want is a query that will determine the first due date and then return that record along with all other records with the same style regardless of the due date. It should then be followed by the next due date of another style and keep going. A successful output would be in this order... Record_ID Due_Date Style ========= ========== ===== 100 2018-01-01 10 106 2018-01-02 10 103 2018-01-04 10 101 2018-01-02 20 104 2018-01-05 20 102 2018-01-03 12 105 2018-01-06 12 If you look at just the first record for each Style the output is in order. See records 100,101,102 If you look at all the records for a given Style the output is sorted by date. See records 100,106,103 If you look at just the Style column the output is has all the like Style together but not necessarily in numerical order. By doing having this output, it is easy to see what Style is due first but all records in that same Style will be completed prior to moving on to the next Style A: Here's one option using a subquery that creates a grouping of styles with their corresponding min(duedate). Then you join that back to the original table and order by that date. select * from yourtable t join ( select min(duedate) minduedate, style from yourtable group by style) t2 on t.style = t2.style order by t2.minduedate, t.duedate * *Online Demo
Q: "as we discuss in detail in a moment" - why not "as we'll discuss"? The term 'raising verb' is potentially confusing. It is not the verb itself that undergoes movement. Rather, it is the complement subject that raises into the matrix clause, as we discuss in detail in a moment. (a webpage) I understand that the authors use the Present Simple in a way similar to its use in description of scheduled events: I fly into Bombay at noon, and then speak at the conference at 3:00 p.m. But since it's due to happen "in a moment", it's unlikely to have been scheduled, so wouldn't it be better to say "we'll discuss"? Is there any difference in tone between "we discuss" and "we'll discuss" and which construction is preferable in this context (textbook narrative)? A: It depends on how the writer wants you to perceive the web page. If they want you to think of it as a completed document, which you are coming along and reading now that it's done, then the present is appropriate. "My explanation already exists. You haven't gotten to it yet, but it's there." If they want you to think of it as them talking to you, then the future - "we'll discuss" - would be more appropriate. Both are correct; they just evoke different tones. A: In the transcript of a lecture, "we will discuss" makes perfect sense. But in a book, not so much. Since we will discuss indicates future intention, it would be a mere masquerade (writing as simulacrum of speech) to use "we will" in a book on grammar; items later in a chapter, or in later chapters, aren't really in the future. Moreover, since they already exist, there can be no intention to discuss them, strictly speaking. A: The term 'raising verb' is potentially confusing. It is not the verb itself that undergoes movement. Rather, it is the complement subject that raises into the matrix clause, as we discuss in detail in a moment. (a webpage) I understand that the authors use the Present Simple in a way similar to its use in description of scheduled events: I fly into Bombay at noon, and then speak at the conference at 3:00 p.m. But since it's due to happen "in a moment", it's unlikely to have been scheduled, so wouldn't it be better to say "we'll discuss"? Is there any difference in tone between "we discuss" and "we'll discuss" and which construction is preferable in this context (textbook narrative)? The style of this webpage, although it is a written text, is very much like the style of spoken discourse, in this case a classroom lecture. So everything written in my answer can apply either to this webpage or to a lecture. With one exception (&), which I will mention in a moment; which I'll mention in a moment; which I mention in a moment; which I am going to mention in a moment; which I'm fixing to mention (Southern); which I'm mentioning in a moment; which I'll be mentioning in a moment; which I am to mention in a moment; which I am about to mention; but which I am not quite yet on the point/verge of mentioning.) Firstly, when a speaker uses the Simple Present Tense to refer to the future (hereafter: Futurate Present), she is referring to the future as fact. The speaker is giving the future the same degree of certainity as she gives to a present or past event. Compare: Simple past: The birthday was yesterday. Simple present: The birthday is today. Futurate present: The birthday is tomorrow. It is a small step from this usage to refer to a Plan or Arrangement Considered as Unalterable: I fly into Bombay at noon, and then speak at the conference at 3:00 p.m. The present tense form is used here because the speaker considers this "schedule" or "itenerary" as unalterable; this is what is going to happen. Compare this with the normal way of referring to A Present Arrangment, which is to be plus the present progressive: I am flying into Bombay at noon, and then speaking at the conference at 3:00 p.m. When one uses the progressive (here in the Futurate Present Progressive), one allows for the possibility that the Arrangement may not come to pass: the above is my Arrangement, I intend to stick to it, I believe it will come to pass; but of course if it may not work out as planned. This is also illustrated by the difference between: She gets married next month and She's getting married next month. In the first case, the speaker is expressing as much certainity about the future as one can (stating it in a way that the future event is 100% certain); in the second, the speaker is expressing an Arrangement, but acknowledging that the future is not 100% for certain. If the wedding does not happen next month as scheduled, it is not an unheard of surprise for the second speaker. However, for the first speaker that the wedding may not happen is not even considered a possibility at the moment of speaking. Thus when the lecturer/textbook/webpage states: The term 'raising verb' is potentially confusing. It is not the verb itself that undergoes movement. Rather, it is the complement subject that raises into the matrix clause, as we discuss in detail in a moment. she is referring to the future with the same degree of certainty normally given to a present or past event. That is, the future is assumed to be fact. In terms of a plan/schedule/arrangement, it is regarded as unalterable. The Futurate Present is not the normal way to refer to the future. So it is a marked future and presents the activity as having something of a dramatic quality. This vividness is similar to, but less intense than, using the Simple Present in such as statements "Here comes the bus!" or "Up we go!" Indeed, sometimes the reader may not realize that a Futurate Present is in use. Let's take the first paragraph of the website/lecture and look at the verbs after the pronoun we: In Chapter 4, we introduced subject movement from Spec(VP) to Spec(IP). In this chapter, we address a related type of movement known as subject raising ... The demonstration that English has subject raising relies on the existence of a special class of noun phrases, and we therefore begin our discussion of subject raising with them. We then show that certain verbs trigger subject raising, and we present an analysis of it. We conclude by distinguishing raising from a superficially similar phenomenon called control. Introduced is simple past. But what about the bolded verbs that have a present tense form. Are these referring to present time or to future time? Hint: are the events happening as the speaker speaks or is the speaker expressing an Unalterable Arrangement or Plan? The instance of we therefore begin makes this trickier than it might seem. But taken as a whole, all the uses except introduced are futurate present, which I sometimes call the "Future Vivid." Meanwhile we can repeat your question regarding we discuss as applying to this opening paragraph: Is there any difference in tone between "we discuss" and "we'll discuss" and which construction is preferable in this context (textbook narrative)? In other words, if the text/speaker had used the future marker will or 'll with all the bolded verbs in the first paragraph, would there be any difference in tone? (&)First, I will now mention the one exception I alluded to way above. The one exception between this written text and spoken speech is that your we'll does not occur in the text. Apparently the writers felt that using 'll would be going too far in writing the webpage as if it were spoken. But there are two instances of will as an auxiallary indicating future time. These are ...However, we will continue to use the term 'raising verb' because it is standard in the literature. and ...In fact, there is no reason to think that they are associated with a subject of their own at all. We will represent this fact by associating raising verbs with elementary trees that have no specifier position, as illustrated for seems in (18). Now, the "tone" expressed by we will in both these examples has more than one layer. First, since we are referring to future time, we will retains the basic meaning of a prediction. (This is best seen in such sentences as She'll thank me later and He'll trip over the milk bottles tonight.) Yet, an additional meaning in the uses of (we) will here is to express the speaker's present resolve to do something in the (near) future [Meaning and the English verb, Geoffrey Leech, 3rd ed., upon which much of this answer heavily depends]. The speaker is not only "predicting" something, she is promising something (I'll kiss you when you get home is both a prediction and a promise). In the uses we will continue to use and we will represent both express the website's/textbook's/speaker's current resolve to make good, def 5 on something in the (near) future. Now, let's quote your paragraph in full: The term 'raising verb' is potentially confusing. It is not the verb itself that undergoes movement. Rather, it is the complement subject that raises into the matrix clause, as we discuss in detail in a moment. A better term for the verb class in question might therefore be 'subject raising triggers.' However, we will continue to use the term 'raising verb' because it is standard in the literature. Voilà! Both uses! Hopefully one can see the difference between expressing a future action as Future-as-fact (an Unalterable Plan)--what I might call the "Future Vivid"--on the one hand, and as expressing current resolve to make good on something, on the other. If not, then ask for more examples. Otherwise, this answer has been an epic fail. Notice that will do something has many more uses than just this one. And also note that the present tense form has another use regarding future time than that described here (namely the "subordinate future"). One can also change the uses of Futurate Present in this webpage to that of Current Intention and see how the "tone" (meaning) changes. And ask: are these uses interchangeable? One might ask how near in the future can "will as a promise" express? And even: Is there a difference between the futurate present and some other kind of present? To explore these, one can use the following as starting point As a result, other semantically conceivable subjects are not possible, as the contrast between (5) and (6) shows. We indicate this by putting weather it in italics (indicating its status as a special subject that needs to be licensed) as well as in green (indicating its own status as a licenser). The first question to ask is which tense is the bolded verb? It has the Present Simple form; does it refer to present time or to future time? How do you know? Is this any different from uses of the present tense form in the webpage's opening paragraph? Could you use will indicate here? Main sources include: Meaning and the english verb, Geoffrey Leech, 3rd ed., Routledge The English Verb (Longman Linguistics Library), Frank Robert Palmer, Routledge
Q: Is it possible to make player progress bar in React Native? I'm trying to make progress bar in React Native. I want to use 'react-native-sound-player' and 'react-native-community/slider' libraries. I just make some function like back to before 10 seconds, and forward to 10 seconds. But, I can't present current time in slider. I want to show current time in slider like normal player. But I didn't know how to do. And I have a question. The react-native-sound-player provides getInfo() function. This function return currentTime and duration in 'Promise type'. Is it possible to make real time progress bar using this function? And I'm beginner in React Native so please help me.. Additional information is below. * *I'm using react native 0.68.4 version *this app will be worked on android and ios I want to progress bar working in real time based. Like normal player.
Q: How to run one Azure Automation runbook for all subscriptions in same tenant? How can we run one Azure Automation runbook for all our subscriptions in the same tenant? Currently, I am making use of one runbook which retrieves the resources in the tenant, but it is listing the resources only from one subscription whereas I have 3 subscriptions present. How do I make sure it outputs all the resources from all subscriptions? Please help A: The problem is that the runbook runs in the security context of an Azure automation account and that account is connected to a subscription and therefore only sees resources within that subscription. https://learn.microsoft.com/en-us/azure/automation/automation-create-standalone-account There is a "Azure management group" which works cross subscription https://learn.microsoft.com/en-us/azure/governance/management-groups/overview It may be possible to run the runbook in a context of a management group user that has access to all subscriptions. But I have never tried this so not sure if it would work. I would suggest that you install and run the runbook in each subscription. Then combine the contents of each report.
Q: Discord.js: How to automatically get the channel id where the command is triggered? I basically want to get the channel id of the channel where the message was sent. I could get it manually, but it would be nicer to do it automatically. A: You can do let channelID = message.channel.id in the message event. From documentation: https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=channel A: Looking at the Discord docs, it looks like if you have an object representing a message (and that object is assigned to a variable called myMessage), you can get the channel id with let myChannelid = myMessage.channel_id; // <== THE CHANNEL ID If you want to request the channel itself, you can make a string representing a URL like: let myUrl = "https://discord.com/api/channels/" + myChannelid; Then if you send an HTTP GET request to that URL, the response you get back should include an object representing the channel. NOTE: If you don't already know (and assuming the response Discord provides is actually a JSON string), you'd convert it to a JavaScript object (one of whose properties will be your channel object) like: let imAnObject = JSON.parse(myResponse); ... and the easiest to see what's inside the response might be to just use console.log(imAnObject);
Q: Proof of equivalence theorem about left invertible matrices I am taking a course in Matrix Theory and we have a theorem that states (among other things) that: The following conditions on the matrix $A$ of size $m \times n$ are equivalent: (1) A has left inverse (2) The system $Ax=b$ has at most one solution for any column vector $b$. ... The proof that (1) $\implies$ (2) goes like this: If $Ax=b$ and $V$ is a left inverse, then $VAx=Vb \implies x=Vb$, so we have at most one solution (if any). The thing is, left inverses are not unique right? Take $A = \left( \begin{matrix} 1 \\ 0 \end{matrix} \right)$ That has left inverses $V_1= \left( \begin{matrix} 1 & 0 \end{matrix} \right) $ and $ V_2 = \left( \begin{matrix} 1 & 1 \end{matrix} \right)$ Does this mean that the proof is wrong or am I missing something? A: Yours is a nice observation. The way out of this apparent issue is that if $b=Ax$, then $V_1b = V_2 b = x$. We can check this directly with the matrices of your example, that is \begin{equation}\begin{array}{ccc} A=\begin{bmatrix} 1 \\ 0\end{bmatrix}, & V_1=\begin{bmatrix} 1 & 0\end{bmatrix},& V_2=\begin{bmatrix} 1 & 1\end{bmatrix}\end{array}.\end{equation} In this case $b=Ax$ means that $$ b= \begin{bmatrix} b_1 \\ 0 \end{bmatrix}, $$ for a scalar $b_1$. Then $$ V_1 b= b_1= V_2b.$$ A: Existence of left inverse means $A$ is 1-1, i.e., $Ax_1 = Ax_2$ implies $VAx_1 = VAx_2$ , i.e., $x_1=x_2$. So a solution, if it exists, must be unique. A: Adding an intermediate step could help. The matrix $A$ has a left inverse iff $A$ is injective iff the system $Ax=b$ has at most one solution for every $b$.
Q: How to tell which fields have been deferred/only'd in a Django queryset I am trying to serialize a queryset into json using my custom iterator. On the models I detect the fields in the model and insert them into the JSON dict as I need them. I am having trouble figuring out how to determine which fields have been deferred in the model using the defer or only queryset function. Is there a way, and how, to find out which fields are deferred and how to skip over them? A: Here is how you can check if it's deferred for an actual model instance: from django.db.models.query_utils import DeferredAttribute for field in model_istance._meta.concrete_fields: if not isinstance(model_instance.__class__.__dict__.get(field.attname), DeferredAttribute): # insert in json dict or whatever need to be done .... This way it will not load that field from db. This implementation is actually taken from django. https://github.com/django/django/blob/d818e0c9b2b88276cc499974f9eee893170bf0a8/django/db/models/base.py#L415 A: Current version of Django (1.9) has a method on all model instances: instance.get_deferred_fields() This seems to be the "official" implementation of Alexey's answer. A: Somewhat buried... queryset.query.get_loaded_field_names()
Q: Device not ready, Intel Centrino Advanced-N 6205 [Taylor Peak] Am using Intel Centrino Advanced-N 6205 [Taylor Peak], in HP Probook 6560b. I am receiving an error that "device not ready" on Ubuntu 14.04, I have tried different OS's but all state the same thing. I then compiled kernels 3.16, 4.1.5, and now 4.3.6. All show the same things. I have installed the drivers iwlwifi-6000g2a-ucode in /lib/firmware/ but not help. Also, in all forums I have visited there is not a solution that works for me. Please help ! $ dmesg | grep iwl [ 48.595771] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 48.596011] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 48.596110] iwlwifi 0000:24:00.0: Radio type=0x1-0x0-0x1 [ 49.602152] iwlwifi 0000:24:00.0: Failed to run INIT ucode: -110 [ 49.602160] iwlwifi 0000:24:00.0: Unable to initialize device. [ 49.602320] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 49.602564] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled $ lscpi -nnk | grep -iA2 net 00:19.0 Ethernet controller [0200]: Intel Corporation 82579V Gigabit Network Connection [8086:1503] (rev 04) Subsystem: Hewlett-Packard Company Device [103c:1619] Kernel driver in use: e1000e 24:00.0 Network controller [0280]: Intel Corporation Centrino Advanced-N 6205 [Taylor Peak] [8086:0085] Subsystem: Intel Corporation Centrino Advanced-N 6205 AGN [8086:1311] Kernel driver in use: iwlwifi $ rfkill list 0: hp-wifi: Wireless LAN Soft blocked: no Hard blocked: no 1: phy0: Wireless LAN Soft blocked: no Hard blocked: no $ dmesg | tail -25 [ 7321.282113] iwlwifi 0000:24:00.0: Failed to run INIT ucode: -110 [ 7321.282124] iwlwifi 0000:24:00.0: Unable to initialize device. [ 7321.284095] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 7321.284372] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 7321.284474] iwlwifi 0000:24:00.0: Radio type=0x1-0x0-0x1 [ 7322.293645] iwlwifi 0000:24:00.0: Failed to run INIT ucode: -110 [ 7322.293657] iwlwifi 0000:24:00.0: Unable to initialize device. [ 7322.294107] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 7322.294353] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 7322.294451] iwlwifi 0000:24:00.0: Radio type=0x1-0x0-0x1 [ 7323.301183] iwlwifi 0000:24:00.0: Failed to run INIT ucode: -110 [ 7323.301266] iwlwifi 0000:24:00.0: Unable to initialize device. [ 7323.303038] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 7323.303362] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 7323.303469] iwlwifi 0000:24:00.0: Radio type=0x1-0x0-0x1 [ 7324.312613] iwlwifi 0000:24:00.0: Failed to run INIT ucode: -110 [ 7324.312623] iwlwifi 0000:24:00.0: Unable to initialize device. [ 7324.313008] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 7324.313240] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 7324.313337] iwlwifi 0000:24:00.0: Radio type=0x1-0x0-0x1 [ 7325.320128] iwlwifi 0000:24:00.0: Failed to run INIT ucode: -110 [ 7325.320147] iwlwifi 0000:24:00.0: Unable to initialize device. [ 7325.324200] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 7325.324483] iwlwifi 0000:24:00.0: L1 Enabled - LTR Disabled [ 7325.324587] iwlwifi 0000:24:00.0: Radio type=0x1-0x0-0x1
Q: Create-React-App on Github-pages returns a blank page When testing locally my create-react-quiz app works perfectly. I was basing my project off of this code: https://github.com/mitchgavan/react-multi-choice-quiz/tree/gh-pages. However, when I use npm build deploy on my "GitHub-Pages" branch, a blank page shows up and these errors show up in the console: pk8189.github.io/:1 GET pk8189.github.io/pk8189/futureU-/static/css/main.1dc4d41f.css pk8189.github.io/:1 GET pk8189.github.io/pk8189/futureU-/static/js/main.28e294a0.js This is my repo: https://github.com/pk8189/futureU- What do you think the issue is? Thank you for any help. A: Create React App uses homepage field in your package.json to determine the URL at which the app is served. Since you set it to https://github.com/pk8189/futureU-/, it tries to request assets from /pk8189/futureU-/ which doesn't exist. Change homepage to match your deployed URL: https://pk8189.github.io/futureU-/. Then rebuild by running npm run build and re-deploy. This is described in deployment instructions for GitHub Pages. Please read this part of the User Guide.
Q: Проблемы с созданием объекта при использовании Proxy.newProxyInstance() Всем привет. Столкнулся с проблемой. Объект создаётся через Proxy.newProxyInstance(). Вот весь код: public class NewAPIHolder { private static GeneralAPI generalAPI = (GeneralAPI) Proxy.newProxyInstance( GeneralAPI.class.getClassLoader(), GeneralAPI.class.getInterfaces(), new CFHandler() ); public static ContestAPI getContestAPI() { return generalAPI; } public static ProblemsetAPI getProblemsetAPI() { return generalAPI; } public static UserAPI getUserAPI() { return generalAPI; } private abstract class GeneralAPI implements ContestAPI, ProblemsetAPI, UserAPI {} } На строке с инициализацией generalAPI выбрасывается java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to api.interfaces.NewAPIHolder$GeneralAPI A: Поскольку GeneralAPI - это класс, то не существует способа создать для него прокси при помощи Proxy. Но зачем он вам вообще нужен? public class NewAPIHolder { private static Object generalAPI = Proxy.newProxyInstance( NewAPIHolder.class.getClassLoader(), new Class<?>[] { ContestAPI.class, ProblemsetAPI.class, getUserAPI.class }, new CFHandler() ); public static ContestAPI getContestAPI() { return (ContestAPI)generalAPI; } public static ProblemsetAPI getProblemsetAPI() { return (ProblemsetAPI)generalAPI; } public static UserAPI getUserAPI() { return (UserAPI)generalAPI; } }
Q: Oauth2 Google Drive offline access not working for non-google app files? Having a very frustrating issue with Google Drive API. This is a Google App Engine Java environment. I need to download a file based on an offline permission - the file is shared ("Can Edit") with the user who gives the offline permission. I am requesting full https://www.googleapis.com/auth/drive scope. I store off the refresh token this generates. The app then uses this refresh token to get an access token, which it uses to try and download a file. This works file if the file is a Google Apps file (a Google document, spreadsheet etc.) but gives a 401 if the file is an uploaded file with content (e.g. a PDF file, Word file etc.). I can confirm this at a simple level by appending the share urls with ?access_token=xxxx - this works for the Google Apps file but not for an uploaded normal file, which 401's on the webcontentlink url. Note that the https://www.googleapis.com/drive/v2/files/ endpoint responds correctly with the metadata for the uploaded file using the access token that subsequently fails on the download call. The full html response from either a direct url call (with access_token=) or a servlet call is <HTML> <HEAD> <TITLE>Unauthorized</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <H1>Unauthorized</H1> <H2>Error 401</H2> </BODY> </HTML> Is there a known issue with offline Google auth on non native files in Drive? A: Based on the descriptions of file attributes, you should probably be using the downloadUrl attribute rather than webContentLink. downloadUrl - Short lived download URL for the file. This is only populated for files with content stored in Drive. webContentLink - A link for downloading the content of the file in a browser using cookie based authentication. In cases where the content is shared publicly, the content can be downloaded without any credentials.
Q: Number format string to show only right 2 digits I know I can use substring or other methods, but I'm just curious if there is something to replace the ? below to have it return "09" String.Format({0:?}, 2009); btw, I came across a good cheat sheet while trying to figure this out... http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf A: I saw the question, and at the risk of being flamed, I want to point this out: If you're formatting a DateTime, or you've got a Date you're formatting you can simply do a ToString("yy"). Likewise if you're only dealing with years. DateTime dt = new DateTime(2009, 1, 1); //any DateTime would do, really. return dt.ToString("yy"); //"09" but if this is some weird generic I want the last two characters of a string business, the fastest route is: string numString = someInt.ToString(); return numString.Substring(numString.Length - 2); A: If you have a legitimate need for something more sophisticated, you can always create your own custom format provider: http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx You can then format your strings in whatever pattern you want, and properly encapsulate the functionality for reuse. Here is an example: class Program { static void Main(string[] args) { var date = "2009"; Console.Write(string.Format(new CustomFormatProvider(), "{0:YY}", date)); Console.ReadKey(); } public class CustomFormatProvider : IFormatProvider, ICustomFormatter { public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; else return null; } public string Format(string fmt, object arg, IFormatProvider formatProvider) { string year = arg.ToString(); string result = string.Empty; fmt = fmt.Trim().ToUpper(); if (fmt.Equals("YY")) return year.Substring(2, 2); else if (fmt.Equals("YYYY")) return year; else throw new FormatException(String.Format("{0} is not a valid format string.", fmt)); } } } A: I really think that you ought to do this: String s = "2009"; s.Substring(s.Length - 2); There is no way to format that string to restrict the number of digits like you want to. A: (2009 % 100).ToString("00"); A: I'm 99.9% certain this cannot be done unless you have the year stored in a DateTime...
Q: Circular UIImageView in UITableView without performance hit? I have a UIImageView on each of my UITableView cells, that display a remote image (using SDWebImage). I've done some QuartzCore layer styling to the image view, as such: UIImageView *itemImageView = (UIImageView *)[cell viewWithTag:100]; itemImageView.layer.borderWidth = 1.0f; itemImageView.layer.borderColor = [UIColor concreteColor].CGColor; itemImageView.layer.masksToBounds = NO; itemImageView.clipsToBounds = YES; So now I have a 50x50 square with a faint grey border, but I'd like to make it circular instead of squared. The app Hemoglobe uses circular images in table views, and that's the effect I'd like to achieve. However, I don't want to use cornerRadius, as that degrades my scrolling FPS. Here's Hemoglobe showing circular UIImageViews: Is there any way to get this effect? Thanks. A: Yes, it is possible to give layer.cornerRadius (need to add #import <QuartzCore/QuartzCore.h>) for create circular any control but in your case instead of set layer of UIImageView it is The Best Way to Create Your Image as circular and add it on UIImageView Which have backGroundColor is ClearColor. Also refer this Two Source of code. https://www.cocoacontrols.com/controls/circleview and https://www.cocoacontrols.com/controls/mhlazytableimages This might be helpful in your case: A: To Add border self.ImageView.layer.borderWidth = 3.0f; self.ImageView.layer.borderColor = [UIColor whiteColor].CGColor; For Circular Shape self.ImageView.layer.cornerRadius = self.ImageView.frame.size.width / 2; self.ImageView.clipsToBounds = YES; Refer this link http://www.appcoda.com/ios-programming-circular-image-calayer/ A: Set the height & width of the of the UIImageView to be the same e.g.:Height=60 & Width = 60, then the cornerRadius should be exactly the half.I have kept it 30 in my case.It worked for me. self.imageView.layer.cornerRadius = 30; self.imageView.layer.borderWidth = 3; self.imageView.layer.borderColor = [UIColor whiteColor].CGColor; self.imageView.layer.masksToBounds = YES; A: Usable solution in Swift using extension: extension UIView{ func circleMe(){ let radius = CGRectGetWidth(self.bounds) / 2 self.layer.cornerRadius = radius self.layer.masksToBounds = true } } Usage: self.venueImageView.circleMe() A: If use some autolayout and different cells heights, u better do it this way: override func layoutSubviews() { super.layoutSubviews() logo.layer.cornerRadius = logo.frame.size.height / 2; logo.clipsToBounds = true; } A: Simply set the cornerRadius to half of the width or height (assuming your object's view is square). For example, if your object's view's width and height are both 50: itemImageView.layer.cornerRadius = 25; Update - As user atulkhatri points out, it won't work if you don't add: itemImageView.layer.masksToBounds = YES; A: Use this code.. This will be helpful.. UIImage* image = ...; UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0); // Add a clip before drawing anything, in the shape of an rounded rect [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:50.0] addClip]; // Draw your image [image drawInRect:imageView.bounds]; // Get the image, here setting the UIImageView image imageView.image = UIGraphicsGetImageFromCurrentImageContext(); // Lets forget about that we were drawing UIGraphicsEndImageContext(); It works fine for me. :) A: Here is a more up to date method in swift using IBDesignable and IBInspectable to subclass UIImageView @IBDesignable class RoundableUIImageView: UIImageView { private var _round = false @IBInspectable var round: Bool { set { _round = newValue makeRound() } get { return self._round } } override internal var frame: CGRect { set { super.frame = newValue makeRound() } get { return super.frame } } private func makeRound() { if self.round == true { self.clipsToBounds = true self.layer.cornerRadius = (self.frame.width + self.frame.height) / 4 } else { self.layer.cornerRadius = 0 } } override func layoutSubviews() { makeRound() } } A: I use a Round Image View class… So I just use it instead of UIImageView, and have nothing to tweak… This class also draws an optional border around the circle. There is often a border around rounded pictures. It is not a UIImageView subclass because UIImageView has its own rendering mechanism, and does not call the drawRect method.. Interface : #import <UIKit/UIKit.h> @interface MFRoundImageView : UIView @property(nonatomic,strong) UIImage* image; @property(nonatomic,strong) UIColor* strokeColor; @property(nonatomic,assign) CGFloat strokeWidth; @end Implementation : #import "MFRoundImageView.h" @implementation MFRoundImageView -(void)setImage:(UIImage *)image { _image = image; [self setNeedsDisplay]; } -(void)setStrokeColor:(UIColor *)strokeColor { _strokeColor = strokeColor; [self setNeedsDisplay]; } -(void)setStrokeWidth:(CGFloat)strokeWidth { _strokeWidth = strokeWidth; [self setNeedsDisplay]; } - (void)drawRect:(CGRect)rect { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGPathRef path = CGPathCreateWithEllipseInRect(self.bounds, NULL); CGContextAddPath(ctx, path); CGContextClip(ctx); [self.image drawInRect:rect]; if ( ( _strokeWidth > 0.0f ) && _strokeColor ) { CGContextSetLineWidth(ctx, _strokeWidth*2); // Half border is clipped [_strokeColor setStroke]; CGContextAddPath(ctx, path); CGContextStrokePath(ctx); } CGPathRelease(path); } @end A: Creating circular image view and thats quite easy with the below SO link, just have custom cells for your table view instead of allocating every thing in your cellForRowAtIndexPath method. how to make button round with image background in IPhone? The above link gives you example for buttons just use it for your image views. A: If you showing the images over a solid background color, an easy solution could be to use an overlay image with a transparent circle in the middle. This way you can still use square images and add the circle image above them to get the circular effect. If you don't need to manipulate your images or show them on a complex background color, this can be a simple solution with no performance hit. A: In swift, inside your viewDidLoad method, with the userImage outlet: self.userImage.layer.borderWidth = 1; self.userImage.layer.borderColor = UIColor.whiteColor().CGColor; self.userImage.layer.cornerRadius = self.userImage.frame.size.width / 2; self.userImage.clipsToBounds = true; A: In Swift use this Extension for CircularImageView or RoundedImageView : extension UIView { func circular(borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.whiteColor()) { let radius = CGRectGetWidth(self.bounds) / 2 self.layer.cornerRadius = radius self.layer.masksToBounds = true self.layer.borderWidth = borderWidth self.layer.borderColor = borderColor.CGColor } func roundedCorner(borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.whiteColor()) { let radius = CGRectGetWidth(self.bounds) / 2 self.layer.cornerRadius = radius / 5 self.layer.masksToBounds = true self.layer.borderWidth = borderWidth self.layer.borderColor = borderColor.CGColor } } Usage: self.ImageView.circular() self.ImageView.roundedCorner() A: For circular imageview, use the below code. self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2; self.imageView.clipsToBounds = true Don't forget to change the cornerRadius in viewDidLayoutSubviews method of your UIView. Example: override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2; self.imageView.clipsToBounds = true }
Q: How to click links on a webpage in visual basic I have searched for how to click links on a webpage in vb before, and got a good answer on this site actually. But now I am trying to click another link, and let me just post it's code so it's easier to understand. (First time ever asking a question, so go easy on me lol) <div class="pauseButton" style="display: block;"><a href="#" address="true"></a></div> Here is my code (This is for Pandora btw, and here is my code for it to sign you in.) Public Class fMain Dim elementCollection As HtmlElementCollection Private Sub fMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load wb.Navigate("http://www.pandora.com") End Sub 'buttons Private Sub bLogin_Click(sender As Object, e As EventArgs) Handles bLogin.Click elementCollection = wb.Document.GetElementsByTagName("input") For Each ele As HtmlElement In elementCollection If ele.GetAttribute("name").Equals("email") Then ele.SetAttribute("Value", tbEmail.Text) End If If ele.GetAttribute("name").Equals("password") Then ele.SetAttribute("Value", tbPassword.Text) End If If ele.GetAttribute("type") = "submit" Then ele.InvokeMember("click") End If Next End Sub Private Sub bSignOut_Click(sender As Object, e As EventArgs) Handles bSignOut.Click End Sub Private Sub bPlay_Click(sender As Object, e As EventArgs) Handles bPlay.Click Dim IsRightElement As Boolean = False For Each ele As HtmlElement In wb.Document.Links If IsRightElement Then ele.InvokeMember("click") IsRightElement = False Exit For End If If ele.GetAttribute("class") = "playButton" Then IsRightElement = True End If Next End Sub Private Sub bPause_Click(sender As Object, e As EventArgs) Handles bPause.Click End Sub Private Sub bFavorite_Click(sender As Object, e As EventArgs) Handles bFavorite.Click End Sub End Class Any help would be greatly appreciated, and sorry if I made the question confusing, but pretty much I know how to click a link with specific href="link.com" but here, the only thing distinguishing the play button with any other button is its the href="#" so that is not much help. Again thanks in advanced. (: EDIT: I am trying to make a Pandora streamer, I should have mentioned that earlier. A: If you're using Visual Studio.NET, do this: 1.Drop a HyperLink Control 2.Under the NavigateUrl property, click the ellipsis. You should now get a screen with all the files in your project 3.Select your HTML file. If it isn't part of your project, add it using Browse. A: In the HTML I give the link an ID: <div class="pauseButton" style="display: block;"><a id="LinkID" href="#" address="true"></a></div> VB.Net code to get the element by Id and invoke it: Private Function ClickSubmitButton() Dim theButton As HtmlElement Try ' Link the ID from the web form to the Button var theButton = webbrowser1.Document.GetElementById("LinkID") ' Now do the actual click. theButton.InvokeMember("click") Return True Catch ex As Exception Return False End Try End Function Update: Ok without the LinkID you need to loop through all elements, once you identify the DIV, you know the next element is the link... Dim IsRightElement as Boolean = False For Each ele As HtmlElement In wb.Document.Links If IsRightElement Then ele.InvokeMember("click") IsRightElement = False Exit For End If If ele.GetAttribute("class") = "playButton" Then IsRightElement = True End If Next
Q: Ios error while sorting an NSArray When I try to sort an array, I got an exception like below: *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key levels.' To sort the arrays I use the following lines: NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"levels" ascending:YES]; NSArray *descriptors = [NSArray arrayWithObject: descriptor]; NSArray *reversedLevelIdArray = [levelsDictionary.allKeys sortedArrayUsingDescriptors:descriptors]; The levelsDictionary.allKeys contains the values like below: ( level2, level1 ) What is wrong with my code? A: Using Sort Descriptor... NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES]; NSArray *descriptors = [NSArray arrayWithObject: descriptor]; NSArray *reversedLevelIdArray = [levelsDictionary.allKeys sortedArrayUsingDescriptors:descriptors]; NSLog(@"%@", reversedLevelIdArray); You can use @selector to sort an array... NSArray *resultArray = [levelsDictionary.allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; Using Comparator.... NSArray *resultArray = [levelsDictionary.allKeys sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { return obj2 > obj1; }]; A: You're sorting strings and they are ahving no property or method named levels. You should sort the values instead, like: [levelsDictionary.allKeys sortedArrayUsingSelector:@selector(compare:)]; A: Just use the following codes to sort the array, instead of all of your other line of codes.. NSArray *reversedIdArray = [levelsDictionary.allKeys sortedArrayUsingDescriptors:@selector(caseInsensitiveCompare:)]; A: I have checked you code, you are sorting the data and accessing the wrong key name of dictionary. As you said that your levelDictionary contains the keys name as "level2", "level1", etc.... NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"levels" ascending:YES]; In this code you have used the key name as "levels" is wrong, because I think your dictionary "levelsDictionary" does not contains any key name as "levels". Please try to use the proper key name and your error will resolve.