code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment %load q02_plot/build.py comment Default Imports import pandas as pd import matplotlib.pyplot as plt from greyatomlib.descriptive_stats.q01_calculate_statistics.build import calculate_statistics set dataframe = read csv string data/house_prices_multivariate.csv set sale_price = loc at tuple slice : : string S...
# %load q02_plot/build.py # Default Imports import pandas as pd import matplotlib.pyplot as plt from greyatomlib.descriptive_stats.q01_calculate_statistics.build import calculate_statistics dataframe = pd.read_csv('data/house_prices_multivariate.csv') sale_price = dataframe.loc[:, 'SalePrice'] # Draw the plot for th...
Python
zaydzuhri_stack_edu_python
function IsPointInsideMesh MeshObj PointInObjectSpace begin comment direction is irellevant unless mesh is REALLY wierd shaped set direction = call Vector tuple 1 0 0 set epsilon = direction * 1e-06 set count = 0 set tuple result PointInObjectSpace normal index = call ray_cast PointInObjectSpace direction while result ...
def IsPointInsideMesh(MeshObj, PointInObjectSpace): #direction is irellevant unless mesh is REALLY wierd shaped direction = mathutils.Vector((1,0,0)) epsilon = direction * 1e-6 count = 0 result, PointInObjectSpace, normal, index = MeshObj.ray_cast(PointInObjectSpace, direction) while res...
Python
nomic_cornstack_python_v1
function deletePlayers begin set db = call connect set cur = call cursor comment If you are deleting players, you need to remove them comment from the standings table as well so there aren't any comment orphan standings for players that no longer exist. execute cur string DELETE FROM standings execute cur string DELETE...
def deletePlayers(): db = connect() cur = db.cursor() # If you are deleting players, you need to remove them # from the standings table as well so there aren't any # orphan standings for players that no longer exist. cur.execute("DELETE FROM standings") cur.execute("DELETE FROM players") ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment Reading and preprocessing the data on shelter animals import pandas class AnimalData extends object begin function __init__ self filename=none begin set outcomeTypes = dict string Return_to_owner 0 ; string Euthanasia 1 ; string Died 2 ; string Adoption 3 ; string Transfer 4 set an...
#!/usr/bin/env python3 # Reading and preprocessing the data on shelter animals import pandas class AnimalData(object): def __init__(self, filename=None): self.outcomeTypes = { 'Return_to_owner': 0, 'Euthanasia': 1, 'Died': 2, 'Adoption': 3, 'Tra...
Python
zaydzuhri_stack_edu_python
from socket import * comment instancia socket set s = call socket comment conecta ao localhost na porta descrita call connect tuple string localhost 8729 comment le, codifica e envia a mensagem set minhastr = input string Digite uma mensagem para ser criptografada: set meusbytes = encode str minhastr string UTF-8 call ...
from socket import * s=socket() #instancia socket s.connect(("localhost",8729)) #conecta ao localhost na porta descrita #le, codifica e envia a mensagem minhastr=input ("Digite uma mensagem para ser criptografada: ") meusbytes=str...
Python
zaydzuhri_stack_edu_python
from tkinter import * set width = 720 set height = 720 set root = call Tk set canvas = call Canvas root width=width height=height call pack class Map extends object begin function __init__ self begin set tilemap = list list 0 0 0 1 0 1 0 0 0 0 list 0 0 0 1 0 1 0 1 1 0 list 0 1 1 1 0 1 0 1 1 0 list 0 0 0 0 0 1 0 0 0 0 l...
from tkinter import * width = 720 height =720 root = Tk() canvas = Canvas(root, width=width, height=height) canvas.pack() class Map(object): def __init__(self): self.tilemap = [[0, 0, 0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 1, 1, 0], ...
Python
zaydzuhri_stack_edu_python
function _fetch_object_children self treeitem begin set obj_children = list set path_strings = list set obj = obj set obj_path = obj_path if is instance obj list ? tuple ? set ? frozenset begin set obj_children = list comprehension tuple string i j for tuple i j in sorted enumerate obj set path_strings = list compreh...
def _fetch_object_children( self, treeitem: PythonObjectTreeItem ) -> list[PythonObjectTreeItem]: obj_children = [] path_strings = [] obj = treeitem.obj obj_path = treeitem.obj_path if isinstance(obj, list | tuple | set | frozenset): obj_children = [(str(i...
Python
nomic_cornstack_python_v1
function get_last_node node letter begin for l in letter begin if l not in keys letters begin return none end set node = letters at l end return node end function
def get_last_node(node, letter): for l in letter: if l not in node.letters.keys(): return None node = node.letters[l] return node
Python
nomic_cornstack_python_v1
function test_unordenerd_names self begin comment Setup set data = call DataFrame columns=list string country string region string subregion string city set expected_result = 0 comment Run set result = call get_geographical_granularity data comment Check assert result == expected_result end function
def test_unordenerd_names(self): # Setup data = pd.DataFrame(columns=['country', 'region', 'subregion', 'city']) expected_result = 0 # Run result = get_geographical_granularity(data) # Check assert result == expected_result
Python
nomic_cornstack_python_v1
function test_min_length self begin call validate string call validate string call validate none call validate string kevin call validate string k call validate string kevin call validate string kevintastic with assert raises ValidationError begin call validate string end with assert raises ValidationError begin call v...
def test_min_length(self): Ascii(min_length=0).validate('') Ascii(min_length=0, required=True).validate('') Ascii(min_length=0).validate(None) Ascii(min_length=0).validate('kevin') Ascii(min_length=1).validate('k') Ascii(min_length=5).validate('kevin') Ascii(m...
Python
nomic_cornstack_python_v1
function most_common number_list begin set number_dict = dictionary for number in number_list begin if number in number_dict begin set number_dict at number = number_dict at number + 1 end else begin set number_dict at number = 1 end end set max_number = list - 1 - 1 for number in number_dict begin if max_number == lis...
def most_common(number_list): number_dict = dict() for number in number_list: if number in number_dict: number_dict[number] += 1 else: number_dict[number] = 1 max_number = [-1, -1] for number in number_dict: if max_number == [-1, -1]: max_numb...
Python
zaydzuhri_stack_edu_python
function childrens_iterator self begin comment TODO : add some backtracking to prevent going twice in some places yield self for child in call childrens begin for node in call childrens_iterator begin yield node end end end function
def childrens_iterator(self): # TODO : add some backtracking to prevent going twice in some places yield self for child in self.childrens(): for node in child.childrens_iterator(): yield node
Python
nomic_cornstack_python_v1
function close self begin flush writer end function
def close(self): self.writer.flush()
Python
nomic_cornstack_python_v1
from datetime import datetime import cv2 as cv import os import sys import argparse from skeleton_sequence import SkeletonSequence comment use if necessary comment sys.path.append('/usr/local/python') try begin import pyopenpose as op end except ImportError as e begin print string Error: OpenPose library could not be f...
from datetime import datetime import cv2 as cv import os import sys import argparse from skeleton_sequence import SkeletonSequence # use if necessary # sys.path.append('/usr/local/python') try: import pyopenpose as op except ImportError as e: print('Error: OpenPose library could not be found. Did you enable `...
Python
zaydzuhri_stack_edu_python
function get_cas_list cas_file=CAS_PATH begin set cas_list = list for line in open cas_file begin if not starts with line string # begin append cas_list split line string at 0 end end return cas_list end function
def get_cas_list(cas_file=CAS_PATH): cas_list = [] for line in open(cas_file): if not line.startswith("#"): cas_list.append(line.split("\t")[0]) return cas_list
Python
nomic_cornstack_python_v1
comment Bayley King comment Python 3.7.3 comment Ploting function library for SOFM network import funcs function graphHeatmap Input Output begin string Function to graph the final heatmap for the best input for each output neuron import matplotlib.pyplot as plt import pickle as pkl figure set h = list set output = loa...
# Bayley King # Python 3.7.3 # Ploting function library for SOFM network import funcs def graphHeatmap(Input,Output): ''' Function to graph the final heatmap for the best input for each output neuron ''' import matplotlib.pyplot as plt import pickle as pkl plt.figure() h = [] output = ...
Python
zaydzuhri_stack_edu_python
comment Given an array of unsorted numbers and find a triplet in the array whose sum is as close to the target number comment as possible, return the sum of the triplet. If there are more than one such triplet, return the sum of the comment sum of the triplet with the triplet with the smallest sum. function solution ar...
#Given an array of unsorted numbers and find a triplet in the array whose sum is as close to the target number #as possible, return the sum of the triplet. If there are more than one such triplet, return the sum of the #sum of the triplet with the triplet with the smallest sum. def solution(array, target): array.s...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn import torch.nn.functional as F import pyro from pyro.nn import PyroSample , PyroModule import pyro.distributions as dists class Lenet5Deterministic extends Module begin function __init__ self begin call __init__ set conv1 = conv 2d 1 6 5 stride=1 set conv2 = conv 2d 6 16 5 stride=1 c...
import torch import torch.nn as nn import torch.nn.functional as F import pyro from pyro.nn import PyroSample, PyroModule import pyro.distributions as dists class Lenet5Deterministic(nn.Module): def __init__(self): super(Lenet5Deterministic, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5, s...
Python
zaydzuhri_stack_edu_python
function add_datepart df fldname drop=true time=false begin set fld = df at fldname set fld_dtype = dtype if is instance fld_dtype DatetimeTZDtype begin set fld_dtype = datetime64 end if not call issubdtype fld_dtype datetime64 begin set df at fldname = call to_datetime fld infer_datetime_format=true set fld = call to_...
def add_datepart(df, fldname, drop=True, time=False): fld = df[fldname] fld_dtype = fld.dtype if isinstance(fld_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype): fld_dtype = np.datetime64 if not np.issubdtype(fld_dtype, np.datetime64): df[fldname] = fld = pd.to_datetime(fld, infer_datetime...
Python
nomic_cornstack_python_v1
function normalize_instances self begin if not has attribute self string max_attribute_values begin call compute_instance_attribute_bounds end set new_instances = list for instance in instances begin comment (instance - min_values) / (max_values - min_values) append new_instances call normalize_instance instance end s...
def normalize_instances(self): if not hasattr(self, "max_attribute_values"): self.compute_instance_attribute_bounds() new_instances = [] for instance in self.instances: new_instances.append(self.normalize_instance(instance)) # (instance - min_values) / (max_values - min_v...
Python
nomic_cornstack_python_v1
function add_users data session begin for user in data at string users begin add session call User user_name=user at string user_name first_name=user at string first_name middle_name=user at string middle_name last_name=user at string last_name password=user at string password end end function
def add_users(data, session): for user in data['users']: session.add(User( user_name=user['user_name'], first_name=user['first_name'], middle_name=user['middle_name'], last_name=user['last_name'], password=user['password'] ))
Python
nomic_cornstack_python_v1
function get_bprop_log1p self begin set reciprocal = call Reciprocal function bprop x out dout begin set x_1p = x + 1 set g = call reciprocal x_1p set dx = g * dout return tuple dx 0 end function return bprop end function
def get_bprop_log1p(self): reciprocal = P.Reciprocal() def bprop(x, out, dout): x_1p = x + 1 g = reciprocal(x_1p) dx = g * dout return dx, 0 return bprop
Python
nomic_cornstack_python_v1
comment Conversion from DFA to Regex import json import sys import copy set reg_exp = string set dfa = dict function get_input_symbol begin global dfa set input_symbols = dictionary comprehension st : dictionary comprehension to : string for to in dfa at string states for st in dfa at string states for val in dfa at...
# Conversion from DFA to Regex import json import sys import copy reg_exp = '' dfa = {} def get_input_symbol(): global dfa input_symbols = {st: {to: '' for to in dfa['states']} for st in dfa['states']} for val in dfa['transition_function']: if input_symbols[val[0]][val[2]] == '': inpu...
Python
zaydzuhri_stack_edu_python
function lb self begin return view _lb end function
def lb(self): return self._lb.view()
Python
nomic_cornstack_python_v1
from odoo import fields , models from odoo.exceptions import UserError from odoo.tools.translate import _ function is_allowed_transition old_state new_state begin string :param old_state: the current state of the product :param new_state: the new state of the product :return: True if transistion is allowed, otherwise F...
from odoo import fields, models from odoo.exceptions import UserError from odoo.tools.translate import _ def is_allowed_transition(old_state, new_state): """ :param old_state: the current state of the product :param new_state: the new state of the product :return: True if transistion is allowed, other...
Python
zaydzuhri_stack_edu_python
function write_log self log_type begin set key = call str_to_posix_fully_portable_filename string key set now = call str_to_posix_fully_portable_filename string now set log_filename = string . { now } . { log_type } . { key } .log comment type: ignore with open log_filename string w as fid begin write fid hash end end ...
def write_log(self, log_type: str) -> None: key = str_to_posix_fully_portable_filename(str(self.key)) now = str_to_posix_fully_portable_filename(str(dt.datetime.now())) log_filename = f'.{now}.{log_type}.{key}.log' with self.cache_fs.open(log_filename, 'w') as fid: # type: ignore ...
Python
nomic_cornstack_python_v1
function _home_location self user begin try begin set home = get user string home return _geocoder at home end except tuple AstralError KeyError as e begin raise call DataError e end end function
def _home_location(self, user): try: home = user.get('home') return self._geocoder[home] except (AstralError, KeyError) as e: raise DataError(e)
Python
nomic_cornstack_python_v1
comment encoding: utf-8 string @author: weiyang_tang @contact: weiyang_tang@126.com @file: xlutilsDemo.py @time: 2019-02-04 23:21 @desc: 对已有的excel文件进行修改 import xlrd from xlutils.copy import copy comment 打开想要更改的excel文件 set old_excel = call open_workbook string data/weixinFridendList.xls formatting_info=true comment 将操作文...
# encoding: utf-8 ''' @author: weiyang_tang @contact: weiyang_tang@126.com @file: xlutilsDemo.py @time: 2019-02-04 23:21 @desc: 对已有的excel文件进行修改 ''' import xlrd from xlutils.copy import copy # 打开想要更改的excel文件 old_excel = xlrd.open_workbook('data/weixinFridendList.xls', formatting_info=True) # 将操作文件对象拷贝,变成可写的workbook对象 ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Wed Nov 21 09:31:56 2018 @author: ashish import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import scatter_matrix from sklearn.impute import SimpleImputer from sklearn.preprocessing import On...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 09:31:56 2018 @author: ashish """ import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import scatter_matrix from sklearn.impute import SimpleImputer from sklearn.preprocessing import OneHotEncode...
Python
zaydzuhri_stack_edu_python
function update_repos self begin set errors = false with call ThreadPoolExecutor max_workers=num_worker as executor begin set future_to_update = dictionary comprehension call submit update_module module_path name setup : name for tuple name setup in sorted items modules for future in call as_completed future_to_update ...
def update_repos(self): errors = False with ThreadPoolExecutor(max_workers=self.num_worker) as executor: future_to_update = { executor.submit(update_module, self.module_path, name, setup): name \ for name, setup in sorted(self.modules.items())} for...
Python
nomic_cornstack_python_v1
function get_segment_length self dist=string path_length begin set T = call get_mst set segment_length = call get_edge_attributes call get_graph dist return segment_length end function
def get_segment_length(self, dist='path_length'): T = self.get_mst() segment_length = nx.get_edge_attributes(T.get_graph(), dist) return segment_length
Python
nomic_cornstack_python_v1
function turn_on_all_targets self begin for actor in _target_anatomy_actors begin call SetVisibility true end end function
def turn_on_all_targets(self): for actor in self._target_anatomy_actors: actor.SetVisibility(True)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python from __future__ import division from sys import stdin , stdout set MOD = 1000000007 set tuple K M = map int split read line stdin set size = power 2 K set cnt = 0 for k in call xrange size begin set ln = split read line stdin for l in ln begin if l == string # begin set cnt = cnt + 1 end end en...
#!/usr/bin/python from __future__ import division from sys import stdin, stdout MOD = 1000000007 K, M = map (int, stdin.readline ().split ()) size = pow (2, K) cnt = 0 for k in xrange (size): ln = stdin.readline ().split () for l in ln: if l == '#': cnt += 1 ways = pow (pow (2, pow (4, M, MOD - 1), MOD) - 1...
Python
zaydzuhri_stack_edu_python
function set_cursor_manager self manager_class begin warn string set_cursor_manager is Deprecated DeprecationWarning stacklevel=2 set manager = call manager_class self if not is instance manager CursorManager begin raise call TypeError string manager_class must be a subclass of CursorManager end set __cursor_manager = ...
def set_cursor_manager(self, manager_class): warnings.warn( "set_cursor_manager is Deprecated", DeprecationWarning, stacklevel=2) manager = manager_class(self) if not isinstance(manager, CursorManager): raise TypeError("manager_class must be a subc...
Python
nomic_cornstack_python_v1
from ControllableSprite import ControllableSprite class PoweredSprite extends ControllableSprite begin function __init__ self begin call __init__ set leftSpecailMove1Frames = list set rightSpecailMove1Frames = list set inSM1 = false set inSM1Hit = false set currentSkillObject = none set skillAnimation = none set skil...
from .ControllableSprite import ControllableSprite class PoweredSprite(ControllableSprite): def __init__(self): super().__init__() self.leftSpecailMove1Frames = [] self.rightSpecailMove1Frames = [] self.inSM1 = False self.inSM1Hit = False self.currentSkillObject = ...
Python
zaydzuhri_stack_edu_python
comment @author:SRvSaha comment chandu_and_consecutive_letters.py comment Description :https://www.hackerearth.com/problem/algorithm/chandu-and-consecutive-letters/ set test_cases = input while test_cases > 0 begin set output_string = string set string = call raw_input for i in call xrange length string - 1 begin if i...
# # @author:SRvSaha # chandu_and_consecutive_letters.py # Description :https://www.hackerearth.com/problem/algorithm/chandu-and-consecutive-letters/ # test_cases = input() while test_cases > 0 : output_string = "" string = raw_input() for i in xrange(len(string)-1): if i != len(string)-2: ...
Python
zaydzuhri_stack_edu_python
function done_action self begin set end = now end function
def done_action(self) -> None: self.end = datetime.now()
Python
nomic_cornstack_python_v1
import json import array as arr import numpy as np set filename = string /Users/Michael/Desktop/SummerPhyiscs/run100.json set electron_momenta = list function main begin with open filename as jfile begin set data = load json jfile for i in range length data at string events begin set momentum = data at string events a...
import json import array as arr import numpy as np filename = "/Users/Michael/Desktop/SummerPhyiscs/run100.json" electron_momenta = [] def main(): with open(filename) as jfile: data = json.load(jfile) for i in range(len(data['events'])): momentum = data['events'][str(i)]['particles'][0]...
Python
zaydzuhri_stack_edu_python
import tarfile from pathlib import Path function create_tar src dst exts=string jpeg|jpg|png begin string Creates archive from folders with images. set tuple src dst = list comprehension call Path p for p in tuple src dst set images = list for ext in split exts string | begin for case in tuple lower ext upper ext begi...
import tarfile from pathlib import Path def create_tar(src: Path, dst: Path, exts: str='jpeg|jpg|png'): """Creates archive from folders with images.""" src, dst = [Path(p) for p in (src, dst)] images = [] for ext in exts.split('|'): for case in (ext.lower(), ext.upper()): for fil...
Python
zaydzuhri_stack_edu_python
function datadog_tags self begin return get pulumi self string datadog_tags end function
def datadog_tags(self) -> Optional[Sequence['outputs.ServiceIntegrationEndpointDatadogUserConfigDatadogTag']]: return pulumi.get(self, "datadog_tags")
Python
nomic_cornstack_python_v1
function grant_user_access self user db_names strict=true begin set user = call get_name user set uri = string /%s/%s/databases % tuple uri_base user set db_names = call _get_db_names db_names strict=strict set dbs = list comprehension dict string name db_name for db_name in db_names set body = dict string databases db...
def grant_user_access(self, user, db_names, strict=True): user = utils.get_name(user) uri = "/%s/%s/databases" % (self.uri_base, user) db_names = self._get_db_names(db_names, strict=strict) dbs = [{"name": db_name} for db_name in db_names] body = {"databases": dbs} try: ...
Python
nomic_cornstack_python_v1
class BinarySearchTree begin function __init__ self data begin set left = none set right = none set data = data end function function print_tree self begin if left begin call print_tree end print data if right begin call print_tree end end function end class function add root begin if root == none begin return 0 end re...
class BinarySearchTree: def __init__(self,data): self.left = None self.right = None self.data = data def print_tree(self): if self.left: self.left.print_tree() print(self.data) if self.right: self.right.print_tree() def add(root): if ...
Python
zaydzuhri_stack_edu_python
function editable_str self begin return join string list comprehension call __unicode__ for e in entries end function
def editable_str(self): return "\n".join([e.__unicode__() for e in self.entries])
Python
nomic_cornstack_python_v1
function testGetInterfaceStatus self begin call get_interface_status file_name=string get_interface_status.xml interface_status=sysDict at string interface_status end function
def testGetInterfaceStatus(self): self.sys_cfg.get_interface_status( file_name='get_interface_status.xml', interface_status=sysDict['interface_status'])
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: comment 예외 처리를 이용해서 숫자와 문자가 혼용되어 있는 배열을 정렬하기 set integer = list set string = list while true begin set data = input string 입력하세요(quit를 입력하면 프로그램 종료) : if lower data == string quit begin break end comment 우선 데이터를 정수화 해서 정수 리스트에 담는다 try begin append intege...
#!/usr/bin/env python # coding: utf-8 # In[1]: # 예외 처리를 이용해서 숫자와 문자가 혼용되어 있는 배열을 정렬하기 integer =list() string = list() while True : data = input('입력하세요(quit를 입력하면 프로그램 종료) :') if data.lower() =='quit': break try : # 우선 데이터를 정수화 해서 정수 리스트에 담는다 integer.append(int(data)) except : # 오류가 나면...
Python
zaydzuhri_stack_edu_python
function times_list soup_times begin comment convert all bs4 tags to strings set html_str_times = list map str soup_times comment remove all tags from time stamps. set no_tag_times = list map de_tag html_str_times set abs_times = list map abstime no_tag_times return call split_halves abs_times end function
def times_list(soup_times): html_str_times = list(map(str, soup_times))#convert all bs4 tags to strings no_tag_times = list(map(de_tag, html_str_times)) #remove all tags from time stamps. abs_times = list(map(abstime, no_tag_times)) return split_halves(abs_times)
Python
nomic_cornstack_python_v1
import os import re import linecache import numpy as np import pandas as pd import codecs function get_value file begin set ans = list set f = open file string r string utf_16_be set lines = read lines f 1000 set lineA = lines at 2 set pitchA = split re string , lineA set lineB = lines at 4 set pitchB = split re strin...
import os import re import linecache import numpy as np import pandas as pd import codecs def get_value(file): ans = [] f = codecs.open(file, 'r', 'utf_16_be') lines = f.readlines(1000) lineA = lines[2] pitchA = re.split(',', lineA) lineB = lines[4] pitchB = re.split(',', li...
Python
zaydzuhri_stack_edu_python
function _get_bounding_box_from_neighbors self neighbors begin set west = west set east = east set south = none if get neighbors string south begin set south = south end else begin set south = south end set north = none if get neighbors string north begin set north = north end else begin set north = north end return ca...
def _get_bounding_box_from_neighbors(self, neighbors: dict): west = BoundingBox.from_geohash(neighbors["west"]).west east = BoundingBox.from_geohash(neighbors["east"]).east south = None if neighbors.get("south"): south = BoundingBox.from_geohash(neighbors["south"]).south ...
Python
nomic_cornstack_python_v1
function encode_data df begin set min_val = min - 0.05 set max_val = max + 0.05 set resolution = 0.0001 set n = integer max_val - min_val / resolution set df at string Change_id = as type df at string Change - min_val / resolution int return tuple df n end function
def encode_data(df): min_val = df['Change'].min()- 0.05 max_val = df['Change'].max()+ 0.05 resolution = 0.0001 n = int((max_val-min_val)/resolution) df['Change_id'] = ((df['Change']-min_val)/resolution).astype(int) return df, n
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np from scipy import stats from ggplot import * set stroop = read csv string stroopdata.csv set stroop at string difference = Incongruent - Congruent mean stroop variance stroop standard deviation stroop describe stroop comment Standard error of the mean standard deviation stroop / s...
import pandas as pd import numpy as np from scipy import stats from ggplot import * stroop = pd.read_csv('stroopdata.csv') stroop['difference'] = stroop.Incongruent - stroop.Congruent stroop.mean() stroop.var() stroop.std() stroop.describe() # Standard error of the mean stroop.std() / np.sqrt(stroop.count()) # Expl...
Python
zaydzuhri_stack_edu_python
function __filter_jobs self job_url begin set soup = call __get_html_parser job_url comment {'class': 'FYwKg WaMPc_4'}) set results = find soup string div dict string data-automation string jobAdDetails set listed_items = find all results string li set job_description = call PrefixTrie for item in listed_items begin se...
def __filter_jobs(self, job_url: str): soup = self.__get_html_parser(job_url) results = soup.find('div', {'data-automation': 'jobAdDetails'}) # {'class': 'FYwKg WaMPc_4'}) listed_items = results.find_all('li') job_description = PrefixTrie() for item in listed_items: ...
Python
nomic_cornstack_python_v1
function classify_dot_segments classifiers run_ids db_name db_folder=none begin if db_folder is none begin set db_folder = config at string db_folder end with call switch_database db_name db_folder begin set clf_result : Dict at tuple int Dict at tuple str Union at tuple bool int = dict for data_id in run_ids begin se...
def classify_dot_segments( classifiers: DotClassifierDict, run_ids: List[int], db_name: str, db_folder: Optional[str] = None, ) -> Dict[int, Dict[str, Union[bool, int]]]: if db_folder is None: db_folder = nt.config["db_folder"] with nt.switch_database(db_name, db_folder): clf_r...
Python
nomic_cornstack_python_v1
function RadialModel radii intens dims center q pa c=0.0 begin comment IMPORT STUFF from scipy import interpolate as interp comment END IMPORT comment y,x! set n = tuple dims at slice - 1 : : - 1 comment y,x! set ecenter = tuple center at slice - 1 : : - 1 set radial_mask = call dist_superellipse n ecenter q=q pos_an...
def RadialModel(radii,intens,dims,center,q,pa,c=0.): # IMPORT STUFF from scipy import interpolate as interp # END IMPORT n = tuple(dims[-1::-1]) # y,x! ecenter = tuple(center[-1::-1]) # y,x! radial_mask = dist_superellipse(n,ecenter,q=q,pos_ang=pa,c=c) arg = num.where(radial_mask<=radii...
Python
nomic_cornstack_python_v1
function complex_intervals f eps=none inf=none sup=none fast=false sqf=false begin return call dmp_complex_intervals rep lev dom eps=eps inf=inf sup=sup fast=fast end function
def complex_intervals(f, eps=None, inf=None, sup=None, fast=False, sqf=False): return dmp_complex_intervals(f.rep, f.lev, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
Python
nomic_cornstack_python_v1
function get_searchkey self begin return expiration_date end function
def get_searchkey(self): return self.expiration_date
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- comment vi: set ft=python sts=4 ts=4 sw=4 et: function ambiguous_match string pattern wildcards begin string Match strings via a custom, regular-expression-like syntax based on wildcard characters (e.g., * and ...
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: def ambiguous_match(string, pattern, wildcards): """ Match strings via a custom, regular-expression-like syntax based on wildcard characters (e.g., * and ? and # etc....
Python
zaydzuhri_stack_edu_python
function db_for_write self model **hints begin if app_label == string display_map begin return string datastore end return none end function
def db_for_write(self, model, **hints): if model._meta.app_label == 'display_map': return 'datastore' return None
Python
nomic_cornstack_python_v1
string Problem Challenge 1 Find the Corrupt Pair (easy) We are given an unsorted array containing ‘n’ numbers taken from the range 1 to ‘n’. The array originally contained all the numbers from 1 to ‘n’, but due to a data error, one of the numbers got duplicated which also resulted in one number going missing. Find both...
''' Problem Challenge 1 Find the Corrupt Pair (easy) We are given an unsorted array containing ‘n’ numbers taken from the range 1 to ‘n’. The array originally contained all the numbers from 1 to ‘n’, but due to a data error, one of the numbers got duplicated which also resulted in one number going missing. Find both ...
Python
zaydzuhri_stack_edu_python
function get_name self op_type begin function _gen t begin set t = lower t if t not in local_op_namespace begin set local_op_namespace at t = START_IDX set suffix = string end else begin set local_op_namespace at t = local_op_namespace at t + 1 set suffix = string { local_op_namespace at t - 1 } end return string { ca...
def get_name(self, op_type): def _gen(t): t = t.lower() if t not in self.local_op_namespace: self.local_op_namespace[t] = START_IDX suffix = "" else: self.local_op_namespace[t] += 1 suffix = f"{self.local_op_nam...
Python
nomic_cornstack_python_v1
comment --------------------------------------------------------------- comment python best courses https://courses.tanpham.org/ comment --------------------------------------------------------------- comment Write a Python program that accepts an integer (n) and computes the value of comment n+nn+nnn. Go to the editor...
# --------------------------------------------------------------- # python best courses https://courses.tanpham.org/ # --------------------------------------------------------------- # Write a Python program that accepts an integer (n) and computes the value of # n+nn+nnn. Go to the editor # Sample value of n is 5 # Ex...
Python
zaydzuhri_stack_edu_python
class BankAccount begin function __init__ self name balance begin set name = name set balance = balance end function function deposit self amount begin set balance = balance + amount end function function withdraw self amount begin set balance = balance - amount end function function get_balance self begin return balan...
class BankAccount: def __init__(self, name, balance): self.name = name self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def get_balance(self): return self.balance
Python
flytech_python_25k
function generate_distorted_t t C sigma begin set S_u = call generate_S_u t set m = call multivariate_normal mean=zeros length C cov=C set noise = call generate_noisy_window length t sigma return dot S_u m + noise end function
def generate_distorted_t(t, C, sigma): S_u = generate_S_u(t) m= np.random.multivariate_normal(mean= np.zeros(len(C)), cov=C) noise= generate_noisy_window(len(t), sigma) return np.dot(S_u, m) + noise
Python
nomic_cornstack_python_v1
function tearDown self begin call Empty end function
def tearDown(self): self._resolver_context.Empty()
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- function parttion nums low high begin set key = nums at low while low < high begin while low < high and nums at high > key begin set high = high - 1 end comment 当出现<key的情况 if low < high begin comment 交换key和<key的元素 set tuple nums at low nums at high = tuple nums at high nums at low end else ...
# -*- coding:utf-8 -*- def parttion(nums, low, high): key = nums[low] while low < high: while low < high and nums[high] > key: high -= 1 if low < high: # 当出现<key的情况 nums[low], nums[high] = nums[high], nums[low] # 交换key和<key的元素 else: break w...
Python
zaydzuhri_stack_edu_python
from unittest import TestCase from Util.extensions import convert_int_to_degrees , convert_angle_to_compass_direction , convert_compass_direction_to_angle , CompassDirections class extensions extends TestCase begin function test_convert_int_to_degrees self begin set normal_degree = 50 set ret_normal_degrees = call conv...
from unittest import TestCase from Util.extensions import convert_int_to_degrees, convert_angle_to_compass_direction, \ convert_compass_direction_to_angle, CompassDirections class extensions(TestCase): def test_convert_int_to_degrees(self): normal_degree = 50 ret_normal_degrees = convert_int_t...
Python
zaydzuhri_stack_edu_python
function format_raw_input user_input begin comment Replace silly “ or ” characters with " comment TODO: Swap out with regex set raw_input = replace replace replace replace strip user_input string “ string " string ” string " string , string string string comment Break apart the string into each coordinate set raw_inpu...
def format_raw_input(user_input): # Replace silly “ or ” characters with " # TODO: Swap out with regex raw_input = user_input.strip().replace( '“', '"').replace("”", '"').replace(",", "").replace("\n", " ") # Break apart the string into each coordinate raw_inputs = [r.replace('"', '') for r ...
Python
nomic_cornstack_python_v1
for i in range nofroads begin append l tuple split input end set roads = list comprehension tuple integer x integer y integer z for tuple x y z in l set m = list set nofqueries = integer input for i in range nofqueries begin append m tuple split input end set queries = list comprehension tuple integer x integer y for ...
for i in range(nofroads): l.append(tuple(input().split())) roads = [(int(x), int(y), int(z)) for (x, y, z) in l] m = [] nofqueries = int(input()) for i in range(nofqueries): m.append(tuple(input().split())) queries = [(int(x), int(y)) for (x, y) in m] country = dict() for i in range(nofcities): country[i ...
Python
zaydzuhri_stack_edu_python
function R_Zh_nexrad d begin import numpy as np comment Ref set zh = d at 3 comment Coefficients set c = 0.017 set a = 0.714 set est = c * zh ^ a / 12 return tuple est d at - 1 end function
def R_Zh_nexrad (d) : import numpy as np zh = d[3] # Ref # Coefficients c = 0.017 a = 0.714 est = c * zh ** a / 12 return est, d[-1]
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt import operator set dataSet = array list list 1 1.1 list 1 1 list 0 0 list 0 0.1 set labels = array list string A string A string B string B set tr_labels = array list list string A list string A list string B list string B comment inputX 单个点 comment 训练得出结果 function cl...
import numpy as np import matplotlib.pyplot as plt import operator dataSet = np.array([[1,1.1],[1,1],[0,0],[0,0.1]]) labels = np.array(["A","A","B","B"]) tr_labels = np.array([["A"],['A'],['B'],['B']]) # inputX 单个点 # 训练得出结果 def classify(inputX, train_set,labels,k): # if(train_set.shape[1] != len(inputX[0])): ...
Python
zaydzuhri_stack_edu_python
function testall cls requests statuses=none begin return call _testall requests Testall statuses end function
def testall(cls, requests, statuses=None): return _testall(requests, MPI.Request.Testall, statuses)
Python
nomic_cornstack_python_v1
function _install_ngs_tools begin call _install_bowtie call _install_bwa call _install_samtools call _install_fastx_toolkit call _install_maq comment _install_bfast() if install_ucsc begin call _install_ucsc_tools end end function
def _install_ngs_tools(): _install_bowtie() _install_bwa() _install_samtools() _install_fastx_toolkit() _install_maq() #_install_bfast() if env.install_ucsc: _install_ucsc_tools()
Python
nomic_cornstack_python_v1
comment @lc app=leetcode.cn id=449 lang=python comment [449] 序列化和反序列化二叉搜索树 comment https://leetcode-cn.com/problems/serialize-and-deserialize-bst/description/ comment algorithms comment Medium (51.36%) comment Likes: 71 comment Dislikes: 0 comment Total Accepted: 5.4K comment Total Submissions: 10.3K comment Testcase E...
# # @lc app=leetcode.cn id=449 lang=python # # [449] 序列化和反序列化二叉搜索树 # # https://leetcode-cn.com/problems/serialize-and-deserialize-bst/description/ # # algorithms # Medium (51.36%) # Likes: 71 # Dislikes: 0 # Total Accepted: 5.4K # Total Submissions: 10.3K # Testcase Example: '[2,1,3]' # # 序列化是将数据结构或对象转换为一系列位的过程,...
Python
zaydzuhri_stack_edu_python
import csv import pandas as pd function load_dataset dataset_name begin set files_folder = dataset_name + string / set dataSetIn = files_folder + string Export_textiles.tsv comment dataSetIn = files_folder + 'diag.tsv' comment dataSetIn = files_folder + 'dd.tsv' comment print dataSetIn with open dataSetIn as input begi...
import csv import pandas as pd def load_dataset(dataset_name): files_folder = dataset_name+'/' dataSetIn = files_folder + 'Export_textiles.tsv' # dataSetIn = files_folder + 'diag.tsv' # dataSetIn = files_folder + 'dd.tsv' # print dataSetIn with open(dataSetIn) as input: dataArray = [x...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt from sklearn import datasets from sklearn import svm from sklearn import preprocessing import binarize comment digits = datasets.load_digits() comment print(digits.data) comment print(digits.target) comment clf = svm.SVC(gamma=0.001, C=100) comment img = digits.images[2] comment print im...
import matplotlib.pyplot as plt from sklearn import datasets from sklearn import svm from sklearn import preprocessing import binarize #digits = datasets.load_digits() ##print(digits.data) ##print(digits.target) #clf = svm.SVC(gamma=0.001, C=100) #img = digits.images[2] #print img #binr = preprocessing.binarize(im...
Python
zaydzuhri_stack_edu_python
function evolve_all_hosts h_dt tis drift_rate=0.0 theta=0.0 nsnps=0 binary_genomes=false begin return dictionary comprehension ix : call evolve_host hh=genomes ti=tis at ix drift_rate=drift_rate theta=theta nsnps=nsnps binary_genomes=binary_genomes for tuple ix genomes in items h_dt end function
def evolve_all_hosts(h_dt, tis, drift_rate=0.0, theta=0.0, nsnps=0, binary_genomes=False): return {ix: evolve_host(hh=genomes, ti=tis[ix], drift_rate=drift_rate, theta=theta, nsnps=nsnps, binary_genomes=binary_genomes) for ix, genomes in h_dt.items()}
Python
nomic_cornstack_python_v1
function alexnet pretrained=false begin set model = call AlexNet if pretrained begin set model_path = string ./model/alexnet.pth.tar set pretrained_model = load torch model_path load state dict model pretrained_model at string state_dict end return model end function
def alexnet(pretrained=False): model = AlexNet() if pretrained: model_path = './model/alexnet.pth.tar' pretrained_model = torch.load(model_path) model.load_state_dict(pretrained_model['state_dict']) return model
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt class Net extends Module begin function __init__ self begin call __init__ set fc1 = linear 13 70 set fc2 = linear 70 2 comment self.fc3 = nn.Linear(35, 2) comment self.fc4 = nn.Linear(16, 2) set dropout = dropout p=0.0 en...
import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(13,70) self.fc2 = nn.Linear(70,2) # self.fc3 = nn.Linear(35, 2) # self.fc4 = nn.Line...
Python
zaydzuhri_stack_edu_python
function test_task_failed self begin set task1 = call FailedTask call Mock total_retries=0 set task2 = call Mock execute_after=0 set g = call TaskDependencyGraph call MockWorkflowContext set seq = call sequence add seq task1 task2 with call limited_sleep_mock begin call assertRaisesRegex WorkflowFailed string failtask ...
def test_task_failed(self): task1 = FailedTask(mock.Mock(), total_retries=0) task2 = mock.Mock(execute_after=0) g = TaskDependencyGraph(MockWorkflowContext()) seq = g.sequence() seq.add(task1, task2) with limited_sleep_mock(): self.assertRaisesRegex(Workflo...
Python
nomic_cornstack_python_v1
comment DeepYellowJ - Version 0.1 (c) 2016 Ahmad Nazeri comment Piece - piece.py comment This file is the object class for a piece. comment The piece keeps track of name, color, comment point value, and if it has been moved. class Piece begin comment Constructor for Piece. comment Parameters: comment name - String comm...
## DeepYellowJ - Version 0.1 (c) 2016 Ahmad Nazeri # Piece - piece.py # # This file is the object class for a piece. # The piece keeps track of name, color, # point value, and if it has been moved. class Piece: # Constructor for Piece. # # Parameters: # name - String # colo...
Python
zaydzuhri_stack_edu_python
comment encoding:utf-8 comment 图像直方图均衡化 import numpy as np import cv2 comment 读取灰度图像 set image = call imread string ../images/jay.jpg 0 image show string Original image call waitKey 0 comment 灰度图像直方图均衡化 set eq = call equalizeHist image image show string Histogram Equalization horizontal stack list image eq call waitKey...
#encoding:utf-8 # #图像直方图均衡化 # import numpy as np import cv2 image = cv2.imread("../images/jay.jpg",0)#读取灰度图像 cv2.imshow("Original",image) cv2.waitKey(0) eq = cv2.equalizeHist(image)#灰度图像直方图均衡化 cv2.imshow("Histogram Equalization", np.hstack([image, eq])) cv2.waitKey(0)
Python
zaydzuhri_stack_edu_python
function rsa_decrypt enc_msg private_key begin set key = call import_key private_key set cipher_rsa = call new key set msg = call decrypt enc_msg return decode msg end function
def rsa_decrypt(enc_msg: bytes, private_key: bytes) -> str: key = RSA.import_key(private_key) cipher_rsa = PKCS1_OAEP.new(key) msg = cipher_rsa.decrypt(enc_msg) return msg.decode()
Python
nomic_cornstack_python_v1
function remove_list_duplicates lista unique=false begin string Remove duplicated elements in a list. Args: lista: List with elements to clean duplicates. set result = list set allready = list for elem in lista begin if elem not in result begin append result elem end else begin append allready elem end end if unique ...
def remove_list_duplicates(lista, unique=False): """ Remove duplicated elements in a list. Args: lista: List with elements to clean duplicates. """ result = [] allready = [] for elem in lista: if elem not in result: result.append(elem) else: a...
Python
jtatman_500k
comment !/usr/bin/python from struct import * import os function bin num begin return call pack string >i num end function function build name begin set input = open name + string .list set levels = split read input string close input set filenames = list set special = list set story = list set clicks = list for in...
#!/usr/bin/python from struct import * import os def bin (num): return pack('>i', num) def build (name): input = open(name + '.list') levels = input.read().split("\n\n") input.close() filenames = [] special = [] story = [] clicks = [] for info in levels: info = info.strip() if not info or info.st...
Python
zaydzuhri_stack_edu_python
string Pandas Part-II import pandas as pd set teams = list string Rajasthan Royals string Delhi Capitals string Chennai Super Kings string Mumbai Indians string Delhi Capitals string Kolkata Knight Riders string Chennai Super Kings string Deccan Chargers string Kings XI Punjab string Mumbai Indias set ranks = list 2 3 ...
""" Pandas Part-II """ import pandas as pd teams = [ "Rajasthan Royals", "Delhi Capitals", "Chennai Super Kings", "Mumbai Indians", "Delhi Capitals", "Kolkata Knight Riders", "Chennai Super Kings", "Deccan Chargers", "Kings XI Punjab", "Mumbai Indias" ] ranks = [2, 3, 4, 1...
Python
zaydzuhri_stack_edu_python
import threading import thread import time class check_threding begin function __init__ self begin pass end function function add_nos self a b c begin set add = a + b + c print string ##### sleep 2 end function end class
import threading import thread import time class check_threding(): def __init__(self): pass def add_nos(self,a,b,c): add = a + b + c print("#####") time.sleep(2)
Python
zaydzuhri_stack_edu_python
import pygame import random import time call init set movement = tuple 1 0 set blockSize = 10 set width = 400 set height = 400 set gameInProgress = true set clock = call Clock set screen = call set_mode tuple width height class button begin function __init__ self x y w h color text=string begin set x = x set y = y set ...
import pygame import random import time pygame.init() movement = (1, 0) blockSize = 10 width = 400 height = 400 gameInProgress = True clock = pygame.time.Clock() screen = pygame.display.set_mode((width, height)) class button: def __init__(self, x, y, w, h, color, text=''): self.x = x self.y = ...
Python
zaydzuhri_stack_edu_python
function get_all self live_query=none begin if live_query begin set tuple lq_filters lq_fields = call _translate_live_query live_query end else begin set lq_filters = dict set lq_fields = dict end set tuple query fields = call build_mongodb_query lq_filters lq_fields if fields != dict begin set mongo_dicts = find ho...
def get_all(self, live_query=None): if live_query: lq_filters, lq_fields = _translate_live_query(live_query) else: lq_filters = {} lq_fields = {} query, fields = mongodb_query.build_mongodb_query(lq_filters, ...
Python
nomic_cornstack_python_v1
set dictionary = dict string Tractors 100 ; string Cars 50
dictionary = { "Tractors": 100, "Cars": 50 }
Python
iamtarun_python_18k_alpaca
string database.py import json from jsonpath import jsonpath from mongoengine import connect import os from models import Enemy , Level , Game , Powerup set DATABASE = string flask-mongodb-graphene set PASSWORD = get environ string MONGODB_PASSWORD set client = call connect DATABASE host=string mongodb+srv://mongograph...
""" database.py """ import json from jsonpath import jsonpath from mongoengine import connect import os from models import Enemy, Level, Game, Powerup DATABASE = "flask-mongodb-graphene" PASSWORD = os.environ.get("MONGODB_PASSWORD") client = connect( DATABASE, host=f"mongodb+srv://mongograph:{PASSWORD}@clust...
Python
zaydzuhri_stack_edu_python
function validate_shares self value begin if value < 1 or value > 100 begin raise call ValidationError string Shares value has to be between 1 and 100. end return value end function
def validate_shares(self, value): if value < 1 or value > 100: raise serializers.ValidationError('Shares value has to be between 1 and 100.') return value
Python
nomic_cornstack_python_v1
comment LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd function lesser_of_two_evens a b begin if a % 2 == 0 and b % 2 == 0 begin return min a b end else begin return max a b end end function comment CHEC...
#LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd def lesser_of_two_evens(a,b): if a%2==0 and b%2==0: return min(a,b) else: return max(a,b) #CHECK result=lesser_of_two_evens(2,...
Python
zaydzuhri_stack_edu_python
function password_strength s begin if length s < 8 begin raise call ValidationError string Password must be more than 8 characters long end end function
def password_strength(s): if len(s) < 8: raise ValidationError('Password must be more than 8 characters long')
Python
nomic_cornstack_python_v1
comment 용현ver function returnGCD num_list begin set num_list = list map lambda x -> integer x num_list set max_num = max num_list set i = 2 comment 최대 공약수 set gcd = 1 set cnt = 0 while true begin comment 입력 받은 수에 대해 특정 i 값으로 나눈값이 모두 0인 것을 찾는 루프문 for num in num_list begin if num % i == 0 begin set cnt = cnt + 1 end end ...
###용현ver def returnGCD(num_list): num_list = list(map(lambda x: int(x), num_list)) max_num = max(num_list) i = 2 gcd = 1 # 최대 공약수 cnt = 0 while True: # 입력 받은 수에 대해 특정 i 값으로 나눈값이 모두 0인 것을 찾는 루프문 for num in num_list: if num % i == 0: cnt += 1 ...
Python
zaydzuhri_stack_edu_python
function sum_list lst begin if length lst == 1 begin return lst at 0 end else begin return lst at 0 + call sum_list lst at slice 1 : : end end function
def sum_list(lst): if len(lst) == 1: return lst[0] else : return lst[0] + sum_list(lst[1:])
Python
nomic_cornstack_python_v1
import os import socket import struct from typing import List , Tuple from cares import rc4 try begin from cares import RR end except ImportError begin class RR begin string resource record of DNS, see https://www.ietf.org/rfc/rfc1035.txt for detail set __slots__ = list string domain_name string qtype string qcls strin...
import os import socket import struct from typing import List, Tuple from .cares import rc4 try: from .cares import RR except ImportError: class RR: """resource record of DNS, see https://www.ietf.org/rfc/rfc1035.txt for detail""" __slots__ = ["domain_name", "qtype", "qcls", "ttl", "valu...
Python
zaydzuhri_stack_edu_python
comment Unit 21. 터틀 그래픽스로 그림 그리기 comment 21.3 복잡한 도형 그리기 comment 21.3.1 원을 반복해서 그리기 import turtle as t comment 원을 60번 그림 set n = 60 call shape string turtle comment 거북이 속도를 가장 빠르게 설정 call speed string fastest for i in range n begin comment 반지름이 120인 원을 그림 call circle 120 comment 오른쪽으로 6도 회전 call right 360 / n end call ...
### Unit 21. 터틀 그래픽스로 그림 그리기 ## 21.3 복잡한 도형 그리기 ## 21.3.1 원을 반복해서 그리기 import turtle as t n = 60 # 원을 60번 그림 t.shape('turtle') t.speed('fastest') # 거북이 속도를 가장 빠르게 설정 for i in range(n): t.circle(120) # 반지름이 120인 원을 그림 t.right(360 / n) # 오른쪽으로 6도 회전 t.mainloop() ## 속도 ## 'fastest': 0 ## 'fa...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Dec 25 13:50:07 2019 @author: niles import numpy as np import pandas as pd import matplotlib.pyplot as plt comment converts a data into dataframe set dataset = read csv string 50_Startups.csv comment converts a data in to array set X = values set Y = values from sklea...
# -*- coding: utf-8 -*- """ Created on Wed Dec 25 13:50:07 2019 @author: niles """ import numpy as np import pandas as pd import matplotlib.pyplot as plt # converts a data into dataframe dataset=pd.read_csv('50_Startups.csv') # converts a data in to array X=dataset.iloc[:,:-1].values Y=dataset.ilo...
Python
zaydzuhri_stack_edu_python
string 클래스 오브젝트 : (객체 지향 프로그래밍 - OOP: Obj. Oriented Progmng) ** 함수형 프로그래밍 / 객체지향 프로그래밍 = 파이썬 특징의 2축! 1.클래스명 작명 = 파스칼 케이스 (ThisIsPascalCase) - 클래스 함수(매서드)의 첫번째 인자 = 인스턴스 자신(Self) - 클래스간 띄어쓰기는 2칸 / 함수(매서드)는 1칸 이다. 2.오브젝트(객체) : 클래스 오브젝트 <--> 인스턴스 - 값 (field) = 클래스변수 or 인스턴스 변수 - 기능 (method) = 매서드, 매직매서드, 더블언더스코어 3.클래스만의 매...
""" 클래스 오브젝트 : (객체 지향 프로그래밍 - OOP: Obj. Oriented Progmng) ** 함수형 프로그래밍 / 객체지향 프로그래밍 = 파이썬 특징의 2축! 1.클래스명 작명 = 파스칼 케이스 (ThisIsPascalCase) - 클래스 함수(매서드)의 첫번째 인자 = 인스턴스 자신(Self) - 클래스간 띄어쓰기는 2칸 / 함수(매서드)는 1칸 이다. 2.오브젝트(객체) : 클래스 오브젝트 <--> 인스턴스 - 값 (field) = 클래스변수 or 인스턴스 변수 - 기능 (method) = 매서드, 매직매서드, 더블언...
Python
zaydzuhri_stack_edu_python
function __init__ self data test_num=0 begin comment Initiate parent class and inherit all attributes and methods call __init__ data=data args=none test_num=test_num end function
def __init__(self,data,test_num=0): # Initiate parent class and inherit all attributes and methods super().__init__(data=data,args=None,test_num=test_num)
Python
nomic_cornstack_python_v1
function scale_number number factor begin set scaled_number = number * factor set rounded_number = integer scaled_number * 10 + 0.5 // 10 return rounded_number end function comment Output: 5 print call scale_number 10 0.5 comment Output: 8 print call scale_number 5 1.5 comment Output: -20 print call scale_number 100 - ...
def scale_number(number, factor): scaled_number = number * factor rounded_number = int(scaled_number * 10 + 0.5) // 10 return rounded_number print(scale_number(10, 0.5)) # Output: 5 print(scale_number(5, 1.5)) # Output: 8 print(scale_number(100, -0.2)) # Output: -20 print(scale_number(3.14159, 2.71828)...
Python
jtatman_500k