code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function mode self begin return get pulumi self string mode end function
def mode(self) -> Optional[str]: return pulumi.get(self, "mode")
Python
nomic_cornstack_python_v1
from random import randint from threading import Thread from tkinter import Tk , DoubleVar , HORIZONTAL , messagebox , Label , LEFT from tkinter.ttk import Frame , Button , Progressbar from time import sleep import shutil import os from pathlib import Path import psutil import webbrowser class Worker extends Thread beg...
from random import randint from threading import Thread from tkinter import Tk, DoubleVar, HORIZONTAL, messagebox, Label, LEFT from tkinter.ttk import Frame, Button, Progressbar from time import sleep import shutil import os from pathlib import Path import psutil import webbrowser class Worker(Thread): ...
Python
zaydzuhri_stack_edu_python
function insert hash_table key value begin comment SAME HASH KEY, INSERT IN THE SAME INDEX POSITION comment SAME KEY, REPLACE THE VALUE IN THE INDEX POSITION set hash_key = call hash key % length hash_table print string ********************** print string HASH KEY: hash_key set key_exists = false set bucket = hash_tabl...
def insert(hash_table, key, value): # SAME HASH KEY, INSERT IN THE SAME INDEX POSITION # SAME KEY, REPLACE THE VALUE IN THE INDEX POSITION hash_key = hash(key) % len(hash_table) print("**********************") print("HASH KEY: ", hash_key) key_exists = False bucket = hash_table[hash_key] ...
Python
zaydzuhri_stack_edu_python
function upload_file self local_filename bucket key_object compress=false begin try begin with open local_filename string rb as data begin if compress begin set compressed_io = call BytesIO with call GzipFile fileobj=compressed_io mode=string wb as out_gzp begin call copyfileobj data out_gzp end set key_object = key_ob...
def upload_file(self, local_filename, bucket, key_object, compress=False): try: with open(local_filename, 'rb') as data: if compress: compressed_io = BytesIO() with gzip.GzipFile(fileobj=compressed_io, mode='wb') as out_gzp: ...
Python
nomic_cornstack_python_v1
comment this is a unit test file for our math_func.py file, first we need to import the file which contains the functions comment add test keyword begining of the methods/ units needs to be tested import math_func function test_add begin assert add math_func 7 3 == 10 assert add math_func 7 == 9 assert add math_func 5 ...
# this is a unit test file for our math_func.py file, first we need to import the file which contains the functions # add test keyword begining of the methods/ units needs to be tested import math_func def test_add(): assert math_func.add(7,3)==10 assert math_func.add(7)==9 assert math_func.add(5)==7 ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- import os , cgi , cgitb
#!/usr/bin/python # -*- coding: utf-8 -*- import os, cgi, cgitb
Python
zaydzuhri_stack_edu_python
function checkIfValidMessage self begin set values = dictionary set isReply = isReply if isReply begin comment message is a reply, check if it follows the required format if string tags in values and values at string tags != list begin comment reply shouldn't contain tags return tuple false string A reply shouldn't co...
def checkIfValidMessage(self): values = self.dict() isReply = self.isReply if isReply: # message is a reply, check if it follows the required format if "tags" in values and values["tags"] != []: # reply shouldn't contain tags return False...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment ->str 表示该函数的返回值是str类型的 function demo name age=20 hobbit=string 爱好打篮球 begin print name type name print age type age print hobbit type hobbit return string hello world end function comment 这里的参数1会显示黄色, 但是可以运行不会报错 call demo 1 2 comment 正常显示 call demo strin...
# !/usr/bin/env python # -*- coding: utf-8 -*- def demo(name: str, age: 'int > 0' = 20, hobbit: str = "爱好打篮球") -> str: # ->str 表示该函数的返回值是str类型的 print(name, type(name)) print(age, type(age)) print(hobbit, type(hobbit)) return "hello world" demo(1, 2) # 这里的参数1会显示黄色, 但是可以运行不会报错 demo('小小', 2) # 正常显示 ...
Python
zaydzuhri_stack_edu_python
function answer_msg self context begin set msg = call _get_base_message ANSWER_QUESTION call _add_thread msg call _add_relationship msg for_relationship set response = answer_str return msg end function
def answer_msg(self, context): msg = self._get_base_message(self.ANSWER_QUESTION) self._add_thread(msg) self._add_relationship(msg, self.for_relationship) msg.response = self.answer_str return msg
Python
nomic_cornstack_python_v1
import gpt_2_simple as gpt2 comment Load the GPT-2 model set sess = call start_tf_sess call load_gpt2 sess run_name=string run1 comment Generate a response text set generated_text = call generate sess temperature=0.7 prefix=string I'm feeling sad. length=30 return_as_list=true at 0 comment Print the response print gene...
import gpt_2_simple as gpt2 # Load the GPT-2 model sess = gpt2.start_tf_sess() gpt2.load_gpt2(sess, run_name='run1') # Generate a response text generated_text = gpt2.generate(sess, temperature=0.7, prefix="I'm feeling sad.", length=30, return_as_list=True )[0] # Print the response print(generated_text)
Python
iamtarun_python_18k_alpaca
function stop self begin set stop = now set duration = stop - start set start = stop return duration end function
def stop(self): self.stop = datetime.now() duration = self.stop - self.start self.start = self.stop return duration
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 function init_module bot begin execute cursor string CREATE TABLE IF NOT EXISTS Stomach (id INTEGER PRIMARY KEY AUTOINCREMENT, victim TEXT NOT NULL) call register_command string eat command_eat call register_command string spit command_spit call register_command string vomit command_vomit ...
#!/usr/bin/env python3 def init_module(bot): bot.cursor.execute( "CREATE TABLE IF NOT EXISTS Stomach " "(id INTEGER PRIMARY KEY AUTOINCREMENT, victim TEXT NOT NULL)" ) bot.register_command("eat", command_eat) bot.register_command("spit", command_spit) bot.register_command("v...
Python
zaydzuhri_stack_edu_python
function siblings self begin string :return: a list of this node's sibling nodes. :rtype: NodeList set impl_nodelist = call get_node_children impl_node return call _convert_nodelist list comprehension n for n in impl_nodelist if n != impl_node end function
def siblings(self): """ :return: a list of this node's sibling nodes. :rtype: NodeList """ impl_nodelist = self.adapter.get_node_children(self.parent.impl_node) return self._convert_nodelist( [n for n in impl_nodelist if n != self.impl_node])
Python
jtatman_500k
function has_actor self aid begin string Checks if the given id is used in the host by some actor. :param str. aid: identifier of the actor to check. :return: True if the id is used within the host. set url = string %s://%s/%s % tuple transport netloc aid return url in keys actors end function
def has_actor(self, aid): ''' Checks if the given id is used in the host by some actor. :param str. aid: identifier of the actor to check. :return: True if the id is used within the host. ''' url = '%s://%s/%s' % (self.transport, self.host_url.netloc, aid) return...
Python
jtatman_500k
function update_config_file self begin set config = load yaml open CONFIG_FILENAME Loader=RoundTripLoader set config_template = load yaml open CONFIG_TEMPLATE_FILENAME Loader=Loader if not config begin set config = dict end for tuple key value in items config_template begin call insert_to_config key value config end s...
def update_config_file(self): config = yaml.load(open(utils.CONFIG_FILENAME), Loader=yaml.RoundTripLoader) config_template = yaml.load(open(utils.CONFIG_TEMPLATE_FILENAME), Loader=yaml.Loader) if not config: config = {} for key, value in config_template.items(): self.insert_...
Python
nomic_cornstack_python_v1
function name self name begin set _name = name end function
def name(self, name): self._name = name
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import PontuaTexto as pt comment categoria set palavra = string network set texto = string A lot of security network software made for internet location runs in a thin Linux box set pote = call PontuaTexto palavra texto
#!/usr/bin/env python # -*- coding: utf-8 -*- import PontuaTexto as pt palavra="network" # categoria texto="A lot of security network software made for internet location runs in a thin Linux box " pote = pt.PontuaTexto(palavra, texto)
Python
zaydzuhri_stack_edu_python
import mysql.connector import datetime set dbpw = input string Enter your MySQL database password for the user root set db = call connect host=string localhost user=string root passwd=dbpw set mycursor = call cursor execute mycursor string create database if not exists movies; execute mycursor string USE MOVIES; execut...
import mysql.connector import datetime dbpw=input("Enter your MySQL database password for the user root ") db=mysql.connector.connect( host='localhost', user='root', passwd=dbpw ) mycursor=db.cursor() mycursor.execute("create database if not exists movies;") mycursor.execute("USE MOVIES;") mycursor.execute(...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/python2 comment from __future__ import division import sys import math comment import StringIO comment import re comment import timeit comment import itertools comment sys.stdin = StringIO.StringIO("4\n9 0123456789 oF8\nFoo oF8 0123456789\n13 0123456789abcdef 01\nCODE O!CDE? A?JM!.\n") comment sys.st...
#! /usr/bin/python2 # from __future__ import division import sys import math # import StringIO # import re # import timeit # import itertools # sys.stdin = StringIO.StringIO("4\n9 0123456789 oF8\nFoo oF8 0123456789\n13 0123456789abcdef 01\nCODE O!CDE? A?JM!.\n") # sys.stdin = StringIO.StringIO("1\nelcomew elcome to co...
Python
zaydzuhri_stack_edu_python
function get_db begin set db = get attribute g string _database none if db is none begin set db = call connect DATABASE set _database = call connect DATABASE set row_factory = make_dicts end return db end function
def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) db.row_factory = make_dicts return db
Python
nomic_cornstack_python_v1
import requests set user = input string Nombre de usuario: set payload = dict string username user set r = get requests string https://fortnite-public-api.theapinetwork.com/prod09/users/id params=payload if status_code == 200 begin set doc = json r print string uid string - doc at string uid print string username strin...
import requests user = input ("Nombre de usuario: " ) payload = {'username' : user} r=requests.get('https://fortnite-public-api.theapinetwork.com/prod09/users/id', params=payload) if r.status_code == 200: doc=r.json() print ("uid","-", doc ["uid"]) print ("username","-",doc ["username"]) print ("pla...
Python
zaydzuhri_stack_edu_python
function user_info self begin set user_info = call get_user_by_session return user_info end function
def user_info(self): user_info = self.auth.get_user_by_session() return user_info
Python
nomic_cornstack_python_v1
function lookup_semantic_areas semantic_areas use_case_ontology begin comment search for list of semantic areas if type semantic_areas == list begin set rows = loc at call isin semantic_areas at list string iri string label string semantic_area_label end else begin comment search for single semantic area set rows = loc...
def lookup_semantic_areas(semantic_areas, use_case_ontology): if type(semantic_areas) == list: # search for list of semantic areas rows = use_case_ontology.loc[use_case_ontology['semantic_area_label'].isin(semantic_areas)][ ['iri', 'label', 'semantic_area_label']] else: # ...
Python
nomic_cornstack_python_v1
function install_biolinux target=none begin call _check_version call _setup_environment set tuple pkg_install lib_install = call _read_main_config if target is none or target == string packages begin if distribution in list string ubuntu begin call _setup_apt_sources call _setup_apt_automation call _add_apt_gpg_keys ca...
def install_biolinux(target=None): _check_version() _setup_environment() pkg_install, lib_install = _read_main_config() if target is None or target == "packages": if env.distribution in ["ubuntu"]: _setup_apt_sources() _setup_apt_automation() _add_apt_gpg_keys...
Python
nomic_cornstack_python_v1
function _update self **kwargs begin string Use separate URL for updating the source file. if string content in kwargs begin set content = pop kwargs string content set path = call _construct_path_to_source_content put path dumps dict string content content end call _update keyword kwargs end function
def _update(self, **kwargs): """Use separate URL for updating the source file.""" if 'content' in kwargs: content = kwargs.pop('content') path = self._construct_path_to_source_content() self._http.put(path, json.dumps({'content': content})) super(Resource, sel...
Python
jtatman_500k
function sample_paths S0 N u d q M begin comment M sample paths at once set value = S0 * ones tuple M 1 set paths = zeros tuple M N + 1 set paths at tuple slice : : 0 = value at tuple slice : : 0 comment time steps for i in array range 1 N + 1 1 begin set random_values = call rvs size=tuple M 1 p=q set up_moves =...
def sample_paths(S0, N, u, d, q, M): value = S0*np.ones((M,1)) # M sample paths at once paths = np.zeros((M, N+1)) paths[:,0] = value[:,0] for i in np.arange(1, N+1,1): # time steps random_values = bernoulli.rvs(size=(M,1),p=q) up_moves = random_values*u down_moves = -1*(random_v...
Python
nomic_cornstack_python_v1
function from_dict cls _dict begin set args = dict if string result in _dict begin set args at string result = call from_dict get _dict string result end else begin raise call ValueError string Required property 'result' not present in TrueClientIpResp JSON end if string success in _dict begin set args at string succe...
def from_dict(cls, _dict: Dict) -> 'TrueClientIpResp': args = {} if 'result' in _dict: args['result'] = TrueClientIpRespResult.from_dict(_dict.get('result')) else: raise ValueError('Required property \'result\' not present in TrueClientIpResp JSON') if 'success' i...
Python
nomic_cornstack_python_v1
with open string review.inp string r as f begin set line = read f set tuple a b c = map int split line string end set time = min a b c with open string review.out string w as f begin write f time end
with open('review.inp','r') as f: line = f.read() a,b,c = map(int,line.split(' ')) time = min(a,b,c) with open('review.out','w') as f: f.write(time)
Python
zaydzuhri_stack_edu_python
function extract_umi input_fq output_fq begin set pattern = string .{15}.*(?P<discard_1>%s){s<=2}(?P<umi_1>.{12})(?P<discard_2>.*) % PRE_UMI_ADAPTER set logfile = output_fq + string .log set args = format string extract -I {infq} -S {outfq} -L {log} --extract-method='regex' --bc-pattern '{pattern}' infq=input_fq outfq=...
def extract_umi(input_fq, output_fq): pattern = ".{15}.*(?P<discard_1>%s){s<=2}(?P<umi_1>.{12})(?P<discard_2>.*)" % PRE_UMI_ADAPTER logfile = output_fq+'.log' args = "extract -I {infq} -S {outfq} -L {log} \ --extract-method='regex' \ --bc-pattern '{pattern}...
Python
nomic_cornstack_python_v1
function test_is_url_from_local_instance_returns_false_if_url_is_not_from_local_instance self begin comment Arrange / Act set return_value = call is_url_from_local_instance comment Assert assert equal return_value false end function
def test_is_url_from_local_instance_returns_false_if_url_is_not_from_local_instance( self, ): # Arrange / Act return_value = BlobDownloader( "http://google.com" ).is_url_from_local_instance() # Assert self.assertEqual(return_value, False)
Python
nomic_cornstack_python_v1
from PyQt5.QtWidgets import QApplication , QPushButton set app = call QApplication list set btn = call QPushButton string Close call connect closeAllWindows show
from PyQt5.QtWidgets import QApplication, QPushButton app = QApplication([]) btn = QPushButton('Close') btn.clicked.connect(QApplication.closeAllWindows) btn.show()
Python
flytech_python_25k
import csv set fileName = string Feb17/Feb 17 - Tampa to Cleveland Part 1 errors.csv with open fileName string rU as f begin set reader = reader f set your_list = list reader end comment print your_list, len (your_list) comment get rid of the first line if it doesn't start with a user if string property in your_list at...
import csv fileName = 'Feb17/Feb 17 - Tampa to Cleveland Part 1 errors.csv' with open(fileName, 'rU') as f: reader = csv.reader(f) your_list = list(reader) #print your_list, len (your_list) # get rid of the first line if it doesn't start with a user if "property" in your_list[0][0]: your_list = your_list...
Python
zaydzuhri_stack_edu_python
function __init__ self request params model model_admin begin call __init__ request params model model_admin if boundaries is none or length boundaries < 2 begin raise call ValueError format string The range filter '{}' does not specify at least 2 items in 'boundaries'. __name__ end if filter_on is none begin set filte...
def __init__(self, request, params, model, model_admin): super().__init__(request, params, model, model_admin) if self.boundaries is None or len(self.boundaries) < 2: raise ValueError( "The range filter '{}' does not specify at least " "2 items in 'boundaries'...
Python
nomic_cornstack_python_v1
function rotate2 self nums k begin set foo = copy nums set arrayLength = length nums for i in range arrayLength begin set index = i + k % arrayLength set foo at index = nums at i end for j in range arrayLength begin set nums at j = foo at j end end function
def rotate2(self, nums, k) -> None: foo = nums.copy() arrayLength= len(nums) for i in range(arrayLength): index = (i+k) % arrayLength foo[index] = nums[i] for j in range(arrayLength): nums[j] = foo[j]
Python
nomic_cornstack_python_v1
function test_get_all_ids_none self begin set id_store = call IdStore TEST_FILENAME assert is none call get_all_ids end function
def test_get_all_ids_none(self): id_store = IdStore(self.TEST_FILENAME) self.assertIsNone(id_store.get_all_ids())
Python
nomic_cornstack_python_v1
import websockets import asyncio import threading function worker loop port callback begin call set_event_loop loop comment https://pypi.org/project/websockets/ async function echo websocket path begin async_for message in websocket begin call callback message comment print("wsserve.py revceived message", message) comm...
import websockets import asyncio import threading def worker(loop, port, callback): asyncio.set_event_loop(loop) # https://pypi.org/project/websockets/ async def echo(websocket, path): async for message in websocket: callback(message) #print("wsserve.py revceived message", ...
Python
zaydzuhri_stack_edu_python
import numpy as np from random import shuffle function softmax_loss_naive W X y reg begin string Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy...
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X:...
Python
zaydzuhri_stack_edu_python
import sys import cx_Oracle import re from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class RegisterWindow extends QWidget begin function __init__ self parent begin call __init__ parent set pp = parent set width = 1100 set height = 730 comment self.oImage = QImage("E:\pythonStudy\ottr...
import sys import cx_Oracle import re from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class RegisterWindow(QWidget): def __init__(self, parent): super().__init__(parent) self.pp = parent self.width = 1100 self.height = 730 ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np set dataset = read csv string monthlyexp vs incom.csv set X = values set y = values from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeRegressor set tuple x_train x_test y_train y_test = train test split X y random_state=0 test_size=0.2 set l...
import pandas as pd import numpy as np dataset=pd.read_csv("monthlyexp vs incom.csv") X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeRegressor x_train,x_test,y_train,y_test=train_test_split(X,y,...
Python
zaydzuhri_stack_edu_python
import argparse comment Create a text file with the .tex format which makes a parallel between HYP et HYP with LM comment output file containing: comment Ref: & tʰi˩˥ le˧qæ˧˥ mv̩˩mɤ\hl{˩}tʰɑ˥dʑo˩ tʰi˩˥ hĩ˧ɳɯ˩ le˧wo˧˥ ə˧mv̩˧ki˥ \\ comment Hyp: & tʰi˩˥ le˧qæ˧˥ mv̩˩ mɤ\hl{˧}tʰɑ˥dʑo˩ tʰi˩˥ hĩ˧ɳɯ˩ le˧wo˧˥ ə˧mv̩˧ki˥ \\ com...
import argparse # Create a text file with the .tex format which makes a parallel between HYP et HYP with LM # output file containing: # Ref: & tʰi˩˥ le˧qæ˧˥ mv̩˩mɤ\hl{˩}tʰɑ˥dʑo˩ tʰi˩˥ hĩ˧ɳɯ˩ le˧wo˧˥ ə˧mv̩˧ki˥ \\ # Hyp: & tʰi˩˥ le˧qæ˧˥ mv̩˩ mɤ\hl{˧}tʰɑ˥dʑo˩ tʰi˩˥ hĩ˧ɳɯ˩ le˧wo˧˥ ə˧mv̩˧ki˥ \\ # Ref: & tʰi˩˥ le˧qæ˧˥ mv...
Python
zaydzuhri_stack_edu_python
function deserialize self str begin try begin if header is none begin set header = call Header end if drag_force is none begin set drag_force = call Vector3Ext end set end = 0 set _x = self set start = end set end = end + 12 set tuple seq secs nsecs = call unpack str at slice start : end : set start = end set end = end...
def deserialize(self, str): try: if self.header is None: self.header = std_msgs.msg.Header() if self.drag_force is None: self.drag_force = fssim_common.msg.Vector3Ext() end = 0 _x = self start = end end += 12 (_x.header.seq, _x.header.stamp.secs, _x.header.s...
Python
nomic_cornstack_python_v1
function tick_to_time self tick begin comment Check that the tick isn't too big if tick >= MAX_TICK begin raise call IndexError string Supplied tick is too large. end comment If we haven't compute the mapping for a tick this large, compute it if tick >= length __tick_to_time begin call _update_tick_to_time tick end com...
def tick_to_time(self, tick): # Check that the tick isn't too big if tick >= MAX_TICK: raise IndexError('Supplied tick is too large.') # If we haven't compute the mapping for a tick this large, compute it if tick >= len(self.__tick_to_time): self._update_tick_to_t...
Python
nomic_cornstack_python_v1
function remove self block begin remove chain block end function
def remove(self, block): self.chain.remove(block)
Python
nomic_cornstack_python_v1
comment create by fanfan on 2018/11/9 0009 import numpy as np import random class Grid_Mdp_Id begin function __init__ self initial_state=none begin set states = list 1 2 3 4 5 6 7 8 set terminal_states = dict set terminal_states at 6 = 1 set terminal_states at 7 = 1 set terminal_states at 8 = 1 set current_state = 1 i...
# create by fanfan on 2018/11/9 0009 import numpy as np import random class Grid_Mdp_Id: def __init__(self,initial_state = None): self.states = [1,2,3,4,5,6,7,8] self.terminal_states = {} self.terminal_states[6] = 1 self.terminal_states[7] = 1 self.terminal_states[8] = 1 ...
Python
zaydzuhri_stack_edu_python
function groupParamsBySize File paramsToGroupBySize has_cycles begin set p1 = paramsToGroupBySize at 0 set p2 = paramsToGroupBySize at 1 if has_cycles begin for cycle in call getCycleRange File begin set v1 = call getValue File p1 cycle set v2 = call getValue File p2 cycle if v1 > v2 begin call swapValues File tuple p1...
def groupParamsBySize(File, paramsToGroupBySize, has_cycles): p1 = paramsToGroupBySize[0] p2 = paramsToGroupBySize[1] if has_cycles: for cycle in getCycleRange(File): v1 = getValue(File, p1, cycle) v2 = getValue(File, p2, cycle) if v1 > v2: swapVal...
Python
nomic_cornstack_python_v1
function url_quote_part s safechars=string / encoding=none begin if is instance s unicode begin if encoding is none begin set encoding = url_encoding end set s = encode s encoding string ignore end return quote s safechars end function
def url_quote_part(s, safechars='/', encoding=None): if isinstance(s, unicode): if encoding is None: encoding = url_encoding s = s.encode(encoding, 'ignore') return urllib.quote(s, safechars)
Python
nomic_cornstack_python_v1
function moveBall self begin comment move ball one step set vx = call get_vx set vy = call get_vy set x = x + vx set y = y + vy comment COLLISIONS if vy > 0 begin set balltop = y + BALL_DIAMETER if balltop >= GAME_HEIGHT begin call set_vy - vy end if call _getCollidingObject != none and call _getCollidingObject != _pad...
def moveBall(self): #move ball one step vx = self._ball.get_vx() vy = self._ball.get_vy() self._ball.x = self._ball.x + vx self._ball.y = self._ball.y + vy #COLLISIONS if vy > 0: balltop = self._ball.y + BALL_DIAMETER if b...
Python
nomic_cornstack_python_v1
comment ch15_4.py import cv2 set src = call imread string easy.jpg comment 影像轉成灰階 set src_gray = call cvtColor src COLOR_BGR2GRAY comment 二值化處理影像 set tuple ret dst_binary = call threshold src_gray 127 255 THRESH_BINARY comment 找尋影像內的輪廓 set tuple contours hierarchy = call findContours dst_binary RETR_EXTERNAL CHAIN_APPR...
# ch15_4.py import cv2 src = cv2.imread("easy.jpg") src_gray = cv2.cvtColor(src,cv2.COLOR_BGR2GRAY) # 影像轉成灰階 # 二值化處理影像 ret, dst_binary = cv2.threshold(src_gray,127,255,cv2.THRESH_BINARY) # 找尋影像內的輪廓 contours, hierarchy = cv2.findContours(dst_binary, cv2.RETR_EXTERNAL, cv2...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[5]: import pandas as pd import numpy as mp import argparse import os comment In[ ]: set parser = call ArgumentParser call add_argument string -tp string --targetpath type=str default=none help=string where the total csv is call add_argument string -sp string...
#!/usr/bin/env python # coding: utf-8 # In[5]: import pandas as pd import numpy as mp import argparse import os # In[ ]: parser = argparse.ArgumentParser() # parser.add_argument('-tp','--targetpath', type =str ,default = None, help = 'where the total csv is' ) parser.add_argument('-sp','--savepath', type =str ,...
Python
zaydzuhri_stack_edu_python
comment !/bin/python import sys set n = integer strip call raw_input set A = map int split strip call raw_input string set minDist = 100000000 for i in range n begin for j in range i + 1 n begin if A at i == A at j begin set dist = j - i if dist < minDist begin set minDist = dist end end end end
#!/bin/python import sys n = int(raw_input().strip()) A = map(int,raw_input().strip().split(' ')) minDist = 100000000 for i in range(n): for j in range(i+1,n): if A[i]==A[j]: dist = j-i if dist<minDist: minDist=dist
Python
zaydzuhri_stack_edu_python
while true begin append numerosLista integer input string Digite um número: set resposta = upper string input string Você deseja continuar? [S/N] if resposta == string N begin break end end set numerosListaContrario = sorted numerosLista reverse=true print string Você digitou { length numerosLista } elementos print str...
while True: numerosLista.append(int(input('Digite um número: '))) resposta = str(input('Você deseja continuar? [S/N] ')).upper() if resposta == 'N': break numerosListaContrario = sorted(numerosLista, reverse = True) print(f'Você digitou {len(numerosLista)} elementos') print(f'Os valores em ordem d...
Python
zaydzuhri_stack_edu_python
function do_s3_static_url parser token begin return call do_s3_media_url parser token static=true end function
def do_s3_static_url(parser, token): return do_s3_media_url(parser, token, static=True)
Python
nomic_cornstack_python_v1
from entities import * from datetime import timedelta , datetime import pygame , math class Projectile extends Entity begin string speed is a 2d array [x, y] function __init__ self rect speed owner damage=1 begin call __init__ self rect set xSpeed = speed at 0 set ySpeed = speed at 1 set destroy_on_collide = true set t...
from entities import * from datetime import timedelta,datetime import pygame, math class Projectile(Entity): '''speed is a 2d array [x, y]''' def __init__(self, rect, speed, owner, damage=1): Entity.__init__(self, rect) self.xSpeed = speed[0] self.ySpeed = speed[1] self.destroy_on_collide = True self.tota...
Python
zaydzuhri_stack_edu_python
function score self data begin set total_sentences = length data function num_food_sentences prev sentence begin if call _sentence_contains_food_word sentence begin return prev + 1 end else begin return prev end end function set food_sentences = reduce num_food_sentences data 0 return tuple food_sentences / total_sente...
def score(self, data): total_sentences = len(data) def num_food_sentences(prev, sentence): if self._sentence_contains_food_word(sentence): return prev + 1 else: return prev food_sentences = reduce(num_food_sentences, data, 0) retu...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python from scipy.spatial.distance import pdist import numpy as np import math import numpy.linalg as linalg from metrics import * from sklearn.cross_validation import KFold function getMembership x data labels label begin set class_examples = data at call ix_ labels == label set mean = mean np class_...
#!/usr/bin/python from scipy.spatial.distance import pdist import numpy as np import math import numpy.linalg as linalg from metrics import * from sklearn.cross_validation import KFold def getMembership(x, data, labels, label): class_examples = data[np.ix_(labels == label)] mean = np.mean(class_examples,axis=...
Python
zaydzuhri_stack_edu_python
from tensorflow.keras.layers import Layer import tensorflow_probability as tfp import tensorflow as tf class RobustScaler extends Layer begin function __init__ self unit_variance=false begin set q_min = 25.0 set q_max = 75.0 set qs = call convert_to_tensor list 25 50 75 set unit_variance = unit_variance call __init__ e...
from tensorflow.keras.layers import Layer import tensorflow_probability as tfp import tensorflow as tf class RobustScaler(Layer): def __init__(self, unit_variance=False): self.q_min = 25.0 self.q_max = 75.0 self.qs = tf.convert_to_tensor([25, 50, 75]) self.unit_variance = unit_vari...
Python
zaydzuhri_stack_edu_python
import json import requests from nba_py import player string Gets player id, given first name and last name Last name is NOT required function get_player_id first_name last_name=none begin comment print("first name is " + first_name) comment print("last name is " + last_name) comment if last_name is not None: try begin...
import json import requests from nba_py import player """ Gets player id, given first name and last name Last name is NOT required """ def get_player_id(first_name, last_name=None): # print("first name is " + first_name) # print("last name is " + last_name) # if last_name is not None: try: pl...
Python
zaydzuhri_stack_edu_python
function post self title begin set data_dict = call get_json set data_dict at string title = title set response = dict string success 200 try begin call build_document data_dict end except InvalidDataException begin set response = call error_document string Bad request format, missing 'content' key end return response ...
def post(self, title: str) -> None: data_dict = request.get_json() data_dict['title'] = title response = {'success': 200} try: self.document_builder.build_document(data_dict) except InvalidDataException: response = error_document( "Bad req...
Python
nomic_cornstack_python_v1
function query self query timeout=none begin if call _dynamicResponseRequired name begin return call succeed call _doDynamicResponse query end return call fail call DomainError end function
def query(self, query, timeout=None): if self._dynamicResponseRequired(query.name.name): return defer.succeed(self._doDynamicResponse(query)) return defer.fail(error.DomainError())
Python
nomic_cornstack_python_v1
from selenium import webdriver import time comment 뷰티풀수프 임포트 from bs4 import BeautifulSoup comment 웹 드라이버 활성화 및 알라딘 홈페이지 이동. set driver = call Chrome string C:\Users\admin\Desktop\java\github_up\python_practice\crawling\chromedriver.exe get driver string https://www.aladin.co.kr sleep 1.5 comment 베스트셀러 탭 클릭 call click ...
from selenium import webdriver import time # 뷰티풀수프 임포트 from bs4 import BeautifulSoup # 웹 드라이버 활성화 및 알라딘 홈페이지 이동. driver = webdriver.Chrome(r'C:\Users\admin\Desktop\java\github_up\python_practice\crawling\chromedriver.exe') driver.get('https://www.aladin.co.kr') time.sleep(1.5) # 베스트셀러 탭 클릭 driver.find_element_by_xpat...
Python
zaydzuhri_stack_edu_python
function get_first_egress_interface_for_nodes self node1 node2 begin set interfaces = call get_egress_interfaces_name_for_nodes node1 node2 if not interfaces begin raise call RuntimeError string No egress interface for nodes end return interfaces at 0 end function
def get_first_egress_interface_for_nodes(self, node1, node2): interfaces = self.get_egress_interfaces_name_for_nodes(node1, node2) if not interfaces: raise RuntimeError(u"No egress interface for nodes") return interfaces[0]
Python
nomic_cornstack_python_v1
function getProvider client begin if not client begin raise call ValueError string Failed to initialize with empty client end set clientType = call getClientType set queryClass = get __queryClassByClientType clientType if not queryClass begin raise call InitException string Query class was not found end return call que...
def getProvider(client): if not client: raise ValueError('Failed to initialize with empty client') clientType = client.getClientType() queryClass = __queryClassByClientType.get(clientType) if not queryClass: raise InitException('Query class was not found') return queryClass(client)
Python
nomic_cornstack_python_v1
function start_cm_agent root_pass hosts=call read_host_file begin set err_hosts = list for h in hosts begin set ssh = call ssh_connect h ssh_port username root_pass call exec_command string chmod a+x %s/etc/init.d/cloudera-scm-agent % CMF_ROOT set tuple stdin stdout stderr = call exec_command string %s/etc/init.d/clou...
def start_cm_agent(root_pass, hosts = read_host_file()): err_hosts = [] for h in hosts: ssh = ssh_connect(h, ssh_port, username, root_pass) ssh.exec_command('chmod a+x %s/etc/init.d/cloudera-scm-agent' % CMF_ROOT) stdin, stdout, stderr = ssh.exec_command('%s/etc/init.d/cloudera-scm-agent...
Python
nomic_cornstack_python_v1
function test_get_currency_info mocker expected_response expected_data client begin patch string requests.Session.request return_value=expected_response set actual_data = call get_currency_info currency_id=1 assert actual_data == expected_data end function
def test_get_currency_info(mocker, expected_response, expected_data, client) -> None: mocker.patch("requests.Session.request", return_value=expected_response) actual_data = client.get_currency_info(currency_id=1) assert actual_data == expected_data
Python
nomic_cornstack_python_v1
if __name__ == string __main__ begin comment Task 1 string Make a program that has some sentence (a string) on input and returns a dict containing all unique words as keys and the number of occurrences as values. set sentence = string It was a bright cold day in April and the clocks were striking thirteen set words_in_...
if __name__ == '__main__': # Task 1 """ Make a program that has some sentence (a string) on input and returns a dict containing all unique words as keys and the number of occurrences as values. """ sentence = "It was a bright cold day in April and the clocks were striking thirteen" words...
Python
zaydzuhri_stack_edu_python
function transform self X begin set output = copy X if columns is not none begin for col in columns begin set output at col = fit transform call LabelEncoder output at col end end else begin for tuple colname col in call iteritems begin set output at colname = fit transform call LabelEncoder col end end return output e...
def transform(self, X): output = X.copy() if self.columns is not None: for col in self.columns: output[col] = LabelEncoder().fit_transform(output[col]) else: for colname, col in output.iteritems(): output[colname] = LabelEncoder().fit_trans...
Python
nomic_cornstack_python_v1
import random import kivy import win32com.client as win from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.gridlayout import GridLayout from kivy.lang.builder import Builder from kivy.properties import NumericProperty , ReferenceListProperty , ObjectProperty , StringProperty from kivy.c...
import random import kivy import win32com.client as win from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.gridlayout import GridLayout from kivy.lang.builder import Builder from kivy.properties import ( NumericProperty, ReferenceListProperty, ObjectProperty, StringProperty ) f...
Python
zaydzuhri_stack_edu_python
import discord import os from discord.ext import commands import random class Fun extends Cog begin function __init__ self bot res logger begin set bot = bot set res = res set logger = logger set lastForemanCmdCaller = none end function decorator call command name=string 99 help=string Responds with a random quote from...
import discord import os from discord.ext import commands import random class Fun(commands.Cog): def __init__(self, bot, res, logger): self.bot = bot self.res = res self.logger = logger self.lastForemanCmdCaller = None @commands.command(name='99', help='Responds with a random ...
Python
zaydzuhri_stack_edu_python
function deactivate object_ begin set color = array list 1 0 0 end function
def deactivate(object_): object_.color = np.array([1, 0, 0])
Python
nomic_cornstack_python_v1
if x > 0 begin set answer = 1 end else if x < 0 begin set answer = - 1 end else begin set answer = 0 end print string sign(x) = answer
if x > 0: answer = 1 elif x<0: answer = -1 else: answer = 0 print("sign(x) = ", answer)
Python
zaydzuhri_stack_edu_python
function report_model_F self begin print string h k qx qz q model F for tuple a b c d e f g in zip h k qx qz q call _model F begin print format string {0: 1d} {1: 1d} {2: .3f} {3: .3f} {4: .3f} {5: 7.2f} {6: 7.2f} a b c d e f g end end function
def report_model_F(self): print(" h k qx qz q model F") for a, b, c, d, e, f, g in zip(self.h, self.k, self.qx, self.qz, self.q, self._model(), self.F): print("{0: 1d} {1: 1d} {2: .3f} {3: .3f} {4: .3f} {5: 7.2f} {6: 7.2f}" .format(a,...
Python
nomic_cornstack_python_v1
function add_features df_in rolling_win_size=15 begin set sensor_cols = list set index = call get_loc string TTF for i in columns at slice 2 : index : begin append sensor_cols i end set sensor_av_cols = list comprehension nm + string _av for nm in sensor_cols set sensor_sd_cols = list comprehension nm + string _sd fo...
def add_features(df_in, rolling_win_size=15): sensor_cols = [] index = df_in.columns.get_loc('TTF') for i in df_in.columns[2:index]: sensor_cols.append(i) sensor_av_cols = [nm+'_av' for nm in sensor_cols] sensor_sd_cols = [nm+'_sd' for nm in sensor_cols] df_out = pd.DataFrame() w...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Tue Aug 17 10:31:19 2021 @author: siddharthgehlot comment Linked List class Node begin function __init__ self data begin set data = data set next = none end function end class class LinkedList begin function __init__ self begin set head = non...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 17 10:31:19 2021 @author: siddharthgehlot """ # Linked List class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None #in...
Python
zaydzuhri_stack_edu_python
function coefficients self force_characters=false begin raise NotImplementedError end function
def coefficients(self, force_characters = False) : raise NotImplementedError
Python
nomic_cornstack_python_v1
function _create_address address_data=none anonymous=false begin if address_data is none begin set address_data = copy VALID_ADDRESS end if anonymous and is_authenticated begin call logout end if not anonymous begin call force_login user end set response = post path=reverse string user:address_list data=address_data re...
def _create_address(address_data: Optional[Dict] = None, anonymous: bool = False): if address_data is None: address_data = VALID_ADDRESS.copy() if anonymous and user.is_authenticated: client.logout() if not anonymous: client.force_login(user) respons...
Python
nomic_cornstack_python_v1
for i in range M begin set tuple num res = split input string set num = integer num - 1 if num not in ac_set begin if res == string AC begin set ac_cnt = ac_cnt + 1 set wa_cnt = wa_cnt + wa_cnt_list at num add ac_set num end else begin set wa_cnt_list at num = wa_cnt_list at num + 1 end end end print ac_cnt wa_cnt
for i in range(M): num, res = input().split(' ') num = int(num) - 1 if num not in ac_set: if res == 'AC': ac_cnt += 1 wa_cnt += wa_cnt_list[num] ac_set.add(num) else: wa_cnt_list[num] += 1 print(ac_cnt, wa_cnt)
Python
zaydzuhri_stack_edu_python
import numpy as np import math function InputPoint Point Start NbPoint begin for i in range NbPoint begin set tuple Point at i at 0 Point at i at 1 = map float split input string Titik ke-%d : % i + 1 string , set Start at i = Point at i end end function function Translate Point dx dy NbPoint begin for i in range NbPoi...
import numpy as np import math def InputPoint(Point, Start, NbPoint) : for i in range (NbPoint) : Point[i][0], Point[i][1] = map(float, input('Titik ke-%d : ' %(i+1)).split(',')) Start[i] = Point[i] def Translate(Point, dx, dy, NbPoint) : for i in range (NbPoint) : Point[i][0] += dx ...
Python
zaydzuhri_stack_edu_python
from flask import current_app , json class TestAPI extends object begin function test_success self client begin string test main endpoint, should always return 200 if route is right set route = config at string ROUTE_SUCCESS set response = get client route set req = post route assert status_code == 200 msg string route...
from flask import current_app, json class TestAPI(object): def test_success(self, client): """ test main endpoint, should always return 200 if route is right """ route = current_app.config['ROUTE_SUCCESS'] response = client.get(route) req = client.post(route) ...
Python
zaydzuhri_stack_edu_python
string Cracking the Coding Interview When given an int, return the int value phrased in English. Eg 1320 Two Thousand Three Hundred Twenty (no "ands" required) comment ws -> wordset function english_phrasing ws begin set dict_nums_1 = dict string one 1 ; string two 2 ; string three 3 ; string four 4 ; string five 5 ; s...
""" Cracking the Coding Interview When given an int, return the int value phrased in English. Eg 1320 Two Thousand Three Hundred Twenty (no "ands" required) """ # ws -> wordset def english_phrasing(ws): dict_nums_1 = { "one": 1, "two": 2, "three": 3, "four": 4, "five":...
Python
zaydzuhri_stack_edu_python
comment search.py comment --------- comment Licensing Information: You are free to use or extend these projects for comment educational purposes provided that (1) you do not distribute or publish comment solutions, (2) you retain this notice, and (3) you provide clear comment attribution to UC Berkeley, including a lin...
# search.py # --------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # A...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 set DRIVER_APP_GEOFENCE_DISTANCE_MOTORCYCLE_DEFAULT = 600.0 set DRIVER_APP_GEOFENCE_DISTANCE_DEFAULT = 743.59 set DRIVER_APP_GEOFENCE_DISTANCE_VAN = 1500.0 set TRANSPORT_TYPE_MOTORCYCLE = string motocycle set TRANSPORT_TYPE_BICYCLE = string bike set TRANSPORT_TYPE_VAN = string van set TRANSPORT_TY...
# coding: utf-8 DRIVER_APP_GEOFENCE_DISTANCE_MOTORCYCLE_DEFAULT = 600.0 DRIVER_APP_GEOFENCE_DISTANCE_DEFAULT = 743.59 DRIVER_APP_GEOFENCE_DISTANCE_VAN = 1500.0 TRANSPORT_TYPE_MOTORCYCLE = 'motocycle' TRANSPORT_TYPE_BICYCLE = 'bike' TRANSPORT_TYPE_VAN = 'van' TRANSPORT_TYPE_CAR = 'car' def get_checkin_geofence_radiu...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python string Stylesheet Processor Usage: yasp graph <input-directory> <template-file-name> <output-directory> <output-file-name> yasp open <file-name> yasp dot2pdf <output-directory> <dot-file-name> <pdf-file-name> yasp [--help] yasp [--version] Options: --help show this screen. --version show ve...
#!/usr/bin/env python """Stylesheet Processor Usage: yasp graph <input-directory> <template-file-name> <output-directory> <output-file-name> yasp open <file-name> yasp dot2pdf <output-directory> <dot-file-name> <pdf-file-name> yasp [--help] yasp [--version] Options: --help show this sc...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import elasticsearch from elasticsearch import helpers import requests import urllib import json import time from datetime import date from dateutil.rrule import rrule , DAILY import dust_raw comment from .common import COORDINATE_DICT import common set es = call Elasticsearch string local...
# -*- coding: utf-8 -*- import elasticsearch from elasticsearch import helpers import requests import urllib import json import time from datetime import date from dateutil.rrule import rrule, DAILY import dust_raw # from .common import COORDINATE_DICT import common es = elasticsearch.Elasticsearch('localhost:9200') ...
Python
zaydzuhri_stack_edu_python
from typing import List class Solution begin function canCompleteCircuit self gas cost begin set N = length gas set diff = list comprehension gas at i - cost at i for i in range N set start_pos = 0 set partial_sum = 0 set total = 0 for i in range N begin set partial_sum = partial_sum + diff at i if partial_sum < 0 begi...
from typing import List class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: N = len(gas) diff = [gas[i] - cost[i] for i in range(N)] start_pos = 0 partial_sum = 0 total = 0 for i in range(N): partial_sum += diff[...
Python
zaydzuhri_stack_edu_python
function bound_spec self name begin string Returns an input selector or derived spec bound to the study, i.e. where the repository tree is checked for existing outputs Parameters ---------- name : Str A name of a fileset or field comment If the provided "name" is actually a data item or parameter then comment replace i...
def bound_spec(self, name): """ Returns an input selector or derived spec bound to the study, i.e. where the repository tree is checked for existing outputs Parameters ---------- name : Str A name of a fileset or field """ # If the provided "n...
Python
jtatman_500k
function length self begin return size end function
def length(self): return self.size
Python
nomic_cornstack_python_v1
function get_loss self X y begin set tuple y_hat loss = call get_loss X y return tuple y_hat loss + rf * sum sum absolute w axis=0 end function
def get_loss(self, X, y): y_hat, loss = super().get_loss(X, y) return y_hat, loss + self.rf*np.sum(np.sum(abs(self.w), axis=0))
Python
nomic_cornstack_python_v1
from SystemUtilities import Configuration function print_status_classification_results sentences classifications event_type begin with open data_dir + string status_classification_ + event_type + string _debug.txt string wb as file begin for i in range 0 length sentences - 1 1 begin set sent = sentences at i set predic...
from SystemUtilities import Configuration def print_status_classification_results(sentences, classifications, event_type): with open(Configuration.data_dir + "status_classification_"+event_type+"_debug.txt", "wb") as file: for i in range(0, len(sentences)-1, 1): sent = sentences[i] ...
Python
zaydzuhri_stack_edu_python
function read_memory self address rtntype=string int begin set length = STRUCT_CTYPE_CODE_AND_SIZE at rtntype at 1 set buf = call create_string_buffer length set count = call c_ulong set rv = call ReadProcessMemory hproc address buf length call byref count if not rv begin comment failed to read return false end else be...
def read_memory(self, address, rtntype='int'): length = STRUCT_CTYPE_CODE_AND_SIZE[rtntype][1] buf = create_string_buffer(length) count = c_ulong() rv = kernel32.ReadProcessMemory(self.hproc, address, buf, length, byref(count)) if not rv...
Python
nomic_cornstack_python_v1
function __init__ self shape ssize pos=none begin call __init__ set pos = pos or call Vec2d 0 0 set shape = shape comment image set image = call convert_alpha set color = call Color string black set ssize = ssize set rect = call Rect tuple 0 0 ssize end function
def __init__(self, shape, ssize, pos=None): super(Obstacle, self).__init__() self.pos = pos or Vec2d(0, 0) self.shape = shape # image self.image = pygame.Surface(ssize).convert_alpha() self.color = pygame.Color("black") self.ssize = ssize self.rect = pygam...
Python
nomic_cornstack_python_v1
function start_from_textalign_file self maxNoeud=0 max_length_galaxie=1000000 begin call disabled_window set project_directory = join string / split get current directory string / at slice : - 2 : comment Ask for textAlign file localisation set file = call open_text_align_file project_directory if file == tuple or fi...
def start_from_textalign_file(self, maxNoeud=0, max_length_galaxie=1000000): self.interface.disabled_window() project_directory = '/'.join(os.getcwd().split('/')[:-2]) file = self.interface.open_text_align_file(project_directory) # Ask for textAlign file localisation if file == () or fi...
Python
nomic_cornstack_python_v1
function set_key_color self color begin string Set a color to be transparent during blitting functions. Args: color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. call TCOD_image_set_key_color image_c color end function
def set_key_color(self, color: Tuple[int, int, int]) -> None: """Set a color to be transparent during blitting functions. Args: color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. """ lib.TCOD_image_set_key_color(self....
Python
jtatman_500k
from sol3 import * comment # # # # # # # # # START OF COPY&PASTE FROM EX1 - THE PRESUBMIT USES THE READ_IMAGE FUNCTION # # # # # # # # # # from scipy.misc import imread from skimage.color import rgb2gray set tuple GREYSCALE COLOR RGBDIM = tuple 1 2 3 set MAX_PIX_VAL = 255 function is_valid_args filename representation ...
from sol3 import * # # # # # # # # # # START OF COPY&PASTE FROM EX1 - THE PRESUBMIT USES THE READ_IMAGE FUNCTION # # # # # # # # # # from scipy.misc import imread from skimage.color import rgb2gray GREYSCALE, COLOR, RGBDIM = 1, 2, 3 MAX_PIX_VAL = 255 def is_valid_args(filename: str, representation: int) -> bool: r...
Python
zaydzuhri_stack_edu_python
from gensim.models import FastText import pandas as pd from sklearn.model_selection import train_test_split from data.data_constructor import get_company_data , get_items_cat , get_location_data import numpy as np from sklearn.utils import shuffle class FeatureBuilder begin function __init__ self ordering=list string c...
from gensim.models import FastText import pandas as pd from sklearn.model_selection import train_test_split from data.data_constructor import get_company_data,get_items_cat,get_location_data import numpy as np from sklearn.utils import shuffle class FeatureBuilder: def __init__(self, ordering = ['company','locat...
Python
zaydzuhri_stack_edu_python
function session_scope begin set session = session try begin yield session commit session end except any begin rollback session raise end comment finally: comment don't close session comment session.close() pass end function
def session_scope(): session = app.db.session try: yield session session.commit() except: session.rollback() raise # finally: # don't close session # session.close() pass
Python
nomic_cornstack_python_v1
import math function mergeSort list begin return call mergeSortHelper 0 length list - 1 list end function function mergeSortHelper start end list begin if start == end begin return list list at start end set mid = floor start + end / 2 set sortedLeft = call mergeSortHelper start mid list set sortedRight = call mergeSor...
import math def mergeSort(list): return mergeSortHelper(0, len(list)-1, list) def mergeSortHelper(start, end, list): if start == end: return [list[start]] mid = math.floor((start + end) / 2) sortedLeft = mergeSortHelper(start, mid, list) sortedRight = mergeSortHelper(mid + 1, end, list) ...
Python
zaydzuhri_stack_edu_python
function _get_header_value self header begin set value = call _get_header_value header if value is none begin return end try begin set tuple pedigree start stop = split value end except ValueError begin try begin set tuple pedigree start _dash stop = split value end except ValueError begin set pedigree = value set star...
def _get_header_value(self, header): value = super(PedigreeValidator, self)._get_header_value(header) if value is None: return try: pedigree, start, stop = value.split() except ValueError: try: pedigree, start, _dash, stop = value.split...
Python
nomic_cornstack_python_v1
function whitening im begin set im = as type im string float32 for i in range call shape im at 0 begin comment /(np.std(im[:,:,i])+1e-9) set im at tuple i slice : : slice : : = im at tuple i slice : : slice : : - mean np im at tuple i slice : : slice : : end return im end function
def whitening(im): im = im.astype("float32") for i in range(np.shape(im)[0]): im[i,:,:] = (im[i,:,:]- np.mean(im[i,:,:]))#/(np.std(im[:,:,i])+1e-9) return im
Python
nomic_cornstack_python_v1
function split_data self df valid_boundary=2016 test_boundary=2018 begin set stock_count = length sl set test_ratio = 0.2 print string Stock count:%d % stock_count set train_x = list set test_x = list for tuple label_ d_ in enumerate sl begin set stock_train_len = integer length train_y * 1 - test_ratio set train_x =...
def split_data(self, df, valid_boundary=2016, test_boundary=2018): stock_count = len(self.sl) test_ratio = 0.2 print('Stock count:%d'% stock_count) train_x = [] test_x = [] for label_, d_ in enumerate(self.sl): stock_train_len = int(len(d_.train_y) * (1 - tes...
Python
nomic_cornstack_python_v1
function test_parameters begin with raises TypeError begin set google = call Stock string data/GOOG.json end with raises TypeError begin set google = call Stock string Google end with raises FileNotFoundError begin set google = call Stock string Google string data/non-existing.json end end function
def test_parameters(): with pytest.raises(TypeError): google = Stock("data/GOOG.json") with pytest.raises(TypeError): google = Stock("Google") with pytest.raises(FileNotFoundError): google = Stock("Google", "data/non-existing.json")
Python
nomic_cornstack_python_v1