image background change on scroll Posted: 21 Sep 2021 08:21 AM PDT i am trying to change background image on scroll, but cant seem to find any guide, so i will try my luck here. here is a video of exactly what i am trying to achieve - https://www.youtube.com/watch?v=7u1aIxQCIXg i want to have a background image, and text that goes over when i scroll, and when i come to a certain point, the background image changes/fades over and not scrolls up from the bottom i have tried some, but does not have the skills at this point |
Reading Glyphs from a String using codePointAt(i) or Charseterset issue Posted: 21 Sep 2021 08:21 AM PDT I created a text editor for JavaFx which is painting the text on a Canvas, gyph by glyph. I use String.codePointAt(i) to correctly load the glyphs. Somehow the first glyph is a strange one, I don't know why. The file was loaded using Charset UTF-16 LE Here is the rendered string, the first glyph is strange: And here you can see the textLine and ch bytes after the first character: And here is the code I use to iterate a text line: int i = 0; while (i < textLine.length()) { int codePoint = textLine.codePointAt(i); i += Character.charCount(codePoint); String ch = Character.toString( cp ); graphicContext.fillText( ch, x, y); } Is this code wrong or it is an encoding and file issue? |
Size of an object of a class containing a string and an integer data member Posted: 21 Sep 2021 08:21 AM PDT I found this code on geeksforgeeks while studying about new operator overloading: #include<iostream> #include<stdlib.h> using namespace std; class student { string name; int age; public: student() { cout<< "Constructor is called\n" ; } student(string name, int age) { this->name = name; this->age = age; } void display() { cout<< "Name:" << name << endl; cout<< "Age:" << age << endl; } void * operator new(size_t size) { cout<< "Overloading new operator with size: " << size << endl; void * p = ::operator new(size); //void * p = malloc(size); will also work fine return p; } void operator delete(void * p) { cout<< "Overloading delete operator " << endl; free(p); } }; int main() { student * p = new student("Yash", 24); p->display(); delete p; } In the output it is showing that the number of bytes of memory to be allocated for the object is 40 bytes . When I print the sizeof(string) it was coming out to be 32 bytes , then why the memory allocated for the object is 40 bytes shouldn't it be 36 bytes ? |
Pandas Groupby Multiple Conditions KeyError Posted: 21 Sep 2021 08:21 AM PDT I have a df called df_out with column names such as this in the following insert but I cannot for some reason use 'groupby' function with the column headers since it keeps giving me KeyError: 'year'. I"ve researched and tried stripping white space, resetting the index, allowing white space before my groupby setting, etc and I cannot get past this KeyError. The df_out looks like this: df_out.columns Out[185]: Index(['year', 'month', 'BARTON CHAPEL', 'BARTON I', 'BIG HORN I', 'BLUE CREEK', 'BUFFALO RIDGE I', 'CAYUGA RIDGE', 'COLORADO GREEN', 'DESERT WIND', 'DRY LAKE I', 'EL CABO', 'GROTON', 'NEW HARVEST', 'PENASCAL I', 'RUGBY', 'TULE'], dtype='object', name='plant_name') But, when I use df_out.head(), I get a different answer with the leading column of 'plant_name' so this maybe is where the error is coming from or related. Here is the output columns from - df_out.head() Out[187]: plant_name year month BARTON CHAPEL BARTON I BIG HORN I BLUE CREEK \ 0 1991 1 6.432285 7.324126 5.170067 6.736384 1 1991 2 7.121324 6.973586 4.922693 7.473527 2 1991 3 8.125793 8.681317 5.796599 8.401855 3 1991 4 7.454972 8.037764 7.272292 7.961625 4 1991 5 7.012809 6.530013 6.626949 6.009825 plant_name BUFFALO RIDGE I CAYUGA RIDGE COLORADO GREEN DESERT WIND \ 0 7.163790 7.145323 5.783629 5.682003 1 7.595744 7.724717 6.245952 6.269524 2 8.111411 9.626075 7.918871 6.657648 3 8.807458 8.618806 7.011444 5.848736 4 7.734852 6.267097 7.410013 5.099610 plant_name DRY LAKE I EL CABO GROTON NEW HARVEST PENASCAL I \ 0 4.721089 10.747285 7.456640 6.921801 6.296425 1 5.095923 8.891057 7.239762 7.449122 6.484241 2 8.409637 12.238508 8.274046 8.824758 8.444960 3 7.893694 10.837139 6.381736 8.840431 7.282444 4 8.496976 8.636882 6.856747 7.469825 7.999530 plant_name RUGBY TULE 0 7.028360 4.110605 1 6.394687 5.257128 2 6.859462 10.789516 3 7.590153 7.425153 4 7.556546 8.085255 My groupby statement that is getting the KeyError looks like this and I'm trying to calculate the average by rows of year and month based on a subset of columns from df_out found in the list - 'west': west=['BIG HORN I','DRY LAKE I', 'TULE'] westavg = df_out[df_out.columns[df_out.columns.isin(west)]].groupby(['year','month']).mean() thank you very much, |
Doesn't java have pointer? Posted: 21 Sep 2021 08:21 AM PDT Hi everyone who read this post, i have a question about java programming. Is that java have pointer? I heard someone said "Java has pointer" and other person said "Java doesn't have pointer" ? I need a explain about this question. |
Symfony 5 + Api Platform Desencrypt id filter collection dont work Posted: 21 Sep 2021 08:21 AM PDT i need to decode a encrypted id sending in query params for a collection. This is my configuration service.yml client.default.filter: parent: 'api_platform.doctrine.orm.search_filter' arguments: [ { clients.id: 'exact' } ] tags: [ 'api_platform.filter' ] autowire: false autoconfigure: false public: false entity.yml collectionOperations: get: method: 'GET' filters: ['client.default.filter'] swagger_context: parameters: - name: clients.id in: query items: - type: interger FilterEventSubscriber public function onRequestEvent(RequestEvent $event) { $request = $event->getRequest(); $params = $request->query->all(); $this->logger->info("FilterEventSubscriber params after: ".json_encode($params)); foreach ($params as $key => $value) { if (EncryptUtils::isValid($value)) { $params[$key] = EncryptUtils::integerDecrypt($value); $event->getRequest()->query->set($key,$params[$key]); $event->getRequest()->overrideGlobals(); } } $this->logger->info("FilterEventSubscriber params before: ".json_encode($event->getRequest()->query->all())); } So far it decodes the parameter, but somewhere in the core of api platform or symfony it does not add it to the doctrine query. Someone know who happens? Or another solutions to decode query params for all collection which have filters? |
How do I make the inline form be in the same line as the buttons? Posted: 21 Sep 2021 08:20 AM PDT I am making an app with Bootstrap 4. I have 3 buttons and an inline form, and I want the inline form to be in the same line as the buttons. Currently with this code the form is below the buttons. How can I make everything be in the same line? <button type="button" class="mb-2 mr-2 btn btn-primary"> <span>Agregar</span> </button> <div class="d-inline dropdown"> <button aria-haspopup="true" aria-expanded="false" id="menuUtilidades" type="button" class="mr-2 mb-2 dropdown-toggle btn btn-primary">Utilidades</button> </div> <div class="d-inline dropdown"> <button aria-haspopup="true" aria-expanded="false" id="menuReportes" type="button" class="mb-2 dropdown-toggle btn btn-primary">Reportes</button> </div> <form class="mb-2 form-inline"> <!-- form that should be in same line --!> </form> |
How can I put the file in Firebase Storage? - React Posted: 21 Sep 2021 08:20 AM PDT I'm having a hard time putting the file in firebase so I can retrieve its getDownloadURL . Here's what I got import React, {useState, useEffect} from 'react' import { Container, Button, Row, Col, Form, Alert } from 'react-bootstrap' import PageHeader from '../components/PageHeader' import { projectFirestore, projectStorage } from '../firebase/config' const Dashboard = () => { const [ error, setError] = useState('') const [ name, setName ] = useState("") const [ link, setLink ] = useState("") const [ file, setFile ] = useState(null) const [ desc, setDesc ] = useState("") const [ projects, setProjects ] = useState([]) const [ url, setUrl ] = useState("") const [ message, setMessage ] = useState("") useEffect(() => { projectFirestore.collection('projects').onSnapshot((snapshot) =>{ const tempProject = [] snapshot.forEach(doc => { tempProject.push({...doc.data(), id: doc.id}); }) setProjects(tempProject) }) }, []) const onNameChange = (e) => { setName(e.target.value) } const onLinkChange = (e) => { setLink(e.target.value) } const onDescChange = (e) => { setDesc(e.target.value) } const handleSubmit = async (e) => { e.preventDefault() try { setMessage('') setError('') if(!name){ return } const storageRef = projectStorage.ref() const fileRef = storageRef.child(file.name) await fileRef.put(file) setUrl(fileRef.getDownloadURL()) projectFirestore.collection('projects') .doc( name, link, url, desc ) .set({ name, link, url, desc }) setMessage('Project added succesfully') setName('') setLink('') setFile(null) setDesc('') } catch { setError('Project fail to add') } } return ( <div className=""> <Container> <PageHeader title="Dashboard" /> <Row> <Col xs={12}> <h4>Add Project</h4> {message && <Alert variant="success">{message}</Alert> } {error && <Alert variant="danger">{error}</Alert> } <Form onSubmit={handleSubmit}> <Row> <Col xs={12} lg={8}> <Form.Group className="mb-3"> <Form.Label>Name</Form.Label> <Form.Control type="text" value={name} onChange={onNameChange}/> </Form.Group> <Form.Group className="mb-3"> <Form.Label>Description</Form.Label> <Form.Control as="textarea" rows={5} value={desc} onChange={onDescChange}/> </Form.Group> <Form.Group className="mb-3"> <Form.Label>Link</Form.Label> <Form.Control type="text" value={link} onChange={onLinkChange} /> </Form.Group> </Col> <Col xs={12} lg={4}> <Form.Group className="mb-3"> <Form.Label>Image</Form.Label> <Form.Control type="file" onChange={(e) => setFile(e.target.files[0])}/> </Form.Group> <div> {projects.map(project => ( <div key={project.id} to={`/${project.id}`}> <img src={project.url} alt={project.name} /> <h5>{project.name}</h5> </div> ))} </div> </Col> </Row> <div className="d-flex justify-content-end"> <Button variant="primary" type="submit"> Send</Button> </div> </Form> </Col> </Row> </Container> </div> ) } export default Dashboard |
Javascript array object Posted: 21 Sep 2021 08:21 AM PDT How to store an array to a object like const obj = Iq2Lbqy660Nh_RP4z9jUhPZ1CZw; const arr = ['Peter','Tony','Rahul']; const obj = [{"name":'Peter', "age":19},{"name":'Tony', "age":20},{"name":'Rahul',"age":25}]; |
Cannot setfocus to control after subform requery Posted: 21 Sep 2021 08:21 AM PDT I have a simple form with a subform. In the main form is a field for the user to scan a UPC code. The UPC is found in the recordset then the subform is requeried to display the scanned item. The last command in the sub sets focus back to the UPC field in the main form for the next scan. Everything works except for setfocus. Tried decompile & C/R also imported all to new db. Dim db As Database Dim rstManifest As Recordset Dim strUPC As String Dim strLotNum As String Dim strCriteria As String Set db = CurrentDb Set rstManifest = db.OpenRecordset("tblManifest", dbOpenDynaset) strUPC = Me.UPCScan strLotNum = Me.LotNum strCriteria = "[UPC] = '" & strUPC & "' And [Scanned] = False" With rstManifest .MoveFirst .FindFirst strCriteria If rstManifest.NoMatch Then MsgBox "UPC Item " & strUPC & " not found", vbOKOnly, "Try Again" GoTo Cleanup Else .Edit !LotNum = Me.LotNum !DateItemAdded = Now() !Scanned = True .Update Me!Manifest.Form.Requery End If End With Cleanup: If IsNull(Me.LotNum Or Me.LotNum = "") Then Me.LotNum = strLotNum End If Me!UPCScan = Null Me.UPCScan.SetFocus 'This line does not work 'DoCmd.GoToControl "UPCScan" 'Does not work either rstManifest.Close Set rstManifest = Nothing Set db = Nothing |
Angular - ERROR TypeError: Cannot read properties of undefined (reading 'vehicle_image') Posted: 21 Sep 2021 08:21 AM PDT In my Angular-12 project I am trying to edit data that has image. The code is shown below: interface: export class VehicleResponse { results!: { vehicle: IVehicle }; } export interface IVehicle { id?: number; registration_number: string; vehicle_image?: any; } service: getVehicleById(id: number): Observable<VehicleResponse> { return this.http.get<VehicleResponse>(this.api.baseURL + 'vehicles/fetchbyid/' + id, this.httpOptions); } public updateVehicle(id: number, data: any) { return this.http.post(this.api.baseURL + 'vehicles/update/' + id, data, this.httpOptions1); } component import { IVehicle, VehicleResponse } from 'src/app/models/vehicle.model'; import { VehicleService } from 'src/app/services/vehicle.service'; editForm!: FormGroup; vehicle!: IVehicle; vehicledata!: IVehicle; isLoading = false; data: any; isSubmitted = false; _id!: number; vehicleImageDirectoryPath: any = this.api.imageURL + 'vehicle_images/'; url = ''; files ? : any; constructor( private fb: FormBuilder, private router: Router, private api: ApiService, private route: ActivatedRoute, private store: Store < AppState > , private vehicleService: VehicleService ) {} onSelectFile(event: any) { if (event.target.files && event.target.files[0]) { var reader = new FileReader(); reader.readAsDataURL(event.target.files[0]); // read file as data url this.files = event.target.files[0]; // associates the file to the a different property reader.onload = (event: any) => { // called once readAsDataURL is completed // console.log(event); this.url = event.target.result; } } } editVehicle() { this.editForm = this.fb.group({ registration_number: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]], vehicle_image: ['', [ RxwebValidators.extension({ extensions: ["jpg", "jpeg", "bmp", "png", "gif", "svg"] }) ]] }); } loadVehicleById() { this.vehicleService.getVehicleById(this._id) .subscribe( (data: VehicleResponse) => { this.vehicledata = data.results.vehicle; this.editForm.patchValue({ registration_number: this.vehicledata.registration_number, vehicle_image: this.vehicledata.vehicle_image, }); this.isLoading = false; } ); } ngOnInit(): void { this._id = this.route.snapshot.params['id']; bsCustomFileInput.init(); this.editVehicle(); this.loadVehicleById(); this.isLoading = false; } submitForm() { this.isSubmitted = true; // stop here if form is invalid if (this.editForm.invalid) { return; } this.isLoading = true; const formVehicleData = this.editForm.getRawValue(); const formData = new FormData(); formData.append('registration_number', formVehicleData.registration_number); if (this.files) { formData.append("vehicle_image", this.files, this.files.name); } this.vehicleService.updateVehicle(this._id, formData).subscribe(res => { this.data = res; }); } <div class="card-body"> <form [formGroup]="editForm" (ngSubmit)="submitForm()"> <div class="col-lg-4"> <div class="form-group"> <label for="registration_number">Registration No.:<span style="color:red;">*</span></label> <input type="text" formControlName="registration_number" placeholder="XB-547-AG" class="form-control" required/> </div> <div *ngIf="isSubmitted || (fc.registration_number.touched && fc.registration_number.invalid)"> <div *ngIf="fc.registration_number.hasError('required')"> <div class="text-danger"> Registration Number is required! </div> </div> <div *ngIf="fc.registration_number.hasError('minlength')"> <div class="text-danger"> Registration Number cannot be less than 2 characters! </div> </div> <div *ngIf="fc.registration_number.hasError('maxlength')"> <div class="text-danger"> Registration Number cannot be more than 50 characters! </div> </div> </div> </div> <div class="col-lg-4"> <div class="form-group"> <label for="vehicle_image">Vehicle Image:</label> <div class="card-body box-profile"> <div class="text-center"> <img class="profile-user-img img-fluid img-circle" [src]="vehicledata.vehicle_image ? vehicleImageDirectoryPath+vehicledata.vehicle_image : url || 'assets/img/no-image.png'" alt="No Vehicle Image" onerror="this.src='assets/img/no-image.png'" style="height:150px; width:150px"> </div> <div class="form-group"> <input formControlName="vehicle_image" id="vehicle_image" type="file" class="form-control" accept=".jpg,.jpeg,.bmp,.png,.gif,.svg" (change)="onSelectFile($event)"> <div *ngIf="fc.vehicle_image.touched && fc.vehicle_image.invalid"> <div *ngIf="fc.vehicle_image.hasError('extension')"> <div class="text-danger"> Enter valid File Type! </div> </div> </div> </div> </div> </div> </div> <div class="card-footer"> <button type="submit" class="btn btn-success" [disabled]="isLoading" class="btn btn-success" (click)="editValidate()"> <span *ngIf="isLoading" class="spinner-border spinner-border-sm mr-1"></span> <i class="fa fa-save" aria-hidden="true"></i> Save</button> </div> </form> </div> While trying to retrieve and view the data before I eventually update, I got this error: ERROR TypeError: Cannot read properties of undefined (reading 'vehicle_image') at VehicleEditComponent_Template (vehicle-edit.component.html:245) It highlights this page: [src]="vehicledata.vehicle_image ? vehicleImageDirectoryPath+vehicledata.vehicle_image : urlVehicle || 'assets/img/no-image.png'" But the registration_number was displayed. vehicle_image exists. Could it be because the image is null? How do I resolve this? Thanks |
What mistake am I doing in my multiplication program? [closed] Posted: 21 Sep 2021 08:21 AM PDT There's a question in my book to create a multiplication game. I tried my best, but there is an error. Please help me figure it out, so I can't repeat the mistake. The image of my code error is below. from random import randint mark=0 NumberOfTimes10 = eval(int(input('How many questions do you want ? '))) for i in range(NumberOfTimes10): a=randint(1,10) b=randint(1,10) question= (input('Question', i4+1, ': ', a,'x', b) if question==a*b]: # <- SyntaxError on ":" character. print('Right!') mark=mark+1 else: print('Wrong! The answer is', a*b) print('You scored', mark) |
why won't discord chatbot in javascript respond? Posted: 21 Sep 2021 08:21 AM PDT I am working on this simple chatbot following the discord tutorial. The chatbot has logged in to my server... I type in the chat room on Discord 'ping,' but the chatbot does not respond "Pong" as it should. Below is the main,js code: const { Client, Intents } = require('discord.js'); const client = new Client({ intents: [Intents.FLAGS.GUILDS] }); client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); }); client.on('interactionCreate', async interaction => { if (!interaction.isCommand()) return; if (interaction.commandName === 'ping') { console.log("we got a hello!") await interaction.reply('Pong!'); } }); client.login('token'); NOTE: I have a secret token where it has 'token' in my Terminal it says Logged in as Quote.it#4979! and my bot is online when I view it in the server in Discord. But nothing happens when in discord I write in 'ping' Any way I can better diagnose what is going on? Thank you |
AKS File Share Persistent Mounting with Managed Identity - Having issue after key Rotation Posted: 21 Sep 2021 08:21 AM PDT Mounted Azure File shares in AKS deployments using Cluster UAMI with Reader & Storage account key operator service role. It was successfully mounted in all the POD replicas and able to create the files/list all the files of Azure file share from a pod. But, it is not working after key rotation. Also, I tried to create new deployment, storage class, PVC. Still, facing permission issues while PODs are getting created. Stage 1: (First Time Process) - Created AKS Cluster, Storage File share, User managed Identity.
- Assigned the UAMI to Cluster and provided the Reader & Storage account key operator service roles in new storage scope.
- Created new Custom Storage class, PVC, deployments. Result: All functionalities were working as expected.
Stage 2: (Failure Process) - Created new deployment after key rotation as existing PODs were unable to access the Azure File Share. Permission issue.
- Then, Created new Storage Class/PVC/deployment - Still same permission issue.
Error: default 13s Warning FailedMount pod/myapp-deploymentkey1-67465fb9df-9xcrz MountVolume.SetUp failed for volume "xx" : mount failed: exit status 32 Mounting command: mount Mounting arguments: -t cifs -o file_mode=0777,dir_mode=0777,vers=3.0,actimeo=30,mfsymlinks,<masked> //{StorageName}.file.core.windows.net/sample1 /var/lib/kubelet/pods/xx8/volumes/kubernetes.io~azure-file/pvc-cxx Output: mount error(13): Permission denied Refer to the mount.cifs(8) manual page (e.g. man mount.cifs) default 13s Warning FailedMount pod/myapp-deploymentkey1-67465fb9df-jwmcc MountVolume.SetUp failed for volume "xx" : mount failed: exit status 32 Mounting command: mount Mounting arguments: -t cifs -o file_mode=0777,dir_mode=0777,vers=3.0,actimeo=30,mfsymlinks,<masked> //{StorageName}.file.core.windows.net/sample1 /var/lib/kubelet/pods/xxx/volumes/kubernetes.io~azure-file/pvc-xx Output: mount error(13): Permission denied |
How to dynamically assign values to a list using groovy Posted: 21 Sep 2021 08:21 AM PDT I would like to assign values to a list variable based on some changes in my repo. I have a repo named school. Within the school repo, I have subdirectories for students, teachers, courses and rooms. I want to be able to detect changes in these subdirectories like: ... if (lastCommit){ changedStudents = sh (script: "git diff --name-only \"$currentCommit"\ \"^$lastCommit\" | grep \"students/.*\" |wc -l", returnStdout: true) changedTeachers = sh (script: "git diff --name-only \"$currentCommit"\ \"^$lastCommit\" | grep \"teachers/.*\" |wc -l", returnStdout: true) changedCourses = sh (script: "git diff --name-only \"$currentCommit"\ \"^$lastCommit\" | grep \"courses/.*\" |wc -l", returnStdout: true) changedRooms = sh (script: "git diff --name-only \"$currentCommit"\ \"^$lastCommit\" | grep \"rooms/.*\" |wc -l", returnStdout: true) if (!changedStudents.equals("0")||!changedTeachers.equals("0")){ changedCourses = "1" changedRooms = "1" } }else { changedCourses = "1" changedRooms = "1" } ... ... if(!changedCourses.equals("0")){ Do something } if(!changedRooms.equals("0")){ Do another thing } ... What I am trying to achieve is to rewrite the above such that instead of assigning changedCourses = "1" and changedRooms = "1" , I would like to add Courses and Rooms to a list and then loop through that list. Below is what I have managed to write but it doesn't account for the changes in the repo. def mySchool = ["courses", "rooms"] for (item in mySchool){ if (item =="courses"){ println("Do something") } else if ((item =="teachers"){ println("Do another thing")) ... } I am struggling with how to achieve the list based on the repo changes. Please help. |
How to understand "useBox" in react-three-fiber Posted: 21 Sep 2021 08:21 AM PDT I'm interested in learning how to create dynamic objects and group them together entirely in react/JavaScript. I'm looking at the chair and table in this example as my model: https://codesandbox.io/s/ragdoll-physics-forked-bntr9 At this point, I'm not as concerned about the "physics" but just how to create the three object such as a table that consist of 5 3D-Rectangles. I downloaded the above example, and this is the code for the table: function Table() { const [seat] = useBox(() => ({ type: 'Static', position: [9, -0.8, 0], args: [2.5, 0.25, 2.5] })) const [leg1] = useBox(() => ({ type: 'Static', position: [7.2, -3, 1.8], args: [0.25, 2, 0.25] })) const [leg2] = useBox(() => ({ type: 'Static', position: [10.8, -3, 1.8], args: [0.25, 2, 0.25] })) const [leg3] = useBox(() => ({ type: 'Static', position: [7.2, -3, -1.8], args: [0.25, 2, 0.25] })) const [leg4] = useBox(() => ({ type: 'Static', position: [10.8, -3, -1.8], args: [0.25, 2, 0.25] })) return ( <> <Box scale={[5, 0.5, 5]} ref={seat} /> <Box scale={[0.5, 4, 0.5]} ref={leg1} /> <Box scale={[0.5, 4, 0.5]} ref={leg2} /> <Box scale={[0.5, 4, 0.5]} ref={leg3} /> <Box scale={[0.5, 4, 0.5]} ref={leg4} /> <Suspense fallback={null}> <Mug /> </Suspense> </> ) } And at the top of the program I see this: import { Physics, useBox, useCompoundBody, useCylinder, useSphere, usePlane, useConeTwistConstraint, usePointToPointConstraint } from '@react-three/cannon' Googling react-three/cannon took me to https://opensourcelibs.com/lib/use-cannon, and the "github" link took me to https://github.com/pmndrs/use-cannon, which I downloaded. Is there a document to the "useBox", or do I have just have to read code to figure out how it works? Without some doc, I can only do controlled variations, for example, suppose I just want to make the table legs longer, or the table top bigger? I don't understand what joins the legs to the table, but I figure it must be the position or args: I tried changing 1.8 to 2.8 as follows: from const [leg1] = useBox(() => ({ type: 'Static', position: [7.2, -3, 1.8], args: [0.25, 2, 0.25] })) to const [leg1] = useBox(() => ({ type: 'Static', position: [7.2, -3, 2.8], args: [0.25, 2, 0.25] })) and I could see the leg come out from the table top. I knew all table legs had equal length, so I tried changing some number that was the same for all four legs (then later noticed two had 1.l8 and two had -1.8). I'm also guess that some set of three parameters must be length, width, height. Then I tried changing: <Box scale={[0.5, 4, 0.5]} ref={leg1} /> <Box scale={[0.5, 4, 0.5]} ref={leg2} /> to <Box scale={[0.5, 6, 0.5]} ref={leg1} /> <Box scale={[0.5, 6, 0.5]} ref={leg2} /> And that deed indeed length two legs, but up through the top of the table. So bottom line question is not how to do change the length of the legs, but how to find the documentation. I searched the pmndrs library for "useBox", and see a many many matches: I looked at the sources\hooks.ts and found this, which doesn't help me at all: export function useBox(fn: GetByIndex<BoxProps>, fwdRef: Ref<Object3D> = null, deps?: DependencyList) { const defaultBoxArgs: Triplet = [1, 1, 1] return useBody('Box', fn, (args = defaultBoxArgs): Triplet => args, fwdRef, deps) } |
QML ListView: Binding loop detected for property "height" Posted: 21 Sep 2021 08:21 AM PDT I have a QML ListView, and I'm trying to dynamically add elements to it. I want the background rectangle to also scale dynamically as elements are added/removed from the ListView. Right now I get a binding loop, and I understand what they are but I can't figure out where it's coming from. I played around changing the code a bit and I was able to get rid of the binding loop one time but then the ListView couldn't be scrolled. Anyone have any ideas? import QtQuick 2.15 import QtQuick.Window 2.0 Window { visible: true width: 800 height: 800 Rectangle { id: listContainer height: childrenRect.height width: parent.width color: "transparent" anchors { top: parent.top topMargin: 30 left: parent.left leftMargin: 45 } ListView { anchors.top: parent.top anchors.left: parent.left anchors.right: parent.right model: myModel height: childrenRect.height header: Text { z: 2 height: 50 text: "HEADER" color: "black" } delegate: Component { Item { Text { id: userName; text: name; color: "black"; font.pixelSize: 50 anchors { left: parent.left leftMargin: 20 } } Rectangle { height: 1 color: 'black' width: listContainer.width anchors { left: userName.left top: userName.top topMargin: - 12 leftMargin: -15 } } } } spacing: 80 } } ListModel { id: myModel } /* Fill the model with default values on startup */ Component.onCompleted: { for (var i = 0; i < 100; i++) { myModel.append({ name: "Big Animal : " + i }) } } } EDIT: As suggested by @Aditya, the binding loop can be removed by having a static ListView height, but I don't want it to be that way. I'm using the rectangle as a background for the ListView and I want it to scale according to the ListView. For example, if I only add two elements, I want the rectangle to also scale for those two elements and not cover the entire screen. This causes a problem: import QtQuick 2.15 import QtQuick.Window 2.0 Window { visible: true width: 800 height: 800 Rectangle { id: listContainer height: childrenRect.height width: parent.width color: "yellow" anchors { top: parent.top topMargin: 30 left: parent.left leftMargin: 45 } ListView { anchors.top: parent.top anchors.left: parent.left anchors.right: parent.right model: myModel height: 800//childrenRect.height header: Text { z: 2 height: 50 text: "HEADER" color: "black" } delegate: Component { Item { Text { id: userName; text: name; color: "black"; font.pixelSize: 50 anchors { left: parent.left leftMargin: 20 } } Rectangle { height: 1 color: 'black' width: listContainer.width anchors { left: userName.left top: userName.top topMargin: - 12 leftMargin: -15 } } } } spacing: 80 } } ListModel { id: myModel } /* Fill the model with default values on startup */ Component.onCompleted: { for (var i = 0; i < 2; i++) { myModel.append({ name: "Big Animal : " + i }) } } } I also tried separating the header from ListView into a different component and anchoring the listview below it and that worked. The only problem was it could not be scrolled with the listview. Worst case, I could make a scrolling animation for it but that seems like an inefficient solution and I'd like to know why this doesn't work. |
Drive API Update: Posted: 21 Sep 2021 08:21 AM PDT |
Visualize an SVG using Plotly Python Posted: 21 Sep 2021 08:21 AM PDT I'm trying to visualize an image on a plotly plot using px.imshow(). Is it possible to pass in a svg for this rather than an image array? Thanks in advance. |
Join on max value in SQL Posted: 21 Sep 2021 08:21 AM PDT I have been trying to join based on max column values of a table Here is my table structure Table A: | ID | Val | text | | 1 | 423 | tuh | | 2 | 369 | foo | | 3 | 568 | bars | | 4 | 789 | ther | Table B: | Val | Label | | 423 | Adria | | 369 | Adria | | 568 | Adria | | 789 | Bang | Table C: | Label | Val | | Adria | 100 | | Fox | 123 | | Bang | 789 | I have tried this query and for some reason I still do not get the result based on max val in table A select C.Label, A.txt from C join B on B.Label = C.Label left join A on A.Val = B.Val and A.Val = (select max(A.Val) from A as a where a.Val = A.val) where C.Lable = 'Adria' Output: Adria tuh Adria foo Adria bars Expected Output: Adria bars Could someone please help point out what am I missing? |
Jest error on upgrading to latest version - a worker process has failed to exit gracefully Posted: 21 Sep 2021 08:21 AM PDT I recently updated my jest package to the latest version from v24 and on running my unit tests, I am getting this at the end of test suite run: A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --runInBand --detectOpenHandles to find leaks. I added --detectOpenHandles with my test command and the messages goes in the next run. I am not sure how to take it as detectOpenHandles is intended for finding the open handles and not fixing it so how is the message not coming in next run and no other message to guide me on what could be the issue. Has anyone came across similar bhaviour? To add, I am on latest version of jest i.e 27.2.0 now. |
How to load CSS Asynchronously without Inline Scripts (comply with CSP) Posted: 21 Sep 2021 08:21 AM PDT I want to implement Asynchronously loading CSS files for faster performance. However I want security too, so I want my site to have CSP. <link rel="stylesheet" media="print" class="AOcssLoad" .... onload="this.onload=null;this.media='all';" /> Without going into details it wants me to avoid things like onload and many other JS that are part of elements. I want it to look like this <link rel="stylesheet" media="print" class="AOcssLoad" href="" /> Please suggest a way to achieve Asynchronous CSS files without inline JS as used above. We can use inline <script> tags or seperate JS files. I tried the below code as an inline JS.. Below is the HTML for the JS, <script nonce="" type="text/javascript" data-exclude="true"> var Script = document.getElementsByClassName("AOcssLoad"); for (var i = 0 ; i < Script.length; i++) { this.className += " Loading"; Script[i].addEventListener("load", function({ this.onload=null;this.media="all"; this.className += " OnLoad"; }); } </script> While it works, it's highly unreliable. I cannot comprehend the problem, but I shall say it works only 50% of the times, sometimes just reloading the page can solve/break the problem, with no apparent change to css/html/cache as such. Please help me improve on this, or build a better approach for it. Edit: As Suggested in Comments I tried different methods, including the links to other resources from GitHub. Those methods are unreliable I would say they work less than 50% of times. However I tried to use jQuery(document).ready() and add media="all" to all the css files, but that increases TBT (Total Blocking Time) thus impacting my site performance |
Turtle crashes while playing music with playsound2 Posted: 21 Sep 2021 08:21 AM PDT I have simple python turtle code which works fine, but when I add music, music plays, but turtle program crashes. What are the fixes for that? Here is my code: import turtle import playsound2 t = turtle.Turtle() playsound2.playsound("song.mp3") t.forward(50) turtle.mainloop() |
How to convert every page of pdf to a pdf object using python Posted: 21 Sep 2021 08:21 AM PDT I want to create each page of a pdf file to a new pdf object. I am following the mentioned code snippet https://stackoverflow.com/a/490203/13291630 but here it is shown as the creation of a new file, but I want to just create a pdf object without creating a new file and just use that created pdf object as every other pdf. I hope this information helps, Can anyone help me out here. |
How can I display a message or loading animation while flask.send_from_directory is processing? Posted: 21 Sep 2021 08:21 AM PDT I have a simple web application that calls the Spotify API, and, among other things, allows a user to download their "Liked Songs". The 'download' view writes a csv file of the 'Liked Songs' to a tmp directory and then downloads that file using flask.send_from_directory. @bp.route('/download', methods=['GET']) @login_required def download(): ... # Edited with more details below return send_from_directory( temp_dir, target[0], as_attachment=True, attachment_filename=file_name ) It all works as intended but can take a while if a user has many thousands of Liked Songs. During that 20+ seconds I would like to give the user some feedback that the task is processing -- a message or loading animation. I have written a loading animation used elsewhere in my site, but in those cases the view ends with a redirect. I also can reveal a modal with javascript. However, a modal or animation will not automatically close when the "Open Liked Songs.csv" window pops up asking the user to "Open" or "Save", nor after one of those is selected (i.e., when the download view is completed). Is there a way to trigger an event in the Browser Object Model using the window object for the "Open Liked Songs.csv" pop-up window? I do not know how to identify that specific window. Any other suggestions? UPDATE: Thanks to @v25 I realize more details are needed. Here is my code again: @bp.route('/download', methods=['GET']) @login_required def download(backup=False): ... if backup: # For download of 'Liked Songs' playlist_id = '000library' file_name = 'Liked Songs.csv' url = get_endpoint("get-user-saved-tracks") query_limit = 50 count = 0 tracks = [] # The Spotify endpoint is limited at maximum of 50 # so I need to iterate with offsets. # I think this is what is causing the delay. while not len(tracks) % query_limit: params["limit"] = query_limit params["offset"] = query_limit * count section = sh.get_playlist_tracks(header, url, **params) tracks += section["items"] count += 1 if not tracks: flash("Something went wrong. We couldn't get your playlist.") return redirect(url_for('routes.profile')) with NamedTemporaryFile( mode='w+t', encoding='utf8', newline='', prefix=playlist_id + '.', dir=temp_dir, delete=False, ) as csvfile: ... # Writes csv file to temp directory ... return send_from_directory( temp_dir, target[0], as_attachment=True, attachment_filename=file_name ) When I monitor this process with my browser's (FireFox) dev tools 'Network' tab, I can see that it takes a while before status code 200 is returned for my '/download' request. At that point the 'Open Liked Songs.csv' window appears. I think I need some way to trigger my javascript closeModal() when status 200 is returned (polling?). As @v25 suggests below, I am pretty sure it is the iteration of 50-track chunks at the Spotify API that is slowing this down. |
ESLint: Parsing error: This experimental syntax requires enabling one of the following parser plugin(s): 'jsx, flow, typescript' (2:9) Posted: 21 Sep 2021 08:21 AM PDT I am trying to use eslint in webstorm, but it doesn't work and displays an error:ESLint: Parsing error: This experimental syntax requires enabling one of the following parser plugin(s): 'jsx, flow, typescript' (2:9). Here is my .eslintrc and package.json settings. What should I do for fixing the error? package.json { "name": "raonair-frontend", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.11.4", "@testing-library/react": "^11.1.0", "@testing-library/user-event": "^12.1.10", "eslint-config-react-app": "^6.0.0", "react": "^17.0.2", "react-dom": "^17.0.2", "react-router-dom": "^5.2.0", "react-scripts": "4.0.3", "web-vitals": "^1.0.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "prepare": "husky install" }, "parser": "babel-eslint", "eslintConfig": { "extends": [ "react-app", "airbnb", "plugin:flowtype/recommended" ], "plugins": [ "flowtype" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "@babel/eslint-parser": "^7.15.0", "@babel/eslint-plugin": "^7.14.5", "@babel/plugin-syntax-jsx": "^7.14.5", "eslint": "^7.32.0", "eslint-config-airbnb": "^18.2.1", "eslint-config-prettier": "^8.3.0", "eslint-plugin-flowtype": "^5.9.0", "eslint-plugin-import": "^2.23.4", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-react": "^7.24.0", "eslint-plugin-react-hooks": "^4.2.0", "husky": "^7.0.1", "prettier": "^2.3.2" } } .eslintrc { "env": { "browser": true, "node": true }, "extends": [ "airbnb", "airbnb/hooks", "prettier" ], "parser": "@babel/eslint-parser", "parserOptions": { "sourceType": "module", "allowImportExportEveryWhere": false, "ecmaFeatures": { "globalReturn": false, "jsx": true }, "ecmaVersion": 2020, "babelOptions": { "configFile": "./babel.config.js" } }, "plugins": [ "jsx-a11y", "react-hooks", "@babel/", "flowtype", "import" ], "rules": { "import/no-anonymous-default-export": "off", "import/no-extraneous-dependencies": "off", "import/order": [ "error", { "groups": [ "builtin", "external", "internal", "parent", "sibling" ], "newlines-between": "always", "alphabetize": { "order": "asc", "caseInsensitive": false } } ], "import/prefer-default-export": "off", "indent": [ "error", 2, { "SwitchCase": 1 } ], "jsx-a11y/anchor-is-valid": "off", "no-console": "error", "no-unused-vars": "error", "react/jsx-props-no-spreading": "off", "react/react-in-jsx-scope": "off" }, "settings": { "import/resolver": { "typescript": {} }, "insert_final_newline": true } } |
Arabic Date is not showing in Laravel using Carbon Posted: 21 Sep 2021 08:21 AM PDT i want to show date and days in Arabic format using Carbon. but it's showing in English. Carbon::setlocale("ar"); echo Carbon::parse()->format('D d F Y'); Result: Sun 12 May 2019 Expected result: it should show day and month in arabic. |
ERROR 1698 (28000): Access denied for user 'root'@'localhost' Posted: 21 Sep 2021 08:21 AM PDT I'm setting up a new server and keep running into this problem. When I try to log into the MySQL database with the root user, I get the error: ERROR 1698 (28000): Access denied for user 'root'@'localhost' It doesn't matter if I connect through the terminal (SSH), through phpMyAdmin or a MySQL client, e.g., Navicat. They all fail. I looked in the mysql.user table and get the following: +------------------+-------------------+ | user | host | +------------------+-------------------+ | root | % | | root | 127.0.0.1 | | amavisd | localhost | | debian-sys-maint | localhost | | iredadmin | localhost | | iredapd | localhost | | mysql.sys | localhost | | phpmyadmin | localhost | | root | localhost | | roundcube | localhost | | vmail | localhost | | vmailadmin | localhost | | amavisd | test4.folkmann.it | | iredadmin | test4.folkmann.it | | iredapd | test4.folkmann.it | | roundcube | test4.folkmann.it | | vmail | test4.folkmann.it | | vmailadmin | test4.folkmann.it | +------------------+-------------------+ As you can see, user root should have access. The Server is quite simple, as I have tried to troubleshoot this for a while now. It's running Ubuntu 16.04.1 LTS (Xenial Xerus) with Apache, MySQL and PHP, so that it can host websites, and iRedMail 0.9.5-1, so that it can host mail. Log into the MySQL database works fine before I installed iRedMail. I also tried just installing iRedMail, but then root also doesn't work. How can I fix my MySQL login problem or how can I install iRedMail over an existing MySQL install? And yes, I tried the Installation Tips and I can't find those variables in the configuration files. |
current/duration time of html5 video? Posted: 21 Sep 2021 08:21 AM PDT I need a way of getting the total time length of the video and the current time with jquery and displaying it in a couple of <div> tags. <div id="current">0:00</div> <div id="duration">0:00</div> I've been searching all day and I know how to get them I just can't display them. #jquerynoob |
Calculating Time Difference Posted: 21 Sep 2021 08:21 AM PDT at the start and end of my program, I have from time import strftime print int(strftime("%Y-%m-%d %H:%M:%S") Y1=int(strftime("%Y")) m1=int(strftime("%m")) d1=int(strftime("%d")) H1=int(strftime("%H")) M1=int(strftime("%M")) S1=int(strftime("%S")) Y2=int(strftime("%Y")) m2=int(strftime("%m")) d2=int(strftime("%d")) H2=int(strftime("%H")) M2=int(strftime("%M")) S2=int(strftime("%S")) print "Difference is:"+str(Y2-Y1)+":"+str(m2-m1)+":"+str(d2-d1)\ +" "+str(H2-H1)+":"+str(M2-M1)+":"+str(S2-S1) But when I tried to get the difference, I get syntax errors.... I am doing a few things wrong, but I'm not sure what is going on... Basically, I just want to store a time in a variable at the start of my program, then store a 2nd time in a second variable near the end, then at the last bit of the program, compute the difference and display it. I am not trying to time a function speed. I am trying to log how long it took for a user to progress through some menus. What is the best way to do this? |
E-Techbytes: Recent Questions - Stack Overflow >>>>> Download Now
ReplyDelete>>>>> Download Full
E-Techbytes: Recent Questions - Stack Overflow >>>>> Download LINK
>>>>> Download Now
E-Techbytes: Recent Questions - Stack Overflow >>>>> Download Full
>>>>> Download LINK