Smartsheets Geo Mapping Posted: 06 Jun 2022 08:52 PM PDT I'm considering moving to Smartsheet from Dash/Plotly but one of the features I like from my Dashboard is having a mapping tool based on criterias that filter sets of lat and longs. Is there a way to organically use the Lat and Long in Smartsheet to show a map of those locations? or maybe I could keep only the mapping portion of Dash and access it through Smartsheet by the URL? |
why do we initialize z as z = W * X + b in logistic regression? Posted: 06 Jun 2022 08:52 PM PDT I am fairly new to machine learning. I understood that in linear regression we try to fit a line, or a higher degree polynomial to the traning-set, to come up with the best result. I also understood why we use sigmoid function in logistic regression. But i don't understand why we initialize like z = W * X + b . (W: weights, X: I mean why initializing z like this makes sense. It will be really helpful if someone explains this or refer to any article. thanks in advance. |
Changing current working directory (cwd) to current file directory in VSCode Posted: 06 Jun 2022 08:52 PM PDT So I'm trying to change the directory the integrated terminal runs my Python scripts in from the root workspace (the default, I guess) to the running file directory. I want to do this as I'm more used to work with paths relative to running file than to root dir. Also sometimes I use quite large directory trees and even paths to near directory files get quite long by starting them from root dir. This would also allow me to use Path Intellisense extension as it seems to base suggestions on the current file dir. I heard about changing the lauch.json file but I'm looking for a definitive solution that avoids having to change this in all projects. I have already tried to change settings.json cwd option to "terminal.integrated.cwd": "${fileDirname}" but it doesn´t seem to take any effect, even after reloading. I'm not sure what other infos are relevant here, but nevertheless i'm running vscode on windows 11 version 21H2. Any other info feel free to ask. Thank you all in advance |
how to show parameters by pojo in swagger Posted: 06 Jun 2022 08:51 PM PDT spring boot 2.1.2.RELEASE, springfox-boot-starter 3.0.0 i have a controller looks like @GetMapping("/detail") public ResultVO<List<DefaultDto>> listDetail(DefaultCriteria criteria, Pageable pageable) { wherein DefaultCriteria is a custom pojo, and Pageable is from spring. the swagger ui shown as that is it shows all parameters as flatten structure, thus it looks like there is only one pojo. what i want is : swagger shows these 2 pojo parameters on swagger ui like: criteria(DefaultCriteria) field1 field2 pageable(Pageable) field1 field2 or something like DefaultCriteria field1 DefaultCriteria field2 ... Pageable field1 Pageable field2 ... how could i do this? |
React with Ant desing Table.set column by useSate header have check box.Check box not working Posted: 06 Jun 2022 08:51 PM PDT I want to put a checkbox in the header column where the column uses useState. But the checkbox is not working.but checkBox have update is true import React from 'react'; import 'antd/dist/antd.css'; import { Button, Checkbox, Form, Input,Space,Table } from "antd"; const App = () => { const [checkBox,setCheckBox]=React.useState(false) const [columns,setColumns] = React.useState([ { title: 'Name', dataIndex: 'name', key: 'name', }, { title: ()=>{ return ( <> <Space> age <Checkbox onChange={(e)=>setCheckBox(e.target.checked)} checked={checkBox} /> </Space> </> ) }, dataIndex: 'age', key: 'age', }, { title: 'Address', dataIndex: 'address', key: 'address', }]); const dataSource = [ { key: '1', name: 'Mike', age: 32, address: '10 Downing Street', }, { key: '2', name: 'John', age: 42, address: '10 Downing Street', }]; React.useEffect(()=>{ setColumns(columns.filter((ele)=>ele.dataIndex!=='name')) },[]) return ( <> <Table columns={columns} dataSource={dataSource} /> </> ) } export default App; can not checked but in useState in update enter image description here you can coppy into this link:enter link description here |
"unresolved external symbol" after trying to set extern x-y ints to current window coordinates Posted: 06 Jun 2022 08:52 PM PDT Running into a problem trying to use coordinates from a window position after following a glfw window guide. The first example below runs fine and I can see my window coordinates displayed as I drag my window around the screen. The second example is giving me an error though when I actually try and store the current window coordinates for use. Example 1 function definition for callback to see changing window coordinates static void window_pos_callback(GLFWwindow* window, int xPosNew, int yPosNew) { std::cout << xPosNew << " " << yPosNew << endl; } Within my first main: (displays normally) { glfwSetWindowPosCallback(window, window_pos_callback); } Example 2 another function definition for callback to see changing window coordinates, but this time trying to use external ints to store them so that I can eventually use them in main extern int extglfwNewXpos; extern int extglfwNewYpos; static void window_pos_callback(GLFWwindow* window, int xPosNew, int yPosNew) { extglfwNewXpos = xPosNew; extglfwNewYpos = yPosNew; } Within my second example of main: (unresolved external symbol) { glfwSetWindowPosCallback(window, window_pos_callback); std::cout << extglfwNewXpos << " " << extglfwNewYpos << endl; } Question Is there anything similar or a workaround to be able to perform this action? I don't understand why for instance - if I just set the extern int extglfwNewXpos = 100, then I am allowed to use it. However if I try to set it within a function definition now it becomes unresolved? |
matplotlib: colorbar make subplots unequal size Posted: 06 Jun 2022 08:50 PM PDT I make two subplots with a common shared colorbar. So naturally I want to plot the colorbar only once. However, when I do so, then my subplots become unequal in size. How to place the colorbar outside the subplots on the right? Minimal working example below import numpy as np from matplotlib import colors import matplotlib.pyplot as plt res = 100 x = np.linspace(0, 2*np.pi, res) y = np.sin(x) z = np.cos(x) y2 = -np.sin(x)+0.4 z2 = 0.5*np.cos(2*x) fig_width = 200/25.4 fig_height = 100/25.4 fig = plt.figure(figsize=(fig_width, fig_height)) gs = fig.add_gridspec(1, 2, wspace=0) (ax, ax2) = gs.subplots(sharey='row') images = [] images.append(ax.scatter(x, y, c=z)) images.append(ax2.scatter(x, y2, c=z2)) vmin = min(image.get_array().min() for image in images) vmax = max(image.get_array().max() for image in images) norm = colors.Normalize(vmin=vmin, vmax=vmax) for im in images: im.set_norm(norm) cbar = fig.colorbar(images[0], ax=ax2) cbar.set_label("mylabel", loc='top') fig.tight_layout() plt.show() |
In React, how to fix Warning: You provided a `value` prop to a form field without an `onChange` handler." When I do have an onChange handler Posted: 06 Jun 2022 08:50 PM PDT I'm using React with TypeScript and I'm working on building a Todo app. To start, I was setting up an input that changes a state value when it changes. Pretty simple, I've done before. However, this time I'm getting the following error: Warning: You provided a value prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultValue . Otherwise, set either onChange or readOnly . This error makes perfect sense, I need to add an onChange handler to my input field. However, I do have an onChange handler set. My code so far: My main app file import Input from './components/Input'; import './App.css'; const App = () => { type Todo = { completed: boolean, value: string }; // state variables // mode for establish light mode or dark mode const [theme, setTheme] = useState('dark'); const [value, setValue] = useState('banana'); // images for mode switch const sunIcon = './images/icon-sun.svg'; const moonIcon = './images/icon-moon.svg'; let icon: string; if(theme === 'light'){icon = sunIcon} else{icon = moonIcon}; const iconClick = () => { if(theme === 'light') { setTheme('dark'); } else { setTheme('light'); } } const handleKeyPress = (e: any) => { if (e.which === 13) { console.log('enter pressed') } } const handleChange = (e:any) => { setValue(e.target.value); } return( <div className='app' data-theme={theme}> <main> <header> <h1 className='title'>TODO</h1> <img src={icon} alt='color theme switch' onClick={iconClick} className='icon' /> </header> <Input onKeyPress={handleKeyPress} value={value} onChange={handleChange} /> {/* I pass both value and onChange through props */} </main> <footer> </footer> </div> ) } export default App; My Input component return( <div className='todoContainer'> <div className='checkBubble' /> <input type='text' placeholder='Create a new todo' className='input' onKeyPress={props.onKeyPress} value={props.value} onChange={props.handleChange} // I have both the value and onChange passed in through props /> </div> ) } export default Input; I'm sure the solution is simple and I'm just not seeing it. Thanks! |
How do you store something as a closure in haskell? Posted: 06 Jun 2022 08:51 PM PDT I have an environment (env, LambdaExpr letName valexpr) <- next and I want to store env as a closure, which should result in a ClosureVal. How can I do this; I am trying to make is so that if it's a totally anonymous function, then "" is the function name, otherwise if it was built with a let expression, then the let name is its name. Here is what I have: case getValue (eval evalExpr (env, valexpr)) of Right (ClosureVal "" argName funBody cenv) -> -- 2 let env = Env.bind letName (ClosureVal letName argName funBody cenv) cenv -- 3 in case getValue (eval evalExpr (env, funBody)) of -- 4 Right v -> return v Left err -> evalError err How can I fix the second, third, and fourth lines? |
Trouble executing a string query in MySQL Stored Procedure Posted: 06 Jun 2022 08:49 PM PDT Question i have a stored procedure that executes a string query from a function. but when executing the string i keep getting the error Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE rm_sensor_combined SET subid = 0, rmip = '10.7.75.122', dname = 'ESD-' at line 4 Bellow is the content of the procedure. if as_option = "updateData" then SET ls_option := "UPDATE"; SET ls_query = (select fn_Sys_GenUpdateDetail(as_table, ls_option) ); end if; SET @sql := ls_query ; PREPARE stmt FROM @sql; EXECUTE stmt;
stored procedure execution here is the result from the function, therefore the query to be executed quoted ' UPDATE rm_sensor_combined \n SET subid = 0, rmip = '10.7.75.122', dname = 'ESD-001', dlocation = 'FFF-GGG-SS', warning_max = 2000, alert_max = 4000, ispaused = 0, isused = 1, update_by = ''\n where giruid =1 and rscuid = 1 and (subid = 0 or rmip = '10.7.75.122' or dname = 'ESD-001' or dlocation = 'FFF-GGG-SS' or warning_max = 2000 or alert_max = 4000 or ispaused = 0 or isused = 1); \n UPDATE rm_sensor_combined \n SET subid = 0, rmip = '10.7.75.122', dname = 'ESD-002', dlocation = ' - - ', warning_max = 2000, alert_max = 4000, ispaused = 0, isused = 0, update_by = ''\n where giruid =1 and rscuid = 2 and (subid = 0 or rmip = '10.7.75.122' or dname = 'ESD-002' or dlocation = ' - - ' or warning_max = 2000 or alert_max = 4000 or ispaused = 0 or isused = 0); \n ' Unquoted UPDATE rm_sensor_combined SET subid = 0, rmip = '10.7.75.122', dname = 'ESD-001', dlocation = 'FFF-GGG-SS', warning_max = 2000, alert_max = 4000, ispaused = 0, isused = 1, update_by = '' where giruid =1 and rscuid = 1 and (subid = 0 or rmip = '10.7.75.122' or dname = 'ESD-001' or dlocation = 'FFF-GGG-SS' or warning_max = 2000 or alert_max = 4000 or ispaused = 0 or isused = 1); UPDATE rm_sensor_combined SET subid = 0, rmip = '10.7.75.122', dname = 'ESD-002', dlocation = ' - - ', warning_max = 2000, alert_max = 4000, ispaused = 0, isused = 0, update_by = '' where giruid =1 and rscuid = 2 and (subid = 0 or rmip = '10.7.75.122' or dname = 'ESD-002' or dlocation = ' - - ' or warning_max = 2000 or alert_max = 4000 or ispaused = 0 or isused = 0); any help on what is causing the error would help. thanks |
Installing NBIS software Posted: 06 Jun 2022 08:49 PM PDT I was trying to install NBIS software for my project and was getting a error when i try to do make it make[1]: Entering directory '/home/kuuhaku/Desktop/nbis_v5_0_0/Rel_5.0.0/png' Makefile:57: /package.mak: No such file or directory make[1]: *** No rule to make target '/package.mak'. Stop. make[1]: Leaving directory '/home/kuuhaku/Desktop/nbis_v5_0_0/Rel_5.0.0/png' make: *** [makefile:150: it] Error 1 been stuck here for a week, any help would be greatly appreciated |
Create a Java program that will compute for the area of a circle. using Java Posted: 06 Jun 2022 08:48 PM PDT - Create a Java program that will compute for the area of a circle.
a. Assume a value for the circle's radius and set the value of pi to its constant value of 3.1416 b. Declare your variables to handle any floating point or decimal places c. In addition you must create a function/method called computeArea inside your class that receives the pi and radius as its parameter; this function should return the result back to main function |
Uncaught TypeError: Cannot set properties of null (setting ('innerHTML') [duplicate] Posted: 06 Jun 2022 08:48 PM PDT The segment in question would be the document.getElementByID("enemies") which when ran the content is null function drawPlayer(){ content = "<div class='player' style='left:"+player.left+"px; top:"+player.top+"px'></div>"; document.getElementById("players").innerHTML = content; } drawPlayer(); function drawEnemies(){ content = ""; console.log(enemies); for(var idx=0; idx<enemies.length; idx++){ content += "<div class='enemy' style='left:"+enemies[idx].left+"px; top:"+enemies[idx].top+"px'></div>"; console.log(content); } document.getElementById("enemies").innerHTML = content; } // The content here has the Uncaught TypeError: Cannot set properties of null (setting innerHTML) for content; drawEnemies(); |
Running Count of Non-Blank Cells in dynamic named range in Google Sheets Posted: 06 Jun 2022 08:48 PM PDT I'm trying to use a single array formula to pull a running count of non-blank cells in a dynamic range. I know how to do it with a pasted formula with simple cell addresses like so: =COUNTIF($B$3:B3,"<>") However, this requires you to know how many cells you'll be filling and then paste the formula to as many cells. The ranges I'm dealing with will change based on input from the user. Please see below, with desired output in green, using pasted COUNTIF functions: Dynamic ranges are displayed as text on Row 2. Their lengths are based on input to be pasted in Col D, and these ranges would be called via INDIRECT(). Can anyone provide a way that the Countif/Countifs logic from above can be translated to an Array Formula that uses dynamic ranges? |
Get token from paypal express checkout Posted: 06 Jun 2022 08:50 PM PDT |
Python: print() not outputting translated str(), outputs original line of code Posted: 06 Jun 2022 08:48 PM PDT I'm working on a basic Biology program to help me better learn python, but I'm hung up on outputting my converted strings. I have a DNA input that is being translated to an RNA output, but my RNA output reads as "<_io.AextIOWrapper name='input.txt' mode='+r' encoding='cp1252'>" instead of the RNA. My DNA string outputs fine, so I know the program is getting the data correctly. I'm at wits end trying to convert the string back to ASCII to try and use the same print(RNA.read()) function, but I know that's not the proper way. inputbuffer = open("input.txt", "+r") print(inputbuffer.read()) DNA = str(inputbuffer) translation = {65: 85, 84: 65, 71: 67, 67: 71} RNA = DNA.translate(translation) print(RNA) |
requests.packages.urllib3.util.retry import error in Python Posted: 06 Jun 2022 08:48 PM PDT I'm using pipenv with Python 3.9. The following code makes an error on the line 13; from requests.packages.urllib3.util.retry import Retry. The error message is; Import "requests.packages.urllib3.util.retry" could not be resolved. No quick fixes available. But I have no clue what wrong is exactly. Everything is imported properly though. import requests from random import choice import wget from moviepy.editor import * import urllib.request from PIL import Image as IMG import os from keys import * from datetime import datetime, date from csv import reader import pyttsx3 from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry session = requests.Session() retry = Retry(connect=3, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) class DidYouKnow: def __init__(self): self.category = None self.question = None self.answer = None self.searchKey = None self.color = choice(['26,188,156', '22,160,133', '46,204,113', '39,174,96', '52,152,219', '41,128,185', '155,89,182', '142,68,173', '52,73,94', '44,62,80', '241,196,15', '243,156,18', '230,126,34', '211,84,0', '231,76,60', '192,57,43']) def __init__(self, category, question, answer, searchKey): self.category = category self.question = question self.answer = answer self.searchKey = searchKey self.color = choice(['26,188,156', '22,160,133', '46,204,113', '39,174,96', '52,152,219', '41,128,185', '155,89,182', '142,68,173', '52,73,94', '44,62,80', '241,196,15', '243,156,18', '230,126,34', '211,84,0', '231,76,60', '192,57,43']) def generateVideo(self): backgrounds = [] try: # Download a Background Video videos = session.get(f'https://pixabay.com/api/videos/?key={API_KEY}&q={self.searchKey}&min_width=1920&min_height=1080') try: videos = videos.json() except Exception as e: pass if videos["total"] <= 0: print( f'Cannot find background video for {self.searchKey}, Adding random Background') videos = session.get(f'https://pixabay.com/api/videos/?key={API_KEY}&category=backgrounds&min_width=1920&min_height=1080') videos = videos.json() # sorting videos to select best quality videos for video in videos["hits"]: for size in video["videos"]: for quality in video["videos"][size]: if video["videos"][size][quality] == 1920: # print() backgrounds.append(video["videos"][size]) background = choice(backgrounds) wget.download( background["url"], 'temp.mp4') # Editing Video try: self.editVideo() except Exception as err: print("Editing Video", err) except Exception as e: print("Generating Video", e) def editVideo(self): try: baseClip = VideoFileClip( 'temp.mp4') Clip = baseClip.set_duration(16) Clip = Clip.rotate(90) # Clip = Clip.resize((1080,1920)) heading_clip = TextClip( str(self.category), fontsize=100, color='white', bg_color=f'rgb({self.color})', font='Swis721-Cn-BT-Bold-Italic', align='center', kerning=6, transparent=True) heading_clip = heading_clip.set_pos( 'top').set_duration(16).margin(20) question_clip = TextClip( str(self.question), fontsize=130, color='white', stroke_color='black', stroke_width=5, font='tahoma-bold', align='center', method='caption', bg_color=f'rgba({self.color},0.5)') question_clip = question_clip.set_pos( 'center').set_duration(10).margin(10) answer_clip = TextClip( str(self.answer), fontsize=130, color=f'rgb({self.color})', stroke_color='black', stroke_width=5, font='Rockwell-Extra-Bold', align='center', method='caption', bg_color='black') answer_clip = answer_clip.set_pos( 'center').set_duration(6).margin(10, color=(236, 240, 241)) print("trying to concatenate") Fact = concatenate_videoclips( [question_clip, answer_clip], method='chain') Clip = CompositeVideoClip( [Clip, heading_clip, Fact.set_position("center")]) #Generate Both Audio for Question And Answer pyttsx3Driver = "sapi5" if os.name == "nt": pyttsx3Driver = "sapi5" print(f"os windown, using sapi5 as Voice Generator Driver") elif os.name == "posix": pyttsx3Driver = "espeak" print(f"os linux, using espeak as Voice Generator Driver") else: pyttsx3Driver = "nsss" print(f"os mac, using nsss as Voice Generator Driver") engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', choice(voices).id) rate = engine.getProperty('rate') engine.setProperty('rate', 125) engine.save_to_file(self.question, 'question_audio.mp3') engine.runAndWait() engine.save_to_file(self.answer, 'answer_audio.mp3') engine.runAndWait() QuestionAudio = CompositeAudioClip( [AudioFileClip('question_audio.mp3'), AudioFileClip(BACKGROUNDAUDIOFILE)]) QuestionAudio.set_duration(10) QuestionAudio = CompositeAudioClip([QuestionAudio]) AnswerAudio = CompositeAudioClip( [AudioFileClip('answer_audio.mp3')]) AnswerAudio.set_duration(6) audio = concatenate_audioclips([QuestionAudio, AnswerAudio]) print(f'Audio Duration = {audio.duration}') Clip.audio = audio Clip.write_videofile( f'output/{self.question}.mp4') Clip.close() baseClip.close() os.remove('temp.mp4') os.remove('backdrop.jpeg') os.remove('background.jpeg') except Exception as e: print("Error at editing Video:",e) def generatePromoPic(self): try: ims = session.get(f'https://pixabay.com/api/?key={API_KEY}&q={self.searchKey}&image_type=photo&orientation=horizontal&order=popular') try: ims = ims.json() except Exception as E: print(E) if ims["total"] <= 0: print(f'Cannot find image result for {self.searchKey}, Adding random Pic') ims = session.get(f'https://pixabay.com/api/?key={API_KEY}&image_type=photo&orientation=horizontal&order=popular') try: ims = ims.json() except Exception as E: print(E) photo = choice(ims["hits"]) print(f'Downloading: {photo["largeImageURL"]}') opener = urllib.request.build_opener() opener.addheaders = [ ('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')] urllib.request.install_opener(opener) # setting filename and image URL filename = 'background.jpeg' image_url = photo["largeImageURL"] # calling urlretrieve function to get resource urllib.request.urlretrieve(image_url, filename) size = (1920,1920) outfile = "backdrop.jpeg" im = IMG.open(filename) im.resize(size, IMG.ANTIALIAS) im.save(outfile, "JPEG") im = IMG.open(outfile) print(im.size) width, height = im.size imageHeightRemaining = width - height textheight = 200 if imageHeightRemaining < 200 else 300 BGCOLOR = choice(['#1ABC9C', '#16A085', '#2ECC71', '#27AE60', '#3498DB', '#2980B9', '#9B59B6', '#8E44AD', '#34495E', '#2C3E50', '#F1C40F', '#F39C12', '#E67E22', '#D35400', '#E74C3C', '#C0392B']) Title = TextClip( str(self.category), color='white', font='tahoma-bold', align='center', method='caption', size=(1080, 100), bg_color='black').set_position("top") Title = Title.margin(bottom=20) thumbnail = TextClip( str(self.question), color='white', bg_color=BGCOLOR, font='tahoma-bold', align='center', method='caption', size=(1080, textheight)).set_pos(('left', 'bottom')) thumbnail = thumbnail.margin(top=10, bottom=20) back = ImageClip(outfile) back = back.margin(top=20, bottom=20, left=20, right=20) bigBack = TextClip( ' ', color='black', bg_color='black', font='tahoma-bold', align='center', method='caption', size=(1080, 720)).set_pos(('left', 'bottom')) final = CompositeVideoClip( [bigBack, back.set_position("top"), thumbnail.set_position("bottom"), Title.set_position("top")]) final.save_frame(f'output/{self.question}.png', t=1) final.close() except Exception as e: print("GeneratePromoPic", e) def startProcess(category, question, answer, searchKey): didyouknow = DidYouKnow(category, question, answer, searchKey) if not os.path.exists('output'): os.makedirs('output') didyouknow.generatePromoPic() print("PromoPic Generated \n") didyouknow.generateVideo() print("Video Generated \n") with open('data.csv', 'r',) as read_obj: csv_dict_reader = reader(read_obj) next(csv_dict_reader) for row in csv_dict_reader: print(row) startProcess(row[0], row[1], row[2], row[3]) |
Does sqlite need to scan all the datebase where using "select xx from table where a!=b limit 200, 1" Posted: 06 Jun 2022 08:49 PM PDT My sqlite may store billions row of data. Table are like this " name VARCHAR(128), directory VARCHAR(128), prefix VARCHAR(128), crtime INTEGER, filesize INTEGER, " And I didn't create index for any sections. I need to scan all the db to check whether filesize or crtime satisfy some conditions. To improve scanning performance, I want to scan DB like this "select name from table where filesize<100 limit 200, 1" every 200 rows. I'm not very familar with sqlite. So I don't kown whether sqlite will scan all the db if I use this sql command. And are there any more efficient methords? |
Javascript modify array of objects and concat value Posted: 06 Jun 2022 08:52 PM PDT I have an array of objects like this: const data = [ { id: '1', label: 'Last Name', value: 'Smith' }, { id: '1', label: 'Last Name', value: 'Blogs' }, { id: '2', label: 'First Name', value: 'John' }, { id: '2', label: 'First Name', value: 'Joe' } ]; I'm trying to get an output like this: const output = [ {key: 'Employee', value: 'John Smith'}, {key: 'Employee', value: 'Joe Blogs'} ]; I was looking at using reduce, but am stuck on how to properly get a condition to say that if id is 2, then add to output.value, and if id is 1 then concat output.value to the value already there. Both id 1 and id 2 are dynamic and can grow. Id 1 will always be last name and id 2 will always be first name. |
Django 4.0 getting many to many field objects in List View Posted: 06 Jun 2022 08:52 PM PDT I have a book model and a genre model that have a many to many relationship. How would I go about getting all the books for a specific genre in a list view. I'm assuming its faster to get a Genre object and get all the books from it using a query such as "genre.objects.book_set.all" rather than going through all books and seeing if they have the specified genre. However I'm not sure how I would do that in a ListView? I wanna take the genre name from the url and then use that to get the genre object. Here is what I have: urls.py: path('genre/<string:name>', GenreListView.as_view(), name='book-genre'), Models.py: class Genre(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=150, unique=True) description = models.TextField() user_count = models.IntegerField() pages = models.IntegerField() genres = models.ManyToManyField(Genre) image = models.ImageField(default='book_imgs/default.jpg', upload_to='book_imgs') def __str__(self): return self.name Views.py class GenreListView(ListView): model = Genre def get_queryset(self): Not sure what to put here.... return |
Can I plot a colorbar from a list of colors? (Python) Posted: 06 Jun 2022 08:51 PM PDT Here's part of the code I'm working on: cm = LinearSegmentedColormap.from_list('defcol', ["#000000", "#FF0000"]) trace_color = cm(np.linspace(0,1,cycles)) for k, color in zip(range(cycles),trace_color): lis = KL_rest[k::cycles] plt.scatter(scanpoints, lis, color = color, marker = '^', alpha = 0.9) Here I am generating the scatter plot using a for loop, and the colors come from the list trace_color . My question is if I can generate a colorbar, where the colors are from the trace_color and labels on the colorbar come from range(cycles) . I tried to add plt.colorbar() after the for loop but that didn't work. Thanks! |
How to calculate div position relative to the total browser area? Posted: 06 Jun 2022 08:49 PM PDT How to calculate the div position relative to the total browser area? Example: https://i.imgur.com/RPdn8tL.png I'm referring to the position relative to the entire browser area. The orange rectangle is at x249 and y346, how i could automatic get this position? I mean, is possible to read it somewhere or do i need to read something and do a math calc? |
Bigquery run one query using multiple datasets- Query error: Too many arguments to FORMAT for pattern Posted: 06 Jun 2022 08:50 PM PDT I am trying to use loop function to save some efforts running same query using 2 datasets in Bigquery. I created a table which has below metrics (this was created successfully, I saw it under projects): DECLARE data_set_list ARRAY<STRING> DEFAULT ['12345678', '45678912']; CREATE OR REPLACE TABLE `xxx.TEST.Test_file` (date DATE, data_source STRING,promo_identifier STRING,promo_description STRING,deviceCategory STRING, channelGrouping STRING, sourcemedium STRING,landing_page STRING,site STRING, region STRING, sessions INT64, total_events INT64, orders INT64, duration INT64, revenue FLOAT64); Then I had below query to insert numbers however getting error message:"Query error: Query error: Query error: Too many arguments to FORMAT for pattern "\n\nINSERT INTO xx.Test_file \n\nSELECT date,data_source,\npromo_identifier, promo_description, deviceCategory, channelGrouping, sourcemedium, landing_page,\nsite, region,\nSUM(sessions) AS Sessions, SUM(total_events) AS Total_events, SUM(orders) AS Orders, SUM(duration) AS Duration, SUM(revenue) AS Revenue\nfrom \n\n\n\n(select * from xx.xxx.masterdata )\ngroup by 1,2,3,4,5,6,7,8,9,10\n\n\n"; Expected 1; Got 2 at [15:1] FOR data_set IN (SELECT * FROM UNNEST(data_set_list) as id) DO EXECUTE IMMEDIATE FORMAT( """ INSERT INTO `xxx.TEST.Test_file` SELECT FORMAT_DATE("%Y/%m/%d", Date) as date,data_source, promo_identifier, promo_description, deviceCategory, channelGrouping, sourcemedium, landing_page, site, region, SUM(sessions) AS Sessions, SUM(total_events) AS Total_events, SUM(orders) AS Orders, SUM(duration) AS Duration, SUM(revenue) AS Revenue from (select * from `xxx.xxx.masterdata` ) group by 1,2,3,4,5,6,7,8,9,10 """ , data_set.id); END FOR; I found out that when I bring in , data_set.id, it returns error saying "Expected 1; Got 2". when I bring in , data_set.id, data_set.id it returns error saying " Expected 1; Got 3". As this is my first time learning loop, can anyone tell me what does the data_set.id do here? |
Cannot Reshape array of size 200 into shape (28, 28) Posted: 06 Jun 2022 08:48 PM PDT I am trying to make a ML model to OCR of Letters. I have attached the code below, when I try to reshape the array it gives me an error. I was following a tutorial, in which the instructor did the same and didn't get any error at all. What could be the issue? from emnist import extract_training_samples import cv2 as cv import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.decomposition import PCA images, labels = extract_training_samples('letters') classes = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26 } # Checking unique instances of each letter print(pd.Series(labels).value_counts()) # Checking shape of image at index 0 print(images[0].shape) X = np.array(images) Y = np.array(labels) # Checking the data image and label # plt.imshow(X[1], cmap='gray') # plt.show() # print(Y[1]) # Reshaping X to be of (n, 784) dim X_new = X.reshape(len(X), -1) print(X_new.shape) print(Y.shape) # Splitting the data xTrain, xTest, yTrain, yTest = train_test_split(X_new, Y, test_size=0.2, random_state=10) # Finding max value in Training and Testing set and diving them by those print(xTrain.max()) print(xTest.max()) # Scaling the data xTrain = xTrain/255 xTest = xTest/255 # Applying PCA for feature selection print(xTrain.shape, xTest.shape) pca = PCA(.98) xTrain = pca.fit_transform(xTrain) xTest = pca.transform(xTest) print(xTrain.shape, xTest.shape) print(pca.n_components) print(pca.n_features_) model = LogisticRegression(solver='lbfgs', max_iter=400) model.fit(xTrain, yTrain) print(xTest[0].shape) # tr_pred = model.predict(xTrain) # ts_pred = model.predict(xTest) # # print('Training score', accuracy_score(yTrain, tr_pred)) # print('Testing score', accuracy_score(yTest, ts_pred)) plt.imshow(xTest[1].reshape(28, 28), cmap='gray') plt.show() print(yTest[1]) Anyone could help somehow reshape the array into proper dimensions? |
Python big_o seems to return completely incorrect results - what am I doing wrong? Posted: 06 Jun 2022 08:49 PM PDT I am comparing runtimes of different ways of flattening a list of lists using the big_o module, and for following methods my function does not return the expected results, namely: - This one:
def itertools_chain_from_iterable(arr): return list(chain.from_iterable(arr)) returns "constant", which can't possibly be true. - This one:
def merge_extend(self,arr): output = [] for l in arr: output.extend(l) return output returns "cubic" (shouldn't it be quadratic at most?), while... - ..this one
def merge_w_sum(self,arr): return sum(arr,[]) returns "linear" (I'm quite sure it should be quadratic, see proof here. - Furthermore, the list comprehension one
def merge_bucket(self,bucket): return [number for n in bucket for number in n] returns "polynomial", which seems terrifying (would expect linear here as well) Code used to calculate the complexities: print('<function name>:', big_o.big_o(<function name>, lambda n:[big_o.datagen.integers(9900,1,9999999) for n in range(50)], n_measures=20)[0]) Output: complexity of itertools_chain_from_iterable: Constant: time = 0.0013 (sec) complexity of merge_w_sum: Linear: time = 0.46 + 6.2E-07*n (sec) complexity of merge_extend: Cubic: time = 0.048 + -2.3E-18*n^3 (sec) complexity of merge_bucket: Polynomial: time = 0.2 * x^-0.019 (sec) What is it that I'm doing (or understanding) wrong? Many thanks in advance for useful tips! |
matplotlib only plotting date instead of given datetime variable Posted: 06 Jun 2022 08:50 PM PDT I am trying to plot candle sticks but for some reason, the plot does not grab the entire DateTime variable. But only the date. Plotting all candles on the same X axis rather than all 15 min as the data is given in. Following code. ## PLOT Candles plt.figure() #define width of candlestick elements width = .5 width2 = .05 #define up and down prices up = df[df.close>=df.open] down = df[df.close<df.open] print(up) #define colors to use col1 = 'green' col2 = 'red' col3 = 'blue' col4 = 'grey' #plot up prices plt.bar(up.index,up.close-up.open,width,bottom=up.open,color=col1) plt.bar(up.index,up.high-up.close,width2,bottom=up.close,color=col1) plt.bar(up.index,up.low-up.open,width2,bottom=up.open,color=col1) #plot down prices plt.bar(down.index,down.close-down.open,width,bottom=down.open,color=col2) plt.bar(down.index,down.high-down.open,width2,bottom=down.open,color=col2) plt.bar(down.index,down.low-down.close,width2,bottom=down.close,color=col2) plt.show() exit() Following is the print of up print(df[:5].to_dict()) {'open': {Timestamp('2016-01-14 08:15:00'): 1.08719, Timestamp('2016-01-14 08:30:00'): 1.08735, Timestamp('2016-01-14 08:45:00'): 1.08674, Timestamp('2016-01-14 09:00:00'): 1.08674, Timestamp('2016-01-14 09:15:00'): 1.08671}, 'high': {Timestamp('2016-01-14 08:15:00'): 1.08749, Timestamp('2016-01-14 08:30:00'): 1.08739, Timestamp('2016-01-14 08:45:00'): 1.08734, Timestamp('2016-01-14 09:00:00'): 1.08722, Timestamp('2016-01-14 09:15:00'): 1.08673}, 'low': {Timestamp('2016-01-14 08:15:00'): 1.0869, Timestamp('2016-01-14 08:30:00'): 1.08673, Timestamp('2016-01-14 08:45:00'): 1.08669, Timestamp('2016-01-14 09:00:00'): 1.08666, Timestamp('2016-01-14 09:15:00'): 1.08582}, 'close': {Timestamp('2016-01-14 08:15:00'): 1.08736, Timestamp('2016-01-14 08:30:00'): 1.08673, Timestamp('2016-01-14 08:45:00'): 1.08673, Timestamp('2016-01-14 09:00:00'): 1.08671, Timestamp('2016-01-14 09:15:00'): 1.08618}, 'volume': {Timestamp('2016-01-14 08:15:00'): 2181, Timestamp('2016-01-14 08:30:00'): 1738, Timestamp('2016-01-14 08:45:00'): 1938, Timestamp('2016-01-14 09:00:00'): 3010, Timestamp('2016-01-14 09:15:00'): 2734}} |
How do I Put Bottom-shape of the Background Image HTML? Posted: 06 Jun 2022 08:49 PM PDT I want to design the bottom of the background image of my web page , I have the Shape image how can i put that above the Background Image so that the shape will take place over the image, If i am putting that shape image above the bg-color the shape is fitted but not working in in the background image Want to Use this shape In this packground i want to put that shape in the bottom how can i do that? Expected |
Mock testing a function that downloads a file using node-fetch? Posted: 06 Jun 2022 08:48 PM PDT This answer has the following way to download a file using the node-fetch library https://stackoverflow.com/a/51302466: const downloadFile = (async (url, path) => { const res = await fetch(url); const fileStream = fs.createWriteStream(path); await new Promise((resolve, reject) => { res.body.pipe(fileStream); res.body.on("error", reject); fileStream.on("finish", resolve); }); }); How to mock this if a function has this method as part of it? I'm running into weird problems: unit.test.js import { PassThrough } from 'stream'; import { createWriteStream, WriteStream } from 'fs'; import fetch, { Response } from 'node-fetch'; import mocked = jest.mocked; jest.mock('node-fetch'); jest.mock('fs'); describe('downloadfile', () => { const mockedFetch = fetch as jest.MockedFunction<typeof fetch>; const response = Promise.resolve({ ok: true, status: 200, body: { pipe: jest.fn(), on: jest.fn(), }, }); const mockWriteable = new PassThrough(); mocked(createWriteStream).mockReturnValueOnce(mockWriteable as unknown as WriteStream); mockedFetch.mockImplementation(() => response as unknown as Promise<Response>); it('should work', async () => { await downloadfile(); }), ); }); Throws: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined at GlobSync.Object.<anonymous>.GlobSync._readdirEntries (//node_modules/glob/sync.js:300:33) at GlobSync.Object.<anonymous>.GlobSync._readdir (//node_modules/glob/sync.js:288:17) at GlobSync.Object.<anonymous>.GlobSync._processReaddir (//node_modules/glob/sync.js:137:22) at GlobSync.Object.<anonymous>.GlobSync._process (/api/node_modules/glob/sync.js:132:10) What could the solutions be? |
I can't find "Knit" button in RStudio Posted: 06 Jun 2022 08:50 PM PDT I installed RStudio Desktop windows version to study a course on coursera, and i have to knit a certain RMD file. I installed all the packages including "knitr" but i still can't find a knit button in my interface. |
Python 3 Threaded websockets server Posted: 06 Jun 2022 08:51 PM PDT I'm building a Websocket server application in python 3. I'm using this implementation: https://websockets.readthedocs.io/ Basically I want to manage multiple client. Also I want to send data from 2 different thread (one for GPS + one for IMU) GPS thread is refreshed 1Hz, while IMU thread is refresh at 25Hz My problem is in MSGWorker.sendData method: as soon as I uncomment the line @asyncio.coroutine and yield from websocket.send('{"GPS": "%s"}' % data) the whole method does nothing (no print("Send data: foo") in terminal) However with these two line commented my code works as I expect except that I send nothing through the websocket. But, of course, my goal is to send data through the websocket, I just don't understand why it doesn't work ? Any idea ? server.py #!/usr/bin/env python3 import signal, sys sys.path.append('.') import time import websockets import asyncio import threading connected = set() stopFlag = False class GPSWorker (threading.Thread): def __init__(self): threading.Thread.__init__(self) self.data = 0 self.lastData = 0 self.inc = 0 # Simulate GPS data def run(self): while not stopFlag: self.data = self.inc self.inc += 1 time.sleep(1) def get(self): if self.lastData is not self.data: self.lastData = self.data return self.data class IMUWorker (threading.Thread): def __init__(self): threading.Thread.__init__(self) self.data = 0 self.lastData = 0 self.inc = 0 # Simulate IMU data def run(self): while not stopFlag: self.data = self.inc self.inc += 1 time.sleep(0.04) def get(self): if self.lastData is not self.data: self.lastData = self.data return self.data class MSGWorker (threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while not stopFlag: data = gpsWorker.get() if data: self.sendData('{"GPS": "%s"}' % data) data = imuWorker.get() if data: self.sendData('{"IMU": "%s"}' % data) time.sleep(0.04) #@asyncio.coroutine def sendData(self, data): for websocket in connected.copy(): print("Sending data: %s" % data) #yield from websocket.send('{"GPS": "%s"}' % data) @asyncio.coroutine def handler(websocket, path): global connected connected.add(websocket) #TODO: handle client disconnection # i.e connected.remove(websocket) if __name__ == "__main__": print('aeroPi server') gpsWorker = GPSWorker() imuWorker = IMUWorker() msgWorker = MSGWorker() try: gpsWorker.start() imuWorker.start() msgWorker.start() start_server = websockets.serve(handler, 'localhost', 7700) loop = asyncio.get_event_loop() loop.run_until_complete(start_server) loop.run_forever() except KeyboardInterrupt: stopFlag = True loop.close() print("Exiting program...") client.html <!doctype html> <html> <head> <meta charset="UTF-8" /> </head> <body> </body> </html> <script type="text/javascript"> var ws = new WebSocket("ws://localhost:7700", 'json'); ws.onmessage = function (e) { var data = JSON.parse(e.data); console.log(data); }; </script> Thanks you for your help |
No comments:
Post a Comment