[GAS]ライブラリの有効な利用シーン
概要
スギちゃん にライブラリについて質問を受けました。
あるライブラリを使っていたコードを自分のコード内で完結したところ、実行完了までが半分以下になったんだけどなんで~?ってものです。
これってのはライブラリがダメというわけでなく、ライブラリを使用しても自分でコード書いても実行時間がさほど変わらないパターンと、そうでないパターンがあるという認識をしながら、ライブラリを使っていけばいいよ~というお話です。
まとめとコード
ライブラリってのは実際はなにをやってるのかというと、ライブラリの���のメソッドを使用した場合に、その先で実際には自分で書いたような GAS が走ってるイメージで OK です。ただ、自分で書くよりめっちゃ便利で楽なメソッドを作ってくれてるので、多用しちゃうんですね。
例をあげて説明すると、ユーザー ID からユーザー情報を取得するライブラリを作ったとします。
こんな表があるシートをライブラリ化して、User ID を投げるとそのユーザー情報を配列で返してくれるというものです。
いろいろ書き方はあると思いますが、シンプルにこう書きます。
※ 今回はライブラリ化せずに、別 function として動作テストします。
function getUserInformation(userId) { var sheet = SpreadsheetApp.getActiveSheet(); var values = sheet.getDataRange().getValues(); values.shift(); for (var i = 0; i < values.length; i++) { if (values[i][0] !== userId) continue; return values[i]; break; } }
では、このライブラリを追加して、自身のコード内でこんな感じで呼び出した場合。
これは利用シーンとしては OK 判定をあげたいやつです。
function myFunction() { var userId = 'A001'; Logger.log(getUserInformation(userId)); // [A001, hoge, 1.0, male] }
問題となるシーンは、以下のような感じですね。
function myFunction() { var usersId = ['A001', 'A005', 'A006', 'A008', 'A010']; for (var i = 0; i < usersId.length; i++) { var userId = usersId[i]; Logger.log(getUserInformation(userId)); // [A001, hoge, 1.0, male], [A005, hogehoge, 5.0, male], [A006, fugafuga, 6.0, male], [A008, gaogao, 8.0, male], [A010, piyogao, 10.0, male] } }
配列内にある usersId を 1 つづつ判定してログ出力していく場合。
先に結果を見てもらうと、こんな感じです。
例えばこのコードを、ライブラリを使わずにコード内に書いた場合。
function myFunction() { var sheet = SpreadsheetApp.getActiveSheet(); var values = sheet.getDataRange().getValues(); values.shift(); var usersId = ['A001', 'A005', 'A006', 'A008', 'A010']; for (var i = 0; i < usersId.length; i++) { var userId = usersId[i]; for (var j = 0; j < values.length; j++) { if (values[j][0] !== userId) continue; Logger.log(values[j]); // [A001, hoge, 1.0, male], [A005, hogehoge, 5.0, male], [A006, fugafuga, 6.0, male], [A008, gaogao, 8.0, male], [A010, piyogao, 10.0, male] break; } } }
結果は、こんな感じです。
こんな小さなデータだけでも、結構な時間差ですね。
ライブラリを使う前提で、時間を短くするためにはいろいろと方法はあるかと思いますが、今回のボトルネックはライブラリの
sheet.getDataRange().getValues();
部分です。ここを回避する方法としては、配列をスプレッドシートから取得せずにコード内に直接表記する方法が考えられますが、メンテナンスの面から言って、お世辞にもいい選択肢とは言えません。
やるとすれば、ユーザーの全情報を取得するメソッドを作って
function getAllUserInformation() { var sheet = SpreadsheetApp.getActiveSheet(); var values = sheet.getDataRange().getValues(); values.shift(); return values; }
こんな感じで、ログ出力させてあげれば
function myFunction() { var usersId = ['A001', 'A005', 'A006', 'A008', 'A010']; var usersInfo = getAllUserInformation(); for (var i = 0; i < usersId.length; i++) { var userId = usersId[i]; for (var j = 0; j < usersInfo.length; j++) { if (usersInfo[j][0] !== userId) continue; Logger.log(usersInfo[j]); // [A001, hoge, 1.0, male], [A005, hogehoge, 5.0, male], [A006, fugafuga, 6.0, male], [A008, gaogao, 8.0, male], [A010, piyogao, 10.0, male] break; } } }
ライブラリを使ったとしても、そんなに悪い感じではないですね。
今回、ライブラリと連呼しながら実際には面倒だったので、別 function での動作確認となりましたが、function を分ける場合にも注意が必要ってことですね。
便利なライブラリはいろいろとありますが、利用シーンをご注意の上、用法用量を守って正しくお使いください。
0 notes
Blockchain and the Law Workshop @ UCL
April 26 2018
https://www.ucl.ac.uk/laws/events/2018/apr/blockchain-and-law?mc_cid=d361c2bb54&mc_eid=f20555d56f
“The workshop deals with emergent economic, political and legal phenomena in the field of FinTech. It pursues two distinct goals. First, it intends to generate awareness and facilitate a better understanding of the actors, phenomena and dynamics of the new financial order. Second, it explores the political and legal implications of financial and technological innovation based on blockchain technology. These debates will constitute the basis of an edited volume that introduces practitioners and researchers to the regulatory and political challenges of blockchain technologies and its diverse uses.”
Thoughts: To be honest, I found this quite dry. Even though I knew the layout of this event, I still think I expected this to be more of a lecture style and cohesive delivery of material that everyone agreed on, which obviously is never what panel events are like. But I still found that the content was very scattered, information was repeated, and some of the information seemed quite generic. I was definitely not impressed with the speaker that spent most of her presentation talking about AI and its implications - just seemed like she recycled an old presentation and somehow thought it would fit into a workshop specifically about blockchain?? Though I did learn overall, it just wasn’t very consistent or necessarily what I thought I’d get out of this session. Some things I found especially helpful: the three token types explained (by multiple different people haha), the comparison between token launches and other types of funding, and Prof. Ioannis Lianos’s insights on regulatory challenges.
NOTES
Panel 1: Fintech and Blockchain: State of play of the industry
Julian Leitloff, Co-founder & CEO of Fractal Blockchain
Deutsch bank background
Equity crowdfunding
Similar
investors are young and male
Interests of people investing have similar interests: product driven (i need to use this), return driven (privacy), cause driven (i care so much about data privacy)
Similar funding dynamics: Most of the funds are allocated right at the start - people make up their minds before the actual launch
Inherently different
International
More like a currency valuation - the token value does not depend on revenues, isn’t the same as just equity. → tokens not dependent on revenues but on usage (return token ←→ utility token)
Open and transparent way to fundraise for open source projects - token launches
Building this international community is really hard to do - actual international capital market
166 nationals involved
Components of a token launch
Florian Glatz, President of the German blockchain association (Bundesblock)
Thomas Bertani, CEO of Oraclize and EIDOO
Leading data delivery (connection between blockchain applications + any other context)
99% of the market cause started early
Eg. decentralised insurance (delay / smart contracts?), gambling games (implementing lotteries), exchange scalability
HMRC policy paper - vat exemption?
FCA sandbox program
Sterling-backed ERC20 token - allowed to issue sterling pound tokens on the public chain in a regulated manner (using digital identity cards to send payments would facilitate the KYC process on both business and usersides: onboarding of new users into blockchain space). Simple P2P payments without intermediaries.
technical complexities
Uncertainty around value of the coin
Switzerland is moving really fast, and encouraging new startups. Guidelines from FINMA (for financial licenses)
Exchanges: centralised / decentralised
Change one crypto to another, huge implications in regulation because operator in one case is actually holding on to the money VS exchange operator is just facilitating transfer + has no way to steal money or instruct money to move in a way not approved
Wallets: custodial/non custodial → implications
Still not defined
Custodial: If you are a provider of a wallet, and you are custodial provider (can prevent user to spend independently money), you will need a license for KYC
Non custodial: Technical service (can just download and run software themselves) → technically impossible to do KYC
ICO/tokens: classification of tokens, requirements
Robert Kilian, General Counsel, N26
Traditional fintech / fintech bank - 850/900k customers, v small bank, but have to report to 20 regulatory authorities on a daily basis
What’s especially interesting is solutions around digital identity services & Regulatory reporting (there’s a whole world to discover), beyond payments
Every authority has working groups + understands the business models
2 main hurdles
Blockchain based payments (cryptos + settlement systems/target 2) are not very widely accepted on european market, problem in every B2C business
Tech capacities & solutions are all very early stage, need to step up in regards with bringing specialised blockchain fintechs with other banks/fintechs. How you can put them into other solutions/technologies
Ben Whitby, Director of Compliance, TokenCard
Was at HSBC
Prepaid card platform built on ethereum to realise/extract value of ethereum/TLC?? token into Fiat, enabling that through mastercard and other issuers
Built on decentralised - you are holding those assets and they’re under your control (vs custodian wallet or bank, where custodian holds those assets)
SSL technology is driving public/private key infrastructure
Transactions you operate on an ethereum network can be seen by anybody, except your name isn’t associated with it (its your wallet’s address)
People can send you information/tokens if they have your wallet’s address, you can’t stop that. Operators can’t stop it either. [ie. terrorist sending them in]
Need some mechanism of sanctions
Data that is provided to blockchain is open + transparent
Lots of talk about scanning your documents (raw files) on to the blockchain for a digital identity: problem, because once your identity info is on blockchain, even though its encrypted, encryption deteriorates over time + as computer gets more sophisticated. I wouldn’t put anything on it that you ultimately wouldn’t mind being made public.
Youport, sovereign, UN’s 2020 -- will all push forward digital identities, in 2-3 years will probably have to use them
DLT vs public chains
DLT: Reduce operational cost, T+10 seconds. Barriers to entry here are v v significant, good for existing players
Public: support entrepreneurial activity. Enter into an ecosystem and grow your chain
Tokens: evolution of where we are in society, fractional capabilities are game changing, and transacting at near 0 costs, with massively increased trust because you know assets are going to go from point a-b
V important to determine difference between utility and payment tokens
Shouldn’t regulate tokens with yesterday’s regulations
Structure it properly and not hamper the innovation
Personally doesnt use internet banking lol
Sending photos on email/internet is horrible
Risk cannot be delegated - due diligence is important
Panel
Startups are working on quantam computing resistant encryption
People will eventually move to decentralised, non custodial solution
Hackable point is overdone - because systems develop overtime. You never store data on the blockchain, only metadata (??).
Blockhchain is the only proof you have of the timestamp? can’t remove it
Blockchain is the only censorship resistant mechanism that exists today - internet is censored by the government
Liquid assets - can easily sell, more appealing to investors
ICO vs equity funding
ICO: upsides - international market, easy access. Downsides - Technical capacity (wallet, install this, get to know this to the customers, which is a huge process), security
Panel 2: Blockchain and Fintech: Emerging legal issues
Victoria Birch, Partner, Norton Rose Fullbright
For AI to be accepted in any given market, it needs to be perceived by participants in the market as meeting minimum ethical/legal standards
Why are ethical values important?
Humans make decisions against a background of implicit societal ethical norms
AI is capable of autonomous decision making
AI is trained on past data and live operational date and takes on societal norms
Liability, reputation
Eg. HR decisions
Legal risks: supply chain impact, civil liabilities, consumer impact, contractual implications, criminal liability, regulatory breach, human rights/reputation, data privacy, etc
Smart contracts and stuff
Michael McKee, Partner, DLA Piper
European banking authority has defined virtual currency (digital representation used as a means of exchange and can be transferred/stored/traded electronically, not issued by a public authority, not necessarily attached to a fiat currency) - doesn’t have a backer and is decentralised, often are cryptographically secured
3 different categories - not necessarily legal
Payment (ie. bitcoin) - do not entail any claims on their issuers.
Are they money?
Problem with terminology
Store of value - Don’t function well as store of value, lots of volatility
Means of payment - not widely accepted
Unit of account - no
Utility - designed to give their holders access to blockchain powered services/platform, don’t generally create an issue for financial services regulators
Asset - attract most attention from regulators, usually associated with ICOs, that represent debt/equity claim. Offer some interest in profitability of the project - v similar to traditional securities.
Regulatory rationales?
Lots of abusive behaviour has been associated with eg. ICOs
Capacity to manipulate the market, ponzi schemes
ML and terrorism
Retail investors ?
Reducing transaction costs
Risk to global financial system
Forms of regulation
Top down - how people expect
Bottom up - typically industry led
Businesses policing risk - not so much regulation but business decisions by big players in payments world (lloyds bank)
Recent legal and regulatory developments
Supranational level: financial stability board (to G20), european commission action plan, IMF
US is ahead of the game:
CFTC dived in early (regarded as a commodity from a securities perspective, and a property from tax POV)
token issuers and exchanges are “money transmitters” (register and comply with AML/KYC)
FCC has taken very tough stance on ICO - if its an ICO its regarded as a security
UK
Case by case approach (v british), more nuanced in different ICOs (utility vs those that have a more security slant)
Tax: not subject to VAT, but yes to income/corporate gains tax
Germany - the opposite approach to US/UK (capital gains don’t apply, VAT does apply, because they are treated as means of payment)
EU: 4th money laundering directive includes electronic stuff
China takes hostile approach, cracked down on crypto exchanges, banned ICOs
Russia not so hostile, but has a draft bill on digital assets that states that digital financial assets aren’t legal means of payment
Challenges
Protecting retail investors
Internationally harmonised rules?
Whether integration or isolation in cryptos from traditional financial systems
Energy consumption - does this one huge downside outweigh all the rest?
Dr. Philipp Hacker, Humboldt University Berlin
Crypto securities regulation: ICOs under EU financial law
5B (ICO) vs 200M (VC) - blockchain fundraising in 2017
What you want is to avoid a US class action lawsuit (Tezos ICO - securities class action. Personally liable). 7 ICOs are facing this.
EU doesn’t have class action laws
3 archetypes of tokens:
Currency - not securities (exception of “instruments of payment), possibly subject to payment services regulation (PSD2)
investment (assets) - eg. DAO. prospectus regulation, free put option, crypto bank run
Utility - eg. filecoin, comparable to shares in companies (or securitised debt?). Disclosure duties and withdrawal rights, free put option, cryptobank run.
Negotiability (+)
Voting rights (+/-)
Future cash flow / dividends (-)
Possible appreciation in value (+)
Is this enough? 1 / 2 revenues. Two possibilities and zero case law:
1. Enough if expectations of profit raised by promotional materials
2. Generally not enough → financial risks stem from product functionality risks, better addressed by consumer law. Exception if AIV clearly dominates consumptive aspects.
Generally not securities → advantage for ICO system in EU
Recommendations:
Internal: Safe harbour for tokens - disclosure requirements
External: international convention
Dr. Deni Mantzari, University of Reading
Dr Anna Donovan, UCL Laws
Panel
Corporate governance - deep governance issues in open source/DLT communities
Light touch approach, compliant ?? regime
Algorithmic fairness paper
Singapore is the blockchain disneyland
Courts role (vs regulation) in liability - US/singapore
AI liability - victorian cases about when your horse loses control lol
EU courts probably going to get involved, and they’re quite experienced in dealing with technological change
Growing role for expert witnesses with tech background
Common law places them well in responding sensibly with traditional principles that have manifested themselves in new ??
Panel 3: Fintech, Blockchain and the Law: Regulatory Challenges
Dr Matteo Aquilina, Financial Conduct Authority
Talking about blockchain: 1. cryptos, 2. DLT in general
Consumer protection, market integrity, competition in interest of consumers
Cooperates with financial stability part (bank of england) [FB/PC]
Money has 3 core functions
Roughly 60% of BTC transactions are for illegal (years ago, when it was more niche)
ICOs vs standard capital raising - information asymmetry + uncertainty (company is so young) are extreme
Advantages: Improving organisational resilience, improve transparency, efficiency / removing intermediaries / saving costs in existing services
DLT as a game changer not in reforming old services, but eliminating/creating a completely new service
FCA as a whole is a believer in this technology, but we shouldn’t underestimate the risks (esp in consumer protection area + competition in future)
Regulatory sandbox
Dr. Tomaso Aste, Chair, UCL Center of Blockchain Technology (CBT)
Blockchain for regulation
Transactions are verified by a large community, community verification is hard to tamper, verified recorded immutable history of fair play reduces reputation?? → trust
A coordination technology that can create efficient marketplaces from illiquid environments that are not naturally connected and trustworthy
Use cases - Maison Project
Enabling real time regulatory reporting
Enabling a mortgage switching service
Limitations
Basic motor of blockchain is consensus - super inefficient
Consensus requires community validation
Information must be accessible to all network participants
In most cases, this is not affordable - Conflicts with proprietary rights on data, privacy, security
Reliable time stamping?
Research is needed
Prof. Ioannis Lianos, UCL Faculty of Laws
2 main views of regulation
Public interest - who are we protecting? Investors, consumers, etc
Private interest - new competitors to the market?
2 main issues:
1) What is a regulatory problem to be solved? Market failure
Privacy as a theoretical issue - as the equality parameter of competition (after microsoft linkedin merger)
But blockchain doesn’t bring up risk for privacy issues in comparison to digital platforms
Competition authorities often focus on horizontal - potential entrants + substitutes
But also suppliers and buyers are part of this thing
^ looking at porters 5 forces
Competition authorities duty to protect and promote competition and innovation
What about fairness?
Architectural advantage of various companies being able to influence ecosystem (incl. regulators) in a way that is in favour of their own interest. Narratives out there serve particular actors.
Blockchain → bottlenecks? (network effects/externalities)
Ethereum as indisputable platform of choice for tokens
Mining - highly concentrated, 5 operators control 85% of hash power
GDPR’s right to be forgotten vs blockchain immutability
Adaptive algorithms? Harder to deal with learning algorithms
Schumpeterian approaches ←→ imperfect competition
Permissionless innovation - experimentalism - principle of precaution
Currently missing from regulator’s approach: lots of interaction/collab with firms, but not much public consultation (for other stakeholders POV, like consumers)
Self regulation of industry - probably in the form of rating agencies
2) Different tools that regulators have at their disposal
Robert Kilian, General Counsel, N26
Prof. Iris Chiu, UCL Laws
Ben Whitby, Director of Compliance, TokenCard
Panel
EU financial law is heavily based on model of centralised systems (commercial registers)
See what other technologies we have that are decentralised (eg. cloud) - pretty much the same problems (IT, DP, financial regulation)
Public consultation is key, esp in financial regulation / new tech / entrepreneurship
Public chains are the ones that are going to enable innovation, DLT is great for incumbents to strip out costs n such
Crypto assets are borderless in nature, so needs more international coordination
Pittsburgh g20 OTT space - clear guideline
Utility + currency tokens don’t act like securities, consumer law is probably better
Primary (great ambiguity in asset tokens - should be regulated, not be treated like a financial offering) + secondary market (what sort of trading markets are we promoting and whether that is in line with what consumers want) dimension of ICOs
Regulators do engage with public - publishing many discussion papers
Blockchain will enable a much more competitive enviro
Competition authority should promote more Interoperability standards (open banking), more transparency in the market might encourage collusion?
1844 railways act
Regulators get blamed whether they regulate or not
V wait and see - probably foreclosure of one of the big platforms not giving access to a competitor
Functionally equivalent in law
0 notes