반응형
반응형

달력 만들기 

import calendar

def smartphone_calendar():
    print("Welcome to the Smartphone Calendar!")
    
    while True:
        try:
            year = int(input("Enter the year (e.g., 2023): "))
            month = int(input("Enter the month (1-12): "))
            
            if 1 <= month <= 12:
                cal = calendar.TextCalendar(calendar.SUNDAY)
                month_calendar = cal.formatmonth(year, month)
                print("\n" + month_calendar)
            else:
                print("Invalid month. Please enter a value between 1 and 12.")
        
        except ValueError:
            print("Invalid input. Please enter valid numeric values for year and month.")
        
        choice = input("Do you want to view another calendar? (y/n): ")
        if choice.lower() != 'y':
            print("Thank you for using the Smartphone Calendar. Goodbye!")
            break

if __name__ == "__main__":
    smartphone_calendar()

반응형
반응형



PIVOT

 - 행과 열 변환

SELECT 컬럼명 FROM 테이블명
PIVOT([집계 함수]([집계 컬럼명]) FOR [대상 컬럼명] IN ([컬럼이 될 값])) AS 피벗테이블명


WITH A AS
(
    SELECT '1학년' AS '학년', '1반' AS '반', 100 AS '점수'
    UNION ALL SELECT '1학년', '2반', 30
    UNION ALL SELECT '2학년', '1반', 80
    UNION ALL SELECT '2학년', '2반', 90
)
SELECT * FROM A
PIVOT(SUM(점수) FOR 반 IN ([1반],[2반])) AS PVT






UNPIVOT

 - PIVOT의 반대

SELECT 컬럼명 FROM 테이블명
UNPIVOT([집계될 데이터의 컬럼명] FOR [UNPIVOT할 컬럼 데이터의 컬럼명] IN ([UNPIVOT할 컬럼명])) AS 언피벗테이블명


WITH A AS
(
    SELECT '1학년' AS '학년', 100 AS '1반', 30 AS '2반'
    UNION ALL SELECT '2학년', 80, 90
)
SELECT 학년, 반, 점수 FROM A
UNPIVOT(점수 FOR 반 IN ([1반], [2반]))AS UNPVT

반응형
반응형

[Chrome] 크롬 브라우저의 읽기 모드

 

크롬의 비밀 병기, 읽기 모드를 활성화하는 방법

이상한 일이지만 구글은 거의 2개월 전인 지난 3월에 새로운 읽기 모드를 발표하고도 한동안 조용했다. 읽기 모드를 포함한 크롬 버전이 아직 전체 대중에게 공개되지 않아 대다수 사용자는 아직 정식 배포를 기다려야만 한다. 

현재 대다수의 데스크톱 운영체제에서는 5월 30일에, 크롬북에서는 6월 6일에 새로운 크롬 버전이 전 세계에 출시될 예정이다.

하지만 이미 2개월을 기다린 상황에서 인내심을 더 내기는 쉽지 않다. 어떤 PC에서든 크롬 읽기 모드를 바로 사용하는 방법을 알아보자.
 

  • PC에서 크롬을 연다.
  • 기대를 품고 기다린다.
  • 브라우저의 주소창에 chrome:flags를 입력한다.
  • 검색창에서 reading mode를 입력한다.
  • Reading mode라는 줄 옆에 상자를 클릭하고 설정을 기본값에서 활성화(Enabled)로 바꾼다.
  • 화면 하단 파란색의 다시 시작 버튼을 클릭한다. 
  • 이제 완료됐다. 정말 쉬운 절차다.


이제 크롬을 다시 시작하고 새로운 읽기 모드를 사용하는 방법을 알아보자.
 

  • 텍스트가 많은 기사 페이지를 연다.
  • 크롬 오른쪽 상단의 작은 사이드패널 아이콘을 찾는다. 오른쪽에 어두운 막대가 있는 상자로, 검은색 퍼즐 조각과 사용자 프로필 아이콘 사이에 있다. 
  • 읽기 모드 아이콘을 클릭한다.
  • 오른쪽에 패널이 나타나면 맨 위의 읽기 목록이라는 드롭다운 메뉴를 클릭한다.
  • 맨 아래에 있을 읽기 모드를 선택한다.


이제 오른쪽 패널에서는 걸리적거리는 광고나 귀찮은 방해물 없이 깔끔하게 텍스트로만 이루어진 웹페이지가 나타날 것이다.
 

