投稿時間:2022-04-03 09:14:55 RSSフィード2022-04-03 09:00 分まとめ(23件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
python Pythonタグが付けられた新着投稿 - Qiita AtCoder Beginner Contest 246 A~C 3完記事 https://qiita.com/kani_kani_kani/items/5a11c4a1fdb4068ea894 AtCoderBeginnerContestAC完記事アルゴリズムの学習改善のための自身の備忘録及び学習の一環として記事を書くことにしました読んでくれた方で何かありましたら気兼ねなくコメントしてくださいお待ちしておりますAFourPoints問題文概要長方形の点が与えられる残りの点はなにか制約と入力制約leqxiyileqxyxyxyのすべてを頂点に持つ長方形がただ一つ存在しその各辺はx軸またはy軸に平行であり面積はではない入力は全て整数である入力入力は以下の形式で標準入力から与えられる。 2022-04-03 08:26:53
AWS AWSタグが付けられた新着投稿 - Qiita 受験談 AWS Certified Database - Specialty 認定 https://qiita.com/h2m_kinoko/items/c4b271d28698f89a4fda 活用したもの公式サンプル問題問ではありますが、雰囲気や難易度をつかむには十分かなと思います。 2022-04-03 08:12:36
Docker dockerタグが付けられた新着投稿 - Qiita Laravel sail を使って Laravel9 の環境構築を行う https://qiita.com/hinako_n/items/45a7232b0b0ed16bffc8 composerrequirelaravelsaildevphpartisansailinstallSailを起動vendorbinsailupSailコマンドを使うエイリアスの設定デフォルトでSailコマンドはvendorbinsailスクリプトを使用して起動するので、これを簡単に実行できるようにするためエイリアスを設定する。 2022-04-03 08:12:43
海外TECH DEV Community The Ultimate Guide to Getting Started in Data Science https://dev.to/nelsonchege13/the-ultimate-guide-to-getting-started-in-data-science-npp The Ultimate Guide to Getting Started in Data Sciencebelieving that Artificial Intelligence and Machine learning is the next big step in the evolution of computer Technology I found no better time to start learning Data Science than now thanks to LuxAcademy and DataFestAfrica I now have started my journey to be a data scientistHaving completed our first week of the Data Science and Machine Learning Bootcamp Marathon Here are the topics i have been able to learn during that time introduction to pythonhaving experience in python for sometime this was a good refresher of some basic concepts that I had forgotten This also acted as a reminder of the things I used to consider hard but now they are like a breeze to all who think its hard just give it time anaconda and jupyter notebook installationfor a data scientist having anaconda installed on your machine will help you a lot Because anaconda comes pre installed with jupyter notebook it was easy to get everything running very fastrelational databasehaving been in the market for approximately over years relational database have a way of storying data that are related to each other it might be alit bit more work with designing and implementing the database compared to non relational database but querying the data from the database makes it worth all the work done beforeintroduction to pythonhaving experience in python for some time this was a good refresher of some basic concepts that I had forgotten This also acted as a reminder of the things I used to consider hard but now they are like a breeze to all who think it s hard just give it time anaconda and jupyter notebook installationfor a data scientist having anaconda installed on your machine will help you a lot Because anaconda comes pre installed with jupyter notebook it was easy to get everything running very fastrelational databasehaving been in the market for approximately over years relational database have a way of storying data that are related to each other it might be alit bit more work with designing and implementing the database compared to non relational database but querying the data from the database makes it worth all the work done beforeNumPyPython having list it has its advantages and disadvantages One of these disadvantages is that it is slow to work on that s where NumPy comes in it s a python package that contains arrays that can be used it is the faster compared to list because the package is implemented in c code The NumPy is mostly used by other packages that I am going to discuss in this blogPandasPandas extends the array from NumPy into two major parts series and dataframe Of the two the mostly used is dataframe You can think of dataframe as a matrix like shapeMatplotlibAs humans we are more visual creatures That s were Matplotlib comes in this a package that has inbuild graphs that are used to show visual representation of data seaborn As mentioned earlier we are visual creatures and we also that visual representation to look nice Seaborn is a packages that extends the matplotlib library and adds more styling on to the graphs byForest This is a package that contains other packages once you have installed this package you can use all the packages that are in it by importing itPostgreSQL ConnectionHaving PostgreSQL connecting to your python script looks like a huge mountain to climb but it s very easy with a few lines of code you can connect your PostgreSQL database to your python script or projectHaving just completed a week of the Data Science and Machine Learning Bootcamp Marathon it is exciting how I was able to learn all this within a week I won t say I have mastered everything here but I can say that I have learnt the basic tools required in my Data Science career Here are some of the resources for the topics discussed above Get Started with Pandas In mins A complete guide on NumPy for data science An Introduction to Matplotlib A Beginner s Guide to matplotlib for Data Visualization and Exploration in Python Seaborn ーA Step by Step Guide to Catch Your Audience Using Data Visualization Starting with Matplotlib and Seaborn Understand theft to use pyforest to simply package import Auto Import Python Libraries Using Pyforest to import important python libraries python libraries dabccaHow to connect to a Postgres database with Python thanks for readingHappy Coding 2022-04-02 23:37:11
海外TECH DEV Community A guide to build an encrypted email service on Solana with Anchor https://dev.to/gabrieldemian/a-guide-to-build-an-encrypted-email-service-on-solana-with-anchor-2ci7 A guide to build an encrypted email service on Solana with Anchor Project overviewWe will be building an end to end encrypted email service on the Solana blockchain Let me give you a summary of how this program works The user registers himself on our dapp he gets a Diffie Hellmann key pair a private and public key Only the public key is stored on his newly created account on the blockchain And now he can send encrypted emails to someone who is also registered Once the email is sent both parties can decrypt the email locally with their private keys this is secure because the encryption and decryption process is done locally on the client without any network request The blockchain is only used to store public information about the encryption like the iv and salt for example and to register users We will use AES bits with counter mode as our encryption algorithm And elliptic curve Diffie Hellmann for the key exchange PrerequisitesAt least a basic understanding of Rust and the following installed Solana CLIAnchor frameworkAnchor is a framework for Solana that makes our life much easier It handles a lot of dirty work for us Without it we would have to do a lot of tedious things like manual serialization and deserialization ConfigurationMake sure that you generated a development keypair on the Solana CLI And that it has enough SOL to pay for fees Change the current network to the devnet solana config set url devnet and airdrop some SOL with solana airdrop Now let s create our project open up your terminal and paste this command anchor init encrypted mail encrypted mail is the name of the project you can change this to any other name We need to install a few dependencies on the program open the programs encrypted mail Cargo toml file and append the following to the file dependencies uuid version features serde v anchor lang Open your program folder programs encrypted mail src and add a few files to make your structure be exactly the same as this architecture ├ーsrc│├ーcontext rs gt contexts of instructions│├ーerror rs gt error structs│├ーlib rs gt contains all the instructions│├ーstate rs gt state structs│├ーutils rs gt helpers functions CodingNow that we have our foundation let s start to do some code State rsOpen your state rs and paste the following use anchor lang prelude account pub struct Mail pub from Pubkey pub to Pubkey pub id String pub subject String encrypted text pub body String pub authority Pubkey pub created at u public information about encryption and decryption pub iv String pub salt String account pub struct UserAccount pubkey from diffie helman exchange pub diffie pubkey String pub authority Pubkey pub bump u this event allows us to notify clients when a new email is created event pub struct NewEmailEvent pub from Pubkey pub to Pubkey pub id String Solana stores data in accounts and those structs are basically the types of our accounts except for NewEmailEvent The iv and salt are generated when the client encrypt data And it is also used to decrypt it they are not sensitive data so we can store them on the blockchain without fear Context rsOpen your context rs file and paste the following use crate state Mail UserAccount use anchor lang prelude derive Accounts pub struct SendMail lt info gt account init payer authority space discriminator from to id subject body authority created at salt iv pub mail Account lt info Mail gt pub system program Program lt info System gt account mut pub authority Signer lt info gt derive Accounts pub struct Register lt info gt account mut pub authority Signer lt info gt account init payer authority space discriminator public key authority bump seeds b user account authority key as ref bump pub user account Account lt info UserAccount gt pub system program Program lt info System gt helper table for calculating accounts spaces bool byte bit rounded up to byte u or i byte u or i bytes u or i bytes u or i bytes u or i bytes u bytes items x bytes itemSize arrayLength PubKey bytes Same as u vec lt u gt Any multiple of bytes bytes for the prefix Need to allocate the maximum amount of item that could be required String Any multiple of byte bytes for the prefix Same as vec lt u gt Those structs are the context of the instructions They hold and manage all the accounts that the instruction will interact An account will be managed by the account macro you declare if the account is mutable or not if it is a new account to be initialized with x amount of space the constraints that it must obey etc Please read the official documentation about this here An instruction is just a normal function that will be called on the client to interact with the program We have instructions register and send email Error rsOpen your error rs file and paste the following use anchor lang prelude error code pub enum ErrorCode msg Invalid instruction InvalidInstruction msg The body of your email is too long The max is chars InvalidBody msg The subject of your email is too long The max is chars InvalidSubject msg The salt should be exactly chars InvalidSalt msg The IV should be exactly chars InvalidIv msg The diffie publickey should be exactly chars InvalidDiffie This simply maps an error to a message Utils rsOpen your utils rs and paste the following use anchor lang prelude Pubkey use uuid Uuid creates a unique ID for a mail using now body and sender as arguments pub fn get uuid now amp u body amp String sender amp Pubkey gt String const VNAMESPACE amp Uuid amp Uuid from bytes let now now to be bytes let body body as bytes let sender sender to bytes let mut vec vec vec extend from slice amp now vec extend from slice amp body vec extend from slice amp sender Uuid new v VNAMESPACE amp vec to string We have only one helper function the get uuid this will take a few arguments and generate a unique id for each email Lib rsOpen your lib rs file and paste the following use crate error ErrorCode anchor lang prelude context utils pub mod context pub mod error pub mod state pub mod utils declare id KVSSWuXjnmJkzpyXMCdeKpadGsSoKopUUgDiA program pub mod encrypted mail use super use anchor lang Key pub fn send email ctx Context lt SendMail gt subject String body String from Pubkey to Pubkey salt String iv String gt Result lt gt require subject chars count lt ErrorCode InvalidSubject require body chars count lt ErrorCode InvalidBody require salt chars count ErrorCode InvalidSalt require iv chars count ErrorCode InvalidIv let now Clock get unwrap unix timestamp as u let mail amp mut ctx accounts mail let id get uuid amp now amp body amp mail key mail from from mail to to mail id id clone mail subject subject mail body body encrypted body a ciphertext mail created at now mail salt salt mail iv iv mail authority ctx accounts authority key emit state NewEmailEvent from to id Ok pub fn register ctx Context lt Register gt diffie pubkey String gt Result lt gt require diffie pubkey chars count ErrorCode InvalidDiffie let user account amp mut ctx accounts user account user account diffie pubkey diffie pubkey user account authority ctx accounts authority key user account bump ctx bumps get user account unwrap Ok You need to change declare id with your account id Anchor will output this information when you run anchor build The require ensures that the user passes the right data to the instructions If the condition is false it will return an error The ctx bump get user account is an abstraction for generating a bump seed for this PDA please read about PDA s here and here Now that the program itself is done we just need to make some tests on the client TestingAdd a few dependencies with this command yarn add crypto js elliptic text encodingLet s create a file utils ts at the root of the project this file will contain abstractions to make readability easier on our tests Paste the following into the file import PublicKey from solana web js import TextEncoder from text encoding import idl from target idl minerva json import getProvider from project serum anchor import ec from elliptic export const DEVNET WALLET getProvider wallet publicKey export const getUserPDA async seed string authority PublicKey DEVNET WALLET gt const PDA await PublicKey findProgramAddress new TextEncoder encode seed authority toBuffer new PublicKey idl metadata address return PDA export const elliptic new ec curve The getUserPDA will generate a PDA for the user when he registers We need to pass an array of seeds to generate the address The elliptic is just an instance of the curve class that we imported from the elliptic library Open tests encrypted mail ts and let s start testing You can erase everything and paste the following code import Program workspace Provider setProvider from project serum anchor import AES from crypto js aes import enc mode lib from crypto js import Keypair SystemProgram from solana web js import EncryptedMail from target types encrypted mail import DEVNET WALLET getUserPDA elliptic from utils import expect from chai describe beggining encrypted mail tests gt setProvider Provider env generating diffie helmann keys const aliceKeypair elliptic genKeyPair const bobKeypair elliptic genKeyPair const aliceDiffiePublic aliceKeypair getPublic encode hex true const bobDiffiePublic bobKeypair getPublic encode hex true const sharedSecret aliceKeypair derive bobKeypair getPublic toString hex generating blockchain wallets const alice DEVNET WALLET const bob Keypair generate const program workspace EncryptedMail as Program lt EncryptedMail gt We generate key pairs one for Alice and one for Bob We can generate a shared private key from the private of one of them and the public of the other It is the shared private that will be used to encrypt and decrypt the emails Let s add our first test append the following code inside your describe function it can register alice and bob async gt const aliceAccountPDA await getUserPDA user account const bobAccountPDA await getUserPDA user account bob publicKey const airdropTx await program provider connection requestAirdrop bob publicKey await program provider connection confirmTransaction airdropTx await program rpc register aliceDiffiePublic accounts authority alice userAccount aliceAccountPDA systemProgram SystemProgram programId await program rpc register bobDiffiePublic accounts authority bob publicKey userAccount bobAccountPDA systemProgram SystemProgram programId signers bob const users await program account userAccount all console log users users expect users length to equal This is very straightforward the function start by generating the PDA for Alice and Bob and then calls the register instruction from the program and then we get all the userAccounts and check to see if they equal Finally the last test is to encrypt the email send the email and decrypt it back it can encrypt emails send the emails and decrypt it async gt const mailA Keypair generate let cipher AES encrypt simplesmente intankavel o bostil sharedSecret mode mode CTR await program rpc sendEmail very important subject subject cipher ciphertext toString body of email alice from bob publicKey to cipher salt toString salt cipher iv toString iv accounts authority alice mail mailA publicKey systemProgram SystemProgram programId signers mailA const emails await program account mail all const email emails account const plaintext AES decrypt ciphertext enc Hex parse email body iv enc Hex parse email iv salt enc Hex parse email salt as lib CipherParams sharedSecret mode mode CTR console log n console log emails emails console log n console log plaintext plaintext toString enc Utf console log shared secret sharedSecret console log cyphertext emails account body console log n expect plaintext toString enc Utf to equal simplesmente intankavel o bostil First we generate an email account then encrypt the body of the email and call the sendEmail instruction After that we get the email back and decrypt the body of the email And check to see if the decrypted message is the same message that was encrypted To run the tests first you need to build the program with anchor build At the end of the build Anchor will print your program id on your terminal you need to copy this and replace on declare id macro on lib rs and also on Anchor toml This file should look like this programs localnet encrypted mail KVSSWuXjnmJkzpyXMCdeKpadGsSoKopUUgDiA programs devnet encrypted mail KVSSWuXjnmJkzpyXMCdeKpadGsSoKopUUgDiA registry url provider cluster localnet wallet config solana devnet json scripts test npx ts mocha p tsconfig json t tests ts Now you can run anchor deploy and anchor test And that s it The endI could not dive into every technical aspect of Solana in detail because there would be just too much to be explained here I prefer to focus on a more practical approach at first you should read the official documentation of Anchor and Solana to understand better the theory behind all of this If you made it this far congratulations If you got lost at some point you can check the source code here This is my finished frontend dapp of this program make sure you use your wallet on the devnet Also feel free to send me a message if you have any questions 2022-04-02 23:20:34
海外TECH DEV Community The way to remove unused CSS https://dev.to/sawabe0912/the-way-to-remove-unused-css-5g05 The way to remove unused CSSHiI learned how to remove unused CSS in order to polish up the performance score on Lighthouse That s why I will share this method As you can see if I delete unused CSS it will improve the web performance Let s start to identify the unused CSS in the first placeYou can click the three dots on the right top position after you open inspect Then select More tools and Coverage You can click open the CSS file that you want to check and click the black dot Finally you can see the status of CSS usage The CSS highlighted in green means that this CSS code is used on the page that you are viewing The other one highlighted in red is unused on this page You should check the usage of CSS code on other pages as well before deleting it️Thank you for reading 2022-04-02 23:18:53
海外TECH DEV Community Unpacking JavaScript 01: Prototypes(--emulating proto runtime--) https://dev.to/sfundomhlungu/unpacking-javascript-01-prototypes-emulating-proto-runtime--1m68 Unpacking JavaScript Prototypes emulating proto runtime previous article Prototype based LanguageThe prototype pattern is a creational design pattern in software development It is used when the type of objects to create is determined by a prototypical instance which is cloned to produce new objects wikipediaJavaScript like any programming language conforms to a specific design principle pattern as java is built or designed on top of or around the classes paradigm and subsequent patterns so is JavaScript with prototypes prototype simply an object to create other objects think of a template with predefined values and functionality used to create other templates say augmented more functional templates This inevitably means if you were to take a high level concept in JS say arrays and drill down a level deeper behind the scene you will come across an object or objects which in them have other object s and so on until you reach the end or null a chain of sort depicting objects building on top of each other to form more sophisticated objects which by consequence inherit values and properties exposed by objects templates lower in the chain You ve probably come across a statement like this or similar everything in JavaScript is an Object almost everything in JavaScript is an Object or better yet Nearly everything in JavaScript is an object other than six things that are not objects which are ーnull undefined strings numbers boolean and symbols These are called primitive values or primitive types everything about JS objects to carry such statement with confidence you have to know more than JavaScript the language but the inner workings of JS the runtime etc I am feeling a bit bold at the moment I want to come with my own argument and try to defend it everything in JS is an object bold isn t it let s see how quickly it crumbles note arguments are not ultimate truths but paths to said truth you can fairly well come up with your own and are an excellent way to learn the only counter argument to this statement are primitive values even normal functions at first glance they don t act or even look like objects I guess my job is to prove otherwise primitivesconst foo bar const number const bool trueconst arr etcfunction hello To prove if anything is something we need to know what something is it s essence basic building blocks identity etc In this case anything is everything in the JS language and something is an object metaphyics of an objectanything dot operable is an objectlet value name sk print console log this name value print value is said to be dot operablean object is a structure with key s and value s pairs to access said value s you use the keys via a dot or similar approved methodsvalue name dot operationvalue name similar approved methods same as dot operation access a value thru keytherefore anything that is dot operable or uses similar approved methods is an object hence if we see a dot operation or similar appr methods the assumption is the left hand side of that dot is an object if the above is accepted anything dot operable etc is an object I put to you then that at runtime JS primitive values are dot operable therefore even primitive values are objectsfoo split   dot operationnumber toString arr forEach Then it is safe to conclude that during runtime primitive values somehow turn to objects if they didn t to operate on them we would use something of sort split foo toString number forEach arr but the fact that we are able to access these functions directly from a primitive value means it must be an object encapsulating the value data and functionality in itself as key and value pairs foo value bar toString etc I did skip the bool primitive yes good catch and null also undefined to be fair I ve never use bools in form of objects before but they can be dot operable therefore fit the definition let l new Boolean l valueOf falselet f truef valueOf trueas for null and undefined won t even try I have nothing they are a total mystery to me won t even consult MDN which is probably a reason enough to reject the everything argument and go with almost everything is an object Well was this detour useless not really wanted to show that coding is not just about actual coding but thinking about concepts that s how you get good at stuff form opinions about concepts you know and interact with these detours can teach a lot and proving stuff or at least trying to is fun it s not about being right but learning you will see in later articles we will make an assumption about how a fixed array or arrays in general works and build one our assumption is based on our knowledge and interactions with arrays that is how you level up Not dwelling on proving whether or not everything is an object the focus is on prototypes and the inheritance they provide via the chain they form called prototype chain To understand any low level concept especially concepts that are hidden behind abstractions although prototypes are not that hidden and can be accessed and changed by low level I mean most developers generally do not interact with them or they are abstracted away for example in JS classes using the extends keyword abstract prototypical inheritance away from the developer to understand such concepts a simulation emulation or interpretation of what happens during runtime helps to grasp the concept better Since prototypes deal with or are objects to understand them we have to simulate how the JS engine supposedly handles and deal with objects in short building the object runtime as an attempt to understand prototypes and prototypical inheritance Object Runtime Part Key value pairs is an intuitive or go to answer when asked for a simple explanation of objects I propose a simpler explanation an object is a structure that allows setting and getting values using a key Therefore the job of the object runtime is to take an object and a key look for the value associated with key and perform an action a set or get const obj name john surname doe obj name   jane   object gt obj key gt name action gt set denoted by equal obj surname           object gt obj key gt surname action gt get return we can easily emulate the get action compared to the set for set we need some lower level concepts metaprogramming good news emulating the get operation is enough to drive the point home custom get function emulate the get operation on objectsfunction get obj key let type typeof obj key this is a literal object access the actual engine object runtime already knows the type for us there s no better way to know the type so ignore the access and focus on the type switch type case function obj key if type is fn call it break default return obj key else return the valuebeing accessed break first we get the type of the value being accessed object s can hold various types including functions if it s a function the assumption is it s being called in fact that is the only case we can handle without resorting to unnecessary methods to handle both function calls and getting a reference to a function we could use a string function and function as a key to denote a reference or a call in get which is not that necessary in our case but that is one way to solve the function problem being callable and a value at the same time if the value being accessed is a function get calls the function else the value is returned any other value other than functions usage examplelet ob name John surname Doe print function console log this name this surname console log get ob name gt Johnget ob print calling the print function gt John Doewe have a working get runtime all we need to know now to implement prototypes is the role of prototypes chain of objects during a get operation MDN says something along these lines when you access an object s property using a key the JS engine firstly looks for that property in the object s own properties if it does not find it goes down the chain and look for the value in the object s prototype nd level in the chain if the same thing happens goes further down and look for the value in the object s prototype prototype rd level remember the chain we talked about earlier until the property is found or null is reached if null is reached end of the chain then a does not exist error is thrown meaning the value accessed does not exist remember a prototype is just an object which also has a prototype object it builds from or inherits from according to our earlier explanation until a null is reached example let ob object ob name Jane ob own property prototype ob prototype surname Doe prototype ob prototype s prototype age prototype null ob prototype s prototype s prototype gt below denotes next step the engine runtime takes how the engine asks or handles objects accessing name ob name locate ob in memory gt is name a property of ob gt true gt return name accessing surname ob surname locate ob in memory gt is surname a property of ob false gt does ob have a proto gt true gt is surname in ob s prototype gt true gt return surname accesing a value that does not exist statusob status locate ob in memory gt is status a property of ob gt false gt does ob have a proto gt true gt is status in ob s proto gt false gt does ob s proto have a proto gt true gt does ob s proto proto have status false gt does ob s proto proto have a proto gt false gt return throw new error status does not exist on object ob A side note may be an interview question why accessing a value that does not exist in a JS object may be expensive ob status above answers that question very the access operations until null is reached are quiet numerable imagine a longer chain we can implement the prototype chain using a recursive method or better yet the infamous while loop looking at the specification above all we need to do in get is check whether the accessed property exists in the object itself if not look in it s prototype and repeat the process until we find the property if not meaning we reached null throw an error JavaScript handles creating the prototype object for you whenever you declare a new object or create one but for our purpose we need to handle that our selves since we are emulating our object will be something of sort let hello h hello world inheritFrom null will act as our prototype part implementing the prototype chainlet s change our function from get to protoRuntime and add functionality to handle prototypesfunction protoRunTime obj property changed key to property if obj property   checking if the property exists in obj as own property if not look at obj proto let type typeof obj property switch type case function obj property break default return obj property break NEW CODE else if obj inheritFrom if obj has our pseudo proto inheritFrom MAGIC HAPPENES HERE let result handleInherit obj inheritFrom property recursive function that looks for the property in the chain will implement if result null if handleInherit found the value calle protoruntime on that object in the chain return protoRunTime result property else handleInherit did not find the value throw new Error property does not exist on obj prototype also else if obj does not have inheritFrom by consequence property does not exist throw new Error property does not exist on obj the NEW CODE may look daunting but it is quite simple follow the comments in the code let result handleInherit obj inheritFrom property handleInherit returns a value or null let s call handleInherit a chain crawler and will loop crawl over all necessary inheritFrom s prototype objects until it finds a property and returns the object with that property if it reaches the end of the chain null is returned handled by the code below if result null if handleInherit found the value calle protoruntime on that object in the chain return protoRunTime result property else handleInherit did not find the value throw new Error property does not exist on obj prototype also if a value is found handleInherit will return the object inheritFrom with that value then we call protoRunTime over that returned object which will inevetible be trapped by  if obj property and the switch will execute accordingly return protoRunTime result property handleInherit functionfunction handleInherit obj property let current obj while current   if current null if current property break   if current obj has the property we are looking for break and return the current object else if current inheritFrom current current inheritFrom   else make the current s inheritFrom obj current let current and loop again this is the crawling part going down the chain else we no longer have inheritFrom current null   else if we reach the end property does not exist on obj make current null return current   return whatever current is if you understand the switch between current to it s inheritFrom object in the else if block you now understand chain traversal handleInherit is moving down the chain Testing everythinglet baseHello h function console log hey there inheritFrom null let hello h hello world inheritFrom baseHello let Obj hello gt console log hello world init init inheritFrom hello chain Obj gt inherits from hello gt hello inherits baseHelloprotoRunTime Obj hello console log protoRunTime Obj init console log traversal protoRunTime Obj h gt hello world can you see why not hey there remember the spec and chain Conclusionthis was just scratching the surface much more cool stuff coming up this is part of a series of articles Unpacking JavaScript a precursor to a project I am working on projects in JavaScript an eBook building real world projects from engines compilers front end to mobile apps in JS as explained in the intro article along a table of content for upcoming articles Real vs Tutorial projects There s one fundamental difference really the target audience of a tut is you alone you are mastering or at least absorbing concepts learning while a real project the end user is at the forefront you start thinking about user experience application module size maintenance patterns to follow robustness optimization etc while thinking about users you think of yourself too what to gain monetization status a community or whatever in short you are building something for people whether free or to trade which is a very valuable skill and exactly what this eBook is about building real usable beneficial apps modules programs however you view them if the above sounds like something you will be interested in the eBook is progressing very well you can sign up here to receive an update once complete you can also sign up to be notified when future articles are published 2022-04-02 23:04:58
海外TECH DEV Community Unpacking JavaScript 00: Introduction https://dev.to/sfundomhlungu/unpacking-javascript-00-introduction-2c33 Unpacking JavaScript Introductionnext article what and whya series of articles going over intrinsic js topics not essentially beginner material but core fundamentals building blocks of the language enough js to be lethal well kind of depending on your personal definition of lethal this series is a precursor to a body of work I am working on titled projects in JavaScript more on that later To expect in this series of articles is enough JavaScript to build and do pretty cool stuff what we all want really maybe the outline will do more justice than pretty cool stuff introductioncurrently reading prototypesprototype is a design pattern principle at the core of the language JS as JS implements prototypes and prototypical inheritance learning theory is all good and well but I find implementing theory way better which what this article is about emulating prototypes and inheritance we will emulate from stretch how the JS engine supposedly from the spec of course handles and interprets objects and prototypical inheritance during run time OOJSObject oriented JS from classes getters and setters to object composition fairly useful concepts doused with few useful design patterns to build robust or at least coherent object oriented programs at the end a little module project to solidify everything promisesAsynchronous JS is a no brainer and very powerful from creating own promises from stretch to that powerful method chaining method chaining example d js like yAxisG append text attr class axis label attr y attr x innerHeight attr transform rotate attr fill black attr text anchor middle text YaxisLabel Concurrent and Parallel Computingbetter done than said and yes threads do exist in JS web and this article is all about them we can actually have a while true loop and be absolutely non blocking no this script is slowing down your page at all none insane right I know iterators and generatorsThe magic world well sort of Now the fun trickery stuff begins almost magical from pausable functions to custom iterables we get to explore the iterative algorithm and how the for of loop works underneath pretty cool stuff if I say so myself Metaprogrammingis intercepting fundamental language operations to define custom ones I mean this is pretty nifty no need to sell it really better done than said too spoiler alert we will build a fixed array from stretch and more Computational Mediajust fiddling with the canvas and maybe build some weird checkers game with random algorithms who knows Typescriptintroducing types to JS Why the precursor to the project I am working on projects in JavaScriptyou know it s serious when there s a cut scene the story behind projects is simple really but fundamental to it s development See I wasn t always a JS dev until one faithful day a client asked if i could build a simple desktop software for her as any self respecting dev I dare not turn down an opportunity even thou the only language I knew very well back then was python spoiler alert very bad for building simple desktop apps kivy didn t cut it moved the project to c hated the design and finally turned to the omniscient google who suggested electron a framework that ships with the v engine to create a desktop app think of node js but with a webpage as a view using any js module framework having faith in my skills dove head first with no JS or React experience started fiddling combining two and three learning in the process in short that s when it hit me learning syntax is all good and those tricks of a language perfectly fine but nothing ABSOLUTELY nothing beats the evolution you go thru after building a real project which is the aim of this eBook To potentially spark that evolution by building the real stuff not tutorial projects but real projects Real vs Tutorial projectsThere s one fundamental difference really the target audience of a tut is you alone you are mastering or at least absorbing concepts learning while a real project the end user is at the forefront you start thinking about user experience application module size maintenance patterns to follow robustness optimization etc while thinking about users you think of yourself too what to gain monetization status a community or whatever in short you are building something for people whether free or to trade which is a very valuable skill and exactly what this eBook is about building real usable beneficial apps modules programs however you view them if the above sounds like something you will be interested in the eBook is progressing very well you can sign up here to receive an update once complete you can also sign up to be notified when future articles are published next articleneed clarification or raise a concern you can comment below 2022-04-02 23:04:02
海外TECH DEV Community Stolen Notes on EVM (Ethereum Virtual Machine) https://dev.to/abhinavmir/stolen-notes-on-evm-ethereum-virtual-machine-3nn2 Stolen Notes on EVM Ethereum Virtual Machine Author s Notes These are notes stolen from of my favourite articles I ll cite them some day but they re easily reverse searchable This is probably the best singular resource on EVM apart from the papers themselves What is the EVM How does it work At a high level Ethereum Virtual Machine is a deterministic function that outputs a certain value for a certain input The EVM is much like any other computer but it specializes in running smart contracts EVM is like JVM but instead of using any other process virtual machine on Ethereum we use EVM because we need things like finite determinism and gas implementations The compiler design behind EVMSolidity is a high level language choice that compiles into bytecodes machine readable set Solidity is one of the more popular choices otherwise Vyper Flint even C via ceagle can be your choices Opcodes are low level human readable instruction sets that are representative of the deployed creation bytecode This creation bytecode is used to generate the runtime bytecode The following contract is an example pragma solidity contract MyContract uint i For this this is generated object fdbfffefdfeaedffaafdffddeaedffdfffcb opcodes PUSH x PUSH x MSTORE PUSH x PUSH x SSTORE CALLVALUE DUP ISZERO PUSH x JUMPI PUSH x DUP REVERT JUMPDEST POP PUSH xF DUP PUSH x PUSH x CODECOPY PUSH x RETURN INVALID PUSH x PUSH x MSTORE PUSH x DUP REVERT INVALID LOG PUSH x x SLT KECCAK PUSH xEDFFA xAF xD DIFFICULTY xF GT LT CREATE CODECOPY xD xD x SWAP xE PUSH xEDFFDFFF PUSH xB EVM ArchitectureThere are two types of accounts in Ethereum EOA Externally owned accounts and Smart Contracts Both are treated similarly by the EVM have balances and storage Here s one of my favourite graphics for this Focus on the lower two blocks When a transaction caller sends a transactiom a module to recieve input transaction recieves the input and updates storage while storing the arguments in the stack with the program counter The Smart Contract bytecode with the stack is then fed to the EVM for gas estimation via opcodes The gas fee is deducted and the opcode is executed THe memory is then updated If the transaction fails the memory is updated EVM is stack designed so stack operations such as pop push apply to it The overall architecture is similar to any other FSM and instructions are implemented how they re implemented in other stack based machines with obvious differences Different implementations of the Ethereum protocol are implemented in different ways languages such as Geth Parity Mist with different add on features but same core structure of EVM State Consensus Memory Storage State and suchThe Ethereum Virtual Machine has three areas where it can store data storage memory and the stack which are explained in the following paragraphs Each account has a data area called storage which is persistent between function calls and transactions Storage is a key value store that maps bit words to bit words It is not possible to enumerate storage from within a contract it is comparatively costly to read and even more to initialise and modify storage Because of this cost you should minimize what you store in persistent storage to what the contract needs to run Store data like derived calculations caching and aggregates outside of the contract A contract can neither read nor write to any storage apart from its own The second data area is called memory of which a contract obtains a freshly cleared instance for each message call Memory is linear and can be addressed at byte level but reads are limited to a width of bits while writes can be either bits or bits wide Memory is expanded by a word bit when accessing either reading or writing a previously untouched memory word i e any offset within a word At the time of expansion the cost in gas must be paid Memory is more costly the larger it grows it scales quadratically The data in the Blockchain itself is stored via a Merkle Patricia Trie tree Data Structure A Patricia Trie or prefix Tree or radix Tree is an ordered structured tree which takes the applications of usually the data it stores A node s position in the tree defines the key with which that node is associated which makes tries different in comparison to binary search Trees in which a node stores a key that corresponds only to that node In different implementations the state is maintained in different ways For example in Go Ethereum it is done via stateDB go Is the EVM Turing complete why Turing complete machines are machines that despite any complexity of problem will solve a problem given enough time This is of course an abstract idea developed using an infinite tape EVM is quasi Turing complete system because the machine executes as far as the gas is provided Gas is the fundamental fuel for the infrastructure and this solves the halting problem in a way in that you cannot generally determine whether an arbitrary problem provided will keep running forever or not but the gas will not allow any problem to run forever The gas is calculated on an opcode basis For example to calculate one Keccak cryptographic hash it will take gas each time a hash is calculated plus a cost of more gas for every bits of data being hashed What is Gas and why is it important for operations in the EVM Ethereum gas is unique from Bitcoin due to how pieces of code are treated on the platform On Bitcoin gas fee is charged per size unit basis but since Ethereum allows for complex decisive code to be run on the platform it charges gas per operation unit basis Gas isn t a token but rather a unit of measurement of work like joule Now USD lt gt Joule value is decided by market rate but unit of work done is decisive and lawful one by nature one by code If I set a gas fee too low with my transaction although post update I must set a baseFee to my txn no node will choose to pick my transaction and add it to a Block thus resulting in no change in the Blockchain state which is the end goal Gas is important because it allows for monetization of operation Monetization of operation means Nodes are rewarded for maintaining integrity of node There is a punishment for malicious code to cause a DOS like attack As disccused earlier the gas feature of the EVM allows for the quasi Turing complete state of the machine Sure you don t have an infinite tape but gas allows for the scope of usage of tape to be reduced if that makes sense What are Jump Tables and why are they relevant for gas consumption The entry point to the actual code execution is the run method of the EVM interpreter This method is essentially going through the bytecode step by step and for each opcode looking up the opcode in a data structure known as jump table Among other things this table contains a reference to a Go function that is to be executed to process the instruction More specifically an entry in the jump table contains the following fields which partially refer to other tables in other source code files In a jump table each entry has a couple of fields we need to have a look at constant gas and dynamic gas type operation struct execute is the operation function execute executionFunc constantGas uint dynamicGas gasFunc minStack tells how many stack items are required minStack int maxStack specifies the max length the stack can have for this operation to not overflow the stack maxStack int memorySize returns the memory size required for the operation memorySize memorySizeFunc halts bool indicates whether the operation should halt further execution jumps bool indicates whether the program counter should not increment writes bool determines whether this a state modifying operation reverts bool determines whether the operation reverts state implicitly halts returns bool determines whether the operations sets the return data content constant gas is the constant gas value of the operation and dynamic gas is the gas value of the operation as a function of the parameters Since gas is computed from opcode the library gas usage isn t considered since it is computed via jump tables from opcodes But bytecode undergoes the same linking process as the linking process of libraries in C What are Precompiled Contracts These are four so called precompiled contracts meant as a preliminary piece of architecture that may later become native extensions The four contracts in addresses and execute the elliptic curve public key recovery function the SHA bit hash scheme the RIPEMD bit hash scheme and the identity function respectively Full updated list Recovery of ECDSA signatureHash function SHAHash function RIPEMDIdentityModular exponentiation EIP Addition on elliptic curve alt bn EIP Scalar multiplication on elliptic curve alt bn EIP Checking a pairing equation on curve alt bn EIP BLAKEb hash function EIP Implemented in geth as suchvar PrecompiledContractsByzantium map common Address PrecompiledContract common BytesToAddress byte amp ecrecover common BytesToAddress byte amp shahash common BytesToAddress byte amp ripemdhash common BytesToAddress byte amp dataCopy common BytesToAddress byte amp bigModExp common BytesToAddress byte amp bnAdd common BytesToAddress byte amp bnScalarMul common BytesToAddress byte amp bnPairing Precompiled contracts are not native opcodes but are calculations that are implemented in the EVM codebase for efficient calculations without EVM overheads Ref What are the pros and cons of the EVM compared to other VMs JVM is another popular process VM it has it s advantages of course but EVM allows for finality and gas implementation two important factors of the Ethereum ecosystem 2022-04-02 23:00:59
ニュース @日本経済新聞 電子版 けさ4月3日の日経電子版トップ(https://t.co/Y0i6ubDMLX)3本です。 ▶強権中国、戸惑うマネー 株・債券1~3月7400億円流出 https://t.co/pstteU8o0t ▶「キーウ州全域解放」 ウ… https://t.co/jHQxQ2Stts https://twitter.com/nikkei/statuses/1510395427992092676 けさ月日の日経電子版トップ本です。 2022-04-02 23:15:06
ニュース BBC News - Home Diesel delivery highlights UK dependence on Russia https://www.bbc.co.uk/news/business-60948439?at_medium=RSS&at_campaign=KARANGA delivery 2022-04-02 23:37:04
ニュース BBC News - Home The Papers: Tory MP suspended and Baby P case https://www.bbc.co.uk/news/blogs-the-papers-60970634?at_medium=RSS&at_campaign=KARANGA mother 2022-04-02 23:16:26
ニュース BBC News - Home 19 facts about the 2022 Grammy Awards https://www.bbc.co.uk/news/entertainment-arts-60864628?at_medium=RSS&at_campaign=KARANGA awardseverything 2022-04-02 23:35:31
京都 烏丸経済新聞 京都・円山公園のしだれ桜が2年ぶりライトアップ 露店や茶店も営業再開 http://karasuma.keizai.biz/headline/3661/ 京都市東山区 2022-04-03 08:24:55
北海道 北海道新聞 松島、後半途中まで出場 ラグビー、フランス1部 https://www.hokkaido-np.co.jp/article/664805/ 後半途中 2022-04-03 08:17:31
北海道 北海道新聞 韓国の先制攻撃言及を非難 金正恩氏妹らが談話 https://www.hokkaido-np.co.jp/article/664811/ 先制攻撃 2022-04-03 08:27:00
北海道 北海道新聞 函館で住宅火災 焼け跡から2人の遺体 https://www.hokkaido-np.co.jp/article/664760/ 函館市新川町 2022-04-03 08:26:42
北海道 北海道新聞 「キーウ州全域が解放」 ウクライナ国防次官 https://www.hokkaido-np.co.jp/article/664804/ 解放 2022-04-03 08:22:06
北海道 北海道新聞 カブス鈴木がオープン戦2号 エンゼルス戦、大谷は出場せず https://www.hokkaido-np.co.jp/article/664810/ 大リーグ 2022-04-03 08:18:00
北海道 北海道新聞 JR北海道、雪の運休1万2800本 昨年度、過去10年で最多 改善策、実効性どこまで https://www.hokkaido-np.co.jp/article/664781/ 過去 2022-04-03 08:17:23
北海道 北海道新聞 <社説>安保法施行6年 専守防衛の徹底必要だ https://www.hokkaido-np.co.jp/article/664768/ 専守防衛 2022-04-03 08:16:03
北海道 北海道新聞 生乳3万トン超、系統外へ 道内本年度 生産抑制に反発か https://www.hokkaido-np.co.jp/article/664774/ 酪農家 2022-04-03 08:02:06
海外TECH reddit Cloud9 vs. 100 Thieves / LCS 2022 Spring Playoffs - Winners' Bracket Round 1 / Post-Match Discussion https://www.reddit.com/r/leagueoflegends/comments/tuvurg/cloud9_vs_100_thieves_lcs_2022_spring_playoffs/ Cloud vs Thieves LCS Spring Playoffs Winners x Bracket Round Post Match DiscussionLCS SPRING PLAYOFFS Official page Leaguepedia Liquipedia Eventvods com New to LoL Cloud Thieves Thieves advance to face the winner of TL vs EG C falls to face GG C Leaguepedia Liquipedia Website Twitter Facebook YouTube Subreddit Leaguepedia Liquipedia Website Twitter Facebook YouTube Subreddit MATCH C vs Winner Thieves in m Game Breakdown Runes Bans Bans G K T D B C twisted fate tahmkench tryndamere ahri leblanc k H gnar jayce kennen lucian aatrox k HT H C O B C vs Summit renekton TOP ornn Ssumday Blaber diana JNG lee sin Closer Fudge ryze MID viktor Abbedagge Berserker zeri BOT xayah FBI Winsome renata glasc SUP nautilus huhi MATCH C vs Winner Thieves in m Game Breakdown Runes Bans Bans G K T D B C twisted fate tahmkench tryndamere xayah jinx k H HT H M M gnar jayce lucian leona alistar k C B M B C vs Summit renekton TOP ornn Ssumday Blaber diana JNG lee sin Closer Fudge ryze MID viktor Abbedagge Berserker zeri BOT aphelios FBI Winsome renata glasc SUP nautilus huhi MATCH vs C Winner Thieves in m Game Breakdown Runes Bans Bans G K T D B gnar jayce nautilus camille aatrox k I H M M B M B C twisted fate tahmkench viego ahri leblanc k O H vs C Ssumday ornn TOP tryndamere Summit Closer lee sin JNG volibear Blaber Abbedagge azir MID viktor Fudge FBI lucian BOT zeri Berserker huhi nami SUP leona Winsome This thread was created by the Post Match Team submitted by u Soul Sleepwhale to r leagueoflegends link comments 2022-04-02 23:05:06

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)