code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function is_opening self
begin
return _state == STATE_OPENING
end function | def is_opening(self) -> bool:
return self._state == STATE_OPENING | Python | nomic_cornstack_python_v1 |
for i in range integer b
begin
set data = integer input
update my_set list data
end
set difference = my_range - my_set
for j in difference
begin
print j
end
print format string Mario got {} of the dangerous obstacles. length my_set | for i in range(int(b)):
data = int(input())
my_set.update([data])
difference = my_range - my_set
for j in difference:
print(j)
print("Mario got {} of the dangerous obstacles.".format(len(my_set)))
| Python | zaydzuhri_stack_edu_python |
function temperature f g h i j f0
begin
try
begin
if f == 0
begin
set parameters = string f= { f } , g= { g } , h= { h } , i= { i } , j= { j } , f0= { f0 }
error string Error calculating temperature, frequency is 0: { parameters }
return none
end
return 1 / g + h * log f0 / f + i * log f0 / f ^ 2 + j * log f0 / f ^ 3 -... | def temperature(f: float, g: float, h: float, i: float, j: float, f0: float) -> float:
try:
if f == 0:
parameters = f"f={f}, g={g}, h={h}, i={i}, j={j}, f0={f0}"
logging.error(f"Error calculating temperature, frequency is 0: {parameters}")
return None
return 1 / (... | Python | nomic_cornstack_python_v1 |
while index < length ages
begin
if ages at index < 5
begin
append new_ages ages at index
end
set index = index + 1
end
print string old list: + string ages + string new list: + string new_ages
comment ages = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
comment new_ages=[]
comment index=0
comment while index < len(ages) and a... | while index < len(ages):
if ages[index] < 5:
new_ages.append(ages[index])
index=index+1
print("old list: " + str(ages) + "\nnew list: " + str(new_ages))
# ages = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# new_ages=[]
# index=0
# while index < len(ages) and ages[index] < 5 :
# new_ages.append(ages[... | Python | zaydzuhri_stack_edu_python |
function test_neighbours_y
begin
set mesh = call HexagonalMesh 1 1 2
comment assert to_sets(mesh.neighbours) == [{1}, {0}]
assert all
end function | def test_neighbours_y():
mesh = HexagonalMesh(1, 1, 2)
# assert to_sets(mesh.neighbours) == [{1}, {0}]
assert (mesh.neighbours == [[-1, -1, 1, -1, -1, -1],
[-1, -1, -1, 0, -1, -1]]).all() | Python | nomic_cornstack_python_v1 |
function filter_odd_numbers nums
begin
set odd_nums = list
for num in nums
begin
if num % 2 != 0
begin
append odd_nums num
end
end
return odd_nums
end function | def filter_odd_numbers(nums):
odd_nums = []
for num in nums:
if num % 2 != 0:
odd_nums.append(num)
return odd_nums
| Python | jtatman_500k |
comment importing the required module
import matplotlib.pyplot as plt
comment x axis values
set x1 = list 8 1000 100 10000 10000
set x2 = list 4 13 16 29 10000
comment corresponding y axis values
set y1 = list 0 0 0 0.15 0.15
set y2 = list 0 0 0 0.15 3.86
set y3 = list 0 0 0 0.09 0.34
comment plotting the points
plot x... | # importing the required module
import matplotlib.pyplot as plt
# x axis values
x1 = [8, 1000, 100, 10000, 10000]
x2 = [4, 13, 16, 29, 10000]
# corresponding y axis values
y1 = [0, 0, 0, 0.15, 0.15]
y2 = [0, 0, 0, 0.15, 3.86]
y3 = [0, 0, 0, 0.09, 0.34]
# plotting the points
plt.plot(x2, y1, label='Graham')
plt.plo... | Python | zaydzuhri_stack_edu_python |
function init_reset_pw email
begin
info string Trying to send password reset email to { email }
try
begin
call send_password_reset_mail email
end
except BadCode as error
begin
error string Sending password reset e-mail for { email } failed: { error }
return call error_response message=msg
end
return call success_respon... | def init_reset_pw(email: str) -> FluxData:
current_app.logger.info(f'Trying to send password reset email to {email}')
try:
send_password_reset_mail(email)
except BadCode as error:
current_app.logger.error(f'Sending password reset e-mail for {email} failed: {error}')
return error_resp... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import sys
import os
import re
from sas7bdat import SAS7BDAT
class base
begin
function __init__ self
begin
comment path of add-in dataset
set path = string ./data/addin/
comment Path of base dataset
set path_b = string ./data/base.xlsx
end function
function read_base self path_b
b... | ########################################################################################################################
import pandas as pd
import numpy as np
import sys
import os
import re
from sas7bdat import SAS7BDAT
class base():
def __init__(self):
self.path= './data/addin/' #path of add-in dataset
... | Python | zaydzuhri_stack_edu_python |
function __init__ self first_name last_name age
begin
set first_name = first_name
set last_name = last_name
set age = age
end function | def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding:utf-8 -*-
comment author : zlq16
comment date : 2019/10/27
from typing import Set , Dict , List
from agent.utility import OrderBid , VehicleType
from algorithm.route_planning.planner import RoutePlanner
from algorithm.route_planning.utility import get_route_info , get_ro... | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author : zlq16
# date : 2019/10/27
from typing import Set, Dict, List
from agent.utility import OrderBid, VehicleType
from algorithm.route_planning.planner import RoutePlanner
from algorithm.route_planning.utility import get_route_info, get_route_cost_by_route_info, get... | Python | zaydzuhri_stack_edu_python |
import random
set num = random
print num
set num = random integer 30 50
print num
set num = call randrange 30 50 5
print num | import random
num = random.random()
print (num)
num = random.randint(30, 50)
print (num)
num = random.randrange(30, 50, 5)
print (num)
| Python | zaydzuhri_stack_edu_python |
comment TODO: insert open() file locks with fcntl, to avoid race conditions
import os
import json
import logging
import fcntl
class ConfClass
begin
string " This class is meant for methods to handle the configuration file/files. The purpose of the configuration file is to store, and select, which sensor data a customer... | # TODO: insert open() file locks with fcntl, to avoid race conditions
import os
import json
import logging
import fcntl
class ConfClass:
""""
This class is meant for methods to handle the configuration file/files.
The purpose of the configuration file is to store, and select, which sensor
data a cust... | Python | zaydzuhri_stack_edu_python |
if profit > 0
begin
print format string Фирма закончила год с прибылью размером {} profit
set employees = integer input string Введите количество сотрудников:
print format string Прибыль в расчете на 1 сотрудника составляет: {} call __round__ 2
end
else
if profit < 0
begin
print format string Фирма закончила год с убыт... | if profit > 0:
print("Фирма закончила год с прибылью размером {}".format(profit))
employees = int(input("Введите количество сотрудников: "))
print("Прибыль в расчете на 1 сотрудника составляет: {}".format((profit/employees).__round__(2)))
elif profit < 0:
print("Фирма закончила год с убытком размером {}... | Python | zaydzuhri_stack_edu_python |
from django.db import models
from Products.models import Product
from UserBase.models import User
class Item extends Model
begin
comment add on_delete cascade
set Cart = call ForeignKey string ItemList null=true blank=true
set Item = call ForeignKey Product
comment may be decimal also check
set Quantity = call FloatFie... | from django.db import models
from Products.models import Product
from UserBase.models import User
class Item(models.Model):
Cart = models.ForeignKey('ItemList', null=True, blank=True ) # add on_delete cascade
Item = models.ForeignKey(Product)
Quantity = models.FloatField(blank=True, default=1.0) ... | Python | zaydzuhri_stack_edu_python |
comment %%
comment Librerias
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
comment NumPy (Numeric Python) le da a Python capacidades de cálculo similares a los de otros software como MATLAB.
comment SciPy (Scientific Python) es una librería fundamental para computación científica.
from sklearn.... | #%%
# Librerias
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# NumPy (Numeric Python) le da a Python capacidades de cálculo similares a los de otros software como MATLAB.
# SciPy (Scientific Python) es una librería fundamental para computación científica.
from sklearn.model_selection import... | Python | zaydzuhri_stack_edu_python |
string Script to train a classifier to detect vehicles
import cv2
import glob
import matplotlib.image as mpimg
import numpy as np
import pickle
import time
from FeatureExtractor import FeatureExtractor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm... | """Script to train a classifier to detect vehicles"""
import cv2
import glob
import matplotlib.image as mpimg
import numpy as np
import pickle
import time
from FeatureExtractor import FeatureExtractor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm... | Python | zaydzuhri_stack_edu_python |
import salt_utils
import socketio
import sys
import pymongo
import requests
import json
from salt_parser import Parser
set sio = call Client
comment The dictionary containing the command words
set data = dict string Entry list
try
begin
set configData = call openF string config.json
end
except any
begin
comment If the... | import salt_utils
import socketio
import sys
import pymongo
import requests
import json
from salt_parser import Parser
sio = socketio.Client()
#The dictionary containing the command words
data = {"Entry" : []}
try:
configData = salt_utils.openF('config.json')
except:
#If the client has still not been conf... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string https://www.youtube.com/watch?v=EeQ8pwjQxTM
function merge_sort list1
begin
print string Splitting: list1
if length list1 > 1
begin
set mid = length list1 // 2
set left = list1 at slice 0 : mid :
set right = list1 at slice mid : :
call merge_sort left
call merge_sort right
set i = 0
... | #!/usr/bin/python3
"https://www.youtube.com/watch?v=EeQ8pwjQxTM"
def merge_sort(list1):
print("Splitting: ", list1)
if len(list1) > 1:
mid = len(list1) // 2
left = list1[0:mid]
right = list1[mid:]
merge_sort(left)
merge_sort(right)
i=j=k=0
while i < len... | Python | zaydzuhri_stack_edu_python |
function parse_usb_id id
begin
return integer id 16
end function | def parse_usb_id(id):
return int(id, 16) | Python | nomic_cornstack_python_v1 |
comment import Raspberry Pi GPIO library as GPIO
import RPi.GPIO as GPIO
comment set up on-board pins 3, 5, and 7
function setup
begin
call setmode BOARD
comment set on board pin#3 as room light 1 control
setup GPIO 3 OUT
comment set on board pin#5 for room light 2 control
setup GPIO 5 OUT
comment set on board pin#7 fo... | import RPi.GPIO as GPIO # import Raspberry Pi GPIO library as GPIO
def setup(): # set up on-board pins 3, 5, and 7
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.OUT) # set on board pin#3 as room light 1 control
GPIO.setup(5, GPIO.OUT) # set on board pin#5 for room light 2 contro... | Python | zaydzuhri_stack_edu_python |
function get_temperature self unit=string kelvin
begin
string Returns a dict with temperature info :param unit: the unit of measure for the temperature values. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a dict containing temperature values. :raises: ValueError when unknown tem... | def get_temperature(self, unit='kelvin'):
"""Returns a dict with temperature info
:param unit: the unit of measure for the temperature values. May be:
'*kelvin*' (default), '*celsius*' or '*fahrenheit*'
:type unit: str
:returns: a dict containing temperature values.
... | Python | jtatman_500k |
function finished self
begin
return status not in list ACKNOWLEDGED IN_PROGRESS
end function | def finished(self) -> bool:
return self.status not in [self.StatusEnum.ACKNOWLEDGED,
self.StatusEnum.IN_PROGRESS] | Python | nomic_cornstack_python_v1 |
import heapq as hq
function solution jobs
begin
set heap = list
sort jobs key=lambda x -> x at 0
set t = 0
set total = 0
set idx = 0
set work_until = 0
while true
begin
if idx == length jobs and length heap == 0
begin
break
end
while idx < length jobs and t >= jobs at idx at 0
begin
call heappush heap tuple jobs at id... | import heapq as hq
def solution(jobs):
heap = []
jobs.sort(key=lambda x: x[0])
t = 0
total = 0
idx = 0
work_until = 0
while True:
if idx == len(jobs) and len(heap) == 0:
break
while idx < len(jobs) and t >= jobs[idx][0]:
hq.heappush(heap, (jobs[idx]... | Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
comment Strategy for locators on the following features:
comment Continue button, search by id 'continue'
comment Need help link, search by class 'a-expander-prompt'
comment Forgot your password li... | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
# Strategy for locators on the following features:
# Continue button, search by id 'continue'
# Need help link, search by class 'a-expander-prompt'
# Forgot your password link, search by class 'a-... | Python | zaydzuhri_stack_edu_python |
import random
import re
from gensim.models import word2vec
function fileToWords fileName lang
begin
set fil = read lines open fileName
set stuff = list
for line in fil
begin
set line = strip strip line string string
comment line=re.sub(r'[0-9]*',"",line)
comment line=re.sub(r'[.$*&-?\!$%_+\=-`"\'<>~@\(\)\'"]*',"",line... | import random
import re
from gensim.models import word2vec
def fileToWords(fileName,lang):
fil=open(fileName).readlines()
stuff=[]
for line in fil:
line=line.strip('\n').strip('\r')
# line=re.sub(r'[0-9]*',"",line)
# line=re.sub(r'[.$*&-?\!$%_+\=-`"\'<>~@\(\)\'"]*',"",line)
... | Python | zaydzuhri_stack_edu_python |
from ecies.utils import generate_eth_key , generate_key
from ecies import encrypt , decrypt
import logging
set _logger = call getLogger __name__
class PublicKey
begin
function __init__ self name
begin
set _name = name
set _keys_holder = dict
set __private_key = call generate_eth_key
set __public_key = call _generate_p... | from ecies.utils import generate_eth_key, generate_key
from ecies import encrypt, decrypt
import logging
_logger = logging.getLogger(__name__)
class PublicKey:
def __init__(self, name):
self._name = name
self._keys_holder = {}
self.__private_key = generate_eth_key()
self.__public_... | Python | zaydzuhri_stack_edu_python |
comment def f():
comment rem = (3,4,5)
comment a = 1,2, *rem
comment return a
comment b = f()
comment print(b)
function f
begin
set rem = tuple 3.4 5
comment in 3.7 this would have created a syntax error.
return tuple 1 2 *rem
end function
f dist
set b = f dist
print b
comment The same is the case with yield
function f... | # def f():
# rem = (3,4,5)
# a = 1,2, *rem
# return a
#
# b = f()
# print(b)
def f():
rem = (3.4,5)
# in 3.7 this would have created a syntax error.
return 1,2, *rem
f()
b = f()
print(b)
# The same is the case with yield
def f():
rem = (3.4,5)
# in 3.7 this would have created a synta... | Python | zaydzuhri_stack_edu_python |
comment for random calling of fucntion
import asyncio
import time
import requests
set start_time = time
async function say_after i
begin
print string im runnig { i }
set d = get requests string https://test.jobiak.ai:8443/getKeyWordsBasedOnTitle?jobTitle=/ + string i
await sleep 0.01
print string im done { i }
print js... | #for random calling of fucntion
import asyncio
import time
import requests
start_time = time.time()
async def say_after(i):
print(f'im runnig {i}')
d = requests.get('https://test.jobiak.ai:8443/getKeyWordsBasedOnTitle?jobTitle=/'+str(i))
await asyncio.sleep(0.01)
print(f'im done {i}')
prin... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import argparse
import numpy as np
import pygame as pg
import time
from pygame.locals import *
from transitions import Machine
from nao import Nao
function main
begin
set parser = call ArgumentParser
call add_argument string --ip help=string addresse ip du nao
call add_argument string --po... | # -*- coding: utf-8 -*-
import argparse
import numpy as np
import pygame as pg
import time
from pygame.locals import *
from transitions import Machine
from nao import Nao
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--ip', help='addresse ip du nao')
parser.add_argument('--port', h... | Python | zaydzuhri_stack_edu_python |
function _read_file self
begin
with open file string rb as fp
begin
set chunk = read fp block_size
while chunk
begin
yield chunk
set chunk = read fp block_size
end
end
end function | def _read_file(self):
with open(self.file, 'rb') as fp:
chunk = fp.read(self.block_size)
while chunk:
yield chunk
chunk = fp.read(self.block_size) | Python | nomic_cornstack_python_v1 |
function next_document doc
begin
set index = index documentlist doc
set ndoc = documentlist at index + 1 % length documentlist
call activate
end function | def next_document(doc):
index = documentlist.index(doc)
ndoc = documentlist[(index + 1) % len(documentlist)]
ndoc.activate() | Python | nomic_cornstack_python_v1 |
comment 내 풀이
set N = integer input
set cnt = 0
for hour in range N + 1
begin
for minute in range 60
begin
for sec in range 60
begin
if string 3 in string hour + string minute + string sec
begin
set cnt = cnt + 1
end
end
end
end
print cnt
comment 풀이와 해답이 같다~ | # 내 풀이
N = int(input())
cnt = 0
for hour in range(N + 1):
for minute in range(60):
for sec in range(60):
if '3' in str(hour) + str(minute) + str(sec):
cnt += 1
print(cnt)
# 풀이와 해답이 같다~ | Python | zaydzuhri_stack_edu_python |
string toppario.py - parse CHARMM residue topology and forcefield parameter files
from __future__ import division
import warnings
import copy
import functools
import pickle
import math
import utils
set __author__ = string James Gowdy
set __email__ = string jamesgowdy1988@gmail.com
comment Parameters
class ParamDict ext... | """toppario.py - parse CHARMM residue topology and forcefield parameter files"""
from __future__ import division
import warnings
import copy
import functools
import pickle
import math
import utils
__author__ = "James Gowdy"
__email__ = "jamesgowdy1988@gmail.com"
###################################################... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
comment -*- coding: utf-8 --
comment ---------------------------
comment @Time : 2017/5/2 18:32
comment @Site :
comment @File : cnn.py
comment @Author : zhouxinmin
comment @Email : 1141210649@qq.com
comment @Software: PyCharm
import time
import numpy as np
import theano
import theano.tenso... | # ! /usr/bin/env python
# -*- coding: utf-8 --
# ---------------------------
# @Time : 2017/5/2 18:32
# @Site :
# @File : cnn.py
# @Author : zhouxinmin
# @Email : 1141210649@qq.com
# @Software: PyCharm
import time
import numpy as np
import theano
import theano.tensor as T
import lasagne
from sklearn impo... | Python | zaydzuhri_stack_edu_python |
function h cur_bid cur_bidder_value active_values poly_form=false
begin
if not poly_form
begin
return sum 1.0 / array active_values - cur_bid / length active_values - 1.0 - 1.0 / cur_bidder_value - cur_bid
end
else
begin
set active_values_tiled = call tile array active_values tuple length active_values 1 - cur_bid
call... | def h(cur_bid, cur_bidder_value, active_values, poly_form=False):
if not poly_form:
return (sum(1.0 / (np.array(active_values) - cur_bid)) /
(len(active_values) - 1.0) - 1.0 / (cur_bidder_value - cur_bid))
else:
active_values_tiled = np.tile(np.array(active_values), (len(act... | Python | nomic_cornstack_python_v1 |
function capitalize_words input_string
begin
set words = split input_string
set capitalized_words = list comprehension capitalize word for word in words
return join string capitalized_words
end function
comment Example usage:
set input_string = string hello world
set output_string = call capitalize_words input_string
... | def capitalize_words(input_string):
words = input_string.split()
capitalized_words = [word.capitalize() for word in words]
return ' '.join(capitalized_words)
# Example usage:
input_string = "hello world"
output_string = capitalize_words(input_string)
print(output_string) # Output: Hello World
| Python | greatdarklord_python_dataset |
function daysToBday
begin
string Prints to console screen the number of days until their next birthday
set birthMonth = call getIntWithinRange string ENTER ITEGER VALUE FOR BIRTH MONTH FROM 1 TO 12: 1 12
set birthDay = call getIntWithinRange string ENTER INTEGER VALUE FOR DAY YOU WERE BORN: 1 31
comment gets the date f... | def daysToBday():
""" Prints to console screen the number of days until their next birthday"""
birthMonth = getIntWithinRange('ENTER ITEGER VALUE FOR BIRTH MONTH FROM 1 TO 12: ',1,12)
birthDay = getIntWithinRange('ENTER INTEGER VALUE FOR DAY YOU WERE BORN: ',1,31)
today = datetime.datetime.now() #gets the dat... | Python | nomic_cornstack_python_v1 |
function predict self X
begin
set y_pred = zeros shape at 1
set y_pred = argument maximum dot W axis=1
return y_pred
end function | def predict(self, X):
y_pred = np.zeros(X.shape[1])
y_pred = np.argmax(X.dot(self.W), axis = 1)
return y_pred | Python | nomic_cornstack_python_v1 |
function clear_context self context
begin
set context_dics = call _get_instance_dict context
for tuple element client in items context_dics
begin
call bcp_trigger_client client=client element=element name=format string {}_clear show_section context=context
end
end function | def clear_context(self, context):
context_dics = self._get_instance_dict(context)
for element, client in context_dics.items():
self.machine.bcp.interface.bcp_trigger_client(
client=client,
element=element,
name='{}_clear'.format(self.show_secti... | Python | nomic_cornstack_python_v1 |
comment Author : 5IGI0
comment Github : https://github.com/5IGI0
import json
import uuid
import tempfile
import random
import os.path
import shutil
import requests
import base64
from zipfile import ZipFile
function copy filePath targetPath
begin
with open filePath string rb as fp
begin
with open targetPath string wb as... | # Author : 5IGI0
# Github : https://github.com/5IGI0
import json
import uuid
import tempfile
import random
import os.path
import shutil
import requests
import base64
from zipfile import ZipFile
def copy(filePath, targetPath):
with open(filePath, "rb") as fp:
with open(targetPath, "wb") as fpp:
... | Python | zaydzuhri_stack_edu_python |
comment creates a new user
import rsaved
import sys , re , json , time , os
set __version__ = __version__
if __name__ == string __main__
begin
print string rsaved/ { __version__ } create_user.py
if length argv == 2
begin
set feed_url = argv at 1
end
else
if length argv > 2
begin
print string Usage: argv at 0 string [JS... | # creates a new user
import rsaved
import sys, re, json, time, os
__version__ = rsaved.__version__
if __name__ == "__main__":
print(f'rsaved/{__version__} create_user.py')
if len(sys.argv) == 2:
feed_url = sys.argv[1]
elif len(sys.argv) > 2:
print('Usage:', sys.argv[0], '[JSON feed URL]')
print('Feed URL can... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
string @param root: the root of binary tree @return: the root of the minimum subtree
function findSubtree self root
begin
comment write your code here
set node = none
set totalsum = - maxsize
call helper root
return node
end function
function helper self root
begin
if root is none
begin
return 0
en... | class Solution:
"""
@param root: the root of binary tree
@return: the root of the minimum subtree
"""
def findSubtree(self, root):
# write your code here
self.node = None
self.totalsum = -sys.maxsize
self.helper(root)
return self.node
def helper(sel... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
call reset
end function | def setUp(self):
self.parser.reset() | Python | nomic_cornstack_python_v1 |
function __init__ self x has_label=true feature_size=512 add_eos_tag=true add_bos_tag=true max_seq_len=256 label2index=none
begin
set feature_size = feature_size
set add_eos_tag = add_eos_tag
set add_bos_tag = add_bos_tag
set max_seq_len = max_seq_len
set label2index = label2index
set has_label = has_label
set x = x
se... | def __init__(
self,
x: Union[pd.DataFrame, List[Dict[str, Any]]],
has_label: bool = True,
feature_size: int = 512,
add_eos_tag: bool = True,
add_bos_tag: bool = True,
max_seq_len: int = 256,
label2index: Dict[str, int] = None,
):
self.feature_s... | Python | nomic_cornstack_python_v1 |
function test_teams_id_dynamic_datas_nk_designs_post self
begin
pass
end function | def test_teams_id_dynamic_datas_nk_designs_post(self):
pass | Python | nomic_cornstack_python_v1 |
comment Imports
from pprint import pprint
import csv
from pygeocoder import Geocoder
import sys
import os
comment Documentation: http://github.com/gfairchild/yelpapi
from yelpapi import YelpAPI
comment Defining variables
set output_file = string MexicanAddresses.csv
set consumer_key = string MrJMq067KxJXDJ4htdUQvA
set ... | #Imports
####################
from pprint import pprint
import csv
from pygeocoder import Geocoder
import sys
import os
# Documentation: http://github.com/gfairchild/yelpapi
from yelpapi import YelpAPI
#############
#Defining variables
################
output_file = 'MexicanAddresses.csv'
consumer_key = 'MrJMq0... | Python | zaydzuhri_stack_edu_python |
function get_full_juju_status model_name=none
begin
return call get_full_juju_status model_name=model_name
end function | def get_full_juju_status(model_name=None):
return zaza.utilities.juju.get_full_juju_status(
model_name=model_name) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env/python3
comment -*- coding: utf-8 -*-
from config import *
from Model_demo import Model , Observer
class Controller
begin
function __init__ self theta0 dt
begin
comment param init
comment sample time
set dt = dt
comment adaptive params
set theta0 = theta0
set theta = theta0
set a1 = 1 / m
set a2 =... | #!/usr/bin/env/python3
# -*- coding: utf-8 -*-
from config import *
from Model_demo import Model, Observer
class Controller:
def __init__(self, theta0, dt):
# param init
# sample time
self.dt = dt
# adaptive params
self.theta0 = theta0
self.theta = theta0
... | Python | zaydzuhri_stack_edu_python |
import collections
import string
function is_anagram str1 str2
begin
comment Remove whitespace and convert to lowercase
set str1 = lower call translate call maketrans string string whitespace
set str2 = lower call translate call maketrans string string whitespace
comment Count the frequency of each character in eac... | import collections
import string
def is_anagram(str1, str2):
# Remove whitespace and convert to lowercase
str1 = str1.translate(str.maketrans("", "", string.whitespace)).lower()
str2 = str2.translate(str.maketrans("", "", string.whitespace)).lower()
# Count the frequency of each character in each string... | Python | jtatman_500k |
function find_k arr start end _k
begin
set pivot = arr at start
set tuple left right = tuple start + 1 end
while left < right
begin
while left < end + 1 and arr at left < pivot
begin
set left = left + 1
end
while right > start and arr at right > pivot
begin
set right = right - 1
end
if left < right
begin
set tuple arr ... | def find_k(arr, start, end, _k):
pivot = arr[start]
left, right = start + 1, end
while left < right:
while left < end +1 and arr[left] < pivot:
left += 1
while right > start and arr[right] > pivot:
right -= 1
if left < right:
arr[left], arr[r... | Python | zaydzuhri_stack_edu_python |
for i in range size
begin
set val = integer input string Enter number :
append a val
end
for i in range 1 size
begin
set t = a at i
set j = i - 1
while j >= 0 and t < a at j
begin
set a at j + 1 = a at j
set j = j - 1
end
set a at j + 1 = t
end
print string Sorted list is: a | for i in range(size):
val=int(input(" Enter number :"))
a.append(val)
for i in range(1,size):
t=a[i]
j=i-1
while j>=0 and t<a[j]:
a[j+1]=a[j]
j=j-1
a[j+1]=t
print(" Sorted list is:" ,a)
| Python | zaydzuhri_stack_edu_python |
function simple_command_with_pty self
begin
comment Most Unix systems should have stty, which asplodes when not run
comment under a pty, and prints useful info otherwise
set result = run string stty -a hide=true pty=true
comment PTYs use \r\n, not \n, line separation
assert string in stdout
assert pty is true
end func... | def simple_command_with_pty(self):
# Most Unix systems should have stty, which asplodes when not run
# under a pty, and prints useful info otherwise
result = run("stty -a", hide=True, pty=True)
# PTYs use \r\n, not \n, line separation
assert "\r\n" in result.s... | Python | nomic_cornstack_python_v1 |
while respuesta != string SI
begin
print string Pues vale :C
print pregunta
set respuesta = input string SI / NO:
end
print string ¿Quieres ver algunos documentos de diferentes personas?
set respuesta2 = input string SI / NO:
while respuesta2 != string SI
begin
set respuesta3 = input string ¿Quieres salir (SI / NO): ?
... | while respuesta != "SI":
print("Pues vale :C ")
print(pregunta)
respuesta = input("SI / NO: ")
print("¿Quieres ver algunos documentos de diferentes personas?")
respuesta2 = input("SI / NO: ")
while respuesta2 != "SI":
respuesta3 = input("¿Quieres salir (SI / NO): ?")
if respuesta3 == "NO":
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
comment author: Fangyang time:2017/11/12
function demo1
begin
comment 定义一个局部变量
set num = 10
end function | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# author: Fangyang time:2017/11/12
def demo1():
num = 10 # 定义一个局部变量
| Python | zaydzuhri_stack_edu_python |
function sign_up
begin
set form = call SignUpForm
set data = cookies at string csrf_token
if call validate_on_submit
begin
comment Create user, default program, and default membership records
set user = call User username=data at string username email=data at string email password=data at string password first_name=dat... | def sign_up():
form = SignUpForm()
form['csrf_token'].data = request.cookies['csrf_token']
if form.validate_on_submit():
# Create user, default program, and default membership records
user = User(
username=form.data['username'],
email=form.data['email'],
... | Python | nomic_cornstack_python_v1 |
function test_pwrule_get self
begin
comment the function to be tested:
set password_rule1 = get urihandler hmc string /api/console/password-rules/fake-password-rule-oid-1 true
comment properties reduced to those in std test HMC
set exp_password_rule1 = dict string element-id string fake-password-rule-oid-1 ; string ele... | def test_pwrule_get(self):
# the function to be tested:
password_rule1 = self.urihandler.get(
self.hmc, '/api/console/password-rules/fake-password-rule-oid-1',
True)
exp_password_rule1 = { # properties reduced to those in std test HMC
'element-id': 'fake-pa... | Python | nomic_cornstack_python_v1 |
function test_make_dataset_happy_path self
begin
comment User story: user runs src.make_dataset() on the current directory
comment and gets a fully functional dataset
pass
end function | def test_make_dataset_happy_path(self):
# User story: user runs src.make_dataset() on the current directory
# and gets a fully functional dataset
pass | Python | nomic_cornstack_python_v1 |
function count_unique_characters s
begin
comment Create an empty set to store unique characters
set unique_chars = set
comment Iterate over each character in the input string
for char in s
begin
comment Add the character to the set
add unique_chars char
end
comment Return the number of unique characters
return length u... | def count_unique_characters(s):
# Create an empty set to store unique characters
unique_chars = set()
# Iterate over each character in the input string
for char in s:
# Add the character to the set
unique_chars.add(char)
# Return the number of unique characters
return len(uniqu... | Python | jtatman_500k |
function lasso_regression_GD y tx lambda_ initial_w max_iters gamma
begin
set w = initial_w
for n_iter in range max_iters
begin
set g = call compute_gradient_lasso y tx w lambda_
set w = w - gamma * g
end
set loss = norm y - dot w ^ 2 / 2 * shape at 0 + lambda_ * sum
return tuple w loss
end function | def lasso_regression_GD(y, tx, lambda_, initial_w, max_iters, gamma):
w=initial_w
for n_iter in range(max_iters):
g=compute_gradient_lasso(y,tx,w,lambda_)
w=w-gamma*g
loss=np.linalg.norm(y-tx.dot(w))**2/(2*tx.shape[0])+lambda_*np.absolute(w).sum()
return w,loss | Python | nomic_cornstack_python_v1 |
string Created on 07-Nov-20 @author: Kiril Zelenkovski
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema
from tqdm import tqdm
comment Read dataset
set data = read csv string ../data/EURUSD_01-05_2017.csv
comment Rename columns
set columns = list string date s... | """
Created on 07-Nov-20
@author: Kiril Zelenkovski
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema
from tqdm import tqdm
# Read dataset
data = pd.read_csv('../data/EURUSD_01-05_2017.csv')
# Rename columns
data.columns = ['date', 'open', 'high', '... | Python | zaydzuhri_stack_edu_python |
function to_detach h
begin
return if expression type h == Tensor then detach h else tuple generator expression call to_detach v for v in h
end function | def to_detach(h):
return h.detach() if type(h) == torch.Tensor else tuple(to_detach(v) for v in h) | Python | nomic_cornstack_python_v1 |
function inspect rslt init_dict
begin
comment Antibugging
assert is instance rslt dict
assert is instance init_dict dict
comment Update results
set modified_init = deep copy init_dict
for key_ in keys rslt
begin
if key_ in list string fval string success
begin
continue
end
for subkey in keys rslt at key_
begin
set modi... | def inspect(rslt, init_dict):
# Antibugging
assert (isinstance(rslt, dict))
assert (isinstance(init_dict, dict))
# Update results
modified_init = copy.deepcopy(init_dict)
for key_ in rslt.keys():
if key_ in ['fval', 'success']:
continue
for subkey in rslt[key_].ke... | Python | nomic_cornstack_python_v1 |
import os
from dataclasses import dataclass , field
import pandas as pd
import s3
from utils import unpickle , make_pickle
function format_jira jid
begin
string Transforms jira ID to keep same notation across the project. :param jid: Jira ID (ex: SGDS-123, or OMICS-456_do_something)
set jid = strip lower jid
set jid = ... | import os
from dataclasses import dataclass, field
import pandas as pd
import s3
from utils import unpickle, make_pickle
def format_jira(jid: str) -> str:
"""
Transforms jira ID to keep same notation across the project.
:param jid: Jira ID (ex: SGDS-123, or OMICS-456_do_something)
"""
jid = jid.lo... | Python | zaydzuhri_stack_edu_python |
function value self
begin
return get pulumi self string value
end function | def value(self) -> str:
return pulumi.get(self, "value") | Python | nomic_cornstack_python_v1 |
function event11515495
begin
call header 11515495
call if_event_flag_on 0 DarkSmoughIsSupport
comment Time between intermittent one-off Smough attacks.
call wait_random_seconds 12 17
call end_if_event_flag_on DarkOrnsteinAndSmoughPhaseTwoStarted
call disable_chunk 11515470 11515479
call if_entity_health_less_than_or_eq... | def event11515495():
header(11515495)
if_event_flag_on(0, EVENT.DarkSmoughIsSupport)
wait_random_seconds(12, 17) # Time between intermittent one-off Smough attacks.
end_if_event_flag_on(EVENT.DarkOrnsteinAndSmoughPhaseTwoStarted)
flag.disable_chunk(11515470, 11515479)
if_entity_health_less_... | Python | nomic_cornstack_python_v1 |
function test_skip_fields self
begin
set url = string https://api.fns.tunein.com/v1/json”
set res = call merge_response url
set are_present = false
for i in res
begin
if starts with i string skip
begin
set are_present = true
end
end
assert equal are_present false
end function | def test_skip_fields(self):
url = "https://api.fns.tunein.com/v1/json”"
res = merge_response(url)
are_present = False
for i in res:
if i.startswith("skip"):
are_present = True
self.assertEqual(are_present, False) | Python | nomic_cornstack_python_v1 |
import nltk
import csv
from sklearn.utils import shuffle
comment Selecting seven books from Gutenberg digital books and seven different authors
set book_list = list string austen-emma.txt string bible-kjv.txt string bryant-stories.txt string chesterton-ball.txt string edgeworth-parents.txt string melville-moby_dick.txt... | import nltk
import csv
from sklearn.utils import shuffle
# Selecting seven books from Gutenberg digital books and seven different authors
book_list = ["austen-emma.txt", "bible-kjv.txt",
"bryant-stories.txt", "chesterton-ball.txt",
"edgeworth-parents.txt", "melville-moby_dick.txt",
... | Python | zaydzuhri_stack_edu_python |
for i in p12
begin
set i = integer i
if i % 2 != 0
begin
print i end=string
end
end | for i in p12:
i=int(i)
if(i%2!=0):
print(i,end=" ")
| Python | zaydzuhri_stack_edu_python |
comment Подключить нужные для работы библиотеки
import mcpi.minecraft as minecraft
import mcpi.block as block
comment Создаём Minecraft для соединение и взаимолдействия с игрой
set mc = call create
comment Определяем тякущую позицию игрока
set pos = call getTilePos
comment Введем сколько метров кубических под снос
set ... | # Подключить нужные для работы библиотеки
import mcpi.minecraft as minecraft
import mcpi.block as block
# Создаём Minecraft для соединение и взаимолдействия с игрой
mc = minecraft.Minecraft.create()
# Определяем тякущую позицию игрока
pos = mc.player.getTilePos()
# Введем сколько метров кубических под снос
si... | Python | zaydzuhri_stack_edu_python |
comment Python
string Leetcode Problem #349. Intersection of Two Arrays @author Ishaan Radia @author Harshal Suthar
class Solution
begin
function intersection self nums1 nums2
begin
comment Solution with checking if array is unique
set inter = list
end function
end class | #Python
"""
Leetcode Problem #349. Intersection of Two Arrays
@author Ishaan Radia
@author Harshal Suthar
"""
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
#Solution with checking if array is unique
inter = []
| Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
import os
import sys
import time
import numpy as np
import pdb
class Vocab
begin
function __init__ self vocab_limits=- 1
begin
set _vocab_size = vocab_limits
end function
end class | # -*- coding:utf-8 -*-
import os
import sys
import time
import numpy as np
import pdb
class Vocab():
def __init__(self, vocab_limits = -1):
self._vocab_size = vocab_limits
| Python | zaydzuhri_stack_edu_python |
function plugsAlias self plug
begin
pass
end function | def plugsAlias(self, plug):
pass | Python | nomic_cornstack_python_v1 |
function write_visualization self path
begin
call export_graphviz _learner out_file=format string {}-{}.dot path depth_threshold filled=true rounded=true special_characters=true
with open format string {}-{}.dot path depth_threshold as f
begin
set dot_graph = read f
end
comment graph = graphviz.Source(dot_graph)
commen... | def write_visualization(self, path):
tree.export_graphviz(self._learner, out_file="{}-{}.dot".format(path, self.depth_threshold), filled= True, rounded = True, special_characters = True)
with open("{}-{}.dot".format(path, self.depth_threshold)) as f:
dot_graph = f.read()
# graph = g... | Python | nomic_cornstack_python_v1 |
class MergeError extends Exception
begin
function __init__ self value
begin
set value = value
end function
function __str__ self
begin
return call repr value
end function
end class
function texCommands
begin
string tex commands required for tables Returns ------- tex : str string to put in header of latex file
return s... | class MergeError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def texCommands():
"""tex commands required for tables
Returns
-------
tex : str
string to put in header of latex file
"""
return r'''
\use... | Python | zaydzuhri_stack_edu_python |
function registreren
begin
set gegevens_gebruikers = call csvread string gebruikers.csv
set gegevens_status = 0
set mail_lijst = list
set naam = get naam_entry
set mail = lower get email_entry
set wachtwoord = get wachtwoord_entry
set telefoonnummer = get telefoonnummer_entry
comment controle of mail ingevuld is of ma... | def registreren():
gegevens_gebruikers = csvread("gebruikers.csv")
gegevens_status = 0
mail_lijst = []
naam = naam_entry.get()
mail = email_entry.get().lower()
wachtwoord = wachtwoord_entry.get()
telefoonnummer = telefoonnummer_entry.get()
# controle of mail ingevuld is of mail al ger... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
string Created on Fri May 19 14:15:55 2017 @author: zhangchi
class Solution extends object
begin
comment DP问题
function PredictTheWinner self nums
begin
string :type nums: List[int] :rtype: bool
if length nums == 1
begin
if nums at 0 >= 0
begin
return true
end
... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri May 19 14:15:55 2017
@author: zhangchi
"""
class Solution(object):
# DP问题
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 1:
if nums[0] >= 0:
... | Python | zaydzuhri_stack_edu_python |
function makeBox n
begin
return list comprehension if expression i == 0 or i == n - 1 then string # * n else string # + string * n - 2 + string # for i in range n
end function | def makeBox(n):
return ['#' * n if i == 0 or i == n-1 else '#' + ' ' * (n-2) + '#' for i in range(n)]
| Python | zaydzuhri_stack_edu_python |
function expected_utils self t history reserve
begin
string ****************************** * IMPLEMENTATION STARTS HERE * ******************************
comment we will fill the utilities list
set utilities = list
comment getting the history for the previous round [clicks, num_slots]
set previous_round = round t - 1
se... | def expected_utils(self, t, history, reserve):
"""
******************************
* IMPLEMENTATION STARTS HERE *
******************************
"""
# we will fill the utilities list
utilities= list()
# getting the history for the previous round [c... | Python | nomic_cornstack_python_v1 |
function _to_dict self
begin
string Return a json dictionary representing this model.
set _dict = dict
if has attribute self string scope and scope is not none
begin
set _dict at string scope = scope
end
if has attribute self string status and status is not none
begin
set _dict at string status = status
end
if has att... | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'scope') and self.scope is not None:
_dict['scope'] = self.scope
if hasattr(self, 'status') and self.status is not None:
_dict['status'] = self.status
i... | Python | jtatman_500k |
function main
begin
set acc = 0
with open string input.txt string r as f
begin
for line in f
begin
set line = right strip line string
set num = integer line
set acc = acc + num
print num acc
end
end
print string Answer is acc
end function
call main | def main():
acc = 0
with open('input.txt', 'r') as f:
for line in f:
line = line.rstrip('\n')
num = int(line)
acc += num
print(num, acc)
print('Answer is', acc)
main()
| Python | zaydzuhri_stack_edu_python |
function ner_server
begin
set server = call EntityRecognizerServer minimal_ers_mode=true
call initialize
return server
end function | def ner_server():
server = hu_entity.server.EntityRecognizerServer(minimal_ers_mode=True)
server.initialize()
return server | Python | nomic_cornstack_python_v1 |
function list10 a
begin
if a at length a - 1 == 10
begin
return true
end
else
begin
return false
end
end function
print call list10 list 1 2 3 4 5 6 7 8 9 10 | def list10(a):
if a[len(a)-1] == 10:
return True
else:
return False
print(list10([1,2,3,4,5,6,7,8,9,10])) | Python | zaydzuhri_stack_edu_python |
import tweepy
set consumer_key = string
set consumer_secret = string
set access_token = string
set access_token_secret = string
set auth = call OAuthHandler consumer_key consumer_secret
call set_access_token access_token access_token_secret
set api = call API auth
set public_tweets = search string python
for tweet ... | import tweepy
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
public_tweets = api.search('python')
for tweet in public_tweets:
print(tweet.t... | Python | jtatman_500k |
comment 初级
comment 【注:以下6题功能全部自己实现,不能借助于Python内置函数】
comment 1.自定义一个数字列表,获取这个列表中的最小值,并将列表转化为元组
set list1 = list 2 3 1 5 6 - 7 4
set m = list1 at 0
for n in list1
begin
if n < m
begin
set m = n
end
end
print m
print tuple list1
comment 2.自定义一个数字列表,元素为10个 ,找出列表中最大数连同下标一起输出
set list1 = list 2 3 1 5 6 - 7 4
set m = list1 at... | #
# 初级
# 【注:以下6题功能全部自己实现,不能借助于Python内置函数】
# 1.自定义一个数字列表,获取这个列表中的最小值,并将列表转化为元组
list1 = [2, 3, 1, 5, 6, -7, 4]
m = list1[0]
for n in list1:
if n < m:
m = n
print(m)
print(tuple(list1))
# 2.自定义一个数字列表,元素为10个 ,找出列表中最大数连同下标一起输出
list1 = [2, 3, 1, 5, 6, -7, 4]
m = list1[0]
index = 0
for i in range(... | Python | zaydzuhri_stack_edu_python |
function OnPrivTextMessage self msg
begin
call handle_inbound_irc_msg string OnPrivTextMessage msg
return CONTINUE
end function | def OnPrivTextMessage(self, msg):
self.handle_inbound_irc_msg("OnPrivTextMessage", msg)
return znc.CONTINUE | Python | nomic_cornstack_python_v1 |
function forward self curr_ids end_ids sparse=false indices=none almts=none
begin
comment action_masks: BT,
if sparse and indices is none
begin
raise call TypeError string Must provide `indices` in sparse mode.
end
set state_repr = call enc curr_ids end_ids almts=almts
set hid = call hidden state_repr
if sparse
begin
s... | def forward(self,
curr_ids: LT,
end_ids: LT,
# action_masks: BT,
sparse: bool = False,
indices: Optional[NDA] = None,
almts: Optional[Tuple[LT, LT]] = None):
if sparse and indices is None:
raise TypeError... | Python | nomic_cornstack_python_v1 |
function detect_duplicate_characters string
begin
set chars = set
for char in string
begin
if char in chars
begin
return true
end
add chars char
end
return false
end function | def detect_duplicate_characters(string):
chars = set()
for char in string:
if char in chars:
return True
chars.add(char)
return False | Python | jtatman_500k |
function fetch_mirror self repo body
begin
set url = call _repo_url repo other=string /mirror
set response = get rest url
if status_code is not 200
begin
call fail_json msg=info
end
return info
end function | def fetch_mirror(self, repo, body):
url = self._repo_url(repo, other='/mirror')
response = self.rest.get(url)
if response.status_code is not 200:
self.module.fail_json(msg=response.info)
return response.info | Python | nomic_cornstack_python_v1 |
function calc_position_relative_point data point
begin
set numframe = length data at 0
set tuple x_adj y_adj = tuple zeros tuple numframe 1 zeros tuple numframe 1
for idx in range numframe
begin
set tuple x y = tuple data at 0 at idx data at 1 at idx
set x_adj at idx = point at 0 - x
set y_adj at idx = point at 1 - y
e... | def calc_position_relative_point(data, point):
numframe = len(data[0])
x_adj, y_adj = np.zeros((numframe, 1)), np.zeros((numframe, 1))
for idx in range(numframe):
x,y = data[0][idx], data[1][idx]
x_adj[idx] = point[0] - x
y_adj[idx] = point[1] - y
return x_adj, y_adj | Python | nomic_cornstack_python_v1 |
function _setErrorNodesDict self errorDict
begin
set _errorDict = errorDict
end function | def _setErrorNodesDict(self, errorDict):
self._errorDict = errorDict | Python | nomic_cornstack_python_v1 |
function update_row self table id_col id **params
begin
set query_string = format string UPDATE `{}` SET {} WHERE `{}` = %s table join string , list comprehension format string `{}` = %s k for k in keys params id_col
set p = values params
append p id
query self query_string param_tuple=tuple p
call _commit
end function | def update_row(self, table, id_col, id, **params):
query_string = 'UPDATE `{}` SET {} WHERE `{}` = %s'.format(
table,
', '.join(['`{}` = %s'.format(k) for k in params.keys()]),
id_col,
)
p = params.values()
p.append(id)
self.query(query_strin... | Python | nomic_cornstack_python_v1 |
import os
import numpy as np
class Position
begin
set X = 0
set Y = 0
function __init__ self x y
begin
set X = x
set Y = y
end function
end class
class Report
begin
set Time = 0
set IsBtn = false
set Pos = call Position 0 0
set Width = 0
function __init__ self time is_btn
begin
set Time = time
set IsBtn = is_btn
end fu... | import os
import numpy as np
class Position:
X = 0
Y = 0
def __init__(self, x, y):
self.X = x
self.Y = y
class Report:
Time = 0
IsBtn = False
Pos = Position(0, 0)
Width = 0
def __init__(self, time, is_btn):
self.Time = time
self.IsBtn = is_btn
class Tra... | Python | zaydzuhri_stack_edu_python |
function save self path
begin
set output = call DataFrame dict string composition list comprehension p for c in feed_compositions ; string composition_type list comprehension type for c in feed_compositions ; string partial_flux_1 list comprehension f at 0 for f in partial_fluxes ; string partial_flux_2 list comprehens... | def save(self, path: typing.Union[str, Path]) -> None:
output = pandas.DataFrame(
{
"composition": [c.p for c in self.feed_compositions],
"composition_type": [c.type for c in self.feed_compositions],
"partial_flux_1": [f[0] for f in self.partial_fluxes... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python
comment http://adventofcode.com/2018/day/1
import sys
set input_file_name = argv at 1
with open input_file_name string r as file
begin
set puzzle_input = read file
end
set freq_changes = list map int split strip puzzle_input string
print sum freq_changes
set seen_freqs = dict
set current_... | #! /usr/bin/env python
# http://adventofcode.com/2018/day/1
import sys
input_file_name = sys.argv[1]
with open(input_file_name, 'r') as file:
puzzle_input = file.read()
freq_changes = list(map(int, puzzle_input.strip().split('\n')))
print(sum(freq_changes))
seen_freqs = {}
current_freq = 0
i = 0
freq_index =... | Python | zaydzuhri_stack_edu_python |
comment Create a tuple with your first name, last name, and age. Create a list,
comment people, and append your tuple to it. Make more tuples with the
comment corresponding information from your friends and append them to the
comment list. Sort the list. When you learn about sort method, you can use the
comment key par... | # Create a tuple with your first name, last name, and age. Create a list,
# people, and append your tuple to it. Make more tuples with the
# corresponding information from your friends and append them to the
# list. Sort the list. When you learn about sort method, you can use the
# key parameter to sort by any field in... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Dec 1 20:17:20 2015 @author: Rian
import feature_validation as validation
import feature_extraction as extraction
import image_operations as operations
import data_loading as loader
import util
import numpy
from skimage import color , exposure
from sklearn import lda
... | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 1 20:17:20 2015
@author: Rian
"""
import feature_validation as validation
import feature_extraction as extraction
import image_operations as operations
import data_loading as loader
import util
import numpy
from skimage import color, exposure
from sklearn import lda
from... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
string -- Script allowed to train the Doc2Vec model on data base -- To train it, we use documents, each one taking up one entire line. So, each document should be on one line, separated by new lines. The input to Doc2Vec need to be an iterator of LabeledSenten... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
-- Script allowed to train the Doc2Vec model on data base --
To train it, we use documents, each one taking up one entire line. So, each document should be on one line, separated by new lines.
The input to Doc2Vec need to be an iterator of LabeledSentence objects. Ea... | Python | zaydzuhri_stack_edu_python |
function train_model_multi_output_w_tmt x y param_grid=none n_jobs=- 1 cv=5
begin
if param_grid is none
begin
set param_grid = dictionary num_nodes=list 8 128 dropout=list 0.1 0.25 0.5 activation=list string relu num_layers=list 1 2 epochs=list 50 batch_size=list 400 4000 8000
end
set model = call KerasRegressor build_... | def train_model_multi_output_w_tmt(x, y, param_grid=None, n_jobs=-1, cv=5):
if param_grid is None:
param_grid = dict(num_nodes=[8, 128], dropout=[.1, .25, .5], activation=[
'relu'], num_layers=[1, 2], epochs=[50], batch_size=[400, 4000, 8000])
model = KerasRegressor(
... | Python | nomic_cornstack_python_v1 |
string Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters.
function check_upper_lower_case s
begin
set clean_string = list comprehension e for e in s if is alpha e
set upper_case = length list comprehension e for e in clean_string if is upper e
set lower... | """
Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters.
"""
def check_upper_lower_case(s):
clean_string = [e for e in s if e.isalpha()]
upper_case = len([e for e in clean_string if e.isupper()])
lower_case = len([e for e in clean_string if e.islower(... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.