ⓒ ITWorld
그러나 기뻐하기 전에 먼저 읽기 패널의 중요한 기능 몇 가지를 알아보자. 
 

  • 우선 패널과 메인 웹페이지 영역 사이의 선 위에 마우스를 올리고 분할선을 왼쪽으로 드래그하면 패널을 더 넓게 만들 수 있다.

 

ⓒ ITWorld 

  • 두번째로 패널 상단에 있는 표준 글꼴(Standard font)을 클릭하면 여러 가지 글꼴로 바꿀 수 있다.

 

ⓒ ITWorld 

  • 마지막으로 텍스트 크기와 함께 색상, 줄 간격, 글자 간격을 조정하면 같은 영역의 다른 옵션과 어울리도록 웹페이지를 맞춤화할 수 있다.

 

ⓒ ITWorld
이것이 전부다. 이제 보고 싶지 않은 것을 보지 않을 수 있고, 죄책감을 느끼지도 않는 방식으로 모든 텍스트를 읽을 수 있다. 클릭 한 번으로 할 수 있는 일이다.

구글 크롬의 읽기 모드 패널은 현재 안드로이드 버전에서는 사용할 수 없다. 그러나 불편을 감수할 필요는 없다. 안드로이드에는 훨씬 인상적인 자체 읽기 모드 설정이 있기 때문이다. 크롬뿐 아니라 모든 휴대폰 앱에서 작동하고, 텍스트 음성 변환도 할 수 있어 모든 기사를 어디서든 사용자 맞춤형 팟캐스트처럼 들을 수도 있다.

원문보기:
https://www.itworld.co.kr/howto/292435#csidxd83d1fbd53ee766a046529e6600dd42 

반응형
반응형

[javascript] 파라미터 제거하기. remove url parameters with javascript or jquery

 

https://stackoverflow.com/questions/4651990/remove-url-parameters-with-javascript-or-jquery

 

remove url parameters with javascript or jquery

I am trying to use the youtube data api to generate a video playlist. However, the video urls require a format of: youtube.com/watch?v=3sZOD3xKL0Y but what the api generates is: youtube.com/wa...

stackoverflow.com

var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';

url = url.slice( 0, url.indexOf('&') );

alert( url );

 

var url = document.createElement('a');
url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';

console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container
console.log(url.protocol); // https:
console.log(url.host); // developer.mozilla.org
console.log(url.hostname); // developer.mozilla.org
console.log(url.port); // (blank - https assumes port 443)
console.log(url.pathname); // /en-US/search
console.log(url.search); // ?q=URL
console.log(url.hash); // #search-results-close-container
console.log(url.origin); // https://developer.mozilla.org



window.location.replace(window.location.pathname)

https://jsfiddle.net/mill01/hxrejz5L/6/

 

반응형
반응형

What is Flutter Impeller?

https://blog.nonstopio.com/flutter-impellers-d18d47a809d9

 

What is Flutter Impeller?

Flutter 3.10 introduces Impeller in iOS apps by default. So these iOS apps will have less jank and better consistent performance. And for…

blog.nonstopio.com

Credits: wikiHow

Flutter 3.10 introduces Impeller in iOS apps by default. So these iOS apps will have less jank and better consistent performance. And for Android, Impeller is in the development phase. But we should know what Impeller is.

Impeller is a new renderer within Flutter’s engine. Until now, Flutter has been using Skia. Skia has built-in rendering features which can be used for various devices. But Skia is not always optimized solution for Flutter’s needs.

Before going further, let’s see

The basic Scenario of Impeller is that (check this issue)-

If we had a static set of shaders, we could asynchronously compile them on program startup, so that by the time the application runs an animation we can use this static set and not stutter while we prepare a new one.

Medium term we could also determine what specialized shaders we would want to use in each scene, and compile them in the background so that the next time, if all the specialized shaders we would want to use are ready, we could just use them. That way we get the long-term sustained performance benefits of specialized shaders and the short-term smooth start performance benefits of a static shader set.

Yes, our main goal is to eliminate jank or any stuttering that’s happening inside your app. But first, we should know what is Renderer.

Renderer software helps to translate the code into the pixels that are visible on the screen.

Whenever we build any widget into the Flutter that goes into some steps like Widget Tree -> Element Tree -> Render Object Tree.

