code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function select_inputs self address amount
begin
string select UTXOs
set utxos = list
comment starts from negative due to minimal fee
set utxo_sum = call Decimal - 0.01
for tx in sorted call listunspent address=address key=call itemgetter string confirmations
begin
append utxos call TxIn txid=tx at string tx_hash txou... | def select_inputs(self, address: str, amount: int) -> dict:
'''select UTXOs'''
utxos = []
utxo_sum = Decimal(-0.01) # starts from negative due to minimal fee
for tx in sorted(self.listunspent(address=address), key=itemgetter('confirmations')):
utxos.append(
... | Python | jtatman_500k |
function test_nearest_location_adjacent
begin
set locations = list tuple 1 3 tuple 3 5
assert call nearest_location locations 2 == 0
assert call nearest_location locations 3 == 1
end function | def test_nearest_location_adjacent():
locations = [(1, 3), (3, 5)]
assert nearest_location(locations, 2) == 0
assert nearest_location(locations, 3) == 1 | Python | nomic_cornstack_python_v1 |
function state self
begin
return get pulumi self string state
end function | def state(self) -> Optional[str]:
return pulumi.get(self, "state") | Python | nomic_cornstack_python_v1 |
string inPlace = no stable = yes TimeComplexity = O(nlogn) SpaceComplexity =O(n)
function quicksort l
begin
set m = length l
if m == 0 or m == 1
begin
return l
end
set mid = m // 2
set i = 0
set small = list
set large = list
while i < m
begin
if i != mid
begin
if l at i > l at mid
begin
append large l at i
end
else
i... | """
inPlace = no
stable = yes
TimeComplexity = O(nlogn)
SpaceComplexity =O(n)
"""
def quicksort(l):
m=len(l)
if(m==0 or m==1):
return l
mid=m//2
i=0
small=[]
large=[]
while(i<m):
if(i!=mid):
if(l[i]>l[mid]):
large.append(l[i])
elif(l[i]<l[mid]):
small.append(l[i])
else:
if(i<mid):
... | Python | zaydzuhri_stack_edu_python |
async function async_setup_entry hass entry async_add_entities
begin
set account : StarlineAccount = data at DOMAIN at entry_id
set entities = list
for device in values devices
begin
for tuple key value in items SENSOR_TYPES
begin
set sensor = call StarlineSensor account device key *value
if state is not none
begin
ap... | async def async_setup_entry(hass, entry, async_add_entities):
account: StarlineAccount = hass.data[DOMAIN][entry.entry_id]
entities = []
for device in account.api.devices.values():
for key, value in SENSOR_TYPES.items():
sensor = StarlineSensor(account, device, key, *value)
i... | Python | nomic_cornstack_python_v1 |
function strfdelta tdelta fmt=string {D:02}d {H:02}h {M:02}m {S:02}s inputtype=string timedelta
begin
comment noqa
comment Convert tdelta to integer seconds.
if inputtype == string timedelta
begin
set remainder = integer call total_seconds
end
else
if inputtype in list string s string seconds
begin
set remainder = inte... | def strfdelta(tdelta: Union[datetime.timedelta, int, float, str],
fmt='{D:02}d {H:02}h {M:02}m {S:02}s',
inputtype='timedelta'): # noqa
# Convert tdelta to integer seconds.
if inputtype == 'timedelta':
remainder = int(tdelta.total_seconds())
elif inputtype in ['s', 'sec... | Python | nomic_cornstack_python_v1 |
function sendTime self
begin
set timestamp = string format time now string %A, %d. %B %Y %I:%M%p
call send timestamp
end function | def sendTime(self):
timestamp = datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
self.send(timestamp) | Python | nomic_cornstack_python_v1 |
from visual import *
from visual.graph import *
set width = 1024
set height = 768
set title = string bouncing ball
set forward = tuple 0 - 0.3 - 1
set wall = call box pos=call vector - 22 - 2 0 size=call vector 1.5 8 2 color=call vector 0.9 0.7 0.4
set floor = call box pos=call vector - 0 - 6 0 size=call vector 50 0.2 ... | from visual import *
from visual.graph import *
scene.width = 1024
scene.height = 768
scene.title = "bouncing ball"
scene.forward = (0,-.3,-1)
wall=box(pos=vector(-22,-2,0),size=vector(1.5,8,2),color=vector(0.9,0.7,0.4))
floor=box(pos=vector(-0,-6,0),size=vector(50,0.2,4),color=vector(0.6,0.7,0.4))
ball = sph... | Python | zaydzuhri_stack_edu_python |
from torch import nn
from config import config as cfg
import torch
import copy
import transformer_moudles
import torch.nn as nn
from config import config as cfg
from load_data import get_mask
comment transformer
class My_transformer extends Module
begin
function __init__ self
begin
call __init__
comment 复制器
set c = dee... | from torch import nn
from config import config as cfg
import torch
import copy
import transformer_moudles
import torch.nn as nn
from config import config as cfg
from load_data import get_mask
# transformer
class My_transformer(nn.Module):
def __init__(self):
super(My_transformer, self).__init__()
... | Python | zaydzuhri_stack_edu_python |
function _used_reserved_keys self data
begin
return set keys data ? set RESERVED_NAMES
end function | def _used_reserved_keys(self, data):
return set(data.keys()) & set(self.RESERVED_NAMES) | Python | nomic_cornstack_python_v1 |
function to_dict self
begin
set result = dict
for tuple attr _ in call iteritems openapi_types
begin
set value = get attribute self attr
if is instance value list
begin
set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value
end
else
if has attribute value ... | def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
... | Python | nomic_cornstack_python_v1 |
function getzai self nuclide
begin
raise call AbstractClassException ABSTRACT_STR_ERROR
end function | def getzai(self, nuclide: str) -> int:
raise AbstractClassException(ABSTRACT_STR_ERROR) | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[4]:
comment In[118]:
import xml.etree.cElementTree as ET
import time
import codecs
import csv
import re
import sys
call reload sys
call setdefaultencoding string utf-8
comment In[119]:
function byteify input
begin
if is instance input dict
begin
return dictionary comprehension call byte... | # coding: utf-8
# In[4]:
# In[118]:
import xml.etree.cElementTree as ET
import time
import codecs
import csv
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# In[119]:
def byteify(input):
if isinstance(input, dict):
return {byteify(key):byteify(value) for key,value in input.iterite... | Python | zaydzuhri_stack_edu_python |
function toAction key
begin
for item in ACTION_TYPES
begin
if item at 0 == key
begin
return item at 1
end
end
return string None
end function | def toAction(key):
for item in Action.ACTION_TYPES:
if item[0] == key:
return item[1]
return "None" | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
function empty x
begin
set x = x
end function
set img = zeros tuple 400 400 3 uint8
comment Creates a named window with 'color' as title
call namedWindow string color
comment 'B' > track bar name
call createTrackbar string B string color 0 255 empty
comment 'color' > window name
comment '0... | import cv2
import numpy as np
def empty(x):
x=x
img = np.zeros((400,400,3),np.uint8)
cv2.namedWindow('color') # Creates a named window with 'color' as title
cv2.createTrackbar('B','color', 0, 255, empty) # 'B' > track bar name
# 'color' > window name
# '0' > min value
... | Python | zaydzuhri_stack_edu_python |
string Assignment: Checkerboard Write a program that prints a 'checkerboard' pattern to the console. Your program should require no input and produce console output that looks like so: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copy Each star or space represents a square. On a traditional checkerbo... | '''Assignment: Checkerboard
Write a program that prints a 'checkerboard' pattern to the console.
Your program should require no input and produce console output that looks like so:
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
Copy
Each star or space represents a square. On a traditional checker... | Python | zaydzuhri_stack_edu_python |
function __init__ self k data max_guess=tuple 100 100 min_guess=tuple - 100 - 100
begin
set k = k
set data = data
set max_guess = max_guess
set min_guess = min_guess
end function | def __init__(self,k,data,max_guess=(100,100),min_guess=(-100,-100)):
self.k = k
self.data = data
self.max_guess = max_guess
self.min_guess = min_guess | Python | nomic_cornstack_python_v1 |
comment DAY = first day of current month
from datetime import datetime , timedelta
from dateutil.relativedelta import relativedelta
set today = call date
class Intervals
begin
set DAILY = string DAILY
set DAY = string DAY
set LAST_WEEK = string LAST_WEEK
set PREV_WEEK = string PREV_WEEK
set WEEK = string WEEK
set TWO_W... | # DAY = first day of current month
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
today = datetime.utcnow().date()
class Intervals:
DAILY = 'DAILY'
DAY = 'DAY'
LAST_WEEK = 'LAST_WEEK'
PREV_WEEK = 'PREV_WEEK'
WEEK = 'WEEK'
TWO_WEEK = 'TWO_WEEK'
M... | Python | zaydzuhri_stack_edu_python |
function test_rest_v10_dd_systems_systemid_mdtags_get self
begin
pass
end function | def test_rest_v10_dd_systems_systemid_mdtags_get(self):
pass | Python | nomic_cornstack_python_v1 |
function compare_headers stdhdr cmphdr tolerances=none ignore=none
begin
set tolerances = tolerances or DEFAULT_TOLERANCES
set ignore = ignore or list
comment dir() is expensive so we cache results here
set stdhdrNames = directory
set cmphdrNames = directory
comment get the unignored headers
set headers = difference u... | def compare_headers(stdhdr, cmphdr, tolerances=None, ignore=None):
tolerances = tolerances or DEFAULT_TOLERANCES
ignore = ignore or []
# dir() is expensive so we cache results here
stdhdrNames = stdhdr.dir()
cmphdrNames = cmphdr.dir()
# get the unignored headers
headers = set(stdhdrNames)... | Python | nomic_cornstack_python_v1 |
comment Problem name: Creating Strings 1
comment Description: Given a string, your task is to generate all different strings that can be created using its characters.
comment Strategy: use permutations method from itertools module
from itertools import permutations
set string = input
set ls = sorted list set permutatio... | #Problem name: Creating Strings 1
# Description: Given a string, your task is to generate all different strings that can be created using its characters.
# Strategy: use permutations method from itertools module
from itertools import permutations
string=input()
ls=sorted(list(set(permutations(string))))
li=... | Python | zaydzuhri_stack_edu_python |
import config
import telebot
import requests
import os
import datetime
set bot = call TeleBot TOKEN
set start_time = string now
print string MLK bot started at + start_time
set problem = 0
set period = 1
if problem
begin
set problem_message = string Остутствует доступ к серверу с данными.
end
else
begin
set problem_mes... | import config
import telebot
import requests
import os
import datetime
bot = telebot.TeleBot(config.TOKEN)
start_time = str(datetime.datetime.now())
print('MLK bot started at ' + start_time)
problem = 0
period = 1
if problem:
problem_message = 'Остутствует доступ к серверу с данными.\n'
else:
problem_message... | Python | zaydzuhri_stack_edu_python |
function save self *args **kwargs
begin
if not slug
begin
set slug = call slugify call unidecode title
set duplications = filter slug=slug
if exists duplications
begin
set slug = string %s-%s % tuple slug hex
end
else
begin
set slug = slug
end
end
return save *args keyword kwargs
end function | def save(self, *args, **kwargs):
if not self.slug:
slug = slugify(unidecode(self.title))
duplications = type(self).objects.filter(slug=slug)
if duplications.exists():
self.slug = "%s-%s" % (slug, uuid4().hex)
else:
self.slug = slug
... | Python | nomic_cornstack_python_v1 |
for line in data
begin
if line == string
begin
append groups current_group
set current_group = list
continue
end
append current_group strip line
end
set count = 0
for group in groups
begin
print group
set group_set = set
for person in group
begin
for question in person
begin
add group_set question
end
end
set count =... | for line in data:
if line == "\n":
groups.append(current_group)
current_group = []
continue
current_group.append(line.strip())
count = 0
for group in groups:
print(group)
group_set = set()
for person in group:
for question in person:
group_set.add(questio... | Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
import pandas as pd
from urllib.parse import quote
import json
import time
set chrome_options = call ChromeOptions
set driver = call Chrome chrome_options=chrome_options
call maximize_window
set key = string iphone
comment 构造url
set url = string https://search.jd.com/Search?keyword= + quo... | from selenium import webdriver
import pandas as pd
from urllib.parse import quote
import json
import time
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.maximize_window()
key='iphone'
url='https://search.jd.com/Search?keyword='+quote(key)+'&enc=utf-8' #构造ur... | Python | zaydzuhri_stack_edu_python |
string Author: Tris1702 Github: https://github.com/Tris1702 Gmail: phuonghoand2001@gmail.com Thank you so much!
set xchange = string 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
function change x k
begin
set res = string
while x > 0
begin
set r = x % k
set res = xchange at r + res
set x = integer x / k
end
return res
end func... | """
Author: Tris1702
Github: https://github.com/Tris1702
Gmail: phuonghoand2001@gmail.com
Thank you so much!
"""
xchange = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def change(x, k):
res = ''
while (x > 0):
r = x % k
res = xchange[r] + res
x = int(x/k)
return res
T = int(input())
for ... | Python | zaydzuhri_stack_edu_python |
class Address
begin
function __init__ self
begin
set street = string
set state = string
set zipCode = string
end function
end class
class Customer extends object
begin
function __init__ self firstName lastName
begin
set firstName = firstName
set lastName = lastName
set address = list
end function
end class
set cust... | class Address:
def __init__(self):
self.street = ''
self.state = ''
self.zipCode = ''
class Customer(object):
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
self.address = []
customer = Customer()
customer.firstName ... | Python | zaydzuhri_stack_edu_python |
function get_points_for_equipment equipment building pymortar_client
begin
set v = view pymortar name=equipment definition=format string SELECT ?{eq_lower} ?point ?class FROM {building} WHERE {{ ?{eq_lower} rdf:type brick:{eq_class} . ?{eq_lower} bf:hasPoint ?point . ?point rdf:type ?class }}; eq_lower=lower equipment ... | def get_points_for_equipment(equipment, building, pymortar_client):
v = pymortar.View(
name=equipment,
definition="""
SELECT ?{eq_lower} ?point ?class FROM {building} WHERE {{
?{eq_lower} rdf:type brick:{eq_class} .
?{eq_lower} bf:hasPoint ?point .
?point... | Python | nomic_cornstack_python_v1 |
function __init__ self panels
begin
set _panels : List at PlotPanelSetup = list panels
end function | def __init__(self, panels: Sequence[PlotPanelSetup]) -> None:
self._panels: List[PlotPanelSetup] = list(panels) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import base64
import io
import json
import os
import warnings
import re
from decimal import Decimal
import boto3
import short_url
import requests
from PIL import Image
simple filter string error DecompressionBombWarning
function lambda_handler event context
begin
set region = environ at st... | #!/usr/bin/env python3
import base64
import io
import json
import os
import warnings
import re
from decimal import Decimal
import boto3
import short_url
import requests
from PIL import Image
warnings.simplefilter('error', Image.DecompressionBombWarning)
def lambda_handler(event, context):
region = os.environ['... | Python | zaydzuhri_stack_edu_python |
if string bwm in my_car
begin
print string Yepppp
end
else
begin
print string NOOOOO
end | if 'bwm' in my_car:
print("Yepppp")
else:
print("NOOOOO")
| Python | zaydzuhri_stack_edu_python |
from decimal import Decimal
from decimal import InvalidOperation
from weakref import WeakKeyDictionary
from tax_calculator_refactored import tax_constants
from tax_calculator_refactored import tax_calculations as tc
class PositiveDecimal
begin
string Class implementing descriptor protocol for attribute data validation.... | from decimal import Decimal
from decimal import InvalidOperation
from weakref import WeakKeyDictionary
from tax_calculator_refactored import tax_constants
from tax_calculator_refactored import tax_calculations as tc
class PositiveDecimal:
"""Class implementing descriptor protocol for attribute data validation."""... | Python | zaydzuhri_stack_edu_python |
function case_insensitive_lookup_2 dictionary term
begin
return get dictionary lower term
end function | def case_insensitive_lookup_2(dictionary: dict, term: str) -> Optional[str]:
return dictionary.get(term.lower()) | Python | nomic_cornstack_python_v1 |
function check_for_fuzzy_matches_between_unconfirmed_and_typo_group *args
begin
set unconfirmed_merge_no_typos = args at 0
set typos = args at 1
set unconfirmed_list_no_typos = list
set match_pair = tuple
set unconfirmed_merge_typo_list = list
set confirmed_merge_typo_list = list
comment Loop through sets of unconf... | def check_for_fuzzy_matches_between_unconfirmed_and_typo_group(*args):
unconfirmed_merge_no_typos = args[0]
typos = args[1]
unconfirmed_list_no_typos = []
match_pair = ()
unconfirmed_merge_typo_list = []
confirmed_merge_typo_list = []
# Loop through sets of unconfirmed merge pairs to get a... | Python | nomic_cornstack_python_v1 |
function convert_to_upper string
begin
set upper_string = string
for char in string
begin
if ordinal char >= 97 and ordinal char <= 122
begin
set upper_string = upper_string + character ordinal char - 32
end
else
begin
set upper_string = upper_string + char
end
end
return upper_string
end function
set string = string ... | def convert_to_upper(string):
upper_string = ""
for char in string:
if ord(char) >= 97 and ord(char) <= 122:
upper_string += chr(ord(char) - 32)
else:
upper_string += char
return upper_string
string = 'hello world'
upper_string = convert_to_upper(string)
print(upper_... | Python | jtatman_500k |
import pandas as pd
set my_response = sort values call nlargest 20 string cases string cases ascending=false
print my_response | import pandas as pd
my_response = pd.read_csv('data/covid19_total_cases.csv', index_col='index')\
.T.nlargest(20, 'cases').sort_values('cases', ascending=False)
print(my_response)
| Python | zaydzuhri_stack_edu_python |
function get_integrations_speech_dialogflow_agents self **kwargs
begin
set all_params = list string page_number string page_size string name
append all_params string callback
set params = locals
for tuple key val in call iteritems params at string kwargs
begin
if key not in all_params
begin
raise call TypeError string ... | def get_integrations_speech_dialogflow_agents(self, **kwargs):
all_params = ['page_number', 'page_size', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
... | Python | nomic_cornstack_python_v1 |
function maya_main_window
begin
set main_window_ptr = call mainWindow
return call wrapInstance integer main_window_ptr QWidget
end function | def maya_main_window():
main_window_ptr = omui.MQtUtil.mainWindow()
return wrapInstance(int(main_window_ptr), QtWidgets.QWidget) | Python | nomic_cornstack_python_v1 |
function get_errored_courses self
begin
return dict
end function | def get_errored_courses(self):
return {} | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
from src.recommender_functions import get_indices , show_products , cluster_text , get_kmeans_rec , get_lda_recs , get_cos_sim_recs
import autoreload
call set_option string display.max_columns 500
set products = read csv string s3://capstone-3/data/products_wo_na.csv
drop products... | import pandas as pd
import numpy as np
from src.recommender_functions import get_indices, show_products,cluster_text, get_kmeans_rec, get_lda_recs, get_cos_sim_recs
import autoreload
pd.set_option('display.max_columns', 500)
products = pd.read_csv('s3://capstone-3/data/products_wo_na.csv')
products.drop('Unnamed: 0',a... | Python | zaydzuhri_stack_edu_python |
import random
for id in range 49 53
begin
print string insert into SizeOfProduct values( { id } ,'S', { random integer 15 30 * 1000 } , { random integer 1 15 } );
print string insert into SizeOfProduct values( { id } ,'M', { random integer 30 40 * 1000 } , { random integer 1 15 } );
print string insert into SizeOfProdu... | import random
for id in range(49,53):
print(f"insert into SizeOfProduct values({id},'S',{random.randint(15,30)*1000},{random.randint(1,15)});")
print(f"insert into SizeOfProduct values({id},'M',{random.randint(30,40)*1000},{random.randint(1,15)});")
print(f"insert into SizeOfProduct values({id},'L',{random.... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
set __author__ = string Burtsev
import scipy as np
string Some general functions.
comment sigmoid activation function
function sigmoid x k x0
begin
return 1 / 1 + exp - k * x - x0
end function
comment calculation of weighted sum, arguments are lists
function weightedSum inputs weights norm... | # -*- coding: utf-8 -*-
__author__ = 'Burtsev'
import scipy as np
""" Some general functions."""
def sigmoid(x, k, x0): # sigmoid activation function
return 1 / (1 + np.exp(-k * (x - x0)))
def weightedSum(inputs, weights, norm=False): # calculation of weighted sum, arguments are lists
if len(inputs) > 0... | Python | zaydzuhri_stack_edu_python |
async function get_needed_for_level level column_name
begin
if column_name == string profile
begin
return 250 * level
end
comment 350 is base value (level 1)
return integer 2 * 350 * 2 ^ level - 2
end function | async def get_needed_for_level(level: int, column_name: str):
if column_name == "profile":
return 250 * level
return int((2 * 350) * (2 ** (level - 2))) # 350 is base value (level 1) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment Boid implementation in Python using PyGame
import sys
import random
import math
import pygame
from boids.boid_constants import BoidConstants
class BoidBase extends Sprite
begin
function __init__ self x y gender screen maxVelocity=10
begin
set x = x
set y = y
set gender = gender
set ... | #!/usr/bin/env python
# Boid implementation in Python using PyGame
import sys
import random
import math
import pygame
from boids.boid_constants import BoidConstants
class BoidBase(pygame.sprite.Sprite):
def __init__(self, x, y, gender, screen, maxVelocity=10):
self.x = x
self.y = y
self.g... | Python | zaydzuhri_stack_edu_python |
from typing import List
function unique_creator list
begin
set new_list = list
for i in list
begin
if i not in new_list
begin
append new_list i
end
end
return new_list
end function
print call unique_creator list 1 2 3 4 4 4 3 | from typing import List
def unique_creator(list: List):
new_list = []
for i in list:
if i not in new_list:
new_list.append(i)
return new_list
print(unique_creator([1,2,3,4,4,4,3,]))
| Python | zaydzuhri_stack_edu_python |
import io
import socket
import time
import struct
import numpy as np
import threading
import socket
import os
string class connect: def __init__(self): self.drone = '192.168.1.1' self.address = None self.s = socket.socket() port = 5555 self.port = 5555 self.s.bind(('', port)) self.startup() def startup(self): s = self.... | import io
import socket
import time
import struct
import numpy as np
import threading
import socket
import os
'''
class connect:
def __init__(self):
self.drone = '192.168.1.1'
self.address = None
self.s = socket.socket()
port = 5555
self.port = 5555
self.s.bind(('',... | Python | zaydzuhri_stack_edu_python |
function add_vertex self item kind rate=true
begin
if item not in _vertices
begin
set _vertices at item = call _Vertex item kind rate
end
end function | def add_vertex(self, item: Any, kind: str, rate: Optional[bool] = True) -> None:
if item not in self._vertices:
self._vertices[item] = _Vertex(item, kind, rate) | Python | nomic_cornstack_python_v1 |
function space s
begin
set sp = string
for i in range s
begin
set sp = sp + string
end
return sp
end function
set s = input
if length s % 2 == 0
begin
set s = s + string $
end
set rev = s at slice : : - 1
set n = length s - 2 * 2 + 1
set half = length s // 2
set h = half - 1 * 2
set io = 0
for i in range length s
b... | def space(s):
sp="";
for i in range(s):
sp+=" "
return sp
s=input()
if(len(s)%2==0):
s=s+"$"
rev=s[::-1]
n=((len(s)-2)*2)+1
half=(len(s)//2)
h=(half-1)*2
io=0
for i in range(len(s)):
if(half>i):
print(space(io)+str(s[i])+space(n)+str(rev[i]))
n=n-4
io=io+2
elif(half==i):
... | Python | zaydzuhri_stack_edu_python |
import numpy as numpy
class Event
begin
function __init__ self time
begin
set time = time
end function
end class
class Queue
begin
function __init__ self lam mi
begin
set lam = lam
set mi = mi
set ro = lam / mi
set current_queue_time = 0
set server_ready = 1
set next_request_time = call generate_request_time 0
set next... | import numpy as numpy
class Event():
def __init__(self, time):
self.time = time
class Queue():
def __init__(self, lam, mi):
self.lam = lam
self.mi = mi
self.ro = lam / mi
self.current_queue_time = 0
self.server_ready = 1
self.next_request_time = self.g... | Python | zaydzuhri_stack_edu_python |
string The Goal: Like the title suggests, this project involves writing a program that simulates rolling dice. When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer - the number of sides on the die is up to you.) The program will print what that number is. It sho... | """
The Goal: Like the title suggests, this project involves writing a program that
simulates rolling dice. When the program runs, it will randomly choose a number
between 1 and 6. (Or whatever other integer you prefer - the number of sides
on the die is up to you.) The program will print what that number is. It
should... | Python | zaydzuhri_stack_edu_python |
function preprocess_train self G edge_ids edge_labels mode=string train
begin
comment import stellargraph
try
begin
import stellargraph as sg
from stellargraph.mapper import GraphSAGELinkGenerator
end
except any
begin
raise exception SG_ERRMSG
end
if parse version __version__ < parse version string 0.8
begin
raise exce... | def preprocess_train(self, G, edge_ids, edge_labels, mode="train"):
# import stellargraph
try:
import stellargraph as sg
from stellargraph.mapper import GraphSAGELinkGenerator
except:
raise Exception(SG_ERRMSG)
if version.parse(sg.__version__) < versio... | Python | nomic_cornstack_python_v1 |
comment https://twitter.com/mkawa2/status/1394443931564138500
comment 河崎さんの解説ACさせていただきました。
set k = integer input
set mod = 10 ^ 9 + 7
comment 桁和が9の倍数でなければ9の倍数にならない
if k % 9 != 0
begin
exit print 0
end
set dp = list 1 * k + 1
for i in range 1 k
begin
if i - 9 >= 0
begin
set dp at i + 1 = dp at i * 2 - dp at i - 9 % mod
... | # https://twitter.com/mkawa2/status/1394443931564138500
# 河崎さんの解説ACさせていただきました。
k = int(input())
mod = 10 ** 9 + 7
# 桁和が9の倍数でなければ9の倍数にならない
if k % 9 != 0:
exit(print(0))
dp = [1] * (k + 1)
for i in range(1, k):
if i - 9 >= 0:
dp[i + 1] = (dp[i] * 2 - dp[i - 9]) % mod
else:
dp[i + 1] = (dp[i... | Python | zaydzuhri_stack_edu_python |
function DoubleBorder *args **kwargs
begin
return call SizerFlags_DoubleBorder *args keyword kwargs
end function | def DoubleBorder(*args, **kwargs):
return _core_.SizerFlags_DoubleBorder(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
string a=[] for x in range(10): a.append(x) print(a)
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
set x = linear space 0 10 100
set y = x ^ 2
set fig = figure
plot x y
show | """a=[]
for x in range(10):
a.append(x)
print(a)"""
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
x=np.linspace(0,10,100)
y=x**2
fig=plt.figure()
plot(x,y)
show()
| Python | zaydzuhri_stack_edu_python |
function viewCount self
begin
return _last_count
end function | def viewCount(self):
return self._last_count | Python | nomic_cornstack_python_v1 |
function attack_player self npc_name attack_bonus damage_die damage_bonus
begin
set roll = call die_roll 20 1 single_mod=attack_bonus
if roll at 0 >= AC
begin
set damage = call die_roll damage_die at 0 damage_die at 1 single_mod=damage_bonus at 0
print string The + npc_name + string hits! You take + string damage + str... | def attack_player(self, npc_name, attack_bonus, damage_die, damage_bonus):
roll = utils.die_roll(20, 1, single_mod=attack_bonus)
if roll[0] >= self.main_player.AC:
damage = utils.die_roll(damage_die[0], damage_die[1], single_mod=damage_bonus)[0]
print("The " + npc_name ... | Python | nomic_cornstack_python_v1 |
function read_features path
begin
set columns = list string Feature string Correlation
set regex_str = string ([^\s]+)(?:\s+corr=\s+)([^ ]+)
with open path string r as f
begin
set text = read f
end
set feature_tuples = find all text
set index = array range length feature_tuples + 1
comment features and models are 1-ind... | def read_features(path):
columns = ["Feature", "Correlation"]
regex_str = '([^\s]+)(?:\s+corr=\s+)([^\n]+)'
with open(path, 'r') as f:
text = f.read()
feature_tuples = re.compile(regex_str).findall(text)
index = np.arange(len(feature_tuples)) + 1
# features and models are 1-indexed
f... | Python | nomic_cornstack_python_v1 |
function get_authorization_header client user
begin
comment obtain authorization token
set response = post reverse string token-obtain data=dict string username username ; string password raw_password content_type=string application/json
set token = json response at string access
return dict string HTTP_AUTHORIZATION s... | def get_authorization_header(client, user):
# obtain authorization token
response = client.post(
reverse('token-obtain'),
data={'username': user.username, 'password': user.raw_password},
content_type='application/json'
)
token = response.json()['access']
return {'HTTP_AUTHORI... | Python | nomic_cornstack_python_v1 |
function parseAnnotating adqlStatement fieldInfoGetter
begin
set parsedTree = call parseToTree adqlStatement
set ctx = annotate parsedTree fieldInfoGetter
return tuple ctx call builtinMorph parsedTree at 1
end function | def parseAnnotating(adqlStatement, fieldInfoGetter):
parsedTree = parseToTree(adqlStatement)
ctx = annotate(parsedTree, fieldInfoGetter)
return ctx, builtinMorph(parsedTree)[1] | Python | nomic_cornstack_python_v1 |
function backward self grad_output
begin
print string BACKWARD
print grad_output
set grad_input1 = call zero_
set grad_input2 = call zero_
call pow_backward grad_output input1 input2 grad_input1 grad_input2
return tuple grad_input1 grad_input2
end function | def backward(self, grad_output):
print("BACKWARD")
print(grad_output)
grad_input1 = self.input1.new(*self.input1.size()).zero_()
grad_input2 = self.input2.new(*self.input2.size()).zero_()
my_lib.pow_backward(grad_output, self.input1, self.input2, grad_input1, grad_input2)
... | Python | nomic_cornstack_python_v1 |
comment Given a digit string, return all possible letter combinations that the number could represent.
comment A mapping of digit to letters (just like on the telephone buttons) is given below.
comment The digit 0 maps to 0 itself.
comment The digit 1 maps to 1 itself.
comment Input: Digit string "23"
comment Output: [... | # Given a digit string, return all possible letter combinations that the number could represent.
#
# A mapping of digit to letters (just like on the telephone buttons) is given below.
#
#
#
# The digit 0 maps to 0 itself.
# The digit 1 maps to 1 itself.
#
# Input: Digit string "23"
# Output: ["ad", "ae", "af"... | Python | zaydzuhri_stack_edu_python |
function solution n
begin
set ans = 0
while n
begin
if n % 2 == 1
begin
set n = n - 1
set ans = ans + 1
end
set n = n // 2
end
return ans
end function
set s = 5000
print call solution s | def solution(n):
ans = 0
while n:
if n%2 == 1:
n -= 1
ans += 1
n//=2
return ans
s= 5000
print(solution(s)) | Python | zaydzuhri_stack_edu_python |
function dynamic_unroll cell inputs begin_state drop_inputs=0 drop_outputs=0 layout=string TNC valid_length=none
begin
string Unrolls an RNN cell across time steps. Currently, 'TNC' is a preferred layout. unroll on the input of this layout runs much faster. Parameters ---------- cell : an object whose base class is RNN... | def dynamic_unroll(cell, inputs, begin_state, drop_inputs=0, drop_outputs=0,
layout='TNC', valid_length=None):
"""Unrolls an RNN cell across time steps.
Currently, 'TNC' is a preferred layout. unroll on the input of this layout
runs much faster.
Parameters
----------
cell : ... | Python | jtatman_500k |
comment Definition for singly-linked list.
class ListNode
begin
function __init__ self x
begin
set val = x
set next = none
end function
end class
from collections import deque
class Solution
begin
function removeNthFromEnd self head n
begin
if head == none or next == none and n >= 1
begin
return none
end
set temp = hea... | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
from collections import deque
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if((head == None) or (head.next == None and n >= 1)):
... | Python | zaydzuhri_stack_edu_python |
function filter_tod data feedtod ifeed level2=string level2
begin
set tuple nBands nChans nSamples = shape
set mask = zeros nSamples dtype=bool
set medfilt_coefficient = data at string { level2 } /Statistics/filter_coefficients at tuple ifeed Ellipsis
set atmos = data at string { level2 } /Statistics/atmos at tuple ife... | def filter_tod(data,feedtod,ifeed,level2='level2'):
nBands, nChans,nSamples = feedtod.shape
mask = np.zeros(nSamples,dtype=bool)
medfilt_coefficient = data[f'{level2}/Statistics/filter_coefficients'][ifeed,...]
atmos = data[f'{level2}/Statistics/atmos'][ifeed,...]
atmos_coefficient ... | Python | nomic_cornstack_python_v1 |
function test_simple_progress
begin
set pbar = call ProgressTracker interval=1
set field = call ScalarField call UnitGrid list 3
call initialize field
call handle field 2
call finalize
end function | def test_simple_progress():
pbar = trackers.ProgressTracker(interval=1)
field = ScalarField(UnitGrid([3]))
pbar.initialize(field)
pbar.handle(field, 2)
pbar.finalize() | Python | nomic_cornstack_python_v1 |
function __eq__ self other
begin
if not is instance other WorkflowTaskMeta
begin
return false
end
return __dict__ == __dict__
end function | def __eq__(self, other):
if not isinstance(other, WorkflowTaskMeta):
return False
return self.__dict__ == other.__dict__ | Python | nomic_cornstack_python_v1 |
function _manually_initialize self
begin
comment XXX: maybe refactor, this is actually part of the public interface
pass
end function | def _manually_initialize(self) -> None:
# XXX: maybe refactor, this is actually part of the public interface
pass | Python | nomic_cornstack_python_v1 |
import re
import itertools
function generateHappinessMap input
begin
set happiness = dict
for fact in input
begin
set sitting = split fact string happiness units by sitting next to
set nextTo = sitting at 1 at slice : - 1 :
set who = split sitting at 0 string would at 0
set howMuch = split sitting at 0 string would ... | import re
import itertools
def generateHappinessMap(input):
happiness = {}
for fact in input:
sitting = fact.split(" happiness units by sitting next to ")
nextTo = sitting[1][:-1]
who = sitting[0].split(" would ")[0]
howMuch = sitting[0].split(" would ")[1]
howMuch = how... | Python | zaydzuhri_stack_edu_python |
function SBMLLocalParameterConverter_init
begin
return call SBMLLocalParameterConverter_init
end function | def SBMLLocalParameterConverter_init():
return _libsbml.SBMLLocalParameterConverter_init() | Python | nomic_cornstack_python_v1 |
comment coding='utf-8'
string author: Youzhao Yang date: 04/26/2018 github: https://github.com/nnUyi Requirements: python3.6.*
comment part1 show types
set a = 2
print type a
set b = 2.5
print type b
set c = true
print type c
set d = string hello world
print type d
comment part2: basic operation
comment int
set a_plus_... | # coding='utf-8'
'''
author: Youzhao Yang
date: 04/26/2018
github: https://github.com/nnUyi
Requirements:
python3.6.*
'''
# part1 show types
a = 2
print(type(a))
b = 2.5
print(type(b))
c = True
print(type(c))
d = 'hello world'
print(type(d))
# part2: basic operation
# int
a_plus_a = a+a
a_minus_a = a-a
a_di... | Python | zaydzuhri_stack_edu_python |
import re
import sys
import argparse
import math
set parser = call ArgumentParser
call add_argument string --tori string -t help=string .obj file containing 3D model of tori type=str default=string tori.obj
call add_argument string --uke string -u help=string .obj file containing 3D model of uke type=str default=string... | import re
import sys
import argparse
import math
parser = argparse.ArgumentParser()
parser.add_argument(
'--tori',
'-t',
help=".obj file containing 3D model of tori",
type=str,
default="tori.obj"
)
parser.add_argument(
'--uke',
'-u',
help=".obj file containing 3D model of uke",
type=str,
default="uke.... | Python | zaydzuhri_stack_edu_python |
function getOldAddressMap self
begin
Ellipsis
end function | def getOldAddressMap(self) -> ghidra.program.database.map.AddressMap:
... | Python | nomic_cornstack_python_v1 |
import math
function triangle_type A B
begin
comment Check if the angles are valid for a triangle
if not 0 < A < pi and 0 < B < pi
begin
return string Invalid angles: Angles must be between 0 and π.
end
set C = pi - A + B
comment Calculate sin(C) using the sine of complementary angle
set sin_C = sin A + B
comment Calcu... | import math
def triangle_type(A, B):
# Check if the angles are valid for a triangle
if not (0 < A < math.pi and 0 < B < math.pi):
return "Invalid angles: Angles must be between 0 and π."
C = math.pi - (A + B)
# Calculate sin(C) using the sine of complementary angle
sin_C = math.si... | Python | dbands_pythonMath |
function from_dictionary cls dictionary
begin
if dictionary is none
begin
return none
end
comment Extract variables from the dictionary
set enabled = get dictionary string enabled
set spare_serial = get dictionary string spareSerial
set uplink_mode = get dictionary string uplinkMode
set virtual_ip_1 = get dictionary st... | def from_dictionary(cls,
dictionary):
if dictionary is None:
return None
# Extract variables from the dictionary
enabled = dictionary.get('enabled')
spare_serial = dictionary.get('spareSerial')
uplink_mode = dictionary.get('uplinkMode'... | Python | nomic_cornstack_python_v1 |
function provisioning_status_update_time_utc self
begin
return get pulumi self string provisioning_status_update_time_utc
end function | def provisioning_status_update_time_utc(self) -> str:
return pulumi.get(self, "provisioning_status_update_time_utc") | Python | nomic_cornstack_python_v1 |
function remove self key
begin
comment Find the element and keep a
comment reference to the element preceding it
set curr = head
set prev = none
while curr and data != key and data1 != key
begin
set prev = curr
set curr = next
end
comment Unlink it from the list
if prev is none
begin
set head = next
end
else
if curr
be... | def remove(self, key):
# Find the element and keep a
# reference to the element preceding it
curr = self.head
prev = None
while curr and curr.data != key and curr.data1 != key:
prev = curr
curr = curr.next
# Unlink it from the list
... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function uniquePathsWithObstacles self obstacleGrid
begin
string :type obstacleGrid: List[List[int]] :rtype: int
set n = length obstacleGrid
set m = length obstacleGrid at 0
set table = list comprehension list 0 * m for space in range n
for i in range n
begin
if obstacleGrid at i at ... | class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
n = len(obstacleGrid)
m = len(obstacleGrid[0])
table = [[0]*m for space in range(n)]
for i in range(n):
if o... | Python | zaydzuhri_stack_edu_python |
comment EJERCICIO 36
set numLegajo = integer input string Ingrese número de legajo:
set sueldoBasico = integer input string Ingrese sueldo básico:
set antiguedad = integer input string Ingrese antigüedad en la empresa:
set salario = 0
while numLegajo != 0
begin
set salario = sueldoBasico + 5 * sueldoBasico / 100 * anti... | # EJERCICIO 36
numLegajo = int(input("Ingrese número de legajo: "))
sueldoBasico = int(input("Ingrese sueldo básico: "))
antiguedad = int(input("Ingrese antigüedad en la empresa: "))
salario = 0
while numLegajo != 0:
salario = sueldoBasico + ((5 * sueldoBasico) / 100) * antiguedad
if antiguedad > 10:
... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function twoSum self nums target
begin
string :type nums: List[int] :type target: int :rtype: List[int]
set a = dict
set count = 0
for i in nums
begin
if i in a
begin
return list a at i count
end
set a at target - i = count
set count = count + 1
end
end function
end class
set sol = call Solution
p... | class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
a={}
count=0
for i in nums :
if i in a:
return [a[i],count]
a[target-i]=count
count+=1... | Python | zaydzuhri_stack_edu_python |
import sys
import os
import time
import ui
function get_command
begin
string Raises SystemExit exceptions if the format of the command from the CLI is incorrect. Valid commands: python pattis_reid_hw5.py -source=local python pattis_reid_hw5.py -source=remote Also, -source=remote must be run BEFORE -source=local If no e... | import sys
import os
import time
import ui
def get_command():
"""
Raises SystemExit exceptions if the format of the command from the CLI is incorrect.
Valid commands:
python pattis_reid_hw5.py -source=local
python pattis_reid_hw5.py -source=remote
Also, -source=remote must b... | Python | zaydzuhri_stack_edu_python |
function sum_odd_no_multiples_of_3 n current_sum=0
begin
if n == 0
begin
return current_sum
end
else
if n % 3 == 0
begin
return call sum_odd_no_multiples_of_3 n - 1 current_sum
end
else
if n % 2 == 1
begin
set current_sum = current_sum + n
end
return call sum_odd_no_multiples_of_3 n - 1 current_sum
end function
comment... | def sum_odd_no_multiples_of_3(n, current_sum=0):
if n == 0:
return current_sum
elif n % 3 == 0:
return sum_odd_no_multiples_of_3(n-1, current_sum)
elif n % 2 == 1:
current_sum += n
return sum_odd_no_multiples_of_3(n-1, current_sum)
# Test the function
n = 10
result = sum_odd_no_... | Python | greatdarklord_python_dataset |
import string
from conf import EMPTY , INITIAL_BOARD , WHITE , BLACK
from square import Square
from exception import InvalidBoard
class Board
begin
set valid = set string rRnNbBqQkKpP.
function __init__ self
begin
call reset
end function
function set_config self matrix=none flat=none
begin
call validate matrix=matrix f... | import string
from conf import EMPTY, INITIAL_BOARD, WHITE, BLACK
from square import Square
from exception import InvalidBoard
class Board:
valid = set('rRnNbBqQkKpP.')
def __init__(self):
self.reset()
def set_config(self, matrix=None, flat=None):
Board.validate(matrix=matrix, flat=flat... | Python | zaydzuhri_stack_edu_python |
function clean self value
begin
comment Handle null values: either we're missing a required value
if not value and required
begin
raise call ValidationError string Missing required field
end
comment Or the null value is optional: return None and exit
if not value
begin
return none
end
comment Decode our incoming JSON a... | def clean(self, value):
# Handle null values: either we're missing a required value
if not value and self.required:
raise ValidationError("Missing required field")
# Or the null value is optional: return None and exit
if not value:
return None
# Decode ou... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
set df = read csv string fake_reg.csv
print head df
comment The df could be a gemstone which based on its 2 features it will have a selling price.
comment Can prepare a regression here to predict what the future price of a gems... | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('fake_reg.csv')
print(df.head())
#The df could be a gemstone which based on its 2 features it will have a selling price.
#Can prepare a regression here to predict what the future price of a gemston... | Python | zaydzuhri_stack_edu_python |
function setup_logger name
begin
set level = get attribute settings string LOG_LEVEL string INFO
set logger = call getLogger name
call setLevel get attribute logging level INFO
set propagate = false
comment Setup the default handler
if has attribute settings string LOG_FILE and LOG_FILE
begin
set handler = call Rotatin... | def setup_logger(name):
level = getattr(settings, 'LOG_LEVEL', 'INFO')
logger = logging.getLogger(name)
logger.setLevel(getattr(logging, level, logging.INFO))
logger.propagate = False
# Setup the default handler
if hasattr(settings, 'LOG_FILE') and settings.LOG_FILE:
handler = logging.... | Python | nomic_cornstack_python_v1 |
function tasks_to_html tasks header=string logf=string
begin
set s = string
set s = s + string <html> <body>
set s = s + string <p>%s</p> % header
set s = s + string <p><a href="javascript:window.location.reload(true)">Reload</a></p>
if logf != string
begin
set s = s + string <p><a href="%s">Log</a></p> % logf
end
s... | def tasks_to_html(tasks,header="",logf=""):
s = ""
s += "<html>\n<body>"
s += "<p>%s</p>\n"%header
s += '<p><a href="javascript:window.location.reload(true)">Reload</a></p>\n'
if logf!="":
s += '<p><a href="%s">Log</a></p>\n'%logf
s += tasks_to_html_table(tasks)
return s | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string Task 9: Use the Github API to display the id 10-my_github.py
import requests
from sys import argv
if __name__ == string __main__
begin
set url = string https://api.github.com/users/ + argv at 1
set header = dict string Authorization format string token {} argv at 2
set req = get request... | #!/usr/bin/python3
"""
Task 9:
Use the Github API to display the id
10-my_github.py
"""
import requests
from sys import argv
if __name__ == "__main__":
url = "https://api.github.com/users/" + argv[1]
header = {'Authorization': 'token {}'.format(argv[2])}
req = requests.get(url, headers=header)
try:
... | Python | zaydzuhri_stack_edu_python |
from Domain.obiect import get_id , creeaza_obiect
from Logic.CRUD import adauga_obiect , stergere_obiect , modificare_obiect , get_by_id
function print_menu
begin
print string add. Adaugare obiect
print string delete. Stergere obiect
print string change. Modificare obiect
print string showall. Afisare toate obiectele
p... | from Domain.obiect import get_id, creeaza_obiect
from Logic.CRUD import adauga_obiect, stergere_obiect, modificare_obiect, get_by_id
def print_menu():
print("add. Adaugare obiect")
print("delete. Stergere obiect")
print("change. Modificare obiect")
print("showall. Afisare toate obiectele")
print("... | Python | zaydzuhri_stack_edu_python |
import os
import pandas as pd
import numpy as np
set dataset = read csv string D:\cognitior\Basics of data science\AirPassengers.csv
dataset
length dataset
comment Using length(df.columns) function to check the total number of columns
length columns
comment TAIL Function is used to get the values from the bottom.
tail ... | import os
import pandas as pd
import numpy as np
dataset=pd.read_csv('D:\\cognitior\\Basics of data science\\AirPassengers.csv')
dataset
len(dataset)
#Using length(df.columns) function to check the total number of columns
len(dataset.columns)
#TAIL Function is used to get the values from the bottom.
dataset.tail(... | Python | zaydzuhri_stack_edu_python |
function setup_room_l11
begin
set room = call Room
comment Sprite lists
set wall_list = call SpriteList
set enemigos_list = call SpriteList
set balas_list = call SpriteList
set recargas_list = call SpriteList
set esqueleto = call Skeleton
set center_y = 450
set center_x = 250
append enemigos_list esqueleto
comment Tile... | def setup_room_l11():
room = Room()
# Sprite lists
room.wall_list = arcade.SpriteList()
room.enemigos_list = arcade.SpriteList()
room.balas_list = arcade.SpriteList()
room.recargas_list = arcade.SpriteList()
esqueleto = Enemigos.Skeleton()
esqueleto.center_y = 450
esqueleto.center_... | Python | nomic_cornstack_python_v1 |
function fillComputedValues tv
begin
if string computed not in tv
begin
set tv at string computed = dictionary
end
call fillUUIDFromDiscoverResponse tv
call fillNameFromDiscoverResponse tv
call fillModelFromDiscoverResponse tv
call fillManufacturerFromDiscoverResponse tv
end function | def fillComputedValues(tv):
if 'computed' not in tv:
tv['computed'] = dict()
fillUUIDFromDiscoverResponse(tv)
fillNameFromDiscoverResponse(tv)
fillModelFromDiscoverResponse(tv)
fillManufacturerFromDiscoverResponse(tv) | Python | nomic_cornstack_python_v1 |
comment 프로그램명: 데이터 베이스 구축
comment 작성자 : 이준재
comment 수정일 : 2020-06-12
comment 팀명 : 파이썬클라스 (4조)
comment 프로그램 설명: 데이터 크롤링 후 쿼리셋 형태로 저장
import requests
import urllib.request
from bs4 import BeautifulSoup
import json
import os
import re
set default environ string DJANGO_SETTINGS_MODULE string Main.settings
import django
set... | ################################################
#프로그램명: 데이터 베이스 구축
#작성자 : 이준재
#수정일 : 2020-06-12
#팀명 : 파이썬클라스 (4조)
#프로그램 설명: 데이터 크롤링 후 쿼리셋 형태로 저장
################################################
import requests
import urllib.request
from bs4 import BeautifulSoup
import json
import os
import re
os.environ... | Python | zaydzuhri_stack_edu_python |
for i in range n
begin
print r at i
end | for i in range(n):
print(r[i]) | Python | zaydzuhri_stack_edu_python |
function xor_op x y l
begin
set v = 0
for i in range x y + 1
begin
set v = v ? l at i
end
return v
end function
set tuple n q = split input
set tuple n q = tuple integer n integer q
if n > 0
begin
if n > 1
begin
set tuple l1 l2 = tuple list list
set l = list map int split input
for i in range q
begin
set tuple s1 s2 ... | def xor_op(x,y,l):
v=0
for i in range(x,y+1):
v= v ^ l[i]
return v
n,q=input().split()
n,q=int(n),int(q)
if(n>0):
if(n>1):
l1,l2=[],[]
l=list(map(int,input().split()))
for i in range(q):
s1,s2=input().split()
s1,s2=int(s1),int(s2)
l1.ap... | Python | zaydzuhri_stack_edu_python |
function _updateLastChange self result
begin
if lastChange is none
begin
comment hacky but always save _lastConfigChange the first time to
comment distinguish this from a brand new resource
set _lastConfigChange = changeId
end
if modified or call getAttributeChanges key
begin
set _lastStateChange = changeId
end
end fun... | def _updateLastChange(self, result):
if self.target.lastChange is None:
# hacky but always save _lastConfigChange the first time to
# distinguish this from a brand new resource
self.target._lastConfigChange = self.changeId
if result.modified or self._resourceChanges.g... | Python | nomic_cornstack_python_v1 |
import pandas
import urllib.request
import numpy as np
set hnames = list string sepal-length string sepal-width string petal-length string petal-width string class
set web_path = url open string https://goo.gl/QnHW4g
set dataframe = read csv web_path names=hnames
print dataframe
call set_option string precision 2
set a... | import pandas
import urllib.request
import numpy as np
hnames=["sepal-length","sepal-width","petal-length",'petal-width','class']
web_path=urllib.request.urlopen("https://goo.gl/QnHW4g")
dataframe=pandas.read_csv(web_path,names=hnames)
print(dataframe)
pandas.set_option("precision",2)
a=np.array(dataframe)
print(a)
# ... | Python | zaydzuhri_stack_edu_python |
function isinf x
begin
from amath.DataTypes.Infinity import Infinity
if is instance x Infinity
begin
return true
end
else
if x == decimal string inf
begin
return true
end
else
if x == decimal string -inf
begin
return true
end
else
begin
return false
end
end function | def isinf(x):
from amath.DataTypes.Infinity import Infinity
if isinstance(x, Infinity):
return True
elif x == float("inf"):
return True
elif x == float("-inf"):
return True
else:
return False | Python | nomic_cornstack_python_v1 |
if n % 2 == 0
begin
print string n - 8 + string 8
end
else
begin
print string n - 9 + string 9
end | if n % 2 == 0:
print(str(n-8) + " 8")
else:
print(str(n-9) + " 9")
| Python | zaydzuhri_stack_edu_python |
function fftconvolve in1 in2 mode=string full axis=none
begin
set s1 = array shape
set s2 = array shape
set complex_result = call issubdtype dtype complex or call issubdtype dtype complex
if axis is none
begin
set size = s1 + s2 - 1
set fslice = tuple list comprehension call slice 0 integer sz for sz in size
end
else
b... | def fftconvolve(in1, in2, mode="full", axis=None):
s1 = np.array(in1.shape)
s2 = np.array(in2.shape)
complex_result = (np.issubdtype(in1.dtype, np.complex) or
np.issubdtype(in2.dtype, np.complex))
if axis is None:
size = s1 + s2 - 1
fslice = tuple([ slice(0, int(sz)) for sz in size ])
else:
equal_sha... | 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.