Collage

n. A piece of art made by sticking various different materials, aka PHENOMENA Magazine
Department
programming

programming

Using Selenium: How to keep logged in after closing the driver in Python
I tried the below code on my Mac, and it worked perfectly fine. I don't need to login again. from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait chrome_options = Options() chrome_options.add_experimental_option("detach", True) chrome_options.add_argument("user-data-dir=/tmp/oriel") # chrome_options.add_argument("--start-maximized") browser = webdriver.Chrome(options=chrome_options) wait = WebDriverWait(browser, 10) url = "https://oriel.com" browser.get(url) browser.implicitly_wait(1) print(browser.title) For window you can try changing the path as below chrome_options.add_argument("user-data-dir=C:\\Users\\Oriel\\AppData\\Local\\Google\\Chrome\\User Data\\Default")   Ref. Using selenium: How to keep logged in after closing Driver in Python I want to get my Whatsapp web (web.whatsapp.com) logged in, at the second time opening the Whatsapp web on chrome driver. Following is my code based on Python need your help. from selenium import https://stackoverflow.com/questions/45651879/using-selenium-how-to-keep-logged-in-after-closing-driver-in-python How to start ChromeDriver with existing login GroupsSign inGroupsSelenium UsersConversationsLabelsAboutSend feedbackHelpPrivacy • TermsHow to start ChromeDriver with existing login 11741 viewsChromeJavaSkip to first unread messageTiếu Thủyunread,Nov 26, 2014, 11:59:10 PM11/26/14Reply to auth https://groups.google.com/g/selenium-users/c/CL8kdxhgdj0  
python · June 2, 2023, 3:23 a.m.
selenium
How to move (drag/pan) and zoom an element (image or div) using JavaScript
Check this out!   <!DOCTYPE html> <html> <head> <title>Move (drag/pan) and zoom object (image or div) in pure js</title> <style> html, body { margin: 0; padding: 0; } #zoomContainer { width: 100vw; height: 100vh; overflow: hidden; position: relative; } #zoomImage { position: absolute; cursor: move; transition: transform 0.3s; max-width: 100%; max-height: 100%; top: 0; left: 0; width: 100%; height: 100%; } .zoomButton { position: fixed; top: 20px; padding: 10px; font-size: 16px; background-color: #ffffff; border: none; cursor: pointer; } #zoomInButton { left: 20px; } #zoomOutButton { left: 60px; } </style> </head> <body> <div id="zoomContainer"> <img id="zoomImage" src="bg.jpg" alt="zoom image" /> </div> <button id="zoomInButton" class="zoomButton">zoom in</button> <button id="zoomOutButton" class="zoomButton">zoom out</button> <script> document.addEventListener('DOMContentLoaded', function() { var zoomContainer = document.getElementById('zoomContainer'); var zoomImage = document.getElementById('zoomImage'); var zoomLevel = 1; var minZoomLevel = 1; var maxZoomLevel = 2; var zoomIncrement = 0.2; var isDragging = false; let newPosX = 0, newPosY = 0, startPosX = 0, startPosY = 0; function updateZoomedImage() { var imageWidth = zoomImage.offsetWidth; var imageHeight = zoomImage.offsetHeight; var newImageWidth = imageWidth * zoomLevel; var newImageHeight = imageHeight * zoomLevel; var left = zoomImage.offsetLeft; var top = zoomImage.offsetTop; zoomImage.style.transform = 'scale(' + zoomLevel + ')'; zoomImage.style.width = newImageWidth + 'px'; zoomImage.style.height = newImageHeight + 'px'; // Restrict images from leaving containers if (Math.abs(zoomImage.offsetLeft - newPosX) >= Math.abs((parseInt(zoomImage.style.width, 10) - window.innerWidth) / 2)) { left = 0; } if (Math.abs(zoomImage.offsetTop - newPosY) >= Math.abs((parseInt(zoomImage.style.height, 10) - window.innerHeight) / 2)) { top = 0; } zoomImage.style.left = left + 'px'; zoomImage.style.top = top + 'px'; // when the user clicks down on the element zoomImage.addEventListener('mousedown', function(e) { e.preventDefault(); // get the starting position of the cursor startPosX = e.clientX; startPosY = e.clientY; document.addEventListener('mousemove', mouseMove); document.addEventListener('mouseup', function() { document.removeEventListener('mousemove', mouseMove); }); }); } function zoomIn() { if (zoomLevel < maxZoomLevel) { zoomLevel += zoomIncrement; zoomLevel = Math.min(zoomLevel, maxZoomLevel); updateZoomedImage(); } if (zoomLevel === maxZoomLevel) { document.getElementById('zoomInButton').disabled = true; } document.getElementById('zoomOutButton').disabled = false; } function zoomOut() { if (zoomLevel > minZoomLevel) { zoomLevel -= zoomIncrement; zoomLevel = Math.max(zoomLevel, minZoomLevel); updateZoomedImage(); } if (zoomLevel === minZoomLevel) { document.getElementById('zoomOutButton').disabled = true; } document.getElementById('zoomInButton').disabled = false; if (zoomLevel === 1) { zoomImage.style.cursor = 'move'; } } function mouseMove(e) { // calculate the new position newPosX = startPosX - e.clientX; newPosY = startPosY - e.clientY; // with each move we also want to update the start X and Y startPosX = e.clientX; startPosY = e.clientY; // Restrict images from leaving containers if (Math.abs(zoomImage.offsetLeft - newPosX) >= Math.abs((parseInt(zoomImage.style.width, 10) - window.innerWidth) / 2) || Math.abs(zoomImage.offsetTop - newPosY) >= Math.abs((parseInt(zoomImage.style.height, 10) - window.innerHeight) / 2) ) { return; } // set the element's new position: zoomImage.style.left = (zoomImage.offsetLeft - newPosX) + "px"; zoomImage.style.top = (zoomImage.offsetTop - newPosY) + "px"; } function initialize() { var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; zoomContainer.style.width = windowWidth + 'px'; zoomContainer.style.height = windowHeight + 'px'; updateZoomedImage(); document.getElementById('zoomInButton').addEventListener('click', zoomIn); document.getElementById('zoomOutButton').addEventListener('click', zoomOut); } initialize(); window.addEventListener('resize', function() { initialize(); }); }); </script> </body> </html>   Result: Edit fiddle - JSFiddle - Code Playground Close Start with a boilerplate: jQuery Vue React React + JSX Preact TypeScript CoffeeScript SCSS CSS Grid Bootstrap PostCSS Show boilerplate bar less often? Links: 👍🏻 Roadmap (vote for features) 🐞 Bug tracker 📙 Docs 🎛 Service status Support JSFiddle and g https://jsfiddle.net/xxxvvvxxx/ygwqxcpm/   Ref. How to drag an element using javascript While building out a new image generator, I needed a way to drag and move HTML elements inside of another element. Take a look at what I was building below: This is actually the new Post Image Genera... https://devdojo.com/tnylea/how-to-drag-an-element-using-javascript  
front-end · June 2, 2023, 1:22 a.m.
Executing <script> elements inserted with .innerHTML
Simplified ES6 version of @joshcomley&#39;s answer with an example. No JQuery, No library, No eval, No DOM change, Just pure Javascript. function setInnerHTML(elm, html) { elm.innerHTML = html; Array.from(elm.querySelectorAll("script")) .forEach( oldScriptEl =&gt; { const newScriptEl = document.createElement("script"); Array.from(oldScriptEl.attributes).forEach( attr =&gt; { newScriptEl.setAttribute(attr.name, attr.value) }); const scriptText = document.createTextNode(oldScriptEl.innerHTML); newScriptEl.appendChild(scriptText); oldScriptEl.parentNode.replaceChild(newScriptEl, oldScriptEl); }); } Usage $0.innerHTML = HTML; // does *NOT* run &lt;script&gt; tags in HTML setInnerHTML($0, HTML); // does run &lt;script&gt; tags in HTML &nbsp; Ref. Executing &lt;script&gt; elements inserted with .innerHTML I&#39;ve got a script that inserts some content into an element using innerHTML. The content could for example be: &amp;lt;script type=&quot;text/javascript&quot;&amp;gt;alert(&#39;test&#39;);&amp;lt;/script&amp;gt; &amp;lt;strong&amp;gt;tes... https://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml &nbsp;
front-end · May 23, 2023, 12:52 a.m.
Python Basic
1. Write a Python program to check whether a given number is a narcissistic number or not. For example, 371 is a narcissistic number; it has three digits, and if we cube each digits 33 + 73 + 13 the sum is 371. Other 3-digit narcissistic numbers are 153 = 13 + 53 + 33 370 = 33 + 73 + 03 407 = 43 + 03 + 73. def is_narcissistic_num(num): return num == sum([int(x) ** len(str(num)) for x in str(num)]) for x in range(100, 1000): if is_narcissistic_num(x): print(x) Result: 153 370 371 407 &nbsp; 2.&nbsp;Print a customized calendar. import calendar import re yy = int(input("Enter the year number: ")) mm = int(input("Enter the month number: ")) calendar.setfirstweekday(calendar.SUNDAY) x = calendar.month(yy, mm, 3) pattern = rf" {yy}\n" x = re.sub(pattern, "{}----------------------------\n".format(pattern), x) print(x) Result: Enter the year number: 2023 Enter the month number: 5 May 2023 ---------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Process finished with exit code 0 Ref. Print a calendar starting from today&#39;s date I want to print a calendar of the current month but starting from today&#39;s date in python. Is there any way I can do this? Only thing I thought to try was : import calendar y = int(input(&amp;quot;Input... https://stackoverflow.com/questions/62861105/print-a-calendar-starting-from-todays-date &nbsp; 3. Use Python turtle to plot a function. import turtle as t def line(x1,y1,x2,y2): t.up() t.goto(x1,y1) t.down() t.goto(x2,y2) return line(0,300,0,0) line(0,0,300,0) t.goto(0,0) t.shape("turtle") t.color("red") for x in range(0, 151): y = pow(x, 2) + 1 t.goto(x, y * 0.01) t.done() Result: &nbsp; 4.&nbsp;Replace Python list of blank elements with a specific value (list comprehension) z_list = ['oriel', 'indifference', '', 'hypomania', '', 'my'] z_list = ['xxx' if x == '' else x for x in z_list] print(z_list) &nbsp; 5.&nbsp;The prime numbers from 1 to 100 num=0 while num &lt;= 100: cnt = 0 i = 1 while i&lt;=num: if num % i == 0: cnt += 1 i += 1 if cnt == 2: print(num, end=" ") num += 1 Result: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 &nbsp;
python · May 22, 2023, 2:42 a.m.
Transition Effect and Rotate Cube with CSS & jQuery
Sample code: &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Insert title here&lt;/title&gt; &lt;script src='https://code.jquery.com/jquery-1.9.1.js'&gt;&lt;/script&gt; &lt;style&gt; * { box-sizing: border-box; margin: 0px; } .scene { width: 100%; height: 100vh; perspective: 1000px; } .cube { width: 100%; height: 100vh; position: relative; transform-style: preserve-3d; transform: translateZ(-50vh); transition: transform 1s; } .cube.show-front { transform: translateZ(-50vh) rotateY( 0deg); } .cube.show-bottom { transform: translateZ(-50vh) rotateX( 90deg); } .cube__face { position: absolute; width: 100%; height: 100vh; font-size: 40px; font-weight: bold; color: white; text-align: center; } .cube__face--front { background: hsla( 0, 100%, 50%, 0.7); transform: rotateY( 0deg) translateZ(50vh); } .cube__face--bottom { background: hsla(300, 100%, 50%, 0.7); transform: rotateX(-90deg) translateZ(50vh); } #ajax-loading-screen { background-color: transparent; width: 100%; height: 100%; position: fixed; top: 0; left: 0; display: block; z-index: 1000000000; } #ajax-loading-screen .mask-top { top: 0; left: 0; height: 50%; width: 100%; } #ajax-loading-screen .mask-right { top: 0; right: 0; height: 100%; width: 50%; } #ajax-loading-screen .mask-bottom { bottom: 0; right: 0; height: 50%; width: 100%; } #ajax-loading-screen .mask-left { top: 0; left: 0; height: 100%; width: 50%; } #ajax-loading-screen[data-effect="center_mask_reveal"] span { position: absolute; background: #fff; z-index: 100; -webkit-transition: 0.8s cubic-bezier(0.12,0.75,0.4,1); transition: 0.8s cubic-bezier(0.12,0.75,0.4,1); } #ajax-loading-screen.loaded .mask-top { -webkit-transform: translateY(-100%) translateZ(0); -ms-transform: translateY(-100%) translateZ(0); transform: translateY(-100%) translateZ(0); } #ajax-loading-screen.loaded .mask-right { -webkit-transform: translateX(100%) translateZ(0); -ms-transform: translateX(100%) translateZ(0); transform: translateX(100%) translateZ(0); } #ajax-loading-screen.loaded .mask-bottom { -webkit-transform: translateY(100%) translateZ(0); -ms-transform: translateY(100%) translateZ(0); transform: translateY(100%) translateZ(0); } #ajax-loading-screen.loaded .mask-left { -webkit-transform: translateX(-100%) translateZ(0); -ms-transform: translateX(-100%) translateZ(0); transform: translateX(-100%) translateZ(0); } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="ajax-loading-screen" data-effect="center_mask_reveal"&gt; &lt;span class="mask-top"&gt;&lt;/span&gt; &lt;span class="mask-right"&gt;&lt;/span&gt; &lt;span class="mask-bottom"&gt;&lt;/span&gt; &lt;span class="mask-left"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="scene"&gt; &lt;div class="cube"&gt; &lt;div class="cube__face cube__face--front"&gt;ORIEL&lt;/div&gt; &lt;div class="cube__face cube__face--bottom"&gt;INDIFFERENCE&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script&gt; var currentClass = ''; var cube = document.querySelector('.cube'); var showClass = ''; window.addEventListener('wheel', function(event) { if ( currentClass ) { cube.classList.remove( currentClass ); } if (event.deltaY &lt; 0) { showClass = 'show-front'; } else if (event.deltaY &gt; 0) { showClass = 'show-bottom'; } cube.classList.add( showClass ); currentClass = showClass; }); $(function() { $("#ajax-loading-screen").addClass("loaded"); setTimeout(function() { $("#ajax-loading-screen").hide(); }, 800); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; &nbsp; Result: Edit fiddle - JSFiddle - Code Playground Close Start with a boilerplate: jQuery Vue React React + JSX Preact TypeScript CoffeeScript SCSS CSS Grid Bootstrap PostCSS Show boilerplate bar less often? Links: 👍🏻 Roadmap (vote for features) 🐞 Bug tracker 📙 Docs 🎛 Service status Support JSFiddle and g https://jsfiddle.net/xxxvvvxxx/j4619srL/ &nbsp; Ref. https://codepen.io/desandro/pen/KRWjzm &nbsp;
front-end · May 21, 2023, 10:37 p.m.
How to move multiple turtles at the same time?
from turtle import Turtle, Screen screen = Screen() screen.bgcolor("lightgreen") turtle1 = Turtle(shape='turtle') turtle1.color('red') turtle1.speed("slow") # = 3 turtle1.penup() turtle2 = Turtle(shape='arrow') turtle2.color('blue') turtle2.speed(4) # "slow" (3) &lt; 4 &lt; "normal" (6) turtle2.penup() # user input function perimeter = screen.numinput("Track Perimeter", "Please enter the perimeter:", default=2000, minval=500, maxval=3000) def full_track_crawl(turtle, shortside, longside): speed = turtle.speed() turtle.pendown() for j in range (2): for i in range(0, int(shortside), speed): turtle.forward(speed) yield(0) turtle.left(90) for i in range(0, int(longside), speed): turtle.forward(speed) yield(0) turtle.left(90) turtle.penup() # set the track def drawTrack(perimeter, ratio): shortside = (perimeter / 2.0) / (ratio + 1) longside = ratio * shortside screen.setup(shortside * 2 + 60, longside + 40) turtle1.setposition(-shortside - 10, -longside / 2) turtle2.setposition(10, -longside / 2) generator1 = full_track_crawl(turtle1, shortside, longside) generator2 = full_track_crawl(turtle2, shortside, longside) while (next(generator1, 1) + next(generator2, 1) &lt; 2): pass drawTrack(perimeter, 2) screen.exitonclick() &nbsp; Result: &nbsp; Ref. How to move multiple turtles at the same time? I have an assignment which is asked to set two turtles in a race track (same size but separate track). I am able to make them move, but the second one moves only when the first one moved a half of ... https://stackoverflow.com/questions/40050438/how-to-move-multiple-turtles-at-the-same-time &nbsp;
python · May 21, 2023, 9:56 p.m.
A simple Rock-Paper-Scissors Game written in Python using turtle graphics
발로 만든 게임.ㅋㅋ import turtle as t import random as r import tkinter as tk from tkinter import messagebox def nemo(w, h, c): t.fillcolor(c) t.begin_fill() t.fd(w) t.rt(90) t.fd(h) t.rt(90) t.fd(w) t.rt(90) t.fd(h) t.end_fill() def button(x, y, b_c, msg): t.pu() t.goto(x, y) t.seth(0) nemo(b_w, b_h, b_c) t.goto(x + b_w/2, y - b_h) t.pencolor('white') t.write(msg, align = 'center', font=("Arial", 30, "normal")) b_w = 200; b_h = 60 rock_x = 300; rock_y = 200 scissors_x = 300; scissors_y = 300 paper_x = 300; paper_y = 100 q_x = 300; q_y = -200 c_x = -500; c_y = 300; p_x = -100; p_y = 300 t.speed(500) win = t.Screen() win.setup(1200, 800) button(scissors_x, scissors_y, 'blue', 'Scissors') button(rock_x, rock_y, 'blue', 'Rock') button(paper_x, paper_y, 'blue', 'Paper') button(q_x, q_y, 'black', 'QUIT') button(c_x, c_y, 'red', 'Computer') button(p_x, p_y, 'green', 'Player') t.addshape('imgs/scissors.gif') t.addshape('imgs/rock.gif') t.addshape('imgs/paper.gif') t.title("ORIEL") com = t.Turtle('imgs/paper.gif') player = t.Turtle('imgs/paper.gif') com.pu(); player.pu() com.goto(-400, 0); player.goto(0, 0) t.pu() t.goto(999,999) pw = 0; p = 2 cw = 0; c = 2 def game(c, p): global cw global pw if p == 0: if c == 0: com.shape('imgs/scissors.gif') elif c == 1: com.shape('imgs/rock.gif') cw += 1 else: com.shape('imgs/paper.gif') pw += 1 elif p == 1: if c == 0: com.shape('imgs/scissors.gif') pw += 1 elif c == 1: com.shape('imgs/rock.gif') else: com.shape('imgs/paper.gif') cw += 1 elif p == 2: if c == 0: com.shape('imgs/scissors.gif') cw += 1 elif c == 1: com.shape('imgs/rock.gif') pw += 1 else: com.shape('imgs/paper.gif') if pw == 2 or cw == 2: if pw == 2: print("I won the game. {}:{}".format(pw, cw)) elif cw == 2: print("I lost the game. {}:{}".format(pw, cw)) msg_box = tk.messagebox.askquestion('ORIEL', 'Do you want to continue?', icon='info') if msg_box == 'yes': pw=0; cw=0 else: win.bye() def check(x, y): if(x &gt;= rock_x and x &lt;= rock_x+b_w and y &lt;= rock_y and y &gt;= rock_y-b_h): p = 1 player.shape('imgs/rock.gif') c = r.randint(0, 2) game(c, p) elif(x &gt;= scissors_x and x &lt;= scissors_x+b_w and y &lt;= scissors_y and y &gt;= scissors_y-b_h): p = 0 player.shape('imgs/scissors.gif') c = r.randint(0, 2) game(c, p) elif(x &gt;= paper_x and x &lt;= paper_x+b_w and y &lt;= paper_y and y &gt;= paper_y-b_h): p = 2 player.shape('imgs/paper.gif') c = r.randint(0, 2) game(c, p) elif(x &gt;= q_x and x &lt;= q_x+b_w and y &lt;= q_y and y &gt;= q_y-b_h): win.bye() else: t.goto(999,999) win.onclick(check) t.done() &nbsp; &nbsp;
python · May 15, 2023, 8:23 p.m.
python game
Star Patterns in Python
1. * ** *** **** ***** **** *** ** * i=1 while i &lt;=4: print("*" * i) i+=1 i = 5 while i &gt; 0: print("*" * i) i -= 1 # or i = 1 j = 6 while i &lt; j * 2 - 1: if i &lt; j : print('*' * i) else: print('*' * (j - i + j - 2)) i += 1 2. * ** *** **** ***** i = 0 while(i &lt; 5): i += 1 print('*' * i) 3. ***** **** *** ** * for x in range(5, 0, -1): for y in range(x): print("*", end="") print() 4. * ** *** **** ***** ***** **** *** ** * spaces = 5 for x in range(5): for y in range(spaces-1): print(" ", end="") for z in range(0, x + 1): print("*", end="") print() spaces -= 1 spaces = 0 for x in range(5,0,-1): for y in range(spaces): print(" ", end="") for z in range(0,x): print("*", end="") print() spaces+=1 5. * *** ***** ******* ********* ******* ***** *** * rows = 5 k = 0 for i in range(1, rows + 1): for j in range (1, (rows - i) + 1): print(end = " ") while k != (2 * i - 1): print("*", end = "") k = k + 1 k = 0 print() k = 2 m = 1 for i in range(1, rows): for j in range (1, k): print(end = " ") k = k + 1 while m &lt;= (2 * (rows - i) - 1): print("*", end = "") m = m + 1 m = 1 print() &nbsp;
python · May 9, 2023, 7:33 a.m.
A simple hangman game written in Python using turtle graphics
파이썬 터틀을 이용한 간단한 행맨게임 &nbsp; Result : &nbsp; Code : import random import turtle screen = turtle.Screen() at = turtle.Turtle() word_list = ["테스트", "oriel", "PHENOMENA"] def get_word(): word = random.choice(word_list) return word.upper() def play(word): at.reset() at.pencolor('black') at.pensize(10) at.pu() at.goto(-120, 20) at.pd() word_completion = "_" * len(word) guessed = False guessed_letters = [] guessed_words = [] tries = 6 exec(display_hangman(tries)) print(word_completion) print("\n") while not guessed and tries &gt; 0: guess = screen.textinput("Input", "한 글자만 입력해주세요 : ") if guess is None: break guess = guess.upper() if len(guess) == 1 and guess.isalpha(): if guess in guessed_letters: print("그 글자는 사용했던 글자입니다. 다른 글자를 입력해주세요 : ") elif guess not in word: print(guess, "틀렸습니다.") tries -= 1 exec(display_hangman(tries)) guessed_letters.append(guess) else: print("축하합니다.", guess, "맞는 글자입니다!") guessed_letters.append(guess) word_as_list = list(word_completion) indices = [i for i, letter in enumerate(word) if letter == guess] for index in indices: word_as_list[index] = guess word_completion = "".join(word_as_list) if "_" not in word_completion: guessed = True elif len(guess) == len(word) and guess.isalpha(): if guess in guessed_words: print("", guess) elif guess != word: print(guess, "틀렸습니다.") tries -= 1 exec(display_hangman(tries)) guessed_words.append(guess) else: guessed = True word_completion = word else: print("졌습니다.") exec(display_hangman(tries)) print(word_completion) print("\n") if guessed: print("축하합니다! 게임에서 승리하셨습니다.") else: print("당신은 기회를 다 쓰셨습니다. 단어는 " + word + ". 다음 기회에!") turtle.title("PHENOMENA.COM") turtle.addshape('분필.gif') turtle.shape('분필.gif') turtle.bgpic('칠판.gif') turtle.pu() turtle.goto(-120, 100) turtle.pencolor('black') turtle.pensize(10) turtle.pd() turtle.lt(90) turtle.fd(50) turtle.lt(90) turtle.fd(100) turtle.lt(90) turtle.fd(350) turtle.penup() turtle.goto(-150, -205) turtle.pd() turtle.right(90) turtle.fd(130) turtle.pu() turtle.goto(-120, 100) turtle.pd() def display_hangman(tries): stages = [ # final state: ''' at.pu() at.goto(-120,-100) at.pd() at.lt(90) at.fd(75) ''', # head, torso, both arms, and one leg ''' at.pu() at.goto(-120,-100) at.pd() at.rt(90) at.fd(75) ''', # head, torso, and both arms ''' at.pu() at.goto(-120,-20) at.pd() at.lt(90) at.fd(70) ''', # head, torso, and one arm ''' at.pu() at.goto(-120,-20) at.pd() at.rt(45) at.fd(70) ''', # head and torso ''' at.pu() at.goto(-120,-100) at.pd() at.lt(90) at.fd(115) ''', # head ''' at.circle(40) ''', '' ] return stages[tries] def main(): word = get_word() play(word) while screen.textinput("Next Game", "Play Again? (Y/N) ") in ["y", "Y"]: word = get_word() play(word) if __name__ == "__main__": main() &nbsp;
python · May 8, 2023, 9:51 p.m.
python hangman
Why is document.all falsy?
ECMAScript 사양에 따르면 Boolean 형식으로 출력했을 때 true 또는 false를 반환하는 기준을 다음과 같이 정의한다. &nbsp; &nbsp; 특정객체가 undefined / null 이면 false를 반환 object면 true를 반환 이런식이다. document.all 의 경우 console.log(typeof document.all); 이렇게 type을 확인해보면 undefined가 찍힌다. 따라서 document.all 은 false 다. ​ 그런데 단순히 아래코드의 결과를 보면 console.log(document.all); HTMLAllCollection 즉 object가 나오는데 왜 false가 될까? ​ 답은 아래에 있다. Document: all property - Web APIs | MDN The Document interface&#39;s read-only all property returns an HTMLAllCollection rooted at the document node. In other words, it returns all of the document&#39;s elements, accessible by order (like an array) and by ID (like a regular object). https://developer.mozilla.org/en-US/docs/Web/API/Document/all &nbsp; 이곳에 보면 document.all is the only falsy object accessible to JavaScript, because it has the [[IsHTMLDDA]] internal slot. 이런 문구가 있는데,&nbsp;document.all 은 JavaScript에서 액세스할 수 있는 유일한 false 객체라고 한다. &nbsp; 일단 document.all 은 과거 브라우저(ie 등)에서 쓰였던 웹표준에 어긋나는 코딩방식이다. ECMAScript edition 5 를 제창할 당시 요구사항들을 보면 * all 특성은 모든 html 요소와 일치하는 문서 노드에 뿌리를 둔 HTMLAllCollection을 반환해야 한다. - &quot;all&quot; 에 대해 반환된 개체에는 몇 가지 비정상적인 동작이 있다. * 사용자 에이전트(브라우저)는 all 객체를 JavaScript의 boolean 연산을 했을 때 false 값으로 변환하는 것처럼 작동해야 한다. * 사용자 에이전트는 JavaScript에서 == 및 != 연산자를 사용했을 때 all 객체가 마치 정의되지 않은 값과 동일한 것처럼 작동해야 한다. * 사용자 에이전트는 JavaScript의 typeof 연산자가 all 객체에 적용될 때에 문자열 &#39;undefined&#39;를 반환하도록 작동해야 한다. ​ 이러한 요구 사항들은 작성 당시(ECMAScript 버전 5) 현재 JavaScript 사양을 고의적으로 위반한 것이다. JavaScript 사양에는 ToBoolean() 연산자가 모든 객체를 참 값으로 변환해야 하며 특정 연산자의 목적을 위해 정의되지 않은 것처럼 작동하는 객체에 대한 조항은 없다. 이러한 위반은 레거시 콘텐츠의 두 클래스와의 호환성에 대한 요구에 의해 발생했다. 1. 레거시 사용자 에이전트를 감지하는 방법으로 document.all을 사용하고 2. 다른 하나는 특정 요소의 존재 여부를 먼저 테스트하지 않고. 해당 레거시 사용자 에이전트만 지원하고 document.all 객체를 사용하는 경우이다. ​ 예제코드를 보면 if (document.all) { // 과거 ie같은 브라우저에서 사용 } else if (document.getElementById) { // 최신 브라우저에서 사용 } 기본적으로 오랫동안 document.all은 이러한 방식으로 오래된 브라우저를 감지하는 데 사용되었다. 하지만 document.all 을 먼저 검사하기 때문에 두 속성을 모두 제공하는 최신 브라우저는 여전히 document.all 경로안에 있게 된다. 최신 브라우저에서는 물론 document.getElementById를 사용하는 것을 선호하지만 대부분의 브라우저에는 여전히 이전 버전과의 호환성을 위해 document.all이 있기 때문에 document.all이 true이면 else 문은 실행되지 않게 된다. 그래서 코드를 아래처럼 바꾸어야 한다. if (document.getElementById) { // "최신" 브라우저용 `document.getElementById`를 사용하는 코드 } else if (document.all) { // 과거 ie같은 브라우저용 `document.all`을 사용하는 코드 } 하지만 많은 기존 코드는 아직 그 반대다. ​ 이 문제에 대한 가장 간단한 수정방법은 document.all을 여전히 쓸 수 있는 최신 브라우저에서 단순히 document.all을 &quot;false&quot; 로 만드는 것이다. ​ 요약하면 1. 최신 브라우저에서도 document.all 을 이용하여 html 요소객체에 접근이 가능하다. 2. 하지만 위와 같은 코드로 기존버전/최신버전 브라우저를 구분하는 데에는 한계가 있을수 있고 일일이 수정을 해주어야 한다. 3. 따라서 if (document.all) 으로 검사했을 때에는 단순히 document.all 을 false로 반환함과 동시에, document.all 자체를 요소객체에 접근하는 목적으로도 사용할 수 있도록 object (객체) 로 만들었다. &nbsp; Ref.​ Why is document.all falsy? document.all is a non-primitive object in the DOM that is falsy. For example, this code doesn&#39;t do anything: if (document.all) { alert(&quot;hello&quot;); } Can someone explain why this is? https://stackoverflow.com/questions/10350142/why-is-document-all-falsy &nbsp;
front-end · May 4, 2023, 9:32 p.m.
html javascript
Start Failed, Internal error: recovering IDE to the working state after the critical startup error
JetBrains IDE가&nbsp;갑자기 실행이 안되고 다음과 같은 에러를 뿜어댄다면? Internal error. Please refer to http://jb.gg/ide/critical-startup-errors java.util.concurrent.CompletionException: java.net.BindException: Address already in use: bind at java.base/java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:314) at java.base/java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:319) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1702) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) Caused by: java.net.BindException: Address already in use: bind at java.base/sun.nio.ch.Net.bind0(Native Method) at java.base/sun.nio.ch.Net.bind(Net.java:455) at java.base/sun.nio.ch.Net.bind(Net.java:447) at java.base/sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:227) at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:132) at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:551) at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1346) at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:503) at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:488) at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:985) at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:247) at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:344) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:510) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:518) at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1044) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ... 1 more ----- JRE 11.0.5+10-b520.30 amd64 by JetBrains s.r.o D:\Jetbrains\apps\CLion\ch-0\193.6015.37\jbr &nbsp; 1.&nbsp;cmd를 관리자모드로 실행 2.&nbsp;hyper-v 비활성화 (몇 번의 재시작이 필요함) dism.exe /Online /Disable-Feature:Microsoft-Hyper-V 3.&nbsp;필요한 모든 재시작을 완료하면 원하는 포트를 예약하여 hyper-v가 다시 예약하지 않도록 한다. netsh int ipv4 add excludedportrange protocol=tcp startport=50051 numberofports=1 4.&nbsp;hyper-v를 다시 활성화&nbsp;(이과정에서도 재부팅이 발생) dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All &nbsp; 문제의 해결법을 보면 알 수 있듯이 window가 부팅하면서 JetBrains사의 IDE가 사용하는 포트를 hyper-v가 점유하여 실행이 안된 것이었다. 위처럼 hyper-v를 끄고 재시작만 수행해도 인텔리제이는 실행되었으나 hyper-v는 사용해야 하기에 추가작업을 실행하였다. https://jb.gg/ide/critical-startup-errors &nbsp; 파이참이 실행되지 않을 땐 pycharm.bat를 실행해보자. 그러면 마찬가지로 다음과 같은 오류메시지를 통해서&nbsp;정확한 원인을 알 수 있다. java.util.concurrent.CompletionException: java.net.BindException: Address already in use: bind at java.base/java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:314) at java.base/java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:319) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1702) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665) at java.base/java.lang.Thread.run(Thread.java:834) Caused by: java.net.BindException: Address already in use: bind at java.base/sun.nio.ch.Net.bind0(Native Method) at java.base/sun.nio.ch.Net.bind(Net.java:455) at java.base/sun.nio.ch.Net.bind(Net.java:447) at java.base/sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:227) at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:134) at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:550) at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1334) at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:506) at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:491) at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:973) at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:248) at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:356) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ... 1 more ----- JRE 11.0.9+11-b1145.21 amd64 by JetBrains s.r.o. C:\Program Files\JetBrains\PyCharm Community Edition 2020.3\jbr &nbsp; 간단히 다음 명령어 입력으로 해결할 수 있었다. C:\WINDOWS\system32&gt;net stop winnat The Windows NAT Driver service was stopped successfully. C:\WINDOWS\system32&gt;net start winnat The Windows NAT Driver service was started successfully. https://intellij-support.jetbrains.com/hc/en-us/community/posts/360010020399-Pycharm-2020-3-Internal-Error-java-net-BindException-Address-already-in-use-bind-Windows-10
programming · April 4, 2023, 8:22 a.m.
JetBrains PyCharm
Realtime chat app using Django Daphne Nginx Redis
Create your virtual environment. download package in this order Django==3.0.8 djangorestframework==3.11.0 websocket-client==0.57.0 redis==3.5.3 asgiref==3.2.10 channels-redis==2.4.2 channels==3.0.1 Then create a Django project named ChatApp. django-admin startproject ChatApp After installing channels, add channels to your installed apps. INSTALLED_APPS = [ 'chat.apps.ChatConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # add django channels 'channels' , ] Set the ASGI application to your default ASGI file in the project. ASGI_APPLICATION = 'ChatApp.asgi.application' Create a new app that will have all the chat functionality. python manage.py startapp chat And add your app to the installed apps in settings.py. And add chat/urls.py from django.urls import path, include from chat import views as chat_views urlpatterns = [ path("chat", chat_views.chatPage, name="chat-page"), ] And add chat/routing.py from django.urls import re_path from chat.consumers import ChatConsumer # Here, "ws" is routing to the URL ChatConsumer which # will handle the chat functionality. websocket_urlpatterns = [ re_path(r'ws$', ChatConsumer.as_asgi()), ] And add chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.roomGroupName = "group_chat_gfg" await self.channel_layer.group_add( self.roomGroupName, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.roomGroupName, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] username = text_data_json["username"] await self.channel_layer.group_send( self.roomGroupName, { "type": "sendMessage", "message": message, "username": username, }) async def sendMessage(self, event): message = event["message"] username = event["username"] await self.send(text_data=json.dumps({"message": message, "username": username})) And add ChatApp/asgi.py *&nbsp;Has anyone had problem like this? Traceback (most recent call last): File "/path/to/my/env/bin/daphne", line 11, in &lt;module&gt; sys.exit(CommandLineInterface.entrypoint()) File "/path/to/my/env/lib/python3.6/site-packages/daphne/cli.py", line 161, in entrypoint cls().run(sys.argv[1:]) File "/path/to/my/env/lib/python3.6/site-packages/daphne/cli.py", line 222, in run application = import_by_path(args.application) File "/path/to/my/env/lib/python3.6/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "/path/to/my/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "./my_project/asgi.py", line 5, in &lt;module&gt; application = get_default_application() File "/path/to/my/env/lib/python3.6/site-packages/channels/routing.py", line 33, in get_default_application module = importlib.import_module(path) File "/path/to/my/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "./my_project/routing.py", line 4, in &lt;module&gt; from channels.auth import AuthMiddlewareStack File "/path/to/my/env/lib/python3.6/site-packages/channels/auth.py", line 12, in &lt;module&gt; from django.contrib.auth.models import AnonymousUser File "/path/to/my/env/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in &lt;module&gt; from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/path/to/my/env/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in &lt;module&gt; class AbstractBaseUser(models.Model): File "/path/to/my/env/lib/python3.6/site-packages/django/db/models/base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "/path/to/my/env/lib/python3.6/site-packages/django/apps/registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "/path/to/my/env/lib/python3.6/site-packages/django/apps/registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Then visit this page. Django apps aren&#39;t loaded yet when using asgi I&#39;m tring to run my django project with usage of asgi instead of wsgi. I have set up my routing.py and asgi.py as follows: routing.py from django.conf.urls import url from channels.routing import https://stackoverflow.com/questions/53683806/django-apps-arent-loaded-yet-when-using-asgi &nbsp; ChatApp/settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } &nbsp; Using&nbsp;Redis: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)] }, }, } &nbsp; *&nbsp;Deploying Django Channels: how to keep Daphne running after exiting shell on web server Deploying Django Channels: how to keep Daphne running after exiting shell on web server As practice, I&#39;m trying to deploy Andrew Godwin&#39;s multichat example with Django Channels 2.1.1 on DigitalOcean Ubuntu 16.04.4. However, I don&#39;t know how to exit the Ubuntu server without Channels&#39; ... https://stackoverflow.com/questions/50192967/deploying-django-channels-how-to-keep-daphne-running-after-exiting-shell-on-web &nbsp; Nginx 1. Windows location @django { proxy_pass http://127.0.0.1:1234; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 600s; # this next line adds the Host header so that apache knows which vHost to serve # the $host variable is automatically set to the hostname Nginx is responding to proxy_set_header Host $host; #Websocket support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } 2. Linux with&nbsp;Daphne Make&nbsp;service-name.service [Unit] Description=Indifference Daphne Service After=network.target [Service] Type=simple User=indifference WorkingDirectory=/home/indifference/path/to/indifference ExecStart=/home/indifference/path/to/bin/daphne -p 3333 indifference.asgi:application access-log=/data/logs/indifference/daphne/access.log [Install] WantedBy=multi-user.target chmod 755 service-name.service systemctl daemon-reload systemctl enable service-name.service systemctl start service-name.service Update nginx.conf&nbsp; upstream channels-indifference-backend { server localhost:3333; } ... location /ws { proxy_pass http://channels-indifference-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } &nbsp; Windows Django - dev Create a folder called config config/ commonsettings.py dev.py prod.py make sure that in dev.py and prod.py you import everything from commonsettings.py like this: from .commonsettings import * dev.py sample INSTALLED_APPS = [ ... # 'channels', ... ] ASGI_APPLICATION = None then if you want to run the dev.py settings: python manage.py runserver --settings=config.dev In order to run your asgi application, simply point Daphne to your ASGI application, and optionally set a bind address and port (defaults to localhost, port 8000): daphne -b 0.0.0.0 -p 9001 myproject.asgi:application Nginx WS config is the same with 2. Linux with Daphne *&nbsp;Use ASGI to deploy Django, StreamingHttpResponse cannot be accessed. Async support for StreamingHttpResponse was only added in Django 4.2. &nbsp; You can check the program with this: https://www.phenomena.com/chat &nbsp; Ref. Realtime chat app using Django - GeeksforGeeks A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. https://www.geeksforgeeks.org/realtime-chat-app-using-django/ Django Channel Custom Authentication Middleware __call__() missing 2 required positional arguments: &#39;receive&#39; and &#39;send&#39; I am writing a custom authentication middleware for django channels class TokenAuthMiddleware: def __init__(self, inner): # Store the ASGI application we were passed self.inner = https://stackoverflow.com/questions/64625473/django-channel-custom-authentication-middleware-call-missing-2-required-po Configuring ASGI Django Application using Daphne and Nginx Server Adding Daphne to preexisting project. https://ritiktaneja.medium.com/configuring-asgi-django-application-using-daphne-and-nginx-server-59a90456fe17 Channels cannot be used with StreamingHttpResponse So you&rsquo;re saying that this exact code works if you run it under a wsgi container? https://forum.djangoproject.com/t/channels-cannot-be-used-with-streaminghttpresponse/10105/4 &nbsp;
python · March 2, 2023, 6:55 a.m.
django daphne nginx redis
  • 1
  • 2 (current)
  • 3
  • 4
  • 5