But what happened after that? We will go step by step.

  1. Display List — Render objects contain the instruction for how to actually layout and how that widget should be painted, in the form of instructions, and those instructions are given to the engine as a simple command, which is called Display List. Now an engine will decide whether the widget should be rendered either using Impeller or Skia.

2. Render Pipelines — Render Pipelines that can be used to render everything given in the Display List.

3. Shader — A Shader is nothing but a small piece of code that gets executed on the graphics device.

4. Rasterization — Shaders take the vertices (say for ex. Flutter Logo) and it will move them on the screen where exactly we want to draw it. This process will iterate through all the given triangles of this Flutter Logo(Ex. Fig.1). For each vertex into say triangle of any image, we figure out the specific pixels that are inside it, and this is called rasterization.

Fig. 1 (Ref)

But wait...

Those Shaders and Render Pipeline need compilation to get instructed by the GPU so that GPU can execute it.

AND THIS COMPILATION PROCESS IS VERY EXPENSIVE.

And that’s how Impeller comes into the picture. Let’s discuss this issue in detail.

Shader Compilation Jank Issue —We know that Shaders are the low-level code given to GPU to draw UI on screen.

Skia compiles and generates these shaders (at runtime) when running app for the first time. The generation of shaders requires quite a bit of time(approx. 200ms or more depending on the situation) and this causes the frame, which can’t be rendered within 16ms to jank. This jank is called shader-compilation-jank.

Impeller resolved this issue by pre-compiling a smaller, simpler set of shaders at build time.

First, we will see how exactly Impeller Architecture works,

Now let’s take this Display List and draw it using Impeller.

Impeller Architecture

1. Aiks — The Display List operations are dispatched to Aiks. Aiks is the topmost layer of Impeller and it mainly contains the canvas drawing API.

2. Entity — Aiks takes the higher level commands from the DisplayList and translates them into the simpler self-contained drawing operations called Entities.

3. Contents of Entity — These are the Content Objects of the Entity, and it contains the actual GPU instructions need to draw the Entity.

4. Hardware Abstraction Layer [HAL] — Impeller needs some kind of translation layer by which it can communicate with the GPU, which called as Hardware Abstraction Layer. Render Pipelines contain the Shaders, and each Content of Entity uses the HAL to draw itself by giving instructions to GPU to render these Shaders. This HAL talks to the graphics driver through various standard graphics APIs like Metal on iOS and Vulcan on Android. And then this is how the resulting texture gets displayed on the screen.

Impeller generates and compiles all necessary Shaders (ahead of time) when we build the Flutter Engine. Therefore apps running on Impeller will have a predefined set of Shaders they need, and the shaders can be used without introducing jank into animations. This operation can be done by using Impellerlc Shader Compiler.

Impellerlc Shader Compiler — Impeller has a set of handwritten shaders compiled in advance. Impeller precompiles a smaller, simpler set of shaders at Engine build time so they don’t compile at runtime.

After a preview period since January 2023, Impeller is now on-by-default on iOS in a stable branch. Android up next.

Impeller Architecture

How to Enable Impeller ?

Here, I have taken this example and tried to run it from the IDE (Android Studio).

Pre-Impeller build

Can you see that, the app got stuck at a very early stage of the app run.

Now as per this, to see what direction Android support will take, experiment with Impeller in the 3.7 or later stable release, I enabled Impeller for Android and tried to run the same app from scratch. And got the below observations.

Post-Impeller build

Here, the animation runs smoothly after enabling Impeller.

Hope you enjoyed this article!

Here to make the community stronger by sharing our knowledge. Follow me and my team to stay updated on the latest and greatest in the web & mobile tech world.

Ref:

1] Introducing Impeller

2] Impeller Rendering Engine

3] Shader compilation jank

4] Smaller, simpler set of shaders

반응형
반응형

A list of one-liners you should know to up your knowledge of JavaScript.

1.# Copy content to the clipboard

In order to improve the user experience of the website, we often need to copy the content to the clipboard, so that users can paste it to the designated place.

const copyToClipboard = (content) => navigator.clipboard.writeText(content)

copyToClipboard("Hello fatfish")

2.# Get the mouse selection

Have you encountered this kind of situation before?

We need to get the content selected by the user.

const getSelectedText = () => window.getSelection().toString()

getSelectedText()

3.# Shuffle an array

