code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment !/usr/bin/env python2
import psycopg2
set PopularTitle = string What are the most popular three articles of all time?
set PopularQuery = string SELECT title, count(*) as num FROM articles, log WHERE articles.slug = substring(log.path, 10) GROUP BY title ORDER BY num DESC LIMIT 3;
set MostTitle = string Who are ... | #!/usr/bin/env python2
import psycopg2
PopularTitle = 'What are the most popular three articles of all time?'
PopularQuery = """
SELECT title, count(*) as num FROM articles, log
WHERE articles.slug = substring(log.path, 10)
GROUP BY title ORDER BY num DESC LIMIT 3;
"""
MostTitle = 'Who are the most popula... | Python | zaydzuhri_stack_edu_python |
comment !/usr/local/python/bin/python
comment File: METplus_conf_util.py
comment Author: D. Adriaansen
comment Date: 01 Jun 2018
comment Purpose: Distill down all of the configuration options from conf files in the METplus repository,
comment remove duplicates, and check against an existing file to see if there are new... | #!/usr/local/python/bin/python
#
# File: METplus_conf_util.py
#
# Author: D. Adriaansen
#
# Date: 01 Jun 2018
#
# Purpose: Distill down all of the configuration options from conf files in the METplus repository,
# remove duplicates, and check against an existing file to see if there are new/removed conf
# ... | Python | zaydzuhri_stack_edu_python |
import numpy
import matplotlib
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.colors as mc
import matplotlib.mlab as mlab
from matplotlib.ticker import NullFormatter
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
import matplotlib.path as mpath
imp... | import numpy
import matplotlib
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.colors as mc
import matplotlib.mlab as mlab
from matplotlib.ticker import NullFormatter
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
import matplotlib.path as mpath
imp... | Python | zaydzuhri_stack_edu_python |
import unittest
from window import minWindow
class TestSum extends TestCase
begin
function testIfSmallest self
begin
call assertEquals call minWindow string ADOBECODEBANC string ABC string BANC
end function
function testIfNotSmallest self
begin
assert false call minWindow string ADOBECODEBANC string ABC == string ADOBE... | import unittest
from window import minWindow
class TestSum(unittest.TestCase):
def testIfSmallest(self):
self.assertEquals(minWindow("ADOBECODEBANC","ABC"), "BANC")
def testIfNotSmallest(self):
self.assertFalse(minWindow("ADOBECODEBANC","ABC") == "ADOBEC")
def testIfSmallestSame(self)... | Python | zaydzuhri_stack_edu_python |
function rename_duplicates_across_vol count ggg1 ggg2 vol1=string 25 vol2=string 50 verbose=true
begin
set c2 = list
for tuple k v in items c1
begin
if v == 0
begin
append c2 k
end
end
if verbose
begin
print format string Duplicated galnames between m{:} and m{:}: vol1 vol2
print c2
end
if length c2 > 0
begin
set over... | def rename_duplicates_across_vol(count, ggg1, ggg2, vol1='25', vol2='50', verbose=True):
c2 = []
for k,v in c1.items():
if v == 0:
c2.append(k)
if verbose:
print("Duplicated galnames between m{:} and m{:}: ".format(vol1, vol2))
print(c2)
if len(c2) > 0:
ove... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment ================================================
comment 版本: V1.0.0
comment 作者: jlchen
comment 时间: 20180211
comment 描述: 问董秘_上交所数据爬取
comment 内容:问董秘上交所数据爬取
comment ================================================
import scrapy
from winspider.items import WinspiderItem
import hashlib
... | # -*- coding: utf-8 -*-
# ================================================
# 版本: V1.0.0
# 作者: jlchen
# 时间: 20180211
# 描述: 问董秘_上交所数据爬取
# 内容:问董秘上交所数据爬取
# ================================================
import scrapy
from winspider.items import WinspiderItem
import hashlib
from datetime import datetime
import re
from win... | Python | zaydzuhri_stack_edu_python |
function serialize self
begin
return dict string id id ; string randomNumber randomNumber
end function | def serialize(self):
return {
'id' : self.id,
'randomNumber': self.randomNumber
} | Python | nomic_cornstack_python_v1 |
for i in array
begin
print i end=string
end
print
set modified = list map lambda x -> x ^ 3 array
print modified
set filtered = list filter lambda x -> x < 30 modified
print filtered | for i in array:
print(i,end =' ' )
print()
modified = list(map(lambda x: x**3, array))
print(modified)
filtered = list(filter( lambda x: x < 30,modified))
print(filtered) | Python | zaydzuhri_stack_edu_python |
comment !python
import os
import sys
import argparse
set parser = call ArgumentParser description=string Predicts identifiers.
call add_argument string expr type=str default=none nargs=string ? help=string An expression for which to predict the identifier.
call add_argument string -t string --train dest=string train ac... | #!python
import os
import sys
import argparse
parser = argparse.ArgumentParser(description="Predicts identifiers.")
parser.add_argument("expr", type=str, default=None, nargs="?",
help="An expression for which to predict the identifier.")
parser.add_argument("-t", "--train", dest="train", action="s... | Python | zaydzuhri_stack_edu_python |
function filter_test_messages s
begin
set prefix = string ControlFlowOpsTest:
return list comprehension l at slice length prefix : : for l in split s string if starts with l prefix
end function | def filter_test_messages(s):
prefix = "ControlFlowOpsTest: "
return [l[len(prefix):] for l in s.split("\n") if l.startswith(prefix)] | Python | nomic_cornstack_python_v1 |
import numpy as np
from scipy.interpolate import interp1d
from datetime import datetime
import pickle
from finite_difference import *
comment make this 2 powers above nt
set T = 5000000.0
comment was 1e5
set Nt = integer 10000.0
set Nx = 100
set nframes = 200
function calc_rmse y1 y2 relative=false
begin
string presume... | import numpy as np
from scipy.interpolate import interp1d
from datetime import datetime
import pickle
from finite_difference import *
T=5e6 # make this 2 powers above nt
Nt = int(1e4) # was 1e5
Nx=100
nframes = 200
def calc_rmse(y1,y2, relative=False):
'''
presume y is longer
'''
x1 = np.linspace(0,1,... | Python | zaydzuhri_stack_edu_python |
function get_classification self image
begin
comment Prepare image for insertion to the model (which is based on MobileNet):
set image_resized = call resize image tuple 224 224 interpolation=INTER_LINEAR
set image_resized = call normalize image_resized none alpha=0 beta=1 norm_type=NORM_MINMAX dtype=CV_32F
set image_re... | def get_classification(self, image):
# Prepare image for insertion to the model (which is based on MobileNet):
image_resized = cv2.resize(image, (224, 224), interpolation=cv2.INTER_LINEAR)
image_resized = cv2.normalize(image_resized, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV... | Python | nomic_cornstack_python_v1 |
function get_cartographer_data self object
begin
set data = dict string ancestors list
set result = call arrangement_map_component_by_uri object at string uri
if result
begin
set resp = json get cartographer_client string { result at string ref } objects_before/
set data at string order = get resp string count 0
for a... | def get_cartographer_data(self, object):
data = {"ancestors": []}
result = self.arrangement_map_component_by_uri(object["uri"])
if result:
resp = self.cartographer_client.get(f"{result['ref']}objects_before/").json()
data["order"] = resp.get("count", 0)
for a ... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment ## Finding Your Way In The City
comment In this notebook you'll combine the work of previous exercises to calculate a
comment minimal series of waypoints in order to get from a start location to a goal
comment location.
comment You'll reuse and modify your algorithms from:
comment - A*
com... | # coding: utf-8
# ## Finding Your Way In The City
#
# In this notebook you'll combine the work of previous exercises to calculate a
# minimal series of waypoints in order to get from a start location to a goal
# location.
#
# You'll reuse and modify your algorithms from:
#
# - A*
# - Configuration Space
# - Collineari... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Oct 31 12:02:15 2018 @author: pooja_ranawade
import os
import pandas as pd
import numpy as np
import seaborn.apionly as sns | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 12:02:15 2018
@author: pooja_ranawade
"""
import os
import pandas as pd
import numpy as np
import seaborn.apionly as sns | Python | zaydzuhri_stack_edu_python |
function step self action
begin
comment Implement your step method here
comment return (observation, reward, done, info)
set _state = _state + action
comment print('Step state:', self._state)
set tuple x y = _state
set reward = - x ^ 2 + y ^ 2 ^ 0.5
set done = absolute x < 0.01 and absolute y < 0.01
set next_observatio... | def step(self, action):
# Implement your step method here
# return (observation, reward, done, info)
self._state = self._state + action
# print('Step state:', self._state)
x, y = self._state
reward = - (x ** 2 + y ** 2) ** 0.5
done = abs(x) < 0.01 and abs(y) < 0.0... | Python | nomic_cornstack_python_v1 |
function test_current_date_as_default self
begin
with call freeze_time string 2018-04-12
begin
set result_date = call get_next_lottery_date
end
assert equal result_date call datetime 2018 4 14 20
assert equal string format time result_date string %a %I%p string Sat 08PM
end function | def test_current_date_as_default(self):
with freeze_time('2018-04-12'):
result_date = get_next_lottery_date()
self.assertEqual(result_date, datetime(2018, 4, 14, 20))
self.assertEqual(result_date.strftime('%a %I%p'), 'Sat 08PM') | Python | nomic_cornstack_python_v1 |
string Created on Dec 23, 2013 @author: pandazen
import mis_compare
set ans = true
while ans
begin
print string 1. Compare form fmb vs fmx 2. Compare param report 3. Compare report 4. Compare file vs database 5. Compare all Press enter to quit
set ans = input string What would you like to do now?
if ans == string 1
beg... | '''
Created on Dec 23, 2013
@author: pandazen
'''
import mis_compare
ans = True
while ans:
print("""
1. Compare form fmb vs fmx
2. Compare param report
3. Compare report
4. Compare file vs database
5. Compare all
Press enter to quit
""")
ans=input("What would... | Python | zaydzuhri_stack_edu_python |
class Node
begin
function __init__ self data=none
begin
set data = data
set next = none
end function
end class
class MyLinkedList
begin
function __init__ self
begin
set head = call Node
set tail = head
set size = 0
end function
function enqueue self data
begin
set size = size + 1
set next = call Node data
set tail = ne... | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class MyLinkedList:
def __init__(self):
self.head = Node()
self.tail = self.head
self.size=0
def enqueue(self, data):
self.size += 1
self.tail.next = Node(data)
sel... | Python | zaydzuhri_stack_edu_python |
for i in range 0 n - 2
begin
for j in range i + 1 n - 1
begin
set left = j
set right = n
while right - left > 1
begin
set mid = left + right // 2
if l at i + l at j > l at mid and l at i + l at mid > l at j and l at mid + l at j > l at i
begin
set left = mid
end
else
begin
set right = mid
end
end
comment print(i,j,left... | for i in range(0,n-2):
for j in range(i+1,n-1):
left = j
right = n
while right-left>1:
mid = (left + right)//2
if l[i]+l[j]>l[mid] and l[i]+l[mid]>l[j] and l[mid]+l[j]>l[i]:
left = mid
else:
right = mid
#print(i,j,left)
ans+=(left-j)
print(ans) | Python | zaydzuhri_stack_edu_python |
function getTag self
begin
call pump
for tuple tag key in items CLASSIFICATION_CONTROLS
begin
if call get_pressed at key
begin
return tag
end
end
end function | def getTag(self):
pygame.event.pump()
for tag, key in CLASSIFICATION_CONTROLS.items():
if pygame.key.get_pressed()[key]:
return tag | Python | nomic_cornstack_python_v1 |
function Get self api_config_ref
begin
set req = call ApigatewayProjectsLocationsApisConfigsGetRequest name=call RelativeName
return get projects_locations_apis_configs req
end function | def Get(self, api_config_ref):
req = self.messages.ApigatewayProjectsLocationsApisConfigsGetRequest(
name=api_config_ref.RelativeName())
return self.client.projects_locations_apis_configs.Get(req) | Python | nomic_cornstack_python_v1 |
function any self
begin
for v in values sects
begin
if any v
begin
return true
end
end
if call is_full
begin
return false
end
else
begin
return any defval
end
end function | def any(self):
for v in self.sects.values():
if np.any(v):
return True
if self.is_full():
return False
else:
return np.any(self.defval) | Python | nomic_cornstack_python_v1 |
function get_middle word
begin
try
begin
if length word % 2 == 0
begin
return word at length word // 2 - 1 + word at length word // 2
end
else
begin
return word at length word // 2
end
end
except IndexError
begin
return string
end
end function | def get_middle(word):
try:
if len(word) % 2 == 0:
return word[len(word)//2 - 1] + word[len(word)//2]
else:
return word[len(word)//2]
except IndexError:
return ''
| Python | zaydzuhri_stack_edu_python |
from matplotlib.image import imread
from matplotlib import pyplot as plt , cm
set chromatic = list string C string C# string D string D# string E string F string F# string G string G# string A string A# string B
set key = string A
set blow_bottom = true
set keyind = index chromatic key
set scale = list
append scale ch... | from matplotlib.image import imread
from matplotlib import pyplot as plt,cm
chromatic=['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
key='A'
blow_bottom=True
keyind=chromatic.index(key)
scale=[]
scale.append(chromatic[keyind%12])
scale.append(chromatic[(keyind+2)%12])
scale.append(chromatic[(keyind+4)%12])
s... | Python | zaydzuhri_stack_edu_python |
function isEnabledAdd self div i j word wLen
begin
if div == 0
begin
if any mask at tuple slice i : i + wLen : j == false
begin
return 7
end
end
if div == 1
begin
if any mask at tuple i slice j : j + wLen : == false
begin
return 7
end
end
return call isEnabledAdd div i j word wLen
end function | def isEnabledAdd(self, div, i, j, word, wLen):
if div == 0:
if np.any(self.mask[i:i+wLen, j] == False):
return 7
if div == 1:
if np.any(self.mask[i, j:j+wLen] == False):
return 7
return super().isEnabledAdd(div, i, j, word, wLen) | Python | nomic_cornstack_python_v1 |
function clean_username self username
begin
return username
end function | def clean_username(self, username):
return username | Python | nomic_cornstack_python_v1 |
function start_interface
begin
set last_ip = none
while true
begin
sleep 5
set current_ips = split call get_local_ip
comment check if a network address was found
if length current_ips == 0
begin
set communication = call instance
call lost_connection
continue
end
else
if length current_ips == 1
begin
if not current_ips ... | def start_interface():
last_ip = None
while True:
time.sleep(5)
current_ips = get_local_ip().split()
# check if a network address was found
if len(current_ips) == 0:
communication = interaction.Communication.instance()
communication.lost_connection()
... | Python | nomic_cornstack_python_v1 |
comment Make sure testwheel is installed before running tests
comment Either build the wheel and install it, or run "pip install ." from the root of this project
import unittest
from testwheel import test_module
class TestMethods extends TestCase
begin
function test_fib self
begin
set fib_seq = list comprehension call ... | # Make sure testwheel is installed before running tests
# Either build the wheel and install it, or run "pip install ." from the root of this project
import unittest
from testwheel import test_module
class TestMethods(unittest.TestCase):
def test_fib(self):
fib_seq = [test_module.fib(i) for i in range(1, ... | Python | zaydzuhri_stack_edu_python |
import csv
import random
import numpy as np
import torch
comment utils
function read_in_csv data_fname
begin
comment read in data such that each row is a list of dicts
with open data_fname string r as f
begin
set reader = dict reader f
set headers = fieldnames
comment list of dicts (one per training item)
set d = list ... | import csv
import random
import numpy as np
import torch
# utils
def read_in_csv(data_fname):
# read in data such that each row is a list of dicts
with open(data_fname, 'r') as f:
reader = csv.DictReader(f)
headers = reader.fieldnames
d = [] # list of dicts (one per training item)
... | Python | zaydzuhri_stack_edu_python |
for i in range length data_xishu
begin
append data_xishu_new integer data_xishu at i * integer data_zhishu at i
append data_zhishu_new integer data_zhishu at i - 1
end
comment print(data_xishu_new)
comment print(data_zhishu_new)
for i in range length data_xishu_new
begin
set data at 2 * i = data_xishu_new at i
set data... | for i in range(len(data_xishu)):
data_xishu_new.append(int(data_xishu[i]) * int(data_zhishu[i]))
data_zhishu_new.append(int(data_zhishu[i]) - 1)
# print(data_xishu_new)
# print(data_zhishu_new)
for i in range(len(data_xishu_new)):
data[2 * i] = data_xishu_new[i]
data[2 * i + 1] = data_zhishu_new[i]
# pr... | Python | zaydzuhri_stack_edu_python |
import csv
with open string data\data1\employee_birthday.csv mode=string r as csv_file
begin
set csv_reader = dict reader csv_file delimiter=string ,
set line_count = 0
for row in csv_reader
begin
if line_count == 0
begin
print string Column names are { join string , row }
end
print string { row at string name } works ... | import csv
with open('data\data1\employee_birthday.csv', mode="r") as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=",")
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
print(
f'\t{row["name"]} works ... | Python | zaydzuhri_stack_edu_python |
string py_42577.py range(start int, end int, inc int) str(int) > convert to String 1. input genres Arr append or add (idx, value) 2. sorting and input : a < nowV ? insert : next 3. result calcul 3.1 sum all play v 3.2 answer add v (Answer) arr[10000 *10000] # is maiximum table arr IDX_GEN = 10000; gen_Cnt = 0;
function... | '''
py_42577.py
range(start int, end int, inc int)
str(int) > convert to String
1. input genres Arr append or add (idx, value)
2. sorting and input : a < nowV ? insert : next
3. result calcul
3.1 sum all play v
3.2 answer add v (Answer)
arr[10000 *10000] # is maiximum table
arr
IDX_GE... | Python | zaydzuhri_stack_edu_python |
function next_source self
begin
if not input_files
begin
call init_sources
end
try
begin
set current_file = next
set result = call get_source
end
except StopIteration
begin
set current_file = none
set result = none
end
return result
end function | def next_source(self):
if not self.input_files:
self.init_sources()
try:
self.current_file = self.input_files.next()
result = self.get_source()
except StopIteration:
self.current_file = None
result = None
return result | Python | nomic_cornstack_python_v1 |
function is_volume_muted self
begin
return is_volume_muted
end function | def is_volume_muted(self):
return self.__zone.is_volume_muted | Python | nomic_cornstack_python_v1 |
function check_length_great_circle cont lmin=none lmax=none
begin
set invalid = lambda val -> val is none or val < 0
set cmin = if expression call invalid lmin then true else call length_great_circle >= lmin
set cmax = if expression call invalid lmax then true else call length_great_circle <= lmax
return cmin and cmax
... | def check_length_great_circle(cont, lmin=None, lmax=None):
invalid = lambda val: (val is None) or (val < 0)
cmin = True if invalid(lmin) else (cont.length_great_circle() >= lmin)
cmax = True if invalid(lmax) else (cont.length_great_circle() <= lmax)
return cmin and cmax | Python | nomic_cornstack_python_v1 |
comment Group members : Myungjin Lee, Krishna Akhi Maddalil, Yash Shahapurkar
import math
import copy
class Table
begin
function __init__ self inp depth label parent split att
begin
set label = label
set tabl = inp
set d = depth
set parent = parent
set split = split
set att = att
end function
end class
function DT tabl... | # Group members : Myungjin Lee, Krishna Akhi Maddalil, Yash Shahapurkar
import math
import copy
class Table:
def __init__(self,inp,depth,label,parent,split,att):
self.label=label
self.tabl=inp
self.d=depth
self.parent = parent
self.split = split
self.att = a... | Python | zaydzuhri_stack_edu_python |
comment 수들의 조합
function DFS L s
begin
global cnt
if L == k
begin
if sum res % m == 0
begin
set cnt = cnt + 1
end
end
else
begin
for i in range s n
begin
set res at L = a at i
call DFS L + 1 i + 1
end
end
end function
if __name__ == string __main__
begin
set tuple n k = map int split input
set res = list 0 * k
set a = l... | # 수들의 조합
def DFS(L, s):
global cnt
if L == k:
if sum(res) % m == 0:
cnt += 1
else:
for i in range(s, n):
res[L] = a[i]
DFS(L + 1, i + 1)
if __name__=="__main__":
n, k = map(int, input().split())
res = [0] * k
a = list(map(int, input().split(... | Python | zaydzuhri_stack_edu_python |
function _read_sphr self grh
begin
set sphr = read fid grh at string record_size - itemsize
set sphr = ordered dictionary generator expression split replace item string string string = for item in split decode sphr string utf-8 string at slice : - 1 :
end function | def _read_sphr(self, grh):
sphr = self.fid.read(grh["record_size"] - grh.itemsize)
self.sphr = OrderedDict(
item.replace(" ", "").split("=")
for item in sphr.decode("utf-8").split("\n")[:-1]) | Python | nomic_cornstack_python_v1 |
function getOperandReferences self index
begin
Ellipsis
end function | def getOperandReferences(self, index: int) -> List[ghidra.program.model.symbol.Reference]:
... | Python | nomic_cornstack_python_v1 |
function CreateResources self manifests region
begin
set resource_dict = call ParseDeployConfig messages manifests region
set msg_template = string Created Cloud Deploy resource: {}.
comment Create delivery pipeline first.
comment In case user has both types of pipeline definition in the same
comment config file.
set p... | def CreateResources(self, manifests, region):
resource_dict = manifest_util.ParseDeployConfig(self.messages, manifests,
region)
msg_template = 'Created Cloud Deploy resource: {}.'
# Create delivery pipeline first.
# In case user has both types of pipel... | Python | nomic_cornstack_python_v1 |
function get_album_name g aid
begin
set album = call get_connections id=aid connection_name=string
return album at string name
end function | def get_album_name(g, aid):
album = g.get_connections(id=aid, connection_name='')
return album['name'] | Python | nomic_cornstack_python_v1 |
comment verificar se algum dos é menor ou igual a zero
if l1 <= 0 or l2 <= 0 or l3 <= 0
begin
print string Não são dimensões de um triângulo
call quit
end
comment verificar se realmente é um triângulo
if l1 >= l2 + l3 or l2 >= l1 + l3 or l3 >= l2 + l1
begin
print string Não são dimensões de um triângulo
call quit
end
i... | # verificar se algum dos é menor ou igual a zero
if l1<=0 or l2<=0 or l3<=0:
print("Não são dimensões de um triângulo")
quit()
# verificar se realmente é um triângulo
if l1>=l2+l3 or l2>=l1+l3 or l3>=l2+l1:
print("Não são dimensões de um triângulo")
quit()
if l1==l2 and l2==l3:
print("Equilatero") | Python | zaydzuhri_stack_edu_python |
class InvalidUsageError extends Exception
begin
set status_code = 404
function __init__ self message status_code=none payload=none
begin
call __init__ self
set message = message
if status_code is not none
begin
set status_code = status_code
end
set payload = payload
end function
function to_dict self
begin
set error_in... | class InvalidUsageError(Exception):
status_code = 404
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self)... | Python | zaydzuhri_stack_edu_python |
comment Set the path
import os , sys
append path absolute path path join path directory name path __file__ string ..
from flask.ext.script import Manager , Server
from BookSwap import app
string This script is used for locally modifying the database. Say you want to add some users to the database, you can run 'python m... | # Set the path
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from flask.ext.script import Manager, Server
from BookSwap import app
'''
This script is used for locally modifying the database. Say you want to add
some users to the database, you can run 'python manage.py ... | Python | zaydzuhri_stack_edu_python |
function unshare_job self job users context=none
begin
return call call_method string UserAndJobState.unshare_job list job users _service_ver context
end function | def unshare_job(self, job, users, context=None):
return self._client.call_method(
'UserAndJobState.unshare_job',
[job, users], self._service_ver, context) | Python | nomic_cornstack_python_v1 |
import sys
while true
begin
set tuple H W = list comprehension integer i for i in split read line stdin
if H == W == 0
begin
break
end
set line = string #. * integer W / 2 + 1
for i in range H
begin
if i % 2
begin
print line at slice 1 : W + 1 :
end
else
begin
print line at slice : W :
end
end
print string
end | import sys
while True:
(H, W) = [int(i) for i in sys.stdin.readline().split()]
if H == W == 0:
break
line = "#." * int(W / 2 + 1)
for i in range(H):
if i % 2:
print(line[1:W+1])
else:
print(line[:W])
print("") | Python | zaydzuhri_stack_edu_python |
string Objects related to the musical building blocks Includes helper functions for easy testing.
import pretty_midi
from music_module.constants import *
import math
import random as rm
function export_to_midi instrument tempo=120.0 pm=none name=string test.mid
begin
set name = string generated_midi/ + name
if pm == no... | """
Objects related to the musical building blocks
Includes helper functions for easy testing.
"""
import pretty_midi
from music_module.constants import *
import math
import random as rm
def export_to_midi(instrument, tempo=120.0, pm=None, name="test.mid"):
name = "generated_midi/"+name
if pm == None:
... | Python | zaydzuhri_stack_edu_python |
function _run_split_on_punc self text
begin
set chars = list text
set i = 0
set output = list
set start_new_word = true
while i < length chars
begin
set char = chars at i
if call is_punctuation char
begin
append output list char
set start_new_word = true
end
else
begin
if start_new_word
begin
append output list
end
se... | def _run_split_on_punc(self, text):
chars = list(text)
i = 0
output = []
start_new_word = True
while i < len(chars):
char = chars[i]
if self.char_type.is_punctuation(char):
output.append([char])
start_new_word = True
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment tabliczka_mnozenia.py
function liczby2 a=10 b=100
begin
for i in range 1 10
begin
for j in range 0 10
begin
if i != j
begin
print format string {}{} i j end=string
set ile = ile + 1
end
end
print
end
end function
function liczby3 a=100 b=1000
begin
for ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tabliczka_mnozenia.py
#
def liczby2(a = 10, b = 100):
for i in range(1, 10):
for j in range(0,10):
if i != j:
print("{}{}".format(i, j), end="")
ile += 1
print()
def liczby3(a= 100, b = 1000):
for li... | Python | zaydzuhri_stack_edu_python |
function weed_out_short_notes pairs **kwargs
begin
set duration_threshold = get kwargs string duration_threshold 0.25
return list comprehension tuple n d for tuple n d in pairs if d > duration_threshold
end function | def weed_out_short_notes(pairs, **kwargs):
duration_threshold = kwargs.get('duration_threshold', 0.25)
return [(n, d) for (n, d) in pairs if d > duration_threshold] | Python | nomic_cornstack_python_v1 |
function edge_detection
begin
set original_image_edge = call imread string input_image/wheels.jpg 0
comment Sobel edge detection
set edge_sobel_x = call Sobel original_image_edge - 1 1 0 ksize=3
set edge_sobel_y = call Sobel original_image_edge - 1 0 1 ksize=3
set edge_sobel_combined = call addWeighted edge_sobel_x 0.5... | def edge_detection():
original_image_edge = cv2.imread('input_image/wheels.jpg', 0)
#Sobel edge detection
edge_sobel_x = cv2.Sobel(original_image_edge, -1, 1, 0, ksize=3)
edge_sobel_y = cv2.Sobel(original_image_edge, -1, 0, 1, ksize=3)
edge_sobel_combined = cv2.addWeighted(edge_sobel_x, 0.5, edge... | Python | nomic_cornstack_python_v1 |
function rpt_summary self
begin
set worksheet = call add_worksheet string Summary
if scans_to_reports
begin
call showMessage string Generating 'Summary' Tab
end
call set_column string A:A 10
call set_column string B:B 30
call set_column string C:C 20
call set_column string D:D 50
call set_column string E:E 50
call set_... | def rpt_summary(self):
worksheet = self.workbook.add_worksheet('Summary')
if self.scans_to_reports:
self.scans_to_reports.statusBar().showMessage("Generating 'Summary' Tab")
worksheet.set_column('A:A', 10)
worksheet.set_column('B:B', 30)
worksheet.set_column('C:... | Python | nomic_cornstack_python_v1 |
function deactivate_mouth_events self
begin
call emit call Message string enclosure.mouth.events.deactivate context=dict string destination list string enclosure
end function | def deactivate_mouth_events(self):
self.bus.emit(Message('enclosure.mouth.events.deactivate',
context={"destination": ["enclosure"]})) | Python | nomic_cornstack_python_v1 |
function __init__ self *args **kwargs
begin
call __init__ *args keyword kwargs
set placeholders = dict string company_name string Company Name ; string full_name string Full Name ; string email string Email Address ; string phone string ; string free_consultation_request none ; string project_name string Project Name ... | def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
placeholders = {
'company_name': 'Company Name',
'full_name': 'Full Name',
'email': 'Email Address',
'phone': '',
'free_consultation_request': None,
'project_nam... | Python | nomic_cornstack_python_v1 |
function parse_args argv
begin
set formatter_class = RawDescriptionHelpFormatter
set parser = call ArgumentParser description=string Run torrent-knowledge cli formatter_class=formatter_class
call add_argument string -i string --input_file type=call FileType string r required=true help=string CSV with torrents in format... | def parse_args(argv):
formatter_class = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(description="Run torrent-knowledge cli",
formatter_class=formatter_class)
parser.add_argument("-i", "--input_file",
type=argparse.FileTy... | Python | nomic_cornstack_python_v1 |
import unittest
import data2
from tasks import task2
class Data2Tests extends TestCase
begin
function test_exercise2_for_alice self
begin
set expectation = list a_team c_team
assert equal expectation call exercise2 alice people
end function
function test_exercise1_for_peggy self
begin
set expectation = list b_team
asse... | import unittest
import data2
from tasks import task2
class Data2Tests(unittest.TestCase):
def test_exercise2_for_alice(self):
expectation = [data2.a_team, data2.c_team]
self.assertEqual(expectation, task2.exercise2(data2.alice, data2.people))
def test_exercise1_for_peggy(self):
expe... | Python | zaydzuhri_stack_edu_python |
string 1) Faça um programa que leia a idade de uma pessoa expressa em dias e mostre-a expressa em anos, meses e dias.
comment !/usr/bin/env python
comment -*- coding: latin1 -*-
set idade_dias = integer input string Informe sua idade em dias:
set idade_anos = idade_dias / 365
set idade_dias = idade_dias % 365
set idade... | """
1) Faça um programa que leia a idade de uma pessoa expressa em dias e mostre-a expressa em anos, meses e dias.
"""
#!/usr/bin/env python
# -*- coding: latin1 -*-
idade_dias = int(input('Informe sua idade em dias: '))
idade_anos = idade_dias / 365
idade_dias = idade_dias % 365
idade_meses = idade_dias / 30... | Python | zaydzuhri_stack_edu_python |
from socket import *
comment Setting up server address details
set portNum = 42069
set serverName = call gethostbyname call gethostname
set addr = tuple serverName portNum
comment Communication standards
set bufferSize = 1024
set disconnectMsg = string SHEESH!
set format = string utf-8
comment Create socket
set clientS... | from socket import *
# Setting up server address details
portNum = 42069
serverName = gethostbyname(gethostname())
addr = (serverName, portNum)
# Communication standards
bufferSize = 1024
disconnectMsg = "SHEESH!"
format = 'utf-8'
# Create socket
clientSocket = socket(AF_INET, SOCK_STREAM)
# Connect to address via s... | Python | zaydzuhri_stack_edu_python |
function save_fig self name=none extension=string pdf **savefig_kwargs
begin
return call save_fig name root_dir=directory extension=extension default_overwrite=default_overwrite notebook_mode=false keyword savefig_kwargs
end function | def save_fig(self, name=None, extension='pdf', **savefig_kwargs):
return save_fig(name, root_dir=self.directory, extension=extension,
default_overwrite=self.default_overwrite, notebook_mode=False,
**savefig_kwargs) | Python | nomic_cornstack_python_v1 |
function list_images self
begin
set result = object
set images = list
for value in get result string data list
begin
set extra = dict string architecture get value string architecture ; string disks get value string disks ; string billable_type get value string billable_type ; string pcpus get value string pcpus ; str... | def list_images(self):
result = self.connection.request('/image/server/').object
images = []
for value in result.get('data', []):
extra = {'architecture': value.get('architecture'),
'disks': value.get('disks'),
'billable_type': value.ge... | Python | nomic_cornstack_python_v1 |
comment insert methon in python
from array import *
set a = array string i list
set b = integer input string Enter number :
set c = 0
while c < b
begin
append a integer input string Enter R :
set c = c + 1
end
print a | #insert methon in python
from array import *
a= array('i',[])
b=int(input("Enter number :"))
c=0
while c<b:
a.append(int(input("Enter R :")))
c+=1
print(a)
| Python | zaydzuhri_stack_edu_python |
function call_method self method
begin
if call _method_is_async_generator method
begin
set result = yield call method
end
else
begin
set result = yield call submit method
end
return result
end function | def call_method(self, method):
if self._method_is_async_generator(method):
result = yield method()
else:
result = yield self.executor.submit(method)
return result | Python | nomic_cornstack_python_v1 |
function stream_index self bucket index startkey endkey=none return_terms=none max_results=none continuation=none timeout=none term_regex=none
begin
string Queries a secondary index, streaming matching keys through an iterator. The caller should explicitly close the returned iterator, either using :func:`contextlib.clo... | def stream_index(self, bucket, index, startkey, endkey=None,
return_terms=None, max_results=None, continuation=None,
timeout=None, term_regex=None):
"""
Queries a secondary index, streaming matching keys through an
iterator.
The caller should ex... | Python | jtatman_500k |
function _set_state self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=yc_state_openconfig_interfaces__interfaces_interface_subinterfaces_subinterface_ipv6_addresses_address_vrrp_vrrp_group_interface_tracking_state is_container=string cont... | def _set_state(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_interfaces__interfaces_interface_subinterfaces_subinterface_ipv6_addresses_address_vrrp_vrrp_group_interface_tracking_state, is_container='container', yang_name="state", par... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
comment date: 12.12.2017
comment by: keith crowder
comment name: multiples_of_ten.py
comment exercise 7-3
set number = input string Enter a number:
set number = integer number
if number % 10 == 0
begin
print string The number + string number + string is a multiple of ten.
end
else
begin
print ... | #!/usr/bin/python3
#
# date: 12.12.2017
# by: keith crowder
# name: multiples_of_ten.py
#
# exercise 7-3
#
number = input("Enter a number: ")
number = int(number)
#
if number % 10 == 0:
print("\nThe number " + str(number) + " is a multiple of ten.")
else:
print("\nThe number " + str(number) + " is not a multipl... | Python | zaydzuhri_stack_edu_python |
from array import *
set a = array string i list
for i in range 8
begin
set x = integer input string enter =
append a x
end
for i in range length a
begin
for j in range 0 length a - i - 1
begin
if a at j > a at j + 1
begin
set temp = a at j
set a at j = a at j + 1
set a at j + 1 = temp
end
end
print a
end | from array import *
a = array('i',[])
for i in range(8):
x = int(input("enter = "))
a.append(x)
for i in range(len(a)):
for j in range(0,len(a)-i-1):
if a[j] > a[j+1] :
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
print(a) | Python | zaydzuhri_stack_edu_python |
function _count_concordant_pairs preds target
begin
return sum 0
end function | def _count_concordant_pairs(preds: Tensor, target: Tensor) ->Tensor:
return torch.cat([_concordant_element_sum(preds, target, i) for i in range(preds.shape[0])]).sum(0) | Python | nomic_cornstack_python_v1 |
print string ==== CALCULO DO AUMENTO SALARIAL ====
set salario = decimal input string Qual o valor do seu salario?
set salario = 1.15 * salario
print string o valor do seu salario reajustado em 15% eh: salario | print("==== CALCULO DO AUMENTO SALARIAL ====")
salario = float(input("Qual o valor do seu salario?"))
salario = 1.15*salario
print("o valor do seu salario reajustado em 15% eh:", salario) | Python | zaydzuhri_stack_edu_python |
function install_openssh_server self
begin
call apt_install_packages string openssh-server
end function | def install_openssh_server(self):
self.apt_install_packages('openssh-server') | Python | nomic_cornstack_python_v1 |
comment 1. ACDEFGHIKLMNPQRSTVWY
function is_protein seq
begin
set aminoacids = list string A string C string D string E string F string G string H string I string K string L string M string N string P string Q string R string S string T string V string W string Y
return call issubset aminoacids
end function
comment 2.
... | #1. ACDEFGHIKLMNPQRSTVWY
def is_protein(seq):
aminoacids=["A","C","D","E","F","G","H","I","K","L","M","N","P","Q","R","S","T","V","W","Y"]
return set(seq).issubset(aminoacids)
#2.
def longest_line(file_name):
filetoclose=open(file_name,"r")
fil=filetoclose.readlines()
listnumb=[]
for i in f... | Python | zaydzuhri_stack_edu_python |
comment p [people]
function get_name_by_document_number user_input
begin
for doc in documents
begin
if doc at string number == user_input
begin
return doc at string name
end
end
return user_input
end function
comment s [self]
function get_shelf_by_document_number user_input
begin
for tuple key value in items directorie... | # p [people]
def get_name_by_document_number(user_input):
for doc in documents:
if doc["number"] == user_input:
return doc["name"]
return user_input
# s [self]
def get_shelf_by_document_number(user_input):
for key, value in directories.items():
if user_input in value:
... | Python | zaydzuhri_stack_edu_python |
function solve_normal_cg matvec b ridge=none **kwargs
begin
function _matvec x
begin
string Computes A^T A x.
return call _normal_matvec matvec x
end function
if ridge is not none
begin
set _matvec = call _make_ridge_matvec _matvec ridge=ridge
end
set Ab = call _rmatvec matvec b
return call cg _matvec Ab keyword kwargs... | def solve_normal_cg(matvec: Callable,
b: Any,
ridge: Optional[float] = None,
**kwargs) -> Any:
def _matvec(x):
"""Computes A^T A x."""
return _normal_matvec(matvec, x)
if ridge is not None:
_matvec = _make_ridge_matvec(_matvec, ridge=ridge)
... | Python | nomic_cornstack_python_v1 |
function maybe_run_for_org org task_func task_key lock_timeout
begin
set r = call get_redis_connection
set key = call get_lock_key org task_key
if get r key
begin
warning string Skipping task %s for org #%d as it is still running % tuple task_key id
end
else
begin
with lock key timeout=lock_timeout
begin
set state = ca... | def maybe_run_for_org(org, task_func, task_key, lock_timeout):
r = get_redis_connection()
key = TaskState.get_lock_key(org, task_key)
if r.get(key):
logger.warning("Skipping task %s for org #%d as it is still running" % (task_key, org.id))
else:
with r.lock(key, timeout=lock_timeout):
... | Python | nomic_cornstack_python_v1 |
function test_send_notification_with_reports_filled self fake_requests_obj
begin
comment act like it's March 2012
set fake_date = call datetime year=2012 month=3 day=1
call returns fake_date
call call_command string send_second_report_notification list dict
call eq_ length outbox 3
end function | def test_send_notification_with_reports_filled(self, fake_requests_obj):
# act like it's March 2012
fake_date = datetime.datetime(year=2012, month=3, day=1)
(fake_requests_obj.expects_call().returns(fake_date))
management.call_command('send_second_report_notification', [], {})
e... | Python | nomic_cornstack_python_v1 |
function plot_x_y_drift x y
begin
set x = list comprehension if expression i is none then nan else i for i in x
set y = list comprehension if expression i is none then nan else i for i in y
set mask_x = where x == nan
set mask_y = where y == nan
set mx = array x
set mx at mask_x = masked
set my = array y
set my at mask... | def plot_x_y_drift(x, y):
x = [np.nan if i is None else i for i in x]
y = [np.nan if i is None else i for i in y]
mask_x = np.where(x == np.nan)
mask_y = np.where(y == np.nan)
mx = np.ma.array(x)
mx[mask_x] = np.ma.masked
my = np.ma.array(y)
my[mask_y] = np.ma.masked
fig = plt.figure()
fig.suptitle('Beam Cent... | Python | nomic_cornstack_python_v1 |
comment 4.11 (Guess-the-Number Modification) Modify the previous exercise to count the number of guesses the
comment player makes. If the number is 10 or fewer, display "Either you know the secret or you got lucky!" If the
comment player makes more than 10 guesses, display "You should be able to do better!" Why should ... | # 4.11 (Guess-the-Number Modification) Modify the previous exercise to count the number of guesses the
# player makes. If the number is 10 or fewer, display "Either you know the secret or you got lucky!" If the
# player makes more than 10 guesses, display "You should be able to do better!" Why should it take no more
# ... | Python | zaydzuhri_stack_edu_python |
import sys
set check_list = list
set input_str = string [{()}]
set open_list = string [{(
set close_list = string ]})
comment print(len(input_str))
for i in range 0 length input_str
begin
set ind1 = - 1
set ind = - 2
comment print(input_str[i])
if input_str at 0 == string ]
begin
print string unbalanced
exit
end
appen... | import sys
check_list = []
input_str = "[{()}]"
open_list = "[{("
close_list = "]})"
#print(len(input_str))
for i in range(0,len(input_str)):
ind1 = -1
ind = -2
#print(input_str[i])
if(input_str[0] == ']'):
print("unbalanced")
sys.exit()
check_list.append(input_str[i])
... | Python | zaydzuhri_stack_edu_python |
comment The prime factors of 13195 are 5, 7, 13 and 29.
comment What is the largest prime factor of the number 600851475143 ?
import math
function is_prime x
begin
assert is instance x int
assert x > 1
for i in range 2 integer square root x + 1
begin
if x % i == 0
begin
return false
end
end
for else
begin
return true
e... | # The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
import math
def is_prime(x):
assert isinstance(x, int)
assert x > 1
for i in range(2, int(math.sqrt(x)) + 1):
if x%i == 0:
return False
else:
re... | Python | zaydzuhri_stack_edu_python |
function AppendTraceStep self traceStep
begin
set callResult = call _Call string AppendTraceStep traceStep
end function | def AppendTraceStep(self, traceStep):
callResult = self._Call("AppendTraceStep", traceStep) | Python | nomic_cornstack_python_v1 |
function B_overlay_callback self
begin
set B_overlay_state = not B_overlay_state
call update_tracks
end function | def B_overlay_callback(self):
self.B_overlay_state = not self.B_overlay_state
self.update_tracks() | Python | nomic_cornstack_python_v1 |
comment 5 - Write a function that will take a file name fname and a string s as input. It will return whether s occurs
comment inside the file. It's possible that the file is extremely large so it cannot be read into memory in one shot.
function read_in_chunks file_object chunk_size=1024
begin
while true
begin
set data... | #5 - Write a function that will take a file name fname and a string s as input. It will return whether s occurs
#inside the file. It's possible that the file is extremely large so it cannot be read into memory in one shot.
def read_in_chunks(file_object, chunk_size=1024):
while True:
data = file_... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding:UTF-8 -*-
import requests , json
comment 推送钉钉消息
class AutoInfo
begin
function __init__ self
begin
set url = string https://oapi.dingtalk.com/robot/send?access_token=93970e0a1f796c7e839ff289f9d4314bd5600868d6cabd5b8ab6159bb5577f9d
set headers = dict string Content-type str... | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
import requests,json
#推送钉钉消息
class AutoInfo():
def __init__(self):
self.url = 'https://oapi.dingtalk.com/robot/send?access_token=93970e0a1f796c7e839ff289f9d4314bd5600868d6cabd5b8ab6159bb5577f9d'
self.headers = {
'Content-type': 'application/js... | Python | zaydzuhri_stack_edu_python |
if a < 0
begin
set literal print string a is negative number.
end
else
if a > 0
begin
set literal print string a is positive number.
end
else
begin
set literal print string a is a zero.
end | if a<0 :
{
print('a is negative number. ')
}
elif a>0 :
{
print('a is positive number.')
}
else :
{
print('a is a zero.')
}
| Python | zaydzuhri_stack_edu_python |
function train_booster_layer self dmatrix grad hess lr=none
begin
set n_rows = call num_row
call set_base_margin zeros n_rows dtype=string float32
for channel_idx in range n_channel_from_boosting
begin
for first_dim_idx in range first_dim_from_boosting
begin
for second_dim_idx in range second_dim_from_boosting
begin
se... | def train_booster_layer(self, dmatrix, grad, hess, lr=None):
n_rows = dmatrix.num_row()
dmatrix.set_base_margin(
np.zeros(
n_rows,
dtype='float32'
)
)
for channel_idx in range(self.n_channel_from_boosting):
for first_... | Python | nomic_cornstack_python_v1 |
function update_location_centroid point cluster max_distance min_samples
begin
string Updates the centroid of a location cluster with another point Args: point (:obj:`Point`): Point to add to the cluster cluster (:obj:`list` of :obj:`Point`): Location cluster max_distance (float): Max neighbour distance min_samples (in... | def update_location_centroid(point, cluster, max_distance, min_samples):
""" Updates the centroid of a location cluster with another point
Args:
point (:obj:`Point`): Point to add to the cluster
cluster (:obj:`list` of :obj:`Point`): Location cluster
max_distance (float): Max neighbour ... | Python | jtatman_500k |
import copy
from injector import inject
from simplebbs.domain.BulletinBoard.factory import BulletinFactory
from simplebbs.domain.BulletinBoard.factory.BulletinBoardThreadFactory import BulletinBoardThreadFactory
from simplebbs.domain.BulletinBoard.object.BulletinBoardThread import BulletinBoardThread
from simplebbs.inf... | import copy
from injector import inject
from simplebbs.domain.BulletinBoard.factory import BulletinFactory
from simplebbs.domain.BulletinBoard.factory.BulletinBoardThreadFactory import BulletinBoardThreadFactory
from simplebbs.domain.BulletinBoard.object.BulletinBoardThread import BulletinBoardThread
from simplebbs.i... | Python | zaydzuhri_stack_edu_python |
comment Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre:
comment A média de idade do grupo.
comment Qual o nome do homem mais velho.
comment Quantoas mulheres têm menos de 20 anos.
print string Preciso que informe o nome, idade e sexo de quatro pessoas:
set nomes = list
... | # Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre:
# A média de idade do grupo.
# Qual o nome do homem mais velho.
# Quantoas mulheres têm menos de 20 anos.
print('Preciso que informe o nome, idade e sexo de quatro pessoas: ')
nomes = []
idades = []
sexos = []
for c in r... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import geopandas as gpd
import numpy as np
import matplotlib.pyplot as plt
set data = call read_file string ./Datasets/covid_data_by_neighborhood.geojson
import json
from bokeh.models import CDSView , ColorBar , ColumnDataSource , CustomJS , CustomJSFilter , GeoJSONDataSource , HoverTool , LinearCol... | import pandas as pd
import geopandas as gpd
import numpy as np
import matplotlib.pyplot as plt
data = gpd.read_file("./Datasets/covid_data_by_neighborhood.geojson")
import json
from bokeh.models import (CDSView, ColorBar, ColumnDataSource,
CustomJS, CustomJSFilter,
... | Python | zaydzuhri_stack_edu_python |
class Employee
begin
function __init__ self name salary rating
begin
set name = name
set salary = salary
set rating = rating
end function
function DisplayStats self
begin
return name + string : Workers Salary: %d % salary + string + name + string : Workers Rate: %d % rating
end function
end class
set Sarah = call Empl... | class Employee:
def __init__(self,name,salary,rating):
self.name = name
self.salary = salary
self.rating = rating
def DisplayStats(self):
return self.name +': Workers Salary: %d'%self.salary+'\n'+self.name +': Workers Rate: %d'%self.rating
Sarah = Employee("Sarah",100000,9/9)
BoB... | Python | zaydzuhri_stack_edu_python |
function start self
begin
if not _channel
begin
raise call RuntimeError string RabbitMqMessageConsumer: cannot start consuming event without any subscriber defined.
end
set _thread = thread target=_start
start _thread
end function | def start(self) -> NoReturn:
if not self._channel:
raise RuntimeError(
"RabbitMqMessageConsumer: cannot start consuming event without any subscriber defined."
)
self._thread = threading.Thread(target=self._start)
self._thread.start() | Python | nomic_cornstack_python_v1 |
function bind_expression self bindvalue
begin
return call crypt bindvalue call gen_salt string bf 8
end function | def bind_expression(self, bindvalue):
return func.crypt(bindvalue, func.gen_salt('bf', 8)) | Python | nomic_cornstack_python_v1 |
comment created by Sonder on 2020.09.20
comment O(kn) k is the number of digits
function radix_sort li
begin
set max_num = max li
set max_num_str = string max_num
for i in range length max_num_str
begin
set buckets = list comprehension list for _ in range 10
for val in li
begin
set digit = val // 10 ^ i % 10
append bu... | # created by Sonder on 2020.09.20
# O(kn) k is the number of digits
def radix_sort(li):
max_num = max(li)
max_num_str = str(max_num)
for i in range(len(max_num_str)):
buckets = [[] for _ in range(10)]
for val in li:
digit = (val // (10 ** i)) % 10
buckets[digit].appe... | Python | zaydzuhri_stack_edu_python |
class RotateStr
begin
function rotateString self s offset
begin
if s is none and length s == 0
begin
return
end
set offset = offset % length s
reverse self s 0 length s - offset - 1
reverse self s length s - offset length s - 1
reverse self s 0 length s - 1
end function
function reverse self s start end
begin
while sta... | class RotateStr:
def rotateString(self, s, offset):
if s is none and len(s) == 0:
return
offset %= len(s)
self.reverse(s, 0, len(s) - offset -1)
self.reverse(s, len(s) - offset, len(s) - 1)
self.reverse(s, 0, len(s) - 1)
def rev... | Python | zaydzuhri_stack_edu_python |
comment script to determine is a number is odd or even (use single line statement if applies)
function number_odd_even number
begin
if number % 2 == 0
begin
print format string number {} is odd number
end
if number % 2 != 0
begin
print format string number {} is even number
end
end function
call number_odd_even 1
call ... | # script to determine is a number is odd or even (use single line statement if applies)
def number_odd_even(number):
if number % 2 == 0: print("number {} is odd".format(number))
if number % 2 != 0: print(("number {} is even".format(number)))
number_odd_even(1)
number_odd_even(2)
# this function identify if ... | Python | zaydzuhri_stack_edu_python |
function test_class_definition_with_metaclass self
begin
call script string # script.py class C(object, metaclass=type): 'cdoc' pass
compile
set script = call find_code_component name=string script.py
set class_def = call find_code_component name=string C
set var_object = call find_code_component name=string object
set... | def test_class_definition_with_metaclass(self):
self.script("# script.py\n"
"class C(object, metaclass=type):\n"
" 'cdoc'\n"
" pass\n")
self.compile()
script = self.find_code_component(name="script.py")
class_def = self.f... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
set file = string datasets/rocks_vs_mines.csv
import pandas as pd
set data = read csv file header=none prefix=string V
comment print data.head()
comment print data.tail() | # -*- coding: utf-8 -*-
file = 'datasets/rocks_vs_mines.csv'
import pandas as pd
data = pd.read_csv(file,header=None,prefix='V')
#print data.head()
#print data.tail()
| Python | zaydzuhri_stack_edu_python |
class Solution
begin
function singleNumber self nums
begin
if not nums
begin
return
end
set diff = 0
for num in nums
begin
set diff = diff ? num
end
set diff = diff ? ? diff - 1
set ret = list 0 0
for num in nums
begin
if num ? diff == 0
begin
set ret at 0 = ret at 0 ? num
end
else
begin
set ret at 1 = ret at 1 ? num
e... | class Solution:
def singleNumber(self,nums):
if not nums:
return
diff=0
for num in nums:
diff^=num
diff=diff & ~(diff-1)
ret=[0,0]
for num in nums:
if num&diff==0:
ret[0]^=num
else:
ret[1]^=num
return ret
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment encoding: utf-8
string @author: baibing @contact: 243061887(qq) @software: pycharm @file: 4、生产者与消费者.py @time: 7/8/19 4:54 PM @desc:
string 待理解
function productor c
begin
call send none
for i in range 5
begin
print string 生产者产生数据%d % i
set r = call send string i
print string 消费者消费了数据... | #!/usr/bin/env python
# encoding: utf-8
'''
@author: baibing
@contact: 243061887(qq)
@software: pycharm
@file: 4、生产者与消费者.py
@time: 7/8/19 4:54 PM
@desc:
'''
'''
待理解
'''
def productor(c):
c.send(None)
for i in range(5):
print("生产者产生数据%d"%i)
r = c.send(str(i))
print("消费者消费了数据%s"%r)
c... | Python | zaydzuhri_stack_edu_python |
function encode_auth_token userdata
begin
try
begin
set payload = dict string exp call utcnow + time delta days=10 ; string iat call utcnow ; string uid userdata at string uid ; string pwd userdata at string pwd ; string role userdata at string role
return encode jwt payload SECRET_KEY algorithm=string HS256
end
except... | def encode_auth_token(userdata):
try:
payload = {
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=10),
'iat': datetime.datetime.utcnow(),
'uid': userdata['uid'],
'pwd':userdata['pwd'],
'role': userdata['role'... | 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.