When You Reload Page 404 Not Found In React Js Posted: 24 Jul 2022 09:04 AM PDT I develop some project with react js. When i am using with localhost everything is fine. But when i publish this website and when you refresh page page 404 not found is appear. I used react-router-dom and should i use anything else ( apache express.js etc. ) <Router> <Navbar/> <Routes> <Route path='/' exact element={<Anasayfa/>}/> <Route path='/Hakkimizda' exact element={<Hakkimizda/>}/> <Route path='/Markalar' exact element={<Markalar/>}/> <Route path='/Sektorler' exact element={<Sektorler/>}/> <Route path='/Urunler' exact element={<Urunler/>}/> <Route path='/Iletisim' exact element={<Iletisim/>}/> </Routes> <Footer/> |
-> operator in the middle of a property Posted: 24 Jul 2022 09:04 AM PDT I understand that [-> m] is a non-consecutive GoTo operator and can be used as (e.g.) @(posedge clk) a |=> b [->2] ##1 c; But I came across an example, where I see (in the middle of a property), a -> b. What does that mean? Does it mean if 'a' is true that 'b' is true? Does it behave like an overlapping implication operator? Please see the example below. Thanks. property count_event(reg [15:0] PerfCtr, reg [15:0] event_count); @(posedge DfiClk) disable iff (disable_perfcntcheck) ((PWR_OK === 1'b1) && (Reset === 1'b0) && (DebugPerfCtrEn === 1) && (dfi_event_select === 1) && ($rose(dfi_event))) |-> ##[1:5] !$isunknown(capture_dly) && (!capture_dly -> event_count == PerfCtr) ##1 !$isunknown(capture_dly) && (capture_dly -> event_count == PerfCtr); |
How can I cycle through sessions in flask? Posted: 24 Jul 2022 09:03 AM PDT I have been wondering how I could cycle through sessions. I want to make a system that clears all sessions with the id variable set to the current session id upon going to a specific URL. How can I do that? |
How to convert SlingHttpServletRequest to POJO Posted: 24 Jul 2022 09:03 AM PDT I am writing a Sling servlet extending SlingAllMethodsServlet where this servlet will receive payload as json, currently I am parsing SlingHttpServletRequest to get json from request body. Instead of doing all these things, I would like to receive the payload as model class, similar to Spring framework. Is there any way to achieve this? I tried using Sling models, though the documentation says the SlingHttpServletRequest can be adapted I couldn't get model class from request. For sure I am missing something but not able to figure it out even after researching for few days. Any help is highly appreciated. @Model(adaptables=Resource.class) public class Test{ @Inject private String param; } protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { Test test = resource.adaptTo(Test.class) // getting null |
How to pipe output to DEVNULL without changing return value of subprocess.call Posted: 24 Jul 2022 09:03 AM PDT I'm using Python to run a process using subprocess in a test. The subprocess returns 42 if the process finds error (I've tested this pretty thoroughly): ipdb> subprocess.call(command) ==48142== Conditional jump or move depends on uninitialised value(s) ==48142== at 0x7FFF204718DF: ??? (in /dev/ttys006) ==48142== by 0x7FFF2033F184: ??? (in /dev/ttys006) ==48142== by 0x7FFF20347E2B: ??? (in /dev/ttys006) ==48142== by 0x7FFF2036C964: ??? (in /dev/ttys006) ==48142== by 0x7FFF20344FE5: ??? (in /dev/ttys006) ==48142== by 0x7FFF20343155: ??? (in /dev/ttys006) ==48142== by 0x1000076E1: nativePrint (in ./fur) ==48142== by 0x10000B908: Thread_run (in ./fur) ==48142== by 0x10000D27B: runString (in ./fur) ==48142== by 0x10000D887: runFile (in ./fur) ==48142== by 0x10000E13D: main (in ./fur) ==48142== Hello, world42 Just so we're extra clear that I'm not mistaken on this: ipdb> subprocess.call(command) == 42 ==48144== Conditional jump or move depends on uninitialised value(s) ==48144== at 0x7FFF204718DF: ??? (in /dev/ttys006) ==48144== by 0x7FFF2033F184: ??? (in /dev/ttys006) ==48144== by 0x7FFF20347E2B: ??? (in /dev/ttys006) ==48144== by 0x7FFF2036C964: ??? (in /dev/ttys006) ==48144== by 0x7FFF20344FE5: ??? (in /dev/ttys006) ==48144== by 0x7FFF20343155: ??? (in /dev/ttys006) ==48144== by 0x1000076E1: nativePrint (in ./fur) ==48144== by 0x10000B908: Thread_run (in ./fur) ==48144== by 0x10000D27B: runString (in ./fur) ==48144== by 0x10000D887: runFile (in ./fur) ==48144== by 0x10000E13D: main (in ./fur) ==48144== Hello, worldTrue As you can see, the subprocess I'm running produces a lot of output, which I don't care about, and I'd like my tests to suppress this output, so I follow the docs and pipe both stdout and stderr to devnull, like so: ipdb> subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 0 ...and the return value changes. It appears that this is probably because they're returning the value of the pipe, rather than the subprocess. Is there a way in Python to capture the return value of the command while supressing the output? |
Is it possible to set a default theme at compile time for DaisyUI (Tailwind)? Posted: 24 Jul 2022 09:03 AM PDT DaisyUI has default themes and you can change them with the data-theme attribute e.g. <html data-theme="cupcake"> . It seems as though the default is the light theme. The problem is that I want to be able to use the @apply directive with DaisyUI so that I can have BEM class names in the template and DaisyUI utility classes in the style block. It seems that I can't set a default that will be picked up at compile time. In my tailwind.config I've tried using the light theme to see if I could overwrite it, e.g.: plugins: [require('daisyui')], daisyui: { themes: [ { light: { primary: '#EF3054', secondary: '#C67F43', accent: '#43AA8B', neutral: '#FBF5F3', base100: '#FFFFFF', info: '#3ABFF8', success: '#36D399', warning: '#FBBD23', error: '#F87272', }, }, ], } But this doesn't work. I've tried looking into the library itself for clues into how I could overwrite the default theme at compile time but I can't see how. Although some people consider BEM with Tailwind an anti-pattern, I had long held this view myself as well, I have since changed my mind and feel that the extra effort does help disambiguate your template with the added benefit of allowing bespoke CSS whenever you need to drop into it so please don't suggest just using the inline utility classes as I know this works. |
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7fd42c66d3b0> Posted: 24 Jul 2022 09:02 AM PDT I am trying to do an object detection problem and been working with aquarium dataset from roboflow. I have been trying to create a bounding box for the fishes, but I have getting the error: UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7fd42c66d3b0> I also tried to see what images are corrupted and ran a code import PIL from pathlib import Path from PIL import UnidentifiedImageError count = 0 path = Path("/content/drive/MyDrive/archive/Aquarium Combined").rglob("*.jpg") for img_p in path: try: img = PIL.Image.open(img_p) except PIL.UnidentifiedImageError: print(img_p) count +=1 print(count) It has given me a count of 651 images, but my dataset has 662 images. I guess PIL doesn't know how to decode it or I don't know what the problem is. I will attach a sample image file name /content/drive/MyDrive/archive/Aquarium Combined/test/IMG_2301_jpeg_jpg.rf.2c19ae5efbd1f8611b5578125f001695.jpg Full traceback: UnidentifiedImageError Traceback (most recent call last) <ipython-input-31-2785d562a97e> in <module>() 4 sample[1]['boxes'][:, [1, 0, 3, 2]], 5 [classes[i] for i in sample[1]['labels']], ----> 6 width=4).permute(1, 2, 0) 7 ) 3 frames /usr/local/lib/python3.7/dist-packages/PIL/Image.py in open(fp, mode) 2894 if mode == "P": 2895 from . import ImagePalette -> 2896 2897 im.palette = ImagePalette.ImagePalette("RGB", im.im.getpalette("RGB")) 2898 im.readonly = 1 UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7fd42c66d3b0> Also I am providing the class functions" class AquariumDetection(datasets.VisionDataset): def __init__( self, root: str, split = "train", transform= None, target_transform = None, transforms = None, ) -> None: super().__init__(root, transforms, transform, target_transform) self.split = split self.coco = COCO(os.path.join(root, split, "_annotations.coco.json")) self.ids = list(sorted(self.coco.imgs.keys())) self.ids = [id for id in self.ids if (len(self._load_target(id)) > 0)] def _load_image(self, id: int) -> Image.Image: path = self.coco.loadImgs(id)[0]["file_name"] image = cv2.imread(os.path.join(self.root, self.split, path)) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) return image def _load_target(self, id: int): return self.coco.loadAnns(self.coco.getAnnIds(id)) def __getitem__(self, index: int): id = self.ids[index] image = self._load_image(id) target = copy.deepcopy(self._load_target(id)) boxes = [t['bbox'] + [t['category_id']] for t in target] if self.transforms is not None: transformed = self.transforms(image=image, bboxes=boxes) image = transformed['image'] boxes = transformed['bboxes'] new_boxes = [] for box in boxes: xmin = box[0] ymin = box[1] xmax = xmin + box[2] ymax = ymin + box[3] new_boxes.append([ymin, xmin, ymax, xmax]) boxes = torch.tensor(new_boxes, dtype=torch.float32) _, h, w = image.shape targ = {} targ["boxes"] = boxes targ["labels"] = torch.tensor([t["category_id"] for t in target], dtype=torch.int64) targ["image_id"] = torch.tensor([t["image_id"] for t in target]) targ["area"] = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) targ["iscrowd"] = torch.tensor([t["iscrowd"] for t in target], dtype=torch.int64) targ["img_scale"] = torch.tensor([1.0]) targ['img_size'] = (h, w) image = image.div(255) normalize = T.Compose([T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) return normalize(image), targ, index def __len__(self) -> int: return len(self.ids) |
My gas sensor is not working in my loop function Posted: 24 Jul 2022 09:04 AM PDT enter image description here In the circuit I have lcd and keyboard connected to arduino uno that rotates my servo motor in when correct password is entered....The problem is am trying to have gas sensor in my circuit but it is not working with the project with lcd, keyboard and motor but when i run it in other project it will give expected result...Here is my loop function void loop() { int a = analogRead(A0); Serial.println(a); if(a>600){ digitalWrite(13, HIGH); } else{ digitalWrite(13, LOW); } if( currentposition==0) { displayscreen(); } int l ; char code=keypad.getKey(); if(code!=NO_KEY) { lcd.clear(); lcd.setCursor(0,0); lcd.print("PASSWORD:"); lcd.setCursor(7,1); lcd.print(" "); lcd.setCursor(7,1); for(l=0;l<=currentposition;++l) { lcd.print("*"); keypress(); } if (code==password[currentposition]) { ++currentposition; if(currentposition==4) { unlockdoor(); currentposition=0; } } here is my setup function int a = analogRead(A0); Serial.println(a); if(a>600){ digitalWrite(13, HIGH); } else{ digitalWrite(13, LOW); } |
My if/elif/else statement is not working in python 3 [duplicate] Posted: 24 Jul 2022 09:04 AM PDT I was trying to make a, if statement in Python to provide custom text for each of my friends, and for some reason the code always uses the fred line if I add an elif . It works fine with just and if and else , but just defaults to the Fred code if an elif is involved. Here is the code: if name == "Fred" or "fred": print("Bye Fred.") exit() elif name == "Craig" or "craig": print("Hello, my creator!") else: print("? Do I know you?") |
I cannot figure out the solution for this problem Posted: 24 Jul 2022 09:04 AM PDT Write a program which includes a function sum. This function sum should be designed to add an arbitrary list of parameters. (For e.g., if you call the function sum() as sum (1, 2) it should return the result 3 and if again you call the function sum() as sum(1,3,4) it should return the result 8 |
Visualize Skeleton Posted: 24 Jul 2022 09:04 AM PDT I have positional data of 24 joints which I want to visualize. I am able to read in the data into a pandas data frame. But I am not sure how to do the visualization. I am able to plot the points in a scatter plot with matplotlib, but I am still looking for an elegant way to draw the lines, because not all joints are connected. I know which ones are connected, but implementing it seems very tedious. One way of doing this I thought was to have a 24x24 matrix with entries 0 if the two joints are not connected and 1 if the two joints are connected. Such a matrix I can easily type out myself. But I am not sure how to use this then to plot the lines. |
UP and Down Arrow Icons functionality not working in Reactjs Posted: 24 Jul 2022 09:04 AM PDT Basically I need to show and Hide the div , Up and Down Arrow Icons should change accordingly. As of Now only UP arrow Icon is working and displaying the div , but when i try to hide the div, it is not working....I did like this and its not working , What wrong in my code? Can Anyone help me in this? Here is my Code const [expand, setExpand] = useState(false); <div onClick={() => setExpand(true)}> Accordion <i className={`fas fa-chevron-up ${!expand ? 'fas fa-chevron-down' : ''}`}></i> </div> {expand && <div className="Accordion-Section"></div>} |
Node Server .env file undifined in server.js Posted: 24 Jul 2022 09:03 AM PDT The below screenshot shows my file structure in VS code. I have used npm concurrent to run both backend and frontend simultaneously. My problem is env file is not recognized in the server file. Please tell me what is wrong here. Second picture |
How to parse request body of POST request, if client set content-type="application/xml" and body=null? Posted: 24 Jul 2022 09:04 AM PDT I have POST REST endpoint, which initially doesn't expect any request body. I want to add optional request body for this API. Optional, means I want all clients, which used this API with content-type="application/xml" and empty body, to continue using API in the same manner, without rewriting any single row of code. For content-type="application/json", it works fine, no need client to alter his code. But for "application/xml", clients now receive "400 Bad request" response. Is there any chance to introduce optional request body and support all existing API clients? REST endpoint is written in java, and annotations from "javax.xml.bind.annotation" package are used to declare object model Below is signature of endpoint, defined with swagger annotations. dueDatesDetails - object that is supposed to be added as optional: @POST @Path("/sites/{siteid}/filestatus") public Response linkContent( @ApiParam(value = "site id", required = true) @PathParam("siteid") String siteId, @ApiParam(value = "status", required = true) @QueryParam("status") String status, DueDatesDetails dueDatesDetails) { Here is java object model, that must be optional: @XmlRootElement(name = "duedatesdetails") @XmlAccessorType(XmlAccessType.FIELD) public class DueDatesDetails { @Getter @Setter @XmlElement(name = "duedatedetails") @JsonProperty("duedatesdetails") private List<DueDateDetails> dueDateDetailsList; } |
Laravel Migration Failed After The First File/Run(except file for creating users and password_reset table) Posted: 24 Jul 2022 09:02 AM PDT I tried making database using Laravel Migration, it works only in first file and run... after that, I don't know what it caused to fail. I made date, head, and many more for the database, date successfully implemented but head fail even after I remove date migration file and using limiter on interger didn't give any effect. Error Screenshot .env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=mono DB_USERNAME=root DB_PASSWORD= Localhost create_head_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateHeadTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('head', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('head', 50); $table->interger('tgl', 50); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('head'); } } |
VueJS real SEO friendly 404 page for search engines like Google / MSN Posted: 24 Jul 2022 09:03 AM PDT I am not VueJS programmer, but I work with in a company where we developing a VueJS website. The website have articles. The URL is something like this: http://example.com/here_is_news_from_sofia.htm However if you type: http://example.com/here_is_news_from_blabla.htm You should go to 404 page. I inspected several websites and stackoverflow questions, they explain how you should do catch-all router etc, so finally you get a page with "404 Not Found" text on it. However, in ALL cases, the HTTP code send to the client is not 404, but 200. With my team, I elaborated this: When you go to any article, you get something like this: <html> <body> <div id="app"> <app /> </div> <script src="/js/client.js"></script> </body> </html> Of course, if you click on a link, this page remains and everything is loaded via JS dynamically. Then lets suppose article is not found. VueJS will be able to show "404 Not Found" as text, but because HTTP headers are already send (HTML page is already loaded), it will not be able to send 404 code to the client. For the same reason, VueJS can not send 301 code redirect to the client. VueJS can incorrectly change the URL in the browser to "http://example.com/404.htm" - this is NOT a correct solution for search engines, since this is purely client-side (in-browser) "trick". The other think it can do is to execute fancy redirect, as shown here Vue-router redirect on page not found (404) : Vue.component("page-not-found", { template: "", created: function() { // Redirect outside the app using plain old javascript window.location.href = "/404.htm"; } } This will make the browser to reload the /404.htm page from the server and if the server (Apache / Nginx) is configured correctly, it will send "correct" 404 code to the client. However I don't think Google and MSN will recognize that http://example.com/here_is_news_from_blabla.htm is a 404 page. Am I missing anything? - Is there another way VueJS might handle this situation?
- How VueJS websites gets indexed from search engines like Google and MSN?
- Off topic bonus question - can VueJS generate visible HTML code that contains the article?
|
use weight transfer learning trained in customer data after training in another customer data Posted: 24 Jul 2022 09:03 AM PDT I hope you are well I have a question can I train transfer learning like pre-trained model 'vgg16' trained on ImageNet in my customer data and save weight to train another customer data? How I can do this, please Thanks for ur time |
The clang compiler does not support a feature it reportedly supports Posted: 24 Jul 2022 09:04 AM PDT I'm trying to tailor compiler flags of clang-11 to the apple-m1 CPU, which clang-11 doesn't know about yet. The output of /usr/bin/clang -E - -mcpu=apple-m1 -### on macOS outputs a command with flags like these in it: "-target-feature" "+zcz" From that you can infer the following features of the CPU: armv8.5a+fp-armv8+neon+crc+crypto+dotprod+fp16fml+ras+lse+rdm+rcpc+zcm+zcz+fullfp16+sm4+sha3+sha2+aes However, out of these, +fp-armv8+neon+zcm+zcz+fullfp16 are not recognised to be valid by any clang compiler: $ cc -march=armv8.5a+zcz test.c clang-11: error: the clang compiler does not support '-march=armv8.5a+zcz' How can I tell clang to optimise for those target flags? |
Can not remove meta open graph tags nor style tags in WordPress head, is it really possible? Posted: 24 Jul 2022 09:03 AM PDT I had three old dated og meta tags, and after testing with complete failure all online recipes I could find (with various flavors of wp_head functions) I resigned, built again the culprit template and all fine, lost days will never return. But there's also in the head section a CSS style tag of unknown origin for me (I don't usually inline CSS), which happens to break W3C validation. The tag looks like this, and appears as you see between the parent and child theme: <link rel='stylesheet' id='wpestate_style-css' href='https://www.mysite.es/wp-content/themes/wpresidence/style.css?ver=1.0' type='text/css' media='all' /> <style id='wpestate_style-inline-css' type='text/css'> body::after{ position:absolute; width:0; height:0; overflow:hidden; z-index:-1; // hide images content:url(); // load images } } </style> <link rel='stylesheet' id='wpestate-child-style-css' href='https://www.mysite.es/wp-content/themes/wpresidence-child/style.css?ver=1.0.0' type='text/css' media='all' />''' Again I tried copypastas from here and other sites, like '''add_action( 'wp_enqueue_scripts', '_remove_style', PHP_INT_MAX ); function _remove_style() { wp_dequeue_style( '#wpestate_style' ); }''' '''add_action('init','_remove_style'); function _remove_style(){ global $post; $pageID = array('18618','5701', '17886', '20482', '5707'); if(in_array($post->ID, $pageID)) { wp_dequeue_style('#wpestate_style-inline-css'); } }''' Surely I miss something in my ignorance or failed to reuse these functions (tried the selector with # and without, and the complete name or without the trailing '-css' with I read is added by wp.) What bothers me is: why or how are those metas and styles so removal resistant? Is there any way to find out their origin (like a summary of all wp_head calls, (with a theme with wpresidence and elementor is quite a number of files.) And, finally, if I can do: chapu = jQuery('head style#wpestate_style-inline-css').text(); and fetch easily the fragment I want to delete, why cant I delete it or at least modify it?: console.log(chapu); jQuery('head style#wpestate_style-inline-css').text(''); or jQuery('head style#wpestate_style-inline-css').remove(); I'd appreciate any insight on this. Thanks for reading. |
Viewing NFTs generated in Rinkeby testnet Posted: 24 Jul 2022 09:04 AM PDT |
Data is not coming if i use async in vue js 3 Posted: 24 Jul 2022 09:04 AM PDT I am implementing Quiz App but here I am facing an issue if I put static data in array the questions are coming. Data is not coming if i use async in Vue JS 3 But when get from the API the questions are not showing. when I console the questions are showing in console and not showing in the front end. For ref please find the attached code and image. Home.vue (please see fetchQuestionsFromServer function) <template> <main class="flex h-screen items-center justify-center bg-gray-100"> <!-- quiz container --> <QuizComplatePage v-if="endofQuiz" /> <div class="overflow-hidden bg-white flex-none container relative shadow-lg rounded-lg px-12 py-6" > <img src="@/assets/images/abstract.svg" alt="" class="absolute -top-10 left-0 object-none" /> <!-- contents --> <div class="relative z-20"> <!-- score container --> <div class="text-right text-gray-800"> <p class="text-sm leading-3">Score</p> <p class="font-bold">{{score}}</p> </div> <!-- timer container --> <div class="bg-white shadow-lg p-1 rounded-full w-full h-5 mt-4"> <div class="bg-blue-700 rounded-full w-11/12 h-full" :style= "`width: ${timer}%`" ></div> </div> <!-- question container --> <div class="rounded-lg bg-gray-100 p-2 neumorph-1 text-center font-bold text-gray-800 mt-8" > <div class="bg-white p-5"> {{currentQuestion.question}} </div> </div> <!-- options container --> <div class="mt-8"> <!-- option container --> <div v-for="(choice,item) in currentQuestion.choices" :key="item"> <div class="neumorph-1 option-default bg-gray-100 p-2 rounded-lg mb-3 relative" :ref="optionchosen" @click="onOptionClick(choice,item)" > <div class="bg-blue-700 p-1 transform rotate-45 rounded-md h-10 w-10 text-white font-bold absolute right-0 top-0 shadow-md" > <p class="transform -rotate-45">+10</p> </div> <div class="rounded-lg font-bold flex p-2"> <!-- option ID --> <div class="p-3 rounded-lg">{{item}}</div> <!-- option name --> <div class="flex items-center pl-6">{{choice}}</div> </div> </div> </div> <!-- option container --> </div> <!-- progress indicator container --> <div class="mt-8 text-center"> <div class="h-1 w-12 bg-gray-800 rounded-full mx-auto"></div> <p class="font-bold text-gray-800">{{questionCounter}}/{{questions.length}}</p> </div> </div> </div> </main> </template> <script> import { onMounted, ref } from 'vue' import QuizComplatePage from './QuizCompleteOverlay.vue' export default{ components: { QuizComplatePage }, setup(){ //data let canClick = true let score = ref(0) let timer = ref(100) let endofQuiz = ref(false) let questionCounter = ref(0) const currentQuestion = ref({ question: '', answer: 1, choices: [], }); const questions = [] const loadQuestion = () =>{ canClick = true timer.value=100 //Check question array had questions or not if(questions.length > questionCounter.value){ currentQuestion.value = questions[questionCounter.value] console.log('Current Question is : ', currentQuestion.value); questionCounter.value++ }else{ endofQuiz.value = true console.log('Out of Questions'); } } //methods let itemsRef = [] const optionchosen = (element) =>{ if(element){ itemsRef.push(element) } } const clearSelected = (divselected) =>{ setTimeout(()=>{ divselected.classList.remove('option-correct') divselected.classList.remove('option-wrong') divselected.classList.add('option-default') loadQuestion() },1000) } const onOptionClick = (choice,item) =>{ if(canClick) { const divContainer = itemsRef[item] const optionId = item+1 if(currentQuestion.value.answer ===optionId){ console.log('You are Correct'); score.value += 10 divContainer.classList.add('option-correct') divContainer.classList.remove('option-default') }else{ console.log('You are Wrong'); divContainer.classList.add('option-wrong') divContainer.classList.remove('option-default') } timer.value=100 canClick=false //to go next question clearSelected(divContainer) console.log(choice,item); }else{ console.log('Cant Select Option'); } } const countDownTimer = () =>{ let interval= setInterval(()=>{ if(timer.value>0){ timer.value-- }else{ console.log('Time is over'); clearInterval(interval) } },150) } const fetchQuestionsFromServer = async function(){ fetch('https://opentdb.com/api.php?amount=10&category=18&type=multiple') .then((res) =>{ return res.json() }) .then((data) =>{ const newQuestions = data.results.map((serverQuestion) =>{ const arrangedQuestion = { question: serverQuestion.question, choices: '', answer: '' } const choices = serverQuestion.incorrect_answers arrangedQuestion.answer = Math.floor(Math.random() * 4 + 1) choices.splice(arrangedQuestion.answer-1 , 0 , serverQuestion.correct_answer) arrangedQuestion.choices = choices return arrangedQuestion }) console.log('new formated questions' , newQuestions); questions.value = newQuestions loadQuestion() countDownTimer() console.log('questions: =>' , questions.value); }) } //lifecycle hooks onMounted(() =>{ fetchQuestionsFromServer() }) //return return { timer, currentQuestion, questions, score, questionCounter, loadQuestion, onOptionClick, optionchosen, endofQuiz, } } } </script> <style scoped> .neumorph-1 { box-shadow: 6px 6px 18px rgba(0, 0, 0, 0.09), -6px -6px 18px #ffffff; } .container { max-width: 400px; border-radius: 25px; } </style> QuizComplatePage.vue <template> <div class="w-screen h-screen absolute z-30 bg-white bg-opacity-30 flex justify-center items-center"> <div class="bg-green-700 p-4 text-center text-white"> <p class="font-bold text-2xl">All DOne!</p> <p class="my-4 font-bold text-3xl">100% Score</p> <!-- Buttons --> <div class="flex justify-center"> <div class="rounded-full py-1 w-28 border cursor-pointer hover:text-black hover:bg-white">Done</div> <div class="rounded-full py-1 w-28 border cursor-pointer hover:text-black hover:bg-white">Retry</div> </div> </div> </div> </template> <script> export default { name: 'QuizComplatePage' } </script> <style> </style> Image. |
I cannot compile my javafx maven project on Raspberry pi Posted: 24 Jul 2022 09:04 AM PDT I created a java project which compiles and runs fine on my mac with "mvn compile". But once I fetch it from gitlab on my Pi it won't compile on linux. I consulted many pages but none seem to apply to this particular issue. Can anyone help me? I would be really grateful! The error: [INFO] Scanning for projects... [INFO] [INFO] ----------------------< SmartMirror:SmartMirror >----------------------- [INFO] Building SmartMirror 0.0.1-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.816 s [INFO] Finished at: 2022-07-23T14:54:44+02:00 [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal on project SmartMirror: Could not resolve dependencies for project SmartMirror:SmartMirror:jar:0.0.1-SNAPSHOT: The following artifacts could not be resolved: org.openjfx:javafx-controls:jar:${javafx.platform}:19-ea+9, org.openjfx:javafx-graphics:jar:${javafx.platform}:19-ea+9, org.openjfx:javafx-base:jar:${javafx.platform}:19-ea+9, org.openjfx:javafx-fxml:jar:${javafx.platform}:19-ea+9: Failure to find org.openjfx:javafx-controls:jar:${javafx.platform}:19-ea+9 in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException The POM.xml file: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SmartMirror</groupId> <artifactId>SmartMirror</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <mainClass>main.Main</mainClass> <maven.compiler.source>1.9</maven.compiler.source> <maven.compiler.target>1.9</maven.compiler.target> <javafx.platform>linux</javafx.platform> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.3.0</version> <executions> <execution> <goals> <goal>shade</goal> </goals> <configuration> <shadedArtifactAttached>true</shadedArtifactAttached> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>main.Main</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.10.1</version> </plugin> <plugin> <groupId>org.openjfx</groupId> <artifactId>javafx-maven-plugin</artifactId> <version>0.0.8</version> <configuration> <mainClass>Main</mainClass> </configuration> </plugin> </plugins> </build> <dependencies> <!-- https://mvnrepository.com/artifact/org.openjfx/javafx-controls --> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-controls</artifactId> <version>19-ea+9</version> <classifier>linux</classifier> </dependency> <!-- https://mvnrepository.com/artifact/org.openjfx/javafx-fxml --> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-fxml</artifactId> <version>19-ea+9</version> <classifier>linux</classifier> </dependency> <dependency> <groupId>com.mashape.unirest</groupId> <artifactId>unirest-java</artifactId> <version>1.4.9</version> </dependency> </dependencies> </project> The module-info.java file: module SmartMirror { exports weather to javafx.graphics, javafx.fxml; exports main to javafx.graphics, javafx.fxml; opens weather to javafx.graphics, javafx.fxml; opens main to javafx.graphics, javafx.fxml; requires javafx.base; requires javafx.controls; requires javafx.fxml; requires transitive javafx.graphics; requires transitive json; } Edit: Thank you so far for your answers. Though the issue persists. Any more ideas? |
I am getting a `KeyError` when I receive a request to my API Posted: 24 Jul 2022 09:02 AM PDT I am building a dictionary app with Flask where users can add new words, I am trying to request the word from the word input , I am having issues with the POST request, the error I am receiving on my terminal is this: line 50, in add_word word = req['word'] keyError:'word' and this is how I wrote the code in my app.py file: @app.route('/word', methods= ['POST']) def add_word(): req = request.get_json() word = req['word'] meaning = req['meaning'] conn = mysql.get_db() cur = conn.cursor() cur.execute('insert into word(word, meaning) VALUES (%s, %s)',(word, meaning)) conn.commit() cur.close() return json.dumps("success") here is the json in my JavaScript file, I am posting to my flask app: $('#word-form').submit(function() { let word = $('word').val(); let meaning = $('meaning').val(); $.ajax({ url: '/word', type: 'POST', dataType: 'json', data : JSON.stringify({ 'word': word, 'meaning': meaning }), contentType: 'application/json, charset = UTF-8', success: function(data) { location.reload(); }, error: function(err) { console.log(err); } }) here is the Html page: <div class="div col-md-2 sidenav"> <a href="#" id="word-index" class="side-active">All words</a> <a href="#" id="word-add">Add New</a> <div> <form action="javascript:0" id="word-form"> <div class="form-group"> <label for="word">Word:</label> <input type="text" class="form-control" name="word" id="word" placeholder="Type in the word here:" required> </div> <div class="form-group"> <label for="Meaning">Meaning:</label> <textarea class="form-control" id="meaning" placeholder="enter the meaning here: " required></textarea> </div> <button type="submit" class="btn btn-primary btn-block btn-lg" id="submit">Submit</button> <button type="button" class="btn btn-warning btn-block btn-lg" id="cancel">Cancel</button> </form> </div> </div> <div class="div col-md-10 main"> <table style="border: 2px;"> <thead> <tr> <th>SN</th> <th>Word</th> <th>Meaning</th> <th></th> <th></th> </tr> </thead> <tbody> {% for word in words %} <tr> <td>{{ loop.index }}</td> <td>{{ word['word'] }}</td> <td>{{ word['meaning'] }}</td> <td><button class="btn btn-sm btn-success btn-block edit" id="{{word['id']}}">Edit</button></td> <td><button class="btn btn-sm btn-danger btn-block delete" id="{{word['id']}}">Delete</button></td> </tr> {% else %} <tr> <td colspan="3">The dictionary has no words at the moment, please come bay later</td> </tr> {% endfor %} </tbody> </table> </div> |
How to find closest embedding vectors? Posted: 24 Jul 2022 09:03 AM PDT I have 100K known embedding i.e. [emb_1, emb_2, ..., emb_100000] Each of this embedding is derived from GPT-3 sentence embedding with dimension 2048. My task is given an embedding(embedding_new ) find the closest 10 embedding from the above 100k embedding. The way I am approaching this problem is brute force. Every time a query asks to find the closest embeddings, I compare embedding_new with [emb_1, emb_2, ..., emb_100000] and get the similarity score. Then I do quicksort of the similarity score to get the top 10 closest embedding. Alternatively, I have also thought about using Faiss. Is there a better way to achieve this? |
Create pandas dataframe from multiple sources Posted: 24 Jul 2022 09:04 AM PDT I need to create a pandas dataframe using information from two different sources. For example, for row in df.itertuples(): c1, c2, c3 = row.c1, row.c2, row.c3 returnedDict = function(row.c1, row.c2, row.c3) The first 3 columns in the dataframe I want should contain c1, c2, c3 , and the rest of the columns come from the key of the returnedDict . The number of keys in the returnedDict is 100. How can I initialize such Dataframe and append the row in the dataframe at each for loop ? Expected output col1 col2 col3 key1 ... key100 -------------------------------------------------------------- c1 c2 c3 returnedDict[key1] returnedDict[key100] |
Error: insertOne()` buffering timed out after 10000ms Posted: 24 Jul 2022 09:03 AM PDT I am at the very beginning of learning Mongoose, and I am having trouble saving this model to my database and keep getting an error: insertOne()` buffering timed out after 10000ms This is my code: How can I find a solution for this? |
Is there any way to save a webpage as a pdf document in flutter web view Posted: 24 Jul 2022 09:02 AM PDT I am currently using flutter InAppWebView Plugin. I want to save a web page as a pdf file when the url of the page is given. I have used the printCurrentPage() method of the InAppWebView plugin but it does not return the filepath back to the app after saving the file so that it can be shown in a list view in the app itself. Can anyone help me save the webpage as a pdf and show the saved files as a list view. I have tried webcontent_converter plugin too but it looses some content of the page like images and icon to include in the pdf file. |
Rename OpenAPI's reference generated swagger.json Posted: 24 Jul 2022 09:04 AM PDT I'd like to know how to rename generated swagger.json when I add an OpenAPI service reference to my project in Visual studio 2019 via "Add new OpenAPI service reference" option. I assume it should be something like it's done with a "ClassName". <ItemGroup> <OpenApiReference Include="OpenAPIs\swagger.json" CodeGenerator="NSwagCSharp" Namespace="PetStore.Client"> <SourceUri>https://petstore.swagger.io/v2/swagger.json</SourceUri> <ClassName>PetStoreClient</ClassName> <OutputPath>PetStoreClient.cs</OutputPath> <Options>/GenerateClientInterfaces:true /ClientBaseClass:ClientBase</Options> </OpenApiReference> </ItemGroup> |
How do I create an options popup dialog using firefox addon sdk? Posted: 24 Jul 2022 09:03 AM PDT So I decided recently to create a firefox extension I have been thinking about, but do not have any prior experience with it. I read on the official tutorials and figured that the addons sdk seemed to fit me well, but I seem to have hit a hitch using it. What I want to do is create an options popup dialog, similar to the one you see if you press alt-tools-options. That is, a border with title and close button on the upper part, and a bigger area inside the window where I can define an "intuitive" (default elements with the skin the user is used to) GUI. The tabs at the top (general, privacy security etc.) is nothing I really need, though would not hurt either. So the issue is that from my searches, when you use addon sdk, you are not supposed to use XUL which has those elements, but instead you seem to be supposed to create something custom using HTML in a panel. I don't think its possible to create the top-bar akin to the real options-menu when using that, although if I am wrong I would not mind being corrected. I had a similar issue before, where I wanted a drop-down menu from the toolbar similar to the default ones, which I solved thanks to: How to add a dropdown menu to a firefox addon sdk powered addon toolbar button?. Might be worth noting that that the button opening the options dialog is one of the menuitems created as described there. I was considering that it could probably be possible (aka I am not sure) to use something akin to this, but sadly I do not know how I would create a "separate" (drag-able) popup that I could use this on. If possible, I would prefer there to exist a solution, but if someone knows that it is indeed impossible, please do post that so and I can give up without regrets and just make some sort of custom HTML panel instead :) tldr: Is there a way to create a popup dialog similar (in style) to the options window you can open using alt-tools-options in firefox when developing using addon sdk? |
Two key shortcut in emacs without repressing the first key? Posted: 24 Jul 2022 09:02 AM PDT Suppose I define the following shortcut (global-set-key (kbd "C-d C-j") "Hello!") Is it possible to configure emacs so that if I type "C-d C-j C-j C-j" I will get "Hello! Hello! Hello!" rather than having to type "C-d C-j C-d C-j C-d C-j" ? |