code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment -*- coding: utf-8 -*-
import sys
import pandas as pd
import numpy as np
import math
import csv
import matplotlib.pyplot as plt
function mean x
begin
return sum x / length x
end function
function de_mean x
begin
set x_bar = mean x
return list comprehension x_i - x_bar for x_i in x
end function
comment 輔助計算函式 dot... | # -*- coding: utf-8 -*-
import sys
import pandas as pd
import numpy as np
import math
import csv
import matplotlib.pyplot as plt
def mean(x):
return sum(x) / len(x)
def de_mean(x):
x_bar = mean(x)
return [x_i - x_bar for x_i in x]
# 輔助計算函式 dot product 、sum_of_squares
def dot(v, w):
return sum(v_i * w_i for v_... | Python | zaydzuhri_stack_edu_python |
function ping host
begin
import os , platform
comment Ping parameters as function of OS
if lower call system == string windows
begin
set ping_str = string -n
end
else
begin
set ping_str = string -c
end
comment Ping
return call system string ping + ping_str + string 1 + host == 0
end function | def ping(host):
import os, platform
# Ping parameters as function of OS
if platform.system().lower()=="windows":
ping_str = "-n"
else:
ping_str = "-c"
# Ping
return os.system("ping " + ping_str + " 1 " + host) == 0 | Python | nomic_cornstack_python_v1 |
function isFullWidth self
begin
return boolean
end function | def isFullWidth(self):
return bool() | Python | nomic_cornstack_python_v1 |
function test_get_fpl_team_data_gw1_different_fpl_team_ids
begin
set fetcher = call FPLDataFetcher
comment assume that fpl_team_ids < 100 will all have squads for
comment gameweek 1, and that they will be different..
set team_id_1 = random integer 1 50
set team_id_2 = random integer 51 100
set data_1 = call get_fpl_tea... | def test_get_fpl_team_data_gw1_different_fpl_team_ids():
fetcher = FPLDataFetcher()
# assume that fpl_team_ids < 100 will all have squads for
# gameweek 1, and that they will be different..
team_id_1 = random.randint(1, 50)
team_id_2 = random.randint(51, 100)
data_1 = fetcher.get_fpl_team_data(1... | Python | nomic_cornstack_python_v1 |
import re
string Given a string consisting of alphabets and others characters, remove all the characters other than alphabets and print the string so formed. Examples: Input : str = "$Gee*k;s..fo, r'Ge^eks?" Output : GeeksforGeeks
set str = string $Gee*k;s..fo, r'Ge^eks?
comment for char in str:
comment #print (char)
c... | import re
'''Given a string consisting of alphabets and others characters, remove all the characters other than alphabets and print the string so formed.
Examples:
Input : str = "$Gee*k;s..fo, r'Ge^eks?"
Output : GeeksforGeeks
'''
str = "$Gee*k;s..fo, r'Ge^eks?"
# for char in str:
# #print (char)
# if ord(... | Python | zaydzuhri_stack_edu_python |
function barGraph self
begin
set x = call getNames at 0
set y = call getValues
set nbElem = length y
if nbElem <= 1
begin
bar x y at 0
end
else
begin
set barWidth = 0.3
set r = list
append r array range length y at 0
for i in range 1 nbElem
begin
append r list comprehension x + barWidth for x in r at i - 1
end
for j in... | def barGraph(self):
x = self.graphDatas.getNames()[0]
y = self.graphDatas.getValues()
nbElem = len(y)
if nbElem <= 1:
plt.bar(x, y[0])
else:
barWidth = 0.3
r = list()
r.append(np.arange(len(y[0])))
for i in range(1, nbEl... | Python | nomic_cornstack_python_v1 |
function test_check_bc_duplicates_disable_bcs_dups self
begin
set header = list string SampleID string BarcodeSequence string LinkerPrimerSequence string run_prefix string Description
set mapping_data = list list string s-1 string ACGT string AAAA string 1 string s1&data list string s2 string ACGT string AAAA string 2 ... | def test_check_bc_duplicates_disable_bcs_dups(self):
header =\
['SampleID', 'BarcodeSequence', 'LinkerPrimerSequence', 'run_prefix',
'Description']
mapping_data = [['s-1', 'ACGT', 'AAAA', '1', 's1&data'],
['s2', 'ACGT', 'AAAA', '2', 's2_data']]
... | Python | nomic_cornstack_python_v1 |
function dep_view_prj self
begin
string View the project that is currently selected :returns: None :rtype: None :raises: None
if not cur_dep
begin
return
end
set i = call currentIndex
set item = call internalPointer
if item
begin
set prj = call internal_data
call view_prj prj
end
end function | def dep_view_prj(self, ):
"""View the project that is currently selected
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_dep:
return
i = self.dep_prj_tablev.currentIndex()
item = i.internalPointer()
if item:
p... | Python | jtatman_500k |
function _parse_transform cls transform
begin
comment Extract transform composer Callable
set compose_as = _compose_as at pop transform string compose_as string nn.Sequential
comment Extract the list of actual transform descriptions
set transforms = get transform string transform list
set parsed_transforms = list
for ... | def _parse_transform(cls, transform: T.Dict) -> T.Optional[T.Callable]:
# Extract transform composer Callable
compose_as = cls._compose_as[transform.pop('compose_as', 'nn.Sequential')]
transforms = transform.get('transform', []) # Extract the list of actual transform descriptions
pars... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import logging
set logger = call getLogger string detector
class ParserBasedDetector extends object
begin
function __init__ self file_path type_desc
begin
set file_path = file_path
set file = open file_path
set data = read lines file
set type = type_desc
close ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger('detector')
class ParserBasedDetector(object):
def __init__(self, file_path, type_desc):
file_path = file_path
file = open(file_path)
self.data = file.readlines()
self.type = type_desc
f... | Python | zaydzuhri_stack_edu_python |
comment Write your code below this line 👇
comment Write your code below this line 👇
function prime_checker number
begin
set prime = true
for digits in range 2 number
begin
if number % digits == 0
begin
if number % number == 0
begin
print string Divisible by { digits }
set prime = false
end
else
begin
print string Not... | #Write your code below this line 👇
#Write your code below this line 👇
def prime_checker(number):
prime = True
for digits in range(2, number):
if number % digits == 0:
if number % number == 0:
print (f"Divisible by {digits}")
prime = False
else:
... | Python | zaydzuhri_stack_edu_python |
from datetime import datetime
class BlogPost
begin
function __init__ self author_name title text publication_date
begin
set author_name = author_name
set title = title
set text = text
set publication_date = string parse time publication_date string %Y.%m.%d.
end function
function __str__ self
begin
return string " { ti... | from datetime import datetime
class BlogPost:
def __init__(self, author_name, title, text, publication_date):
self.author_name = author_name
self.title = title
self.text = text
self.publication_date = datetime.strptime(publication_date, '%Y.%m.%d.')
def __str__(self):
return f'''"{self.title... | Python | zaydzuhri_stack_edu_python |
string コピペして使えるutil系を集めたファイル
comment input系
set n = integer input
set tuple a b = map int split input string
comment 基本
set keys = list 1 2 3
set dicts = dictionary comprehension key : string 1 for key in keys
comment データ型
set s = set
add s
comment よく使う関数
comment 商と余り
set tuple q mod = divide mod 10 3
comment 逆行列
set l... | """
コピペして使えるutil系を集めたファイル
"""
##########
### input系
##########
n = int(input())
a, b = map(int, input().split(' '))
##########
### 基本
##########
keys = [1,2,3]
dicts = {key:'1' for key in keys}
##########
### データ型
##########
s = set()
s.add()
##########
### よく使う関数
##########
# 商と余り
q, mod = divmod(10, 3)
# 逆行列
l_2d... | Python | zaydzuhri_stack_edu_python |
import urllib
import requests
import base64
import json
class SpotifyInterface extends object
begin
set BASE_API_URL = string https://api.spotify.com
set AUTHORIZE_URL = string https://accounts.spotify.com/authorize?
set TOKEN_BASE_URL = string https://accounts.spotify.com/api/token
set END_POINTS = dict string playlis... | import urllib
import requests
import base64
import json
class SpotifyInterface(object):
BASE_API_URL = 'https://api.spotify.com'
AUTHORIZE_URL = 'https://accounts.spotify.com/authorize?'
TOKEN_BASE_URL = 'https://accounts.spotify.com/api/token'
END_POINTS = {
'playlist_tracks' : '/v1/users/{user_id}/playlists/... | Python | zaydzuhri_stack_edu_python |
function get_fsignature builtin_name
begin
set signature = _PARAMETRIC_NAME_TO_SIGNATURE at builtin_name
set f = _FSIGNATURE_REGISTRY at signature
comment Since most of the functions don't need to provide symbolic bindings we make
comment a little wrapper that provides trivially empty ones to alleviate the typing
comme... | def get_fsignature(builtin_name: Text) -> SignatureFn:
signature = _PARAMETRIC_NAME_TO_SIGNATURE[builtin_name]
f = _FSIGNATURE_REGISTRY[signature]
# Since most of the functions don't need to provide symbolic bindings we make
# a little wrapper that provides trivially empty ones to alleviate the typing
# burd... | Python | nomic_cornstack_python_v1 |
function Parse self stacktrace_list deps signature=none top_n_frames=none
begin
set callstacks = list
for stacktrace_str in stacktrace_list
begin
set sub_stacktrace = parse _sub_parser stacktrace_str deps signature=signature top_n_frames=top_n_frames
if sub_stacktrace
begin
extend callstacks stacks
end
end
return if e... | def Parse(self, stacktrace_list, deps, signature=None, top_n_frames=None):
callstacks = []
for stacktrace_str in stacktrace_list:
sub_stacktrace = self._sub_parser.Parse(stacktrace_str, deps,
signature=signature,
t... | Python | nomic_cornstack_python_v1 |
function _fromtimestamp cls t utc tz
begin
set tuple frac t = call modf t
set us = round frac * 1000000.0
if us >= 1000000
begin
set t = t + 1
set us = us - 1000000
end
else
if us < 0
begin
set t = t - 1
set us = us + 1000000
end
set converter = if expression utc then gmtime else localtime
set tuple y m d hh mm ss week... | def _fromtimestamp(cls, t, utc, tz):
frac, t = _math.modf(t)
us = round(frac * 1e6)
if us >= 1000000:
t += 1
us -= 1000000
elif us < 0:
t -= 1
us += 1000000
converter = _time.gmtime if utc else _time.localtime
y, m, d, hh, ... | Python | nomic_cornstack_python_v1 |
function format_response data comment
begin
set permalink = call permalink fast=true
if data is none
begin
comment for `not found` reply
set msg_template = format string SyntaxBot --find {0} --version 3 string print
comment stolen from RemindMeBot
set pm_link = format string https://reddit.com/message/compose/?to={0}&s... | def format_response(data, comment):
permalink = comment.permalink(fast=True)
if data is None:
# for `not found` reply
msg_template = 'SyntaxBot --find {0} --version 3'.format('print')
# stolen from RemindMeBot
pm_link = \
'https://reddit.com/message/compose/?to={0}&subje... | Python | nomic_cornstack_python_v1 |
string This problem was recently asked by Google. Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? | '''
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the
list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
'''
| Python | zaydzuhri_stack_edu_python |
comment continue & break
comment 책을 깜빡함
set no_book = list 7
comment 결석한 학생들
set absent = list 2 5
comment 출석번호가 1~10까지있음
for student in range 1 11
begin
comment 학생이 결석에 포함된다면
if student in absent
begin
continue
end
else
if student in no_book
begin
print format string 오늘수업 여기까지. {0}, 교무실로 따라와 student
break
end
print fo... | #continue & break
no_book = [7]#책을 깜빡함
absent = [2,5] #결석한 학생들
for student in range(1,11): #출석번호가 1~10까지있음
if student in absent: #학생이 결석에 포함된다면
continue
elif student in no_book:
print("오늘수업 여기까지. {0}, 교무실로 따라와".format(student))
break
print("{0}, 책을 읽어봐".format(student))
#결론: continue... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import pexpect
from termcolor import colored
set PROMPT = list string # string >>> string > string \$
function main
begin
set host = input string Ingrese el host del ssh a hacer bruteforce:
set usuario = input string Ingrese el usuario del ssh a hacer bruteforce:
set file = open string password... | #!/usr/bin/python
import pexpect
from termcolor import colored
PROMPT = ['# ', '>>> ', '> ', '\$ ']
def main():
host = input('Ingrese el host del ssh a hacer bruteforce: ')
usuario = input('Ingrese el usuario del ssh a hacer bruteforce: ')
file = open('passwordsbruteforce.txt', 'r')
for contrasena in file.readli... | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup as BS
import requests
import os
function cleandir
begin
comment If file directory does not exist, create it
if not is directory path get current directory + string \ScrapedImages
begin
print string Creating directory
make directory os get current directory + string \ScrapedImages
change di... | from bs4 import BeautifulSoup as BS
import requests
import os
def cleandir():
# If file directory does not exist, create it
if not os.path.isdir(os.getcwd() + "\\ScrapedImages"):
print("Creating directory")
os.mkdir(os.getcwd() + "\\ScrapedImages")
os.chdir(os.getcwd() + "\\Scr... | Python | zaydzuhri_stack_edu_python |
function put_bucket_lifecycle_configuration Bucket=none LifecycleConfiguration=none
begin
pass
end function | def put_bucket_lifecycle_configuration(Bucket=None, LifecycleConfiguration=None):
pass | Python | nomic_cornstack_python_v1 |
set c = 5.0
set d = 4
print c * d
print c - d
print c ^ d
print c / d | c = 5.0
d = 4
print(c * d)
print(c - d)
print(c ** d)
print(c / d)
| Python | zaydzuhri_stack_edu_python |
comment imports go at the top of the file
import sys
comment Data Structure
set donor_db = dict string William Gates, III list 653772.32 12.17 ; string Jeff Bezos list 877.33 ; string Paul Allen list 663.23 43.87 1.32 ; string Mark Zuckerberg list 1663.23 4300.87 10432.0 ; string Elon Musk list 2263.23 3300.87 15432.0
... | import sys # imports go at the top of the file
# Data Structure
donor_db = {"William Gates, III": [653772.32, 12.17],
"Jeff Bezos": [877.33],
"Paul Allen": [663.23, 43.87, 1.32],
"Mark Zuckerberg": [1663.23, 4300.87, 10432.0],
"Elon Musk": [2263.23, 3300.87, 15432.0],... | Python | zaydzuhri_stack_edu_python |
comment !/user/bin/python
comment coding:utf-8
set __author__ = string yan.shi
from jieba import posseg
import jieba
import codecs
import re
from jieba import analyse
string 词共现,先对文本分句,这里利用的是一个句子中的词共现方式,也可以设置一个共现窗口 分词使用是jieba,这个可以提取词性 最后计算的相关词可以用gephi作网络图显示
class SimWordsCoccurrence
begin
comment 加载停词
function loadStop... | #!/user/bin/python
#coding:utf-8
__author__ = 'yan.shi'
from jieba import posseg
import jieba
import codecs
import re
from jieba import analyse
'''
词共现,先对文本分句,这里利用的是一个句子中的词共现方式,也可以设置一个共现窗口
分词使用是jieba,这个可以提取词性
最后计算的相关词可以用gephi作网络图显示
'''
class SimWordsCoccurrence():
# 加载停词
def loadStopWords(self, stopwordsPath... | Python | zaydzuhri_stack_edu_python |
from sqlalchemy import Column , Integer , String
from database import Base , db_session
from random import randint
class Company extends Base
begin
set params = list string name string user_id string num_employees string description
set __tablename__ = string Company
set name = call Column String primary_key=false null... | from sqlalchemy import Column, Integer, String
from database import Base, db_session
from random import randint
class Company(Base):
params = [ 'name', 'user_id', 'num_employees', 'description',]
__tablename__ = "Company"
name = Column(String, primary_key=False, nullable=True, unique=True)
user_... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python3
import re
function isPhoneNumber message
begin
set regex = compile string ( \d{3} [-\s)] | \( \d{3} \) ) ? # Area code ( [-\s] ) ? # Separator ( \d{3} ) # First three numbers ( [-\s] ) ? # Separator ( \d{4} ) # Last four numbers VERBOSE
set match = find all message
for x in match
begin
pr... | #! /usr/bin/env python3
import re
def isPhoneNumber(message):
regex = re.compile(
r"""
( \d{3} [-\s)] | \( \d{3} \) ) ? # Area code
( [-\s] ) ? # Separator
( \d{3} ) # First three numbers
( [-\s] ) ? # Sep... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from random import randint
import matplotlib.pyplot as plt
from matplotlib import ticker as tick
comment np.mean()promedio np.std desviacion statistics.variance varianza
set n = 1000
set a = 0
set b = 36
set prom = list
set promedio_promedio = list
set varianza = list
set varianza_promedio = list ... | import numpy as np
from random import randint
import matplotlib.pyplot as plt
from matplotlib import ticker as tick
#np.mean()promedio np.std desviacion statistics.variance varianza
n=1000
a=0
b=36
prom = []
promedio_promedio = []
varianza = []
varianza_promedio = []
FrecR=[]
desviacion = []
desviaci... | Python | zaydzuhri_stack_edu_python |
function get_features fincoords vector orientations
begin
set features = list
set feature_obj = list
for tuple i point in enumerate fincoords
begin
set feature = call FeatureBase array list point at 0 point at 1 point at 2 orientations
set vec = call make_feature_vector vector at i
append features vec
append feature_... | def get_features(fincoords, vector, orientations):
features = []
feature_obj = []
for i,point in enumerate(fincoords):
feature = FeatureBase(np.array([point[0], point[1]]), point[2], orientations)
vec = feature.make_feature_vector(vector[i])
features.append(vec)
feature_obj.append(feature)
return features... | Python | nomic_cornstack_python_v1 |
for i in range n - 1
begin
set result = result + p at i + 1
end
print result | for i in range(n-1):
result += p[i+1]
print(result) | Python | zaydzuhri_stack_edu_python |
from os.path import join , basename
import csv
set DATA_FOLDER = string tempdata
set YEAR = 2014
set filename = join DATA_FOLDER string yob + string YEAR + string .txt
set WRANGLED_HEADS = list string year string name string gender string ratio string females string males string total
set WRANGLED_DATA_FILE = join DATA... | from os.path import join, basename
import csv
DATA_FOLDER = 'tempdata'
YEAR = 2014
filename = join (DATA_FOLDER, 'yob' + str(YEAR) + '.txt')
WRANGLED_HEADS = ['year','name', 'gender', 'ratio', 'females', 'males', 'total']
WRANGLED_DATA_FILE = join(DATA_FOLDER, 'wrangled2014.csv')
namesdict = {}
with open(filename, 'r... | Python | zaydzuhri_stack_edu_python |
comment encoding: UTF-8
import copy
from datetime import time
from vnpy.trader.vtObject import VtTickData , VtBarData
class BarManager extends object
begin
string K线合成器,支持: 1. 基于Tick合成1分钟K线 2. 基于1分钟K线合成X分钟K线(X可以是2、3、5、10、15、30、60)
comment ----------------------------------------------------------------------
function _... | # encoding: UTF-8
import copy
from datetime import time
from vnpy.trader.vtObject import VtTickData, VtBarData
########################################################################
class BarManager(object):
"""
K线合成器,支持:
1. 基于Tick合成1分钟K线
2. 基于1分钟K线合成X分钟K线(X可以是2、3、5、10、15、30、60)
"""
#---... | Python | zaydzuhri_stack_edu_python |
function broyden_solver f x0 y0=none tol=1e-09 maxcount=100 backtrack_c=0.5 verbose=true
begin
set tuple x y = tuple x0 y0
if y is none
begin
set y = f dist x
end
for count in range maxcount
begin
if verbose
begin
call printit count x y
end
if max absolute y < tol
begin
return tuple x y
end
comment initialize J with Ne... | def broyden_solver(f, x0, y0=None, tol=1E-9, maxcount=100, backtrack_c=0.5, verbose=True):
x, y = x0, y0
if y is None:
y = f(x)
for count in range(maxcount):
if verbose:
printit(count, x, y)
if np.max(np.abs(y)) < tol:
return x, y
# initialize J wi... | Python | nomic_cornstack_python_v1 |
import Account
class Transaction
begin
function __init__ self Sender Recipient Amount Signature=none
begin
set sender : Account = Sender
set recipient = Recipient
set amount = Amount
set signature = Signature
end function
function __str__ self
begin
return string Sender: + string sender + string Recipient: + string rec... | import Account
class Transaction():
def __init__(self, Sender, Recipient, Amount, Signature = None):
self.sender: Account = Sender
self.recipient = Recipient
self.amount = Amount
self.signature = Signature
def __str__(self):
return("Sender: " + str(self.sender) + " Reci... | Python | zaydzuhri_stack_edu_python |
import csv
import matplotlib.pyplot as plt
set x1 = list
set y1 = list
set x2 = list
set y2 = list
set x3 = list
set y3 = list
set x4 = list
set y4 = list
set x5 = list
set y5 = list
set x6 = list
set y6 = list
set x7 = list
set y7 = list
with open string spreadsheetThree - MURE-10^7s.csv string r as csvf... | import csv
import matplotlib.pyplot as plt
x1 = []
y1 = []
x2 = []
y2 = []
x3 = []
y3 = []
x4 = []
y4 = []
x5 = []
y5 = []
x6 = []
y6 = []
x7 = []
y7 = []
with open('spreadsheetThree - MURE-10^7s.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x1.append((row[0]))
y1.append((ro... | Python | zaydzuhri_stack_edu_python |
function parse_url_http self furl=none
begin
if furl is none
begin
set furl = file
end
set fuparse = url parse furl
if scheme in list string ftp string http
begin
set conn = call HTTPConnection netloc
end
else
if scheme in list string ftps string https
begin
set conn = call HTTPSConnection netloc context=call _create_u... | def parse_url_http(self, furl=None):
if furl is None:
furl = self.file
self.fuparse = urlparse(furl)
if self.fuparse.scheme in ["ftp", "http"]:
self.conn = http.client.HTTPConnection(self.fuparse.netloc)
elif self.fuparse.scheme in ["ftps", "https"]:
s... | Python | nomic_cornstack_python_v1 |
function chiotnoenechiotnoe
begin
print string Nazovi chislo, suchechka!
set number26 = integer input
if number26 % 2 == 0
begin
print string chiotnoe
end
else
begin
print string nechiotnoe
end
print string xaxa
end function
call chiotnoenechiotnoe | def chiotnoenechiotnoe ():
print ("Nazovi chislo, suchechka!")
number26=int(input())
if number26%2==0: print ("chiotnoe")
else: print ("nechiotnoe")
print ("xaxa")
chiotnoenechiotnoe()
| Python | zaydzuhri_stack_edu_python |
comment https://www.acmicpc.net/problem/13308
import heapq
import sys
from collections import deque , defaultdict
set read = readline
set tuple n m = map int split strip read
set gas = deque list comprehension integer e for e in split strip read
call appendleft 0
set path = default dictionary lambda -> default diction... | # https://www.acmicpc.net/problem/13308
import heapq
import sys
from collections import deque, defaultdict
read = sys.stdin.readline
n, m = map(int, read().strip().split())
gas = deque([int(e) for e in read().strip().split()])
gas.appendleft(0)
path = defaultdict(lambda: defaultdict(lambda: float('inf')))
for _ in ra... | Python | zaydzuhri_stack_edu_python |
function infer_screen_name self screen_name skip_cache=false
begin
set screen_name = lower screen_name
if screen_name at 0 == string @
begin
set screen_name = screen_name at slice 1 : :
end
if not skip_cache
begin
comment If a json file exists, we'll use that. Otherwise go get the data.
try
begin
with open format str... | def infer_screen_name(self, screen_name, skip_cache=False):
screen_name = screen_name.lower()
if screen_name[0] == "@":
screen_name = screen_name[1:]
if not skip_cache:
# If a json file exists, we'll use that. Otherwise go get the data.
try:
wi... | Python | nomic_cornstack_python_v1 |
function remove_root id
begin
info format string Arrived in remove_root(); request.referrer = {req} req=referrer
set user = call get_or_404 id
info format string Preparing to remove root role in make_root(); request.referrer = {req} req=referrer
call remove_role_from_user user string root
commit _datastore
info format ... | def remove_root(id):
current_app.logger.info('Arrived in remove_root(); request.referrer = {req}'.format(req=request.referrer))
user = User.query.get_or_404(id)
current_app.logger.info('Preparing to remove root role in make_root(); request.referrer = {req}'.format(req=request.referrer))
_datastore.re... | Python | nomic_cornstack_python_v1 |
function init_logger
begin
global logger
call fileConfig string ..\Config\Logging.config
if build_target == string PROD
begin
set logger = call getLogger string ProdLogger
end
else
begin
set logger = call getLogger string DefaultLogger
end
comment Set the log level passed as a parameter
set numeric_level = get attribut... | def init_logger():
global logger
logging.config.fileConfig('..\Config\Logging.config')
if (args.build_target == 'PROD'):
logger = logging.getLogger('ProdLogger')
else:
logger = logging.getLogger('DefaultLogger')
# Set the log level passed as a parameter
numeric... | Python | nomic_cornstack_python_v1 |
function __hash__ self
begin
return call hash tuple namespace token token_plural call frozenset items parameters
end function | def __hash__(self) -> int:
return hash((
self.namespace, self.token, self.token_plural,
frozenset(self.parameters.items()),
)) | Python | nomic_cornstack_python_v1 |
from com.bridgelabz.util.utility import Utility
set utility_obj = call Utility
set template = string Hello <<username>>, How are you?
print string Enter your string
set user_string = call get_string
set new_string = call replace_str template string <<username>> user_string
print new_string | from com.bridgelabz.util.utility import Utility
utility_obj = Utility()
template = "Hello <<username>>, How are you?"
print("Enter your string")
user_string = utility_obj.get_string()
new_string = utility_obj.replace_str(template, "<<username>>", user_string)
print(new_string) | Python | zaydzuhri_stack_edu_python |
function get_frequency_dict sequence
begin
comment freqs: dictionary (element_type -> int)
set freq = dict
for x in sequence
begin
set freq at x = get freq x 0 + 1
end
return freq
end function | def get_frequency_dict(sequence):
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq | Python | nomic_cornstack_python_v1 |
function __ne__ self other
begin
if not is instance other Build
begin
return true
end
return call to_dict != call to_dict
end function | def __ne__(self, other):
if not isinstance(other, Build):
return True
return self.to_dict() != other.to_dict() | Python | nomic_cornstack_python_v1 |
function parse_program_params
begin
comment out address
set local_address = none
comment address of the bootstrap node
set remote_address = none
comment our chat name
set name = none
try
begin
if length argv == 3
begin
set local_address = call parse_address argv at 1
set name = argv at 2
end
else
if length argv == 5 an... | def parse_program_params():
local_address = None # out address
remote_address = None # address of the bootstrap node
name = None # our chat name
try:
if len(sys.argv) == 3:
local_address = parse_address(sys.argv[1])
name = sys.argv[2]
elif len(sys.argv) == 5 a... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment I wrote this kernel to mess around with the sketch data and share my experience so far. After exploring the website and the data, I'll use a very basic CNN to classify sketches. This model gets 0.60 on the Public LB when run with 6000 recognized images per clas... | #!/usr/bin/env python
# coding: utf-8
# I wrote this kernel to mess around with the sketch data and share my experience so far. After exploring the website and the data, I'll use a very basic CNN to classify sketches. This model gets 0.60 on the Public LB when run with 6000 recognized images per class.
#
# ## Quick,... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
function getContent
begin
set url = string https://www.mygov.in/covid-19
set r = get requests url
set content = string
if status_code == 200
begin
set content = text
end
return content
end function
function getContent1
begin
set url = string https://www.mohfw.gov.in/
set r... | import requests
from bs4 import BeautifulSoup
def getContent():
url = "https://www.mygov.in/covid-19"
r = requests.get(url)
content = "";
if r.status_code == 200:
content = r.text
return content
def getContent1():
url = "https://www.mohfw.gov.in/"
r = requests.get(url)... | Python | zaydzuhri_stack_edu_python |
function initialize self
begin
call initialize
call set_text text
call set_icon icon
call set_icon_size icon_size
end function | def initialize(self):
super(QtPushButton, self).initialize()
self.set_text(self.shell_obj.text)
self.set_icon(self.shell_obj.icon)
self.set_icon_size(self.shell_obj.icon_size) | Python | nomic_cornstack_python_v1 |
from colorthief import ColorThief
import matplotlib.pyplot as plt
import numpy as np
function identifyColor img_path
begin
set color_thief = call ColorThief img_path
set dm = call get_color quality=1
return call rgb_to_hex dm
end function
function rgb_to_hex rgb
begin
return string %02x%02x%02x % rgb
end function
funct... | from colorthief import ColorThief
import matplotlib.pyplot as plt
import numpy as np
def identifyColor(img_path):
color_thief = ColorThief(img_path)
dm = color_thief.get_color(quality=1)
return rgb_to_hex(dm)
def rgb_to_hex(rgb):
return '%02x%02x%02x' % rgb
def plot():
marker_size=15
xyz=np.a... | Python | zaydzuhri_stack_edu_python |
string Sheets class file
import pickle
import os.path
import enum
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from app.memorization_time import MemorizationTime
comment full access scope
set SCOPES = list string ht... | """ Sheets class file """
import pickle
import os.path
import enum
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from app.memorization_time import MemorizationTime
# full access scope
SCOPES = ["https://www.googlea... | Python | zaydzuhri_stack_edu_python |
import pymongo
import json
import pandas as pd
import ast
from pandas import DataFrame
class DatabaseCommunication
begin
function __init__ self
begin
set mongo = call MongoClient string mongodb+srv://Monika:Monika@learncluster-x6htx.mongodb.net/test?retryWrites=true&w=majority
end function
function add_dataframe_to_col... | import pymongo
import json
import pandas as pd
import ast
from pandas import DataFrame
class DatabaseCommunication:
def __init__(self):
self.mongo = pymongo.MongoClient("mongodb+srv://Monika:Monika@learncluster-x6htx.mongodb.net/test?retryWrites=true&w=majority")
def add_dataframe_to_collection(self... | Python | zaydzuhri_stack_edu_python |
from typing import List
import gspread
from gspread import Worksheet , WorksheetNotFound
from oauth2client.service_account import ServiceAccountCredentials
from pgas.utils import range_grid
class GSpread
begin
set worksheet_rows = 15000
set worksheet_cols = 26
function __init__ self key_file spreadsheet_url
begin
set g... | from typing import List
import gspread
from gspread import Worksheet, WorksheetNotFound
from oauth2client.service_account import ServiceAccountCredentials
from pgas.utils import range_grid
class GSpread:
worksheet_rows = 15000
worksheet_cols = 26
def __init__(self, key_file, spreadsheet_url):
s... | Python | zaydzuhri_stack_edu_python |
function cat_arrays arr1 arr2
begin
set newarr = list comprehension 0 for i in range length arr1 + length arr2
for i in range length arr1
begin
set newarr at i = arr1 at i
end
for i in range length arr2
begin
set newarr at i + length arr1 = arr2 at i
end
return newarr
end function | def cat_arrays(arr1, arr2):
newarr = [0 for i in range(len(arr1) + len(arr2))]
for i in range(len(arr1)):
newarr[i] = arr1[i]
for i in range(len(arr2)):
newarr[i + len(arr1)] = arr2[i]
return newarr | Python | nomic_cornstack_python_v1 |
function test05_pack_values self
begin
set _values = list 0 1 1 1 0 0 1 0 1 1 0 0 1
assert equal call pack_values _values string 0111001011001
end function | def test05_pack_values(self):
_values = [0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1]
self.assertEqual(self.DUT.pack_values(_values), '0111001011001') | Python | nomic_cornstack_python_v1 |
function _evaluate_performance_voltage_clamp baseline_trace indiv_trace
begin
set error = 0
set base_interp = interp 1d t call get_current_summed
set currents = call get_current_summed
for i in range length t
begin
set error = error + call base_interp t at i - currents at i ^ 2
end
return error
end function | def _evaluate_performance_voltage_clamp(baseline_trace: trace.Trace,
indiv_trace: trace.Trace) -> float:
error = 0
base_interp = scipy.interpolate.interp1d(
baseline_trace.t,
baseline_trace.current_response_info.get_current_summed())
currents = indiv_... | Python | nomic_cornstack_python_v1 |
comment calcular aumento e informa o salario
comment para salarios superior a R$ 1.250,00 - aumento de 10%
comment para salarios inferior a R$ 1.250,00 - aumento de 15%
set salario = decimal input string Informe seu salário:
if salario <= 1250.0
begin
set novo = salario + salario * 15 / 100
end
else
begin
set novo = sa... | #calcular aumento e informa o salario
#para salarios superior a R$ 1.250,00 - aumento de 10%
#para salarios inferior a R$ 1.250,00 - aumento de 15%
salario = float(input('Informe seu salário: '))
if salario <= 1250.00:
novo = salario + (salario * 15 / 100)
else:
novo = salario + (salario * 10 / 100)
print('Seu ... | Python | zaydzuhri_stack_edu_python |
function foo
begin
set a = 1
print a
end function
function bar
begin
set a = 2
end function
call foo
bar | def foo():
a = 1
print(a)
def bar():
a = 2
foo()
bar()
| Python | flytech_python_25k |
if word == rev_word
begin
print word + string is a palindrome
end
else
begin
print word + string is not a palindrome
end | if word == rev_word:
print (word + " is a palindrome")
else:
print (word + " is not a palindrome")
| Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function firstUniqChar self s
begin
string :type s: str :rtype: int
end function
end class
comment l = list(s)
comment ll = []
comment for i in range(len(l)):
comment num = l.count(l[i])
comment if num == 1:
comment return i
comment return -1 | class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
# l = list(s)
# ll = []
# for i in range(len(l)):
# num = l.count(l[i])
# if num == 1:
# return i
# return -1 | Python | zaydzuhri_stack_edu_python |
comment install required libraries
comment for mmwave - pip install openradar
import numpy as np
import time
from mmwave.dsp.range_processing import *
from processing_chain import *
import skvideo.io
import matplotlib.pyplot as plt
import cv2
set time_ms = lambda -> integer round time * 1000
set start_time = call time... | # install required libraries
# for mmwave - pip install openradar
import numpy as np
import time
from mmwave.dsp.range_processing import *
from processing_chain import *
import skvideo.io
import matplotlib.pyplot as plt
import cv2
time_ms = lambda: int(round(time.time() * 1000))
start_time = time_ms()
# radar ... | Python | zaydzuhri_stack_edu_python |
function printInorder root
begin
if root
begin
call printInorder left
print data end=string
call printInorder right
end
end function
function printPreorder root
begin
if root
begin
print data end=string
call printPreorder left
call printPreorder right
end
end function
function printPostorder root
begin
if root
begin
ca... | def printInorder(root):
if root:
printInorder(root.left)
print(root.data, end = " ")
printInorder(root.right)
def printPreorder(root):
if root:
print(root.data, end = " ")
printPreorder(root.left)
printPreorder(root.right)
def printPostorder(root):
if root:
... | Python | zaydzuhri_stack_edu_python |
from abc import ABCMeta , abstractmethod
import inspect
import types
from pycalcmodel.core.phy import ModelPhy
import os
string Phy interface file This has been updated to handle 3 scenarios: 1) makePhy can be called inside of PHY_PHY1Example, and then if another PHY wishes to call PHY1Example the phy_name and phy_grou... | from abc import ABCMeta, abstractmethod
import inspect
import types
from pycalcmodel.core.phy import ModelPhy
import os
"""
Phy interface file
This has been updated to handle 3 scenarios:
1) makePhy can be called inside of PHY_PHY1Example, and then if another PHY wishes to call PHY1Example the phy_name and phy_group_... | Python | zaydzuhri_stack_edu_python |
comment Caesar cipher.
function encrypt text shift
begin
set cipher = string
for char in text
begin
set code = ordinal char + shift
if code > ordinal string ~
begin
set code = ordinal string + code - ordinal string ~
end
set cipher = cipher + character code
end
return cipher
end function
function decrypt cipher shift
... | # Caesar cipher.
def encrypt(text, shift):
cipher = ''
for char in text:
code = ord(char) + shift
if code > ord('~'):
code = ord(' ') + (code - ord('~'))
cipher += chr(code)
return cipher
def decrypt(cipher, shift):
decipher = ''
for char in cip... | Python | zaydzuhri_stack_edu_python |
function add_image_text image text
begin
set text_image = copy image
set text_font = FONT_HERSHEY_SIMPLEX
comment from topleft
set text_origin_pos = tuple 170 30
set text_scale = 0.8
set text_color = tuple 20 240 150
set text_line_thick = 2
call putText text_image text text_origin_pos text_font text_scale text_color te... | def add_image_text(image: imageType, text: str) -> imageType:
text_image = image.copy()
text_font = cv2.FONT_HERSHEY_SIMPLEX
text_origin_pos = (170, 30) # from topleft
text_scale = 0.8
text_color = (20, 240, 150)
text_line_thick = 2
cv2.putText(text_image, text, text_origin_pos, text_font, ... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function run self matrix target
begin
if matrix or matrix at 0
begin
set rows = length matrix
set cols = length matrix at 0
set row = 0
set col = cols - 1
while true
begin
if row < rows and col >= 0
begin
if matrix at row at col == target
begin
return true
end
else
if matrix at row a... | class Solution(object):
def run(self, matrix, target):
if matrix or matrix[0]:
rows = len(matrix)
cols = len(matrix[0])
row = 0
col = cols - 1
while True:
if row < rows and col >= 0:
if matrix[row][col] == targe... | Python | zaydzuhri_stack_edu_python |
function correct_mmp df prev_id
begin
if not is_monotonic_decreasing
begin
raise call RuntimeError string `df.scale` is not descending.
end
set prev_a = values at id == prev_id at 0
set a_uniq = unique
set mmp = zeros like a_uniq dtype=int
for tuple i a in enumerate a_uniq
begin
comment Place index of previous halo in ... | def correct_mmp(df, prev_id):
if not df.scale.is_monotonic_decreasing:
raise RuntimeError("`df.scale` is not descending.")
prev_a = df.scale.values[(df.id == prev_id)][0]
a_uniq = df.scale[(df.scale <= prev_a)].unique()
mmp = np.zeros_like(a_uniq, dtype=int)
for i, a in enumerate(a_uniq):
... | Python | nomic_cornstack_python_v1 |
function sabotage self channel=none
begin
return boolean call getAttributeData string SABOTAGE channel
end function | def sabotage(self, channel=None):
return bool(self.getAttributeData("SABOTAGE", channel)) | Python | nomic_cornstack_python_v1 |
import os , sys
try
begin
import pandas as pd
end
except any
begin
call system string pip install pandas
import pandas as pd
end
try
begin
import numpy as np
end
except any
begin
call system string pip install numpy
import numpy as np
end
try
begin
import matplotlib.pyplot as plt
end
except any
begin
call system string... | import os, sys
try:
import pandas as pd
except:
os.system("pip install pandas")
import pandas as pd
try:
import numpy as np
except:
os.system('pip install numpy')
import numpy as np
try:
import matplotlib.pyplot as plt
except:
os.system('pip install matplotlib')
i... | Python | zaydzuhri_stack_edu_python |
function _ss_err self
begin
return sum call square _resids axis=- 2
end function | def _ss_err(self):
return np.sum(np.square(self._resids), axis=-2) | Python | nomic_cornstack_python_v1 |
function SIDFT X D
begin
set N = length X
set x = zeros N string complex
for n in range 0 N 1
begin
for k in range 0 N 1
begin
set x at n = x at n + exp - 1j * 2 * pi * k * D / N * X at k * exp 1j * 2 * pi * k * n / N
end
end
return x / N
end function | def SIDFT(X,D):
N=len(X)
x=np.zeros(N,'complex')
for n in range(0,N,1):
for k in range(0,N,1):
x[n]=x[n]+np.exp(-1j*2*np.pi*k*D/N)*X[k]*np.exp(1j*2*np.pi*k*n/N)
return x/N | Python | nomic_cornstack_python_v1 |
function get_corner_node_prune lcurve
begin
set tuple rho eta = tuple zeros length lcurve zeros length lcurve
for lia in range length lcurve
begin
set rho at lia = lcurve at lia at 0
set eta at lia = lcurve at lia at 1
end
if length rho != length eta
begin
raise call ValueError string both arrays must have the same siz... | def get_corner_node_prune(lcurve):
rho, eta = np.zeros(len(lcurve)), np.zeros(len(lcurve))
for lia in range(len(lcurve)):
rho[lia] = lcurve[lia][0]
eta[lia] = lcurve[lia][1]
if len(rho) != len(eta):
raise ValueError("both arrays must have the same size")
fin = np.isfinit... | Python | nomic_cornstack_python_v1 |
function doit
begin
set myp = call MyPapers
set cites = call Cites mypapers
comment cites.cite_report()
call compare_and_update
end function | def doit():
myp = MyPapers()
cites = Cites(myp.mypapers)
#cites.cite_report()
cites.compare_and_update() | Python | nomic_cornstack_python_v1 |
function test_process_metrics_method_not_writable_dir monkeypatch s3_setup tmpdir
begin
comment remove "default" output file if it already exists
set output_metadata_file = call Path string /tmp / string mlpipeline-ui-metadata.json
call remove_file output_metadata_file
try
begin
call setenv string ELYRA_WRITABLE_CONTAI... | def test_process_metrics_method_not_writable_dir(monkeypatch, s3_setup, tmpdir):
# remove "default" output file if it already exists
output_metadata_file = Path("/tmp") / "mlpipeline-ui-metadata.json"
remove_file(output_metadata_file)
try:
monkeypatch.setenv("ELYRA_WRITABLE_CONTAINER_DIR", "/g... | Python | nomic_cornstack_python_v1 |
from abstract import abssimulator
from actions import tetrisaction
from states import tetrisstate
import random
class TetrisSimulatorClass extends AbstractSimulator
begin
function __init__ self num_players
begin
if num_players > 1
begin
raise call ValueError string Number of players cannot be more than 1 for tetris.
en... | from abstract import abssimulator
from actions import tetrisaction
from states import tetrisstate
import random
class TetrisSimulatorClass(abssimulator.AbstractSimulator):
def __init__(self, num_players):
if num_players > 1:
raise ValueError("Number of players cannot be more than 1 for tetris."... | Python | zaydzuhri_stack_edu_python |
comment 判断是否是回文链表
string 问题解析:就是给你一个字符串,然后看首尾节点值是否一致 算法分析:直接遍历字符串,判断头节点和尾节点的值
comment class Solution:
comment def isPalindrome(self, head):
comment cur = head
comment while cur.next != None:
comment cur = cur.next
comment if cur.val == head.val:
comment return True
comment return False
string 我只能说我太天真了,我把回文链表的意思弄错了。 回文... | #判断是否是回文链表
"""
问题解析:就是给你一个字符串,然后看首尾节点值是否一致
算法分析:直接遍历字符串,判断头节点和尾节点的值
"""
# class Solution:
# def isPalindrome(self, head):
# cur = head
# while cur.next != None:
# cur = cur.next
# if cur.val == head.val:
# return True
# return False
"""
... | Python | zaydzuhri_stack_edu_python |
import pafy
import _thread
from urllib.request import urlopen
from bs4 import BeautifulSoup
import json
import urllib.request
from requests import get
comment Initializing all url
set api = string https://content.googleapis.com/youtube/v3/search?q=
set api3 = string &maxResults=25&part=snippet&key=AIzaSyAjtQHN9pkXswmmv... | import pafy
import _thread
from urllib.request import urlopen
from bs4 import BeautifulSoup
import json
import urllib.request
from requests import get
#Initializing all url
api="https://content.googleapis.com/youtube/v3/search?q="
api3="&maxResults=25&part=snippet&key=AIzaSyAjtQHN9pkXswmmvWLOfpzhEwA3uhUTiJM"
def prin... | Python | zaydzuhri_stack_edu_python |
function test_water_needs_output self
begin
set cline = call WaterCommandline cmd=exes at string water asequence=string asis:ACCCGGGCGCGGT bsequence=string asis:ACCCGAGCGCGGT gapopen=10 gapextend=0.5 auto=true
assert true auto
assert true not stdout
assert true not filter
assert is none outfile
assert raises ValueError... | def test_water_needs_output(self):
cline = WaterCommandline(
cmd=exes["water"],
asequence="asis:ACCCGGGCGCGGT",
bsequence="asis:ACCCGAGCGCGGT",
gapopen=10,
gapextend=0.5,
auto=True,
)
self.assertTrue(cline.auto)
self... | Python | nomic_cornstack_python_v1 |
function SVMs_model train_f test_f y1 y2
begin
set model = support vector classifier
set param_grid = dict string C list 1 10
set cv = call StratifiedKFold n_splits=10 random_state=0
set model = grid search cv support vector classifier gamma=string scale kernel=string linear param_grid iid=true cv=cv refit=true verbose... | def SVMs_model(train_f, test_f, y1, y2):
model = svm.SVC()
param_grid = {'C':[1,10]}
cv = StratifiedKFold(n_splits = 10, random_state = 0)
model = GridSearchCV(svm.SVC(gamma = 'scale', kernel = 'linear'), param_grid, iid = True, cv = cv, refit = True, verbose = 2, scoring = 'f1')
model.fit(train_f, y1)
pan... | Python | nomic_cornstack_python_v1 |
function _apply_sig_clip data e_data sig_thres=2 ymin=0 ymax=1.2 var=string V2 display=false
begin
set filtered_data = call sigma_clip data sigma=sig_thres axis=0
set n_files = shape at 0
comment baselines or bs number
set n_pts = shape at 1
set tuple mn_data_clip std_data_clip = tuple list list
for i in range n_pts
... | def _apply_sig_clip(data, e_data, sig_thres=2, ymin=0, ymax=1.2, var='V2', display=False):
filtered_data = sigma_clip(data, sigma=sig_thres, axis=0)
n_files = data.shape[0]
n_pts = data.shape[1] # baselines or bs number
mn_data_clip, std_data_clip = [], []
for i in range(n_pts):
cond = fi... | Python | nomic_cornstack_python_v1 |
function drawable_iterable drawable unpack_stacks=false reverse_stacks=false
begin
comment Check if we are using a THStack
if call is_stack drawable and unpack_stacks
begin
comment Extract histograms from the stack
set result = list call GetHists
comment Reverse if necessary
if reverse_stacks
begin
reverse result
end
r... | def drawable_iterable(drawable, unpack_stacks = False, reverse_stacks = False):
# Check if we are using a THStack
if is_stack(drawable) and unpack_stacks:
# Extract histograms from the stack
result = list(drawable.GetHists())
# Reverse if necessary
if reverse_stacks:
... | Python | nomic_cornstack_python_v1 |
function __init__ self initial_lr log_interval num_batches logdir=none log_weights=false log_grads=false
begin
set timestamp = replace call isoformat string : string .
if not logdir
begin
set logdir = timestamp
end
set logdir = right strip logdir string / + string /
make directories logdir
for py_file in glob glob stri... | def __init__(self, initial_lr, log_interval, num_batches, logdir=None,
log_weights=False, log_grads=False):
self.timestamp = datetime.datetime.now().isoformat().replace(':', '.')
if not logdir:
logdir = self.timestamp
self.logdir = logdir.rstrip('/') + '/'
... | Python | nomic_cornstack_python_v1 |
function combine_databases name *dbs
begin
pass
end function | def combine_databases(name, *dbs):
pass | Python | nomic_cornstack_python_v1 |
function to_message self
begin
if _msg
begin
return _msg
end
if not _type
begin
raise call MidiHubError string Cannot build message if type is not inferrable.
end
return call Message _type keyword _kwargs
end function | def to_message(self):
if self._msg:
return self._msg
if not self._type:
raise MidiHubError('Cannot build message if type is not inferrable.')
return mido.Message(self._type, **self._kwargs) | Python | nomic_cornstack_python_v1 |
function kafka_connect_config self
begin
return get pulumi self string kafka_connect_config
end function | def kafka_connect_config(self) -> Optional['outputs.KafkaKafkaUserConfigKafkaConnectConfig']:
return pulumi.get(self, "kafka_connect_config") | Python | nomic_cornstack_python_v1 |
function disconnect_notify self receiver key
begin
return call disconnect_signal receiver notify key
end function | def disconnect_notify(self, receiver, key):
return self.disconnect_signal(receiver, Notify(key)) | Python | nomic_cornstack_python_v1 |
function playFile self
begin
open
end function | def playFile(self):
PlayInterface(self._score).open() | Python | nomic_cornstack_python_v1 |
function test_circulation_sweep_discovers_work self
begin
comment Create an analytics integration so we can make sure
comment events are tracked.
set tuple integration ignore = call create _db ExternalIntegration goal=ANALYTICS_GOAL protocol=string core.local_analytics_provider
comment We know about an identifier, but ... | def test_circulation_sweep_discovers_work(self):
# Create an analytics integration so we can make sure
# events are tracked.
integration, ignore = create(
self._db, ExternalIntegration,
goal=ExternalIntegration.ANALYTICS_GOAL,
protocol="core.local_analytics_p... | Python | nomic_cornstack_python_v1 |
comment coding=UTF-8
set N = integer input
set S = input
set slot = string
for idx in range 0 length S 1
begin
comment print(slot)
if length slot == 0
begin
set slot = S at idx
end
else
if length slot == 1
begin
set slot = slot + S at idx
if slot at 0 == slot at 1
begin
set slot = string
end
end
else
if S at idx == s... | #coding=UTF-8
N=int(input())
S=input()
slot=''
for idx in range(0,len(S),1):
# print(slot)
if len(slot)==0:
slot=S[idx]
elif len(slot)==1:
slot=slot+S[idx]
if slot[0]==slot[1]:
slot=''
else:
if S[idx]==slot[0]:
slot=slot[1:len(slot... | Python | zaydzuhri_stack_edu_python |
function create self compute_manager
begin
return call _invoke string create dict string compute_manager compute_manager
end function | def create(self,
compute_manager,
):
return self._invoke('create',
{
'compute_manager': compute_manager,
}) | Python | nomic_cornstack_python_v1 |
function _validate_iptables_rules self vms
begin
for vm in vms
begin
set vm_tap_device = call get_hybrid_port_name neutron_port at string id
set filter_rules = call get_rules_for_table string filter
if not any generator expression vm_tap_device in line for line in filter_rules
begin
raise call IptablesNotConfiguredExce... | def _validate_iptables_rules(self, vms):
for vm in vms:
vm_tap_device = iptables_firewall.get_hybrid_port_name(
vm.neutron_port['id'])
filter_rules = self.iptables_manager.get_rules_for_table('filter')
if not any(vm_tap_device in line for line in filter_rules)... | Python | nomic_cornstack_python_v1 |
function model self value default=none
begin
set default = if expression default then default else value
return get _model value default
end function | def model(self, value, default=None):
default = default if default else value
return self._model.get(value, default) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import roslib
call load_manifest string optical_ardrone
import rospy
import cv2
from sensor_msgs.msg import Image
from geometry_msgs.msg import Polygon , Point32
from cv_bridge import CvBridge , CvBridgeError
import numpy as np
class ConeTracker
begin
function __init__ self
begin
call init_... | #!/usr/bin/env python
import roslib
roslib.load_manifest('optical_ardrone')
import rospy
import cv2
from sensor_msgs.msg import Image
from geometry_msgs.msg import Polygon, Point32
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
class ConeTracker:
def __init__(self):
rospy.init_node('image_conv... | Python | zaydzuhri_stack_edu_python |
function add_edge self e
begin
comment Adds the vertices (in case they don't already exist)
for v in e
begin
call add_vertex v
end
comment Add the edge
add _tosets at e at 0 e at 1
add _fromsets at e at 1 e at 0
end function | def add_edge(self, e):
# Adds the vertices (in case they don't already exist)
for v in e:
self.add_vertex(v)
# Add the edge
self._tosets[e[0]].add(e[1])
self._fromsets[e[1]].add(e[0]) | Python | nomic_cornstack_python_v1 |
function getFile self pathList
begin
set file = none
try
begin
if length pathList == 1
begin
set file = children at pathList at 0
end
else
begin
set file = call getFile pathList at slice 1 : :
end
end
except KeyError
begin
pass
end
return file
end function | def getFile(self, pathList):
file = None
try:
if len(pathList) == 1:
file = self.children[pathList[0]]
else:
file = self.children[pathList[0]].getFile(pathList[1:])
except KeyError:
pass
return file | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment Reverse a string
set name = string Samarendra Mohapatra
set rev_string = name at slice : : - 1
print rev_string | #!/usr/bin/python
#Reverse a string
name = "Samarendra Mohapatra"
rev_string = name[::-1]
print (rev_string)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import argparse
import json
from logicmonitor_core.HostList import HostList
function main
begin
set parser = call ArgumentParser
call add_argument string -c string --company help=string LogicMonitor account required=true
call add_argument string -u string --user help=string LogicMonitor user na... | #!/usr/bin/python
import argparse
import json
from logicmonitor_core.HostList import HostList
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--company",
help="LogicMonitor account",
required=True)
parser.add_argument("-u", "--user... | Python | zaydzuhri_stack_edu_python |
from io import BytesIO
from multiprocessing.pool import Pool
from bs4 import BeautifulSoup
import os
from tqdm import tqdm
from utils import download_from_url
import tarfile
set BOOKS_DOWNLOAD_URL = string http://www.nb.no/sbfil/xml_boker_idf/xml_idf_boker_gz.tar
set BOOKS_ARCHIVE = string xml_idf_boker_gz.tar
function... | from io import BytesIO
from multiprocessing.pool import Pool
from bs4 import BeautifulSoup
import os
from tqdm import tqdm
from utils import download_from_url
import tarfile
BOOKS_DOWNLOAD_URL = "http://www.nb.no/sbfil/xml_boker_idf/xml_idf_boker_gz.tar"
BOOKS_ARCHIVE = "xml_idf_boker_gz.tar"
def _maybe_download(inp... | Python | zaydzuhri_stack_edu_python |
function test_detector_person_example
begin
call perform_capsule_tests call Path string vcap string examples string detector_person_example ALL_IMAGE_PATHS
end function | def test_detector_person_example():
perform_capsule_tests(
Path("vcap", "examples", "detector_person_example"),
ALL_IMAGE_PATHS) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.