How can I compare two dates in Java? Posted: 25 Mar 2021 08:49 AM PDT In my Firebase database, for each item present, I save the date of when it is created and inserted into the db. The date is saved using the ServerValue.TIMESTAMP, the value is saved as a Map. How can I compare the saved value to today's current date in Java? enter image description here |
How resize a div height based on width with pure JavaScript Posted: 25 Mar 2021 08:49 AM PDT while resizing div change height based on width with constraint ratio @example div width:300 and height:600 next Ill change width to 400 height change to 800 based on width enter image description here |
Insert formatted content from HTML in Quill editor on load Posted: 25 Mar 2021 08:49 AM PDT I want to use Quill for writing articles on my website, however I may need to edit those articles at some point. To retrieve my formatted content from Quill and put it into the database, I call quill.root.innerHTML, and everything goes well. However, I'm struggling to find how I could get this HTML content, and then have it displayed in my Quill editor, formatted exactly as it was when I submitted it, when the page loads. Any help would be welcome, thanks in advance! |
Can't open the redirect page. (Twitter Firebase Auth with Vue) Posted: 25 Mar 2021 08:49 AM PDT I'm following this tutorial(+ code) to create a Twitter authentication for my web application. I'm trying to replicate the code but I'm using Vue 3, so I had to do some changes. When I call the signIn action the website tries to load some page but then it's redirecting me back to the main page instead of Twitter LogIn page or directly to the LoggedIn page. There are no errors which makes it even more difficult to figure out. Here's the code: (Login Page) <template> <button @click="signIn">Sign In with Twitter</button> </template> <script> export default { computed: { state() { return this.$store.state.user } }, methods: { signIn () { this.$store.dispatch('signIn') } } } </script> <style scoped> button { margin-top: 5rem; } </style> (Router) import { createWebHistory, createRouter } from 'vue-router'; import Home from '../views/Home.vue'; import Main from '../views/Main.vue'; import * as firebase from "firebase" const routes = [ { path: '/', name: 'Home', component: Home, }, { path: '/app', name: 'Main', component: Main, meta: { requiresAuth: true } }, ]; const router = createRouter({ routes, history: createWebHistory(), }); router.beforeEach((to, from, next) => { const currentUser = firebase.default.auth().currentUser; const requiresAuth = to.matched.some(record => record.meta.requiresAuth); if (requiresAuth && !currentUser) { next('/'); } else if (!requiresAuth && currentUser) { next('/app'); } else { next(); } }); export default router; (Store VueX) import {createStore} from 'vuex' import * as firebase from 'firebase' export const store = createStore({ state() { return { user: null } }, getters: { user(state) { return state.user } }, mutations: { SET_USER (state, payload) { state.user = payload }, LOGOUT (state) { state.user = null } }, actions: { autoSignIn({commit}, payload) { const newUser = { userDetails: payload.providerData } commit('SET_USER', newUser) }, signIn({commit}) { var provider = new firebase.default.auth.TwitterAuthProvider() firebase.default.auth().signInWithRedirect(provider) firebase.default.auth().getRedirectResult().then(result => { //User info console.log(result) var user = result.user commit('SET_USER', user) }).catch(error => { alert(error) return }) }, logout({commit}) { firebase.auth().signOut().then(() => commit('LOGOUT')) .catch((error) => { alert(error) return }) } } }) Any help would be appreciated, Sincerely, Kirill |
Dart, Cloud functions and null safety Posted: 25 Mar 2021 08:49 AM PDT I currently have some code deployed as a cloud function, this code is written in Dart. For this to work I have an index.dart where I call this function in void main() functions["calculate"] = functions.region('europe-west3').https.onRequest(calc); Then I have this as the build.yaml targets: $default: sources: - node/** - lib/** builders: build_node_compilers|entrypoint: options: compiler: dart2js And this is my dependency list name: functions version: 1.0.0 environment: sdk: ">=2.12.2 <3.0.0" dependencies: firebase_functions_interop: ^1.0.2 dev_dependencies: build_runner: ">=1.10.0 <1.11.0" build_node_compilers: any When I want to build my dart code to Javascript code I run: flutter pub run build_runner build -o node:build But this result in Dart2Js finished with: packages/js/js.dart:20:15: Error: Null safety features are disabled for this library. final String? name; ^ packages/path/path.dart:100:4: Error: Null safety features are disabled for this library. Uri? _currentUriBase; ^ packages/path/path.dart:106:7: Error: Null safety features are disabled for this library. String? _current; ^ packages/path/path.dart:120:16: Error: Null safety features are disabled for this library. [String? part2, ^ packages/path/path.dart:121:15: Error: Null safety features are disabled for this library. String? part3, ^ packages/path/path.dart:122:15: Error: Null safety features are disabled for this library. String? part4, ... I tried adding @// @dart=2.9 in the file where my void main() is located, I tried building with flutter pub run --no-sound-null-safety build_runner build -o node:build and dart --no-sound-null-safety run build_runner build -o node:build All with no results... Also lowering my sdk version in the pubspec doesn't fix the issue! Anybody here that can help me? Thanks in advance! |
Next JS rewrites not being applied in getServerSideProps Posted: 25 Mar 2021 08:49 AM PDT I'm having a problem with rewrites in getServerSideProps in Next JS. I have the following rewrite in next.config.js : module.exports = { async rewrites() { return [ { source: "/api/:path*", destination: "http://localhost:5000/api/:path*", }, ]; }, }; This works everywhere, except for in getServerSideProps , where it doesn't get recognized. // axios instance used throughout the app const axios = axios.create({ baseURL: "/api", }); // checkout.tsx export async function getServerSideProps(context) { const res = await axios.get("/cart"); return {props: {data: res.data}} } That gives me the following error: Error: connect ECONNREFUSED 127.0.0.1:80 The _currentUrl from axios is http:/api/cart when I checked it. Is there any reason that my rewrites is only failing in getServerSideProps ? |
Problème avec le user sur mes realisation sur EasyAdmin Posted: 25 Mar 2021 08:49 AM PDT Bonjour a tous, voila je suis sur du symfony5. Je créer le coté admin de mon site avec un bundle EasyAdmin v3. Mon probleme arrive quand j'essaie d'ajouter une réalisations il me met ce message d'erreur enter image description here Il me dis que mon user ne peut pas etre null, mais le souci c'est que j'essaie d'ajouter une realisation avec le compte admin donc j'aimerais qu'il prennent en compte que je sois connecte en admin et me mettre la realisation depuis ce compte. Je vous mets mes code Mon entité realisation <?php namespace App\Entity; use App\Repository\RealisationRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\HttpFoundation\File\File; use Vich\UploaderBundle\Mapping\Annotation as Vich; /** * @ORM\Entity(repositoryClass=RealisationRepository::class) * @Vich\Uploadable */ class Realisation { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $nom; /** * @ORM\Column(type="datetime") */ private $createdAt; /** * @ORM\Column(type="datetime", nullable=true) */ private $dateRealisation; /** * @ORM\Column(type="text") */ private $description; /** * @ORM\Column(type="boolean") */ private $portfolio; /** * @ORM\Column(type="string", length=255) */ private $slug; /** * @ORM\Column(type="string", length=255) */ private $file; /** * @var File * @Vich\UploadableField(mapping="Realisation",fileNameProperty="file") */ private $imageFile; /** * @ORM\ManyToOne(targetEntity=User::class, inversedBy="realisations") * @ORM\JoinColumn(nullable=false) */ private $user; /** * @ORM\ManyToMany(targetEntity=Categorie::class, inversedBy="realisations") */ private $categorie; public function __construct() { $this->categorie = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getNom(): ?string { return $this->nom; } public function setNom(string $nom): self { $this->nom = $nom; return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt): self { $this->createdAt = $createdAt; return $this; } public function getDateRealisation(): ?\DateTimeInterface { return $this->dateRealisation; } public function setDateRealisation(?\DateTimeInterface $dateRealisation): self { $this->dateRealisation = $dateRealisation; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getPortfolio(): ?bool { return $this->portfolio; } public function setPortfolio(bool $portfolio): self { $this->portfolio = $portfolio; return $this; } public function getSlug(): ?string { return $this->slug; } public function setSlug(string $slug): self { $this->slug = $slug; return $this; } public function getFile(): ?string { return $this->file; } public function setFile(string $file): self { $this->file = $file; return $this; } public function getUser(): ?User { return $this->user; } public function setUser(?User $user): self { $this->user = $user; return $this; } /** * @return Collection|Categorie[] */ public function getCategorie(): Collection { return $this->categorie; } public function addCategorie(Categorie $categorie): self { if (!$this->categorie->contains($categorie)) { $this->categorie[] = $categorie; } return $this; } public function removeCategorie(Categorie $categorie): self { $this->categorie->removeElement($categorie); return $this; } /** * @return File */ public function getImageFile(): ?File { return $this->imageFile; } /** * @param File $imageFile */ public function setImageFile(?File $imageFile = null) { $this->imageFile = $imageFile; if(null !== $imageFile){ $this->dateRealisation = new \DateTime(); } } } Mon realisationCrudController <?php namespace App\Controller\Admin; use App\Entity\Realisation; use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController; use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField; use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField; use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField; use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField; use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField; use EasyCorp\Bundle\EasyAdminBundle\Field\TextField; use EasyCorp\Bundle\EasyAdminBundle\Field\TextEditorField; use EasyCorp\Bundle\EasyAdminBundle\Field\IdField; use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField; use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Validator\Constraints\DateTime; use Vich\UploaderBundle\Form\Type\VichFileType; class RealisationCrudController extends AbstractCrudController { public static function getEntityFqcn(): string { return Realisation::class; } public function configureFields(string $pageName): iterable { return [ IntegerField::new('id','ID')->onlyOnIndex(), TextField::new('nom'), TextEditorField::new('description'), DateTimeField::new('createdAt'), DateTimeField::new('dateRealisation'), TextField::new('slug'), BooleanField::new('portfolio'), TextareaField ::new('imageFile') ->setFormType(VichFileType::class) ->setLabel('Image'), ]; } } enter image description here Merci de votre aide |
Angular // component with chart (from chart js) not displayed until I refresh the page Posted: 25 Mar 2021 08:49 AM PDT I'm working on an Angular (11) project and I'm stucked on that attempt: In my application there is a sidebar menu and when I click on a menu item the routerLink send me on details component page. This details component page had another component inside that is a chart made with chart js (it's the linebar.component.ts). My problem is that when I click on my menu item and the details component is displayed, the linebar component will be not desplayed at all until i REFRESH the page. I think this is due to the async nature of the API. Anyone have some idea how to solve it? details.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { DetailsNavbarItemsService } from '../details-navbar-items.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-details', templateUrl: './details.component.html', styleUrls: ['./details.component.scss'] }) export class DetailsComponent implements OnInit { collapsed = true; data: any; id= this.router.snapshot.params.areaid; constructor(private route: Router, private router: ActivatedRoute, private detailsNavbarItemsData: DetailsNavbarItemsService) { } ngOnInit() { this.route.routeReuseStrategy.shouldReuseRoute = () => { // do your task for before route return false; } this.detailsNavbarItemsData.getDetailsNavbarItems(this.id).subscribe((result)=>{ console.log(result); this.data = result; }); } } linebar.component.ts import { Component, OnInit } from '@angular/core'; import { Chart } from 'node_modules/chart.js'; import { ActivatedRoute } from '@angular/router'; import { AppService } from '../../app.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-linebar', templateUrl: './linebar.component.html', styleUrls: ['./linebar.component.scss'] }) export class LinebarComponent implements OnInit { id= this.router.snapshot.params.id; constructor(private route: Router, private router: ActivatedRoute, private appService: AppService) { } ngOnInit() { var ctx = document.getElementById('myChart'); var mixedChart = new Chart(ctx, { type: 'bar', data: { labels: ["30.09.20", "30.06.20", "30.03.20", "30.12.19", ], datasets: [{ label: 'Value', data: [3000, 1500, 6000, 4500], backgroundColor: 'rgba(101, 248, 12, 1)', hoverBackgroundColor: 'rgba(101, 248, 12, 0.2)', barPercentage: 0.4, borderColor: '#65F80C', borderWidth: 1 }, { label: 'Hard Limit', data: [5250, 5250, 5250, 5250], pointBorderWidth: 0, pointBorderColor: 'rgba(248, 12, 62, 0)', pointBackgroundColor: 'rgba(248, 12, 62, 0)', backgroundColor: 'rgba(248, 12, 62, 0.2)', borderColor: '#F80C3E', borderWidth: 1, type: 'line', // this dataset is drawn on top order: 2 }], }, options: { scales: { yAxes: [{ ticks: { suggestedMin: 0, suggestedMax: 6000, }, }], xAxes: [{ gridLines: { display:false } }] }, } }); } } details-navbar-items.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class DetailsNavbarItemsService { url="https://this-is-the-API-url/" constructor(private http: HttpClient) { } getDetailsNavbarItems(id) { return this.http.get(this.url + id); } } |
Django admin saves a copy of the object instead of overwrite Posted: 25 Mar 2021 08:49 AM PDT I have a model with OneToOneFiled named alg_id , and when I go to admin panel and change this filed in existing object, than a new object is created, but I'd like to overwrite same object with different alg_id . When I change other simple text fileds - all works fine. If I change alg_id to one, that already exists in Database, than that object gets overwritten - will be better if I'll get a warning here.. How could I achieve that? ps. this project use 2.2.6 Django version |
Python regex replace alphanumeric with indent Posted: 25 Mar 2021 08:48 AM PDT I'm looking to leverage regex syntax to create an indent (new line) where certain criteria is met. In this case when there is an alphanumeric value following ), pattern. Something like this - but it is not quite working. text_old = some text some text ), some text some text ), some text some text which becomes - text_format = some text some text ), some text some text ), some text some text text_format = text_old.lower().replace('), ^[a-zA-Z0-9_.-]*$','), \n') Do I have the proper syntax here? |
How to measure runtime of bucketin for n? Posted: 25 Mar 2021 08:48 AM PDT I am doing a course for beginners in python. I got this exercise, and I have know idea how to solve it. Please help me out! The exercise: Write code that measures the runtime of bucketing(n) as a function of n, and find the value nmin that minimizes the runtime. |
React, can't set new data after get from api Posted: 25 Mar 2021 08:49 AM PDT I am not sure if I am mistaken about the asynchronous or React itself. const fetchData = async () => { const response = await sessionApi.get("/sessions", { headers: { Authorization: user.user?.token } }) if (response.data.success) { setSessionData(response.data.message) console.log(sessionData) } } this is my fetchData.I try using async in function when I console.log to show data it show empty [] if I change to console.log(response.data.message) It shows my data from request.So that my api is not wasted. useEffect(() => { fetchData() console.log(sessionData) }, []) Ok then I use useEffect in my React web then I console.log(sessionData) but it still empty list const [sessionData, setSessionData] = useState([]) that is my my state. Maybe I am mistaken. Please tell me where I missed. |
Is there a simple way to allow access to my website only through my Android application? Posted: 25 Mar 2021 08:48 AM PDT Is there like any method to only allow direct access to my website only from the android application. Any other requests coming from any where else being blocked or redirected to a restricted access page or similar. Please do provide any ideas or simple solutions and any step by step procedure to do so would be greatly appreciated. Thanks. |
Confused about intervalJoin Posted: 25 Mar 2021 08:49 AM PDT I'm trying to come up with a solution which involves applying some logic after the join operation to pick one event from streamB among multiple EventBs. It would be like a reduce function but it only returns 1 element instead of doing it incrementally. So the end result would be a single (EventA, EventB) pair instead of a cross product of 1 EventA and multiple EventB. streamA .keyBy((a: EventA) => a.common_key) .intervalJoin( streamB .keyBy((b: EventB) => b.common_key) ) .between(Time.days(-30), Time.days(0)) .process(new MyJoinFunction) The data would be ingested like (assuming they have the same key): EventB ts: 1616686386000 EventB ts: 1616686387000 EventB ts: 1616686388000 EventB ts: 1616686389000 EventA ts: 1616686390000 Assume a join operation like above and it generated 1 EventA with 4 EventB, successfully joined and collected in MyJoinFunction . Now what I want to do is, access these values at once and do some logic to correctly match the EventA to exactly one EventB. For example, for the above dataset I need (EventA 1616686390000, EventB 1616686387000). MyJoinFunction will be invoked for each (EventA, EventB) pair but I'd like an operation after this, that lets me access an iterator so I can look through all EventB events for each EventA. I am aware that I can apply another windowing operation after the join to group all the pairs, but I want this to happen immediately after the join succeeds. So if possible, I'd like to avoid adding another window since my window is already large (30 days). Is Flink the correct choice for this use case or I am completely in the wrong? |
simple python text file opening program Posted: 25 Mar 2021 08:50 AM PDT studying foundation year ComSci and I'm trying to get a file to open. Here's my code: def main(): filename = raw_input("Please enter file name ") infile = open(filename,'r') data = infile.read() print data main() I believe the code is correct but when I try and open a file, for example C:\Users\Manol\OneDrive\Documents\Uni\Programming\File Processing File It comes back with Traceback (most recent call last): File "C:\Users\Manol\OneDrive\Documents\Uni\Programming\File Processing File\FirstFileProcessingRead.py", line 6, in <module> main() File "C:\Users\Manol\OneDrive\Documents\Uni\Programming\File Processing File\FirstFileProcessingRead.py", line 3, in main infile = open(filename,'r') IOError: [Errno 13] Permission denied: 'C:\\Users\\Manol\\OneDrive\\Documents\\Uni\\Programming\\File Processing File' |
When I click on with the pointer on the hyperlink it doesn't work Posted: 25 Mar 2021 08:49 AM PDT Help me figure out why "HOME" hyperlink doesn't work please. When I go on the hyperlink it is impossible to click on with the pointer. I tried everything, I'm a rookie, please help. figcaption { position: absolute; cursor: pointer; pointer-events: none; bottom: 0; height: 10%; right: 0px; left: 0px; width: 100%; text-align: center; font-size: 110%; color: black; } .video { position: fixed; width: 80%; padding-top: 56.25%; } .responsive-iframe { position: absolute; top: 0; left: 0; bottom: 0; right: 0; width: 100%; height: 100%; } <div class="video"> <figure> <a href="index.html"> <figcaption>HOME</figcaption> </a> <iframe class="responsive-iframe" src="https://player.vimeo.com/video/..." width="1080" height="459" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe> </figure> </div> |
Can't bind to ngModel even though I'm importing FormsModule & syntax appears correct Posted: 25 Mar 2021 08:48 AM PDT My problems started with an app exercise I was doing in Spring Boot and Angular. I discovered I couldn't bind to ngModel, ngClass, and a few other things. So I've worked my way to the very basics and tried a simple exercise from the book Angular Development with TypeScript, 2nd Ed. When I couldn't get rid of the error, I copied the book's code from GitHub, and I still get the error. Here is the code: app.module.ts import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule {} app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <input type="text" placeholder="Enter shipping address" [(ngModel)]="shippingAddress"> <button (click)="shippingAddress='123 Main Street'">Set Default Address</button> <p>The shipping address is {{ shippingAddress }}</p> ` }) export class AppComponent { shippingAddress: string; } As you can see, FormsModule is imported, and the syntax of [(ngModel)] is correct, yet VS Code STILL shows an error of "Can't bind to ngModel because it isn't a known property of input." I'm hoping that if you all can help me figure out the problem here then the answer will work with the Spring Boot/Angular exercise I'm working on. |
Transform month over month to month and months prior Posted: 25 Mar 2021 08:49 AM PDT Initial table salesman training_date 01/20 02/20 03/20 04/20 05/20 06/20 07/20 08/20 09/20 10/20 11/20 12/20 0 John 2020-11-01 100 20 200 250 0 28 80 30 150 100 300 250 1 Ruddy 2020-07-12 90 50 30 225 300 100 95 10 20 0 20 100 In Python: t1 = {'salesman': ['John', 'Ruddy'], 'training_date':['2020-11-30','2020-07-12'], '01/20': [100, 90], '02/20':[20,50], '03/20':[200,30],'04/20':[250,225],'05/20':[0,300],'06/20':[28,100], '07/20': [80, 95], '08/20':[30,10], '09/20':[150,20],'10/20':[100,0],'11/20':[300,20],'12/20':[250,100], } t1a = pd.DataFrame(data=t1) t1a Dataframe expected: salesman training_date training_month 1m_prior 2m_prior 3m_prior 4m_prior 5m_prior 6m_prior 0 John 2020-11-30 300 100 150 30 80 28 0 1 Ruddy 2020-07-12 95 100 300 225 30 50 90 In Python: t2 = {'salesman': ['John', 'Ruddy'], 'training_date':['2020-11-30','2020-07-12'], 'training_month': [300, 95], '1m_prior':[100,100], '2m_prior':[150,300], '3m_prior':[30,225],'4m_prior':[80,30],'5m_prior':[28,50], '6m_prior': [0, 90]} t2a = pd.DataFrame(data=t2) t2a Explanation: John was trained on November 1st. 1m before November 1st, in October, John generated $100. 2m before November 1st, September, John generated $150. Ruddy was trained on July 12th. 1m before July 12th, in June, Ruddy generated $100. 2m before July 12th, May, Ruddy generated $300. In an ideal case, we start calculating 1 full month, always starting on the 1st of each month. So, if Ruddy was hired on July 12th, 2020, one month before should be 1 June - 30 June. Up to this point, we transform the data manually in Excel. |
RockPaperScissor game not getting expected result - C programming Posted: 25 Mar 2021 08:49 AM PDT I was writing c program on rock paper and scissor game but could not get the expected result. #include<stdio.h> #include<stdlib.h> #include<time.h> int main() { char player[50], choice[10]; puts("Enter your name: "); gets(player); int player1 = 0, comp = 0; for (int i = 0; i < 3; i++) { srand(time(NULL)); printf("%s: ", player); scanf("%s", choice); int computer = rand()%3; if (computer == 0){ printf("computer: rock\n"); } else if(computer == 1){ printf("computer: paper\n"); }else{ printf("computer: scissor\n"); } if (computer == 0 && choice == "paper"){ player1++; }else if (computer == 0 && choice == "rock"){ continue; }else if (computer == 0 && choice == "scissor"){ comp++; }else if (computer == 1 && choice == "paper"){ continue; }else if (computer == 1 && choice == "rock"){ comp++; }else if (computer == 1 && choice == "scissor"){ player1++; }else if (computer == 2 && choice == "paper"){ player1++; }else if (computer == 2 && choice == "rock"){ comp++; }else if (computer == 2 && choice == "scissor"){ continue; }else { printf("Invalid Entry."); } printf("\n"); } if (player1 > comp){ printf("%s wins.", player); }else if (player1 == comp) { printf("%s and computer draws.", player); }else{ printf("%s loses.", player); } return 0; } The program works but I am not getting the expecteed result in all 3 runs of the for loop I get only invalid entry as output due to which I can't count the score and the result as both player and comp variable are idle due to this. output: Enter your name: Sam Sam: rock computer: scissor Invalid Entry. Sam: scissor computer: scissor Invalid Entry. Sam: paper computer: paper Invalid Entry. Sam and computer draws. I have checked to best my skill and could not find any mistake I don't know why if else-if is acting weirdly, Help me to get correct output and explain me what the problem and where the mistake is. |
How to pass data from mapStateToProps to parent component? Posted: 25 Mar 2021 08:48 AM PDT This is my component: export default const NotesComponent = () => { return notesList.map((noteProps) => ( <NewsCard {...notesProps} key={notesProps.id} /> )) } Here is the place where i use this component: const Notes = (props: NotesProps) => { return ( <Container> <NotesComponent /> </Container> ) } const mapStateToProps = (state) => ({ notesData: state.notes.notesData, }) // and other code so mapStateToProps is working correctly I don't know how to pass notesData to NotesComponent , so the NewsCard can read the data. |
Script to group elements where every character is same to each other Posted: 25 Mar 2021 08:48 AM PDT For input: ["abc","def","okg","fed","bca"] expected output should be: ["abc","bca"],["def","fed"],["okg"] here "abc", "bca" and "def", "fed" contains same character and "okg" there is no element which contains these character const arr = ["abc", "def", "okg", "fed", "bca"]; let find = (arr) => { let res = []; for (let i = 0; i < arr.length; i++) { for (let j = 1; j < arr.length; j++) { if (arr[i].search(arr[j])) { res.push(arr[j]); } } } return res; } console.log(find(arr)) |
What is the best way to solve a non-linear kinetic problem using python? Posted: 25 Mar 2021 08:48 AM PDT I have a chemical kinetics problem which involves several species that can transfer electrons between each other. I can describe the kinetics using a system of five differential equations. I am trying to fit the model to time-resolved spectroscopic data. I believe that this system should be solved analytically, so I am trying to solve the system using sympy's dsolve: from sympy import * # Assumptions: Since the concentration of Ascn remains practically constant, [Ascn] is absorbed into k1 Ru2p, Rup, Asc, Rep, Re = symbols('Ru2p Rup Asc Rep Re', cls=Function) Rep0, t, k1, k2, k3, k4 = symbols('Rep0 t k1 k2 k3 k4') eq1 = Eq(diff(Ru2p(t)), -k1*Ru2p(t)) eq2 = Eq(diff(Rup(t)), k1*Ru2p(t) - k2*Rup(t)*Asc(t) - k3*Rup(t)*Rep(t)) eq3 = Eq(diff(Asc(t)), k1*Ru2p(t) - k2*Rup(t)*Asc(t)-k4*Asc(t)*Re(t)) eq4 = Eq(diff(Rep(t)), -k3*Rup(t)*Rep(t) + k4*Asc(t)*Re(t)) eq5 = Eq(diff(Re(t)), k3*Rup(t)*Rep(t) - k4*Asc(t)*Re(t)) system = [eq1, eq2, eq3, eq4, eq5] ics = {Ru2p(0):1,Rup(0):0,Asc(0):0,Rep(0):Rep0,Re(0):0} solution = dsolve(system,[Ru2p(t),Rup(t),Asc(t),Rep(t),Re(t)],ics=ics) print(solution) Running this results in: Traceback (most recent call last): File "Ruthenium.py", line 19, in <module> solution = dsolve(system,[Ru2p(t),Rup(t),Asc(t),Rep(t),Re(t)],ics=ics) File "/home/max/.local/lib/python3.6/site-packages/sympy/solvers/ode/ode.py", line 599, in dsolve raise NotImplementedError NotImplementedError It is not clear to me what exactly is not implemented, so I don't know what is the current limitation with this method for which I need to find a solution. I would appreciate it if someone can give me some tips about how I might be able to solve this system, preferably with python. |
Angular Dialog Button doesn't respond to data binding with boolean Posted: 25 Mar 2021 08:49 AM PDT So, my problem is simple but I couldn't manage to solve it and nor I found any help on internet. I have an angular component with 2 dialogs. I have a button bound to a bool in my typescript, as you can see here: export class ModalDB { constructor(public dialog: MatDialog) { } enabledState: boolean = true; changeStates(){ // let content = document.getElementById('db-pdf-body-scroll') // if (content.scrollTop+5 >= (content.scrollHeight - content.offsetHeight)) { // console.log(this.enabledState) // } this.enabledState = false; console.log(this.enabledState) } toggleButton(){ this.enabledState = false; } ngOnInit():void{ console.log(this.enabledState) document.getElementById("db-pdf-body-scroll").addEventListener( 'scroll', function(event){ if (this.scrollTop+5 >= (this.scrollHeight - this.offsetHeight)) { ModalDB.prototype.changeStates(); } }, true // Capture event ); } closeModalDB(){ console.log("User didnt agree db") this.dialog.closeAll(); } agreeDB(){ console.log("User agreed db") this.dialog.closeAll(); } } Here I have the HTML for this: <div mat-dialog-actions align="end"> <button id="acceptDB" mat-raised-button color="primary" [attr.disabled]="enabledState" (click)="agreeDB()">Sunt de acord</button> <button mat-raised-button color="warn" (click)="closeModalDB()">Nu sunt de acord</button> </div> When I try to log the variable enabledState it changes. So my function works. But for some reason the dom won't change. As much as I tried to fix this I couldn't. I checked the hooks, even tried to split the function in more individual components but nothing solved my problem. |
bulk find and replace with a condition case match and exact match google app script,doc,sheet Posted: 25 Mar 2021 08:49 AM PDT Thank you in advance. I have a sheet with data as follows. Find | Replace | condition | Page number ten | Page No. 10 | match case | Page number 10 | Page No. 10 | match case | ms | Ms | exact match | I want to find and replace text in docs with the condition. The below code works fine for me but whenever ex. Williams it replace with WilliaMs. function replMyText() { var ss = SpreadsheetApp.openById('1-WblrS95VqsM5eRFkWGIHrOm_wGIPL3QnPyxN_j5cOo'); var sh = ss.getSheetByName('find and replace'); var doc = DocumentApp.getActiveDocument(); var rgtxt = doc.getBody(); var rgrep = sh.getRange('A2:B103'); var repA = rgrep.getValues().filter(r => r.every(c => c.toString())); repA.forEach(e => rgtxt.replaceText(...e)); } |
how to manage language redirection for website automatic but keep manual changing? Posted: 25 Mar 2021 08:49 AM PDT I'm dealing with an international magento website. All languages are located in multiple subdirectory (/fr, /de, /es, and ...) I'd like to redirect customers on a header of navigator basis, using %{accept-language}. But i'd like to keep the ability for my customers to change language. Do you how to setup that whith a vhost configuration ? Or is it mandatory to setup this in PHP and keeping the change in a php session ? |
Importing external JavaScript file in VueJS Posted: 25 Mar 2021 08:48 AM PDT I'm using the Vue CLI and I want to import a JavaScript file that is hosted on another server. With everything I tried I get the same error as shown below. How can I solve this problem? How can I import an external JS file? My Vue file is shown below. <!-- Use preprocessors via the lang attribute! e.g. <template lang="pug"> --> <template> <div id="app"> <p>Test</p> <button @click="doSomething">Say hello.</button> </div> </template> <script> import TestFile from "https://.../src/TestFile.js"; export default { data() { return { message: "<h1>anything</h1>" } }, async mounted() { await TestFile.build(); }, methods: { doSomething() { alert(message); }, }, }; </script> <!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> --> <style> </style> |
Custom Gutenberg block focuses on inner block when added to the editor Posted: 25 Mar 2021 08:48 AM PDT I created a custom Gutenberg block with nested inner blocks. The edit function looks like: edit: (props) => { <div className="custom-block"> <InnerBlocks template={[ [ 'core/columns', {'className': 'page-layout-columns columns is-multiline'}, [ [ 'core/column', {'className': 'column is-two-thirds-desktop is-full-tablet is-full-mobile page-layout-main'},[['core/paragraph', {'placeholder': 'Main content area. Start typing to add content, or remove this default paragraph block and then add new blocks.'}]] ], [ 'core/column', {'className': 'column is-one-quarter-desktop is-full-tablet is-full-mobile page-layout-sidebar'},[['core/paragraph', {'placeholder': 'Sidebar content area. Start typing to add content, or remove this default paragraph block and then add new blocks.'}]]], ] ]]} /> </div>} When this block is added to the editor, the core columns block is focused instead of the block wrapper. What should I do to make the block wrapper the initial focus? Any comments are greatly appreciated. Thanks! |
how to fix ReactJs Unhandled Promise Rejection: SyntaxError [duplicate] Posted: 25 Mar 2021 08:48 AM PDT using Fetch API with ReactJS to get list of movies however I get this issue. Can someone help with this fetch("https://reactnative.dev/movies.json", { mode: "no-cors", // 'cors' by default }) .then((response) => response.json()) .then((json) => { console.log(json); }); get this error |
Tensorflow 2.0 (Keras) classification with restricted classes Posted: 25 Mar 2021 08:48 AM PDT Problem background I have a basic classification problem, classifying each row into one of 20 classes. However, there is a twist. For every row, only some of those 20 classes are valid - and this is known upfront. In tensorflow 1.0, I have been nullifying the logits of the impossible classes. The only modfication is the loss function: def getLoss(logits, y, restrictions): logits = tf.where(restrictions, -1000.0 * tf.ones_like(y), logits) return tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y) loss = getLoss(logits, y, restrictions) trainer = tf.train.RMSPropOptimizer(learnRate).minimize(loss) Question I have a working solution for Tensorflow 1.0, it is a simple muodification of the loss function. However, I want to rewrite it in Tensorflow 2.0 and Keras. I assume I would need to pass the class restriction matrix into model.fit() along with the inputs. How would I go about doing this? Suboptimal solution idea One easy solution (also proposed by Frederik) is to concatenate the input and class restriction matrix, and let the neural network learn the concept of class restriction from scratch. However, this is not reliable, and makes the neural network unnecessarily bigger. Is there a better, simpler way with Keras? |
How to fix pip install error for all modules? Posted: 25 Mar 2021 08:49 AM PDT I have been trying to install beeware all day, but I keep getting the error failed with error code 1 in C:\Users\dmcga\AppData\Local\Temp\pip-install- snn9ad__\pythonnet\ Seeing that this error had something to do with pythonnet, I tried installing that using pip install pythonnet I then get the same error, I'll paste everything cmd says below C:\Users\dmcga>pip install pythonnet Collecting pythonnet Using cached https://files.pythonhosted.org/packages/89/3b/ a22cd45b591d6cf490ee8b24d52b9db1f30b4b478b64a9b231c53474731e/pythonnet- 2.3.0.tar.gz Installing collected packages: pythonnet Running setup.py install for pythonnet ... error Complete output from command c:\users\dmcga\appdata\local\programs\python\python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\dmcga\\AppData\\Local\\Temp\\pip-install- snn9ad__\\pythonnet\\setup.py';f=getattr(tokenize, 'open', open) (__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\dmcga\AppData\Local\Temp\pip- record-33b2bjj0\install-record.txt --single-version-externally-managed -- compile: running install running build running build_ext Checking for updates from https://www.nuget.org/api/v2/. Currently running NuGet.exe 3.5.0. Updating NuGet.exe to 4.9.2. Update successful. MSBuild auto-detection: using msbuild version '4.0' from 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319'. Restoring NuGet package NUnit.3.6.0. Restoring NuGet package UnmanagedExports.1.2.7. Restoring NuGet package NUnit.ConsoleRunner.3.6.0. Adding package 'UnmanagedExports.1.2.7' to folder 'C:\Users\dmcga\AppData\Local\Temp\pip-install-snn9ad__\pythonnet\packages' Adding package 'NUnit.3.6.0' to folder 'C:\Users\dmcga\AppData\Local\Temp\pip-install-snn9ad__\pythonnet\packages' Adding package 'NUnit.ConsoleRunner.3.6.0' to folder 'C:\Users\dmcga\AppData\Local\Temp\pip-install-snn9ad__\pythonnet\packages' Added package 'UnmanagedExports.1.2.7' to folder 'C:\Users\dmcga\AppData\Local\Temp\pip-install-snn9ad__\pythonnet\packages' Added package 'NUnit.ConsoleRunner.3.6.0' to folder 'C:\Users\dmcga\AppData\Local\Temp\pip-install-snn9ad__\pythonnet\packages' Added package 'NUnit.3.6.0' to folder 'C:\Users\dmcga\AppData\Local\Temp\pip-install-snn9ad__\pythonnet\packages' NuGet Config files used: C:\Users\dmcga\AppData\Roaming\NuGet\NuGet.Config Feeds used: C:\Users\dmcga\.nuget\packages\ https://api.nuget.org/v3/index.json Installed: 3 package(s) to packages.config projects Traceback (most recent call last): File "tools\geninterop\geninterop.py", line 24, in <module> from pycparser import c_ast, c_parser ModuleNotFoundError: No module named 'pycparser' Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\dmcga\AppData\Local\Temp\pip-install- snn9ad__\pythonnet\setup.py", line 405, in <module> zip_safe=False, File "c:\users\dmcga\appdata\local\programs\python\python37-32\lib\site- packages\setuptools\__init__.py", line 143, in setup return distutils.core.setup(**attrs) File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\core.py", line 148, in setup dist.run_commands() File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\dist.py", line 966, in run_commands self.run_command(cmd) File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "c:\users\dmcga\appdata\local\programs\python\python37-32\lib\site- packages\setuptools\command\install.py", line 61, in run return orig.install.run(self) File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\command\install.py", line 545, in run self.run_command('build') File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\command\build.py", line 135, in run self.run_command(cmd_name) File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\command\build_ext.py", line 339, in run self.build_extensions() File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\command\build_ext.py", line 448, in build_extensions self._build_extensions_serial() File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\distutils\command\build_ext.py", line 473, in _build_extensions_serial self.build_extension(ext) File "C:\Users\dmcga\AppData\Local\Temp\pip-install- snn9ad__\pythonnet\setup.py", line 191, in build_extension subprocess.check_call([sys.executable, geninterop, interop_file]) File "c:\users\dmcga\appdata\local\programs\python\python37- 32\lib\subprocess.py", line 347, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['c:\\users\\dmcga\\appdata\\local\\programs\\python\\python37- 32\\python.exe', 'tools\\geninterop\\geninterop.py', 'src\\runtime\\interop37.cs']' returned non-zero exit status 1. ---------------------------------------- Command "c:\users\dmcga\appdata\local\programs\python\python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\dmcga\\AppData\\Local\\Temp\\pip-install- snn9ad__\\pythonnet\\setup.py';f=getattr(tokenize, 'open', open) (__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\dmcga\AppData\Local\Temp\pip- record-33b2bjj0\install-record.txt --single-version-externally-managed -- compile" failed with error code 1 in C:\Users\dmcga\AppData\Local\Temp\pip- install-snn9ad__\pythonnet\ I am using Python 3.7, pip 19.0.1, Windows 10 This seems to be occurring with almost all modules that I attempt to install, I tried a fresh install of python, but still am getting this error. |
No comments:
Post a Comment