Shuffle an array? This is very common in lottery programs, but it’s not truly random.

const shuffleArray = array => array.sort(() => Math.random() - 0.5)

shuffleArray([ 1, 2,3,4, -1, 0 ]) // [3, 1, 0, 2, 4, -1]

4.# Convert rgba to hexadecimal

We can convert the rgba and hexadecimal color values to each other.

const rgbaToHex = (r, g, b) => "#" + [r, g, b].map(num => parseInt(num).toString(16).padStart(2, '0')).join('')

rgbaToHex(0, 0 ,0) // #000000
rgbaToHex(255, 0, 127) //#ff007f

5.# Convert hexadecimal to rgba

const hexToRgba = hex => {
  const [r, g, b] = hex.match(/\w\w/g).map(val => parseInt(val, 16))
  return `rgba(${r}, ${g}, ${b}, 1)`;
}

hexToRgba('#000000') // rgba(0, 0, 0, 1)
hexToRgba('#ff007f') // rgba(255, 0, 127, 1)

6.# Get the average of multiple numbers

Using reduce we can get the average value of a set of arrays very conveniently.

const average = (...args) => args.reduce((a, b) => a + b, 0) / args.length

average(0, 1, 2, -1, 9, 10) // 3.5

7.# Check if a number is even or odd

How can you tell if a number is odd or even?

const isEven = num => num % 2 === 0

isEven(2) // true
isEven(1) // false

8.# Deduplicate elements in an array

To remove duplicate elements in an array, using Set will make it very easy.

const uniqueArray = (arr) => [...new Set(arr)]

uniqueArray([ 1, 1, 2, 3, 4, 5, -1, 0 ]) // [1, 2, 3, 4, 5, -1, 0]

9.# Check if an object is an empty object

Is it easy to determine if an object is empty?

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object

isEmpty({}) // true
isEmpty({ name: 'fatfish' }) // false

10.# Reverse a string

const reverseStr = str => str.split('').reverse().join('')

reverseStr('fatfish') // hsiftaf

11.# Calculate the interval between two dates

const dayDiff = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)

dayDiff(new Date("2023-06-23"), new Date("1997-05-31")) // 9519

12.# Find the day of the year in which the date falls

Today is June 23, 2023, so what day is it this year?

const dayInYear = (d) => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)

dayInYear(new Date('2023/06/23'))// 174

13.# Capitalize the first letter of the string

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("hello fatfish")  // Hello fatfish

14.# Generate a random string of specified length

const generateRandomString = length => [...Array(length)].map(() => Math.random().toString(36)[2]).join('')

generateRandomString(12) // cysw0gfljoyx
generateRandomString(12) // uoqaugnm8r4s

15.# Get a random integer between two integers

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)

random(1, 100) // 27
random(1, 100) // 84
random(1, 100) // 55

16.# Specified digits rounded

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)

round(3.1415926, 3) //3.142
round(3.1415926, 1) //3.1

17.# Clear all cookies

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`))

18.# Detect if it is dark mode

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode)

19.# Scroll to the top of the page

const goToTop = () => window.scrollTo(0, 0)

goToTop()

20.# Determine if it is an Apple device

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform)

isAppleDevice()

21.# Random Boolean values

const randomBoolean = () => Math.random() >= 0.5

randomBoolean()

22.# Get the type of the variable

const typeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()

typeOf('')     // string
typeOf(0)      // number
typeOf()       // undefined
typeOf(null)   // null
typeOf({})     // object
typeOf([])     // array
typeOf(0)      // number
typeOf(() => {})  // function

23.# Determine if the current tab is active or not

const checkTabInView = () => !document.hidden

24.# Check if an element is focused

const isFocus = (ele) => ele === document.activeElement

25.# Random IP

const generateRandomIP = () => {
  return Array.from({length: 4}, () => Math.floor(Math.random() * 256)).join('.');
}

generateRandomIP() // 220.187.184.113
generateRandomIP() // 254.24.179.151

More content at PlainEnglish.io.

 

 

https://javascript.plainenglish.io/25-killer-javascript-one-liners-thatll-make-you-look-like-a-pro-d43f08529404

 

25 Killer JavaScript One-Liners That’ll Make You Look Like a Pro

A list of one-liners you should know to up your knowledge of JavaScript.

javascript.plainenglish.io

 

반응형

+ Recent posts