code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import numpy as np from Constants import * from Constants import h function rungeKuttaStep p h r begin set k1 = call calcDer p r set k2 = call calcDer p + k1 * h / 2 r set k3 = call calcDer p + k2 * h / 2 r set k4 = call calcDer p + k3 * h r set p = p + h / 6 * k1 + 2 * k2 + 2 * k3 + k4 return p end function function r...
import numpy as np from Constants import * from Constants import h def rungeKuttaStep(p, h, r): k1 = calcDer(p, r) k2 = calcDer(p + k1 * h / 2, r) k3 = calcDer(p + k2 * h / 2, r) k4 = calcDer(p + k3 * h, r) p = p + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4) return p def rungeKutta(x0, y0, z0, r): ...
Python
zaydzuhri_stack_edu_python
function to_json self attrs=none begin if attrs is none begin return __dict__ end set a_dict = dict for stuff in attrs begin try begin set a_dict at stuff = __dict__ at stuff end except any begin pass end end return a_dict end function
def to_json(self, attrs=None): if attrs is None: return self.__dict__ a_dict = {} for stuff in attrs: try: a_dict[stuff] = self.__dict__[stuff] except: pass return a_dict
Python
nomic_cornstack_python_v1
import requests import json comment Define endpoint set endpoint = string https://api.nytimes.com/svc/topstories/v2/home.json? comment Pass API key set payload = dict string api-key string INSERT-KEY-HERE comment Make request to endpoint set req = get requests endpoint params=payload comment Parse the response set data...
import requests import json # Define endpoint endpoint = 'https://api.nytimes.com/svc/topstories/v2/home.json?' # Pass API key payload = {'api-key': 'INSERT-KEY-HERE'} # Make request to endpoint req = requests.get(endpoint, params=payload) # Parse the response data = json.loads(req.text) # Iterate over results and...
Python
jtatman_500k
string use else condition to handle all other cases lower() - convert a string to lower case import turtle set t = call Turtle function draw_circle radius begin call circle radius end function function draw_shape sides length begin set angle = 360 / sides for i in range sides begin call forward length call left angle e...
''' use else condition to handle all other cases lower() - convert a string to lower case ''' import turtle t = turtle.Turtle() def draw_circle(radius): t.circle(radius) def draw_shape(sides, length): angle = 360 / sides for i in range(sides): t.forward(length) t.left(angle) polygon_sid...
Python
zaydzuhri_stack_edu_python
function get_res_name begin return call getenv string RESOURCES_VERSION string res_0.0 end function
def get_res_name(): return os.getenv("RESOURCES_VERSION", "res_0.0")
Python
nomic_cornstack_python_v1
import re set text = string I like apples. I like to eat pizza. I like coding. set matches = find all string ^I like(?: \w+)+ text for match in matches begin print match end
import re text = "I like apples. I like to eat pizza. I like coding." matches = re.findall(r'^I like(?: \w+)+', text) for match in matches: print(match)
Python
jtatman_500k
function construct_image imgs begin comment todo fill missing pieces and if length imgs == 0 begin return none end comment taking the first set tuple w h = size set img_array = call order_2d imgs set x_count = length img_array at 0 set y_count = length img_array set height = h * y_count set width = w * x_count set new_...
def construct_image(imgs): # todo fill missing pieces and if len(imgs) == 0: return None # taking the first w, h = imgs[0][1].size img_array = order_2d(imgs) x_count = len(img_array[0]) y_count = len(img_array) height = h * y_count width = w * x_count new_im = Image.new...
Python
nomic_cornstack_python_v1
function detect self det_iter show_timer=false is_image=true begin comment num_images = det_iter._size comment if not isinstance(det_iter, mx.io.PrefetchingIter): comment det_iter = mx.io.PrefetchingIter(det_iter) comment uncomment following lines to enable layer-wise timing ##################### import time function s...
def detect(self, det_iter, show_timer=False, is_image=True): # num_images = det_iter._size # if not isinstance(det_iter, mx.io.PrefetchingIter): # det_iter = mx.io.PrefetchingIter(det_iter) ########## uncomment following lines to enable layer-wise timing ##################### ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[343]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import pickle comment In[344]: set df = call read_excel string Data_Science_2020_v2.xlsx comment In[ ]: comment df.head() comment df.count() comment df.isnull().sum() comment ## Han...
#!/usr/bin/env python # coding: utf-8 # In[343]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import pickle # In[344]: df = pd.read_excel("Data_Science_2020_v2.xlsx") # In[ ]: #df.head() #df.count() #df.isnull().sum() # ## Handle missing values # In[345]: #handle missing values...
Python
zaydzuhri_stack_edu_python
string June 12, 2019 Given a set of closed intervals, find the smallest set of numbers that covers all the intervals. If there are multiple smallest sets, return any of them. For example, given the intervals [0, 3], [2, 6], [3, 4], [6, 9], one set of numbers that covers all these intervals is {3, 6}. function cover_clo...
''' June 12, 2019 Given a set of closed intervals, find the smallest set of numbers that covers all the intervals. If there are multiple smallest sets, return any of them. For example, given the intervals [0, 3], [2, 6], [3, 4], [6, 9], one set of numbers that covers all these intervals is {3, 6}. ''' def cover_clos...
Python
zaydzuhri_stack_edu_python
function screen self message indent=0 begin return log message level=string screen indent=indent end function
def screen( self, message: str, indent: int=0 ) -> LogEntry: return self.log(message, level="screen", indent=indent)
Python
nomic_cornstack_python_v1
function PlanToConfiguration self robot goal **kw_args begin return call _Snap robot goal keyword kw_args end function
def PlanToConfiguration(self, robot, goal, **kw_args): return self._Snap(robot, goal, **kw_args)
Python
nomic_cornstack_python_v1
function tout_stat self key=none begin return call stat key data_type=string tout end function
def tout_stat(self, key=None): return self.stat(key, data_type='tout')
Python
nomic_cornstack_python_v1
import dronekit_sitl import numpy as np import scipy.integrate as integrate string sitl = dronekit_sitl.start_default() connection_string = sitl.connection_string() # import DroneKit-Python from dronekit import connect, VehicleMode # Connect to the Vehicle. print("Connecting to vehicle on: %s" % (connection_string,)) v...
import dronekit_sitl import numpy as np import scipy.integrate as integrate """ sitl = dronekit_sitl.start_default() connection_string = sitl.connection_string() # import DroneKit-Python from dronekit import connect, VehicleMode # Connect to the Vehicle. print("Connecting to vehicle on: %s" % (connection_string,)) v...
Python
zaydzuhri_stack_edu_python
function assumed_state self begin return _optimistic end function
def assumed_state(self) -> bool: return self._optimistic
Python
nomic_cornstack_python_v1
import unittest from main.Compiler import compile from main.CompilationError import CompilationError set term_incomplete = string const X = 3; IF X* <> X THEN WRITE (X, '..') set int_too_large = string var X; begin X := 100000000000000000; writeln(X) end. set int_limit_ok = string var X; begin X := 4294967295; writeln(...
import unittest from main.Compiler import compile from main.CompilationError import CompilationError term_incomplete = ''' const X = 3; IF X* <> X THEN WRITE (X, '..') ''' int_too_large = ''' var X; begin X := 100000000000000000; writeln(X) end. ''' int_limit_ok = ''' var X; begin X := 4294967295; writeln...
Python
zaydzuhri_stack_edu_python
function _extract_buffers obj threshold=MAX_BYTES begin set buffers = list if is instance obj CannedObject and buffers begin for tuple i buf in enumerate buffers begin if length buf > threshold begin comment buffer larger than threshold, prevent pickling set buffers at i = none append buffers buf end else comment buff...
def _extract_buffers(obj, threshold=MAX_BYTES): buffers = [] if isinstance(obj, CannedObject) and obj.buffers: for i, buf in enumerate(obj.buffers): if len(buf) > threshold: # buffer larger than threshold, prevent pickling obj.buffers[i] = None ...
Python
nomic_cornstack_python_v1
class calculator begin function __init__ self number_list begin set number_list = number_list end function function sum self begin set total = 0 for number in number_list begin set total = total + number end return total end function function avg self begin set total = 0 for number in number_list begin set total = tota...
class calculator: def __init__(self,number_list): self.number_list = number_list def sum(self): total = 0 for number in self.number_list: total = total + number return total def avg(self): total = 0 for number in self.number_list: tot...
Python
zaydzuhri_stack_edu_python
function init *args **kwargs begin comment 0 = success, 1 = failure set exit_code = 0 set frameworks = list get kwargs string framework false if frameworks == list string all begin set frameworks = armory_frameworks end print string EXEC: Retrieved version { armory_version } . print string EXEC: Cleaning up... for key ...
def init(*args, **kwargs): exit_code = 0 # 0 = success, 1 = failure frameworks = [kwargs.get("framework", False)] if frameworks == ["all"]: frameworks = armory_frameworks print(f"EXEC:\tRetrieved version {armory_version}.") print("EXEC:\tCleaning up...") for key in ["framework", "func"...
Python
nomic_cornstack_python_v1
function sample self num_samples=1 begin comment shortcut set shape = shape set loc = loc set scale = scale comment some sampling set U = random sample num_samples set X = 1 / scale * - log U ^ 1 / shape return scale * X + loc end function
def sample(self, num_samples = 1): # shortcut shape = self.shape loc = self.loc scale = self.scale # some sampling U = self.UG.sample(num_samples) X = 1 / scale * (-np.log(U)) ** (1 / shape) return scale * X + loc
Python
nomic_cornstack_python_v1
from pyspark.sql.types import * from pyspark.sql.window import Window from pyspark.sql.session import SparkSession import pyspark.sql.functions as F set spark = call getOrCreate comment data creation################################### set dataList = list tuple 2345 string 2020-12-31 string retail string newyork tuple 2...
from pyspark.sql.types import * from pyspark.sql.window import Window from pyspark.sql.session import SparkSession import pyspark.sql.functions as F spark = SparkSession.builder.master("local").appName("getlatestdate").getOrCreate() #############################data creation################################### ...
Python
zaydzuhri_stack_edu_python
function test_create_delete_database self begin set db_name = string %s-testCreateDeleteDatabase % db_name set dynamic_buckets = call param string other_buckets 1 comment Create Buckets info string Creating '%s' buckets for initial load % num_buckets for _ in range num_buckets begin call __create_database end comment T...
def test_create_delete_database(self): self.db_name = "%s-testCreateDeleteDatabase" % self.db_name dynamic_buckets = self.input.param("other_buckets", 1) # Create Buckets self.log.info("Creating '%s' buckets for initial load" % self.num_buckets) for _ in ran...
Python
nomic_cornstack_python_v1
import json import string set jsn = string {"address":[{"country":"china","city":"wuhan","street":"huangpi"}, {"country":"japan","city":"tokyo","street":"osaki"}]} comment 读取json数据 comment 读取json文件 with open string data.json string r as f begin set p_data = load json f end comment 注意这种文件打开方式,先open,再read set j = open st...
import json import string jsn = '{"address":[{"country":"china","city":"wuhan","street":"huangpi"},\ {"country":"japan","city":"tokyo","street":"osaki"}]}' #读取json数据 with open('data.json','r') as f: #读取json文件 p_data = json.load(f) j = open('data.json','r') #注意这种文件打开方式,先open,再read read_data = j....
Python
zaydzuhri_stack_edu_python
function cancel self begin if receipt and not any generator expression get attribute self parameter for parameter in parameters begin set request = call Request string post RECEIPT_URL + receipt + string /cancel.json dict return request end end function
def cancel(self): if (self.receipt and not any(getattr(self, parameter) for parameter in self.parameters)): request = Request("post", RECEIPT_URL + self.receipt + "/cancel.json", {}) return request
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 with open string input_0301 as input begin set map_input = list comprehension list strip x for x in read lines input end set map_x = length map_input at 0 set map_y = length map_input set trees = list for pos_y in range 1 map_y begin set pos_x = pos_y * 3 % map_x if map_input at pos_y at ...
#!/usr/bin/env python3 with open('input_0301') as input: map_input = [list(x.strip()) for x in input.readlines()] map_x = len(map_input[0]) map_y = len(map_input) trees = [] for pos_y in range(1, map_y): pos_x = (pos_y * 3) % map_x if map_input[pos_y][pos_x] == "#": tree = (pos_x, pos_y) ...
Python
zaydzuhri_stack_edu_python
function get_object self begin set queryset = call filter_queryset call get_queryset comment Getting object by an id of object set obj = call get_object_or_404 queryset pk=data at string order_id comment May raise permission denied call check_object_permissions request obj return obj end function
def get_object(self): queryset = self.filter_queryset(self.get_queryset()) # Getting object by an id of object obj = get_object_or_404(queryset, pk=self.request.data["order_id"]) # May raise permission denied self.check_object_permissions(self.request, obj) return obj
Python
nomic_cornstack_python_v1
function logDirectory self begin return logDir end function
def logDirectory(self): return self.logDir
Python
nomic_cornstack_python_v1
function combine_samplings self new_sampling begin assert type new_sampling == Sampler assert target_variable == target_variable msg string Target variable names do not match. assert length input_variables == length input_variables msg string Input variables length mismatch. assert all list comprehension var in input_v...
def combine_samplings(self, new_sampling): assert type(new_sampling) == Sampler assert new_sampling.target_variable == self.target_variable, "Target variable names do not match." assert len(new_sampling.input_variables) == len(self.input_variables), "Input variables length mismatch." as...
Python
nomic_cornstack_python_v1
function get_dbinfo ibs verbose=true with_imgsize=false with_bytes=false with_contrib=false with_agesex=false with_header=true short=false tag=string dbinfo aid_list=none begin comment TODO Database size in bytes comment TODO: occurrence, contributors, etc... comment Basic variables set request_annot_subset = false com...
def get_dbinfo(ibs, verbose=True, with_imgsize=False, with_bytes=False, with_contrib=False, with_agesex=False, with_header=True, short=False, tag='dbinfo', aid_list=None): # TODO Database size in ...
Python
nomic_cornstack_python_v1
import threading import socket import datetime import logging set FORMAT = string %(asctime)s %(thread)d %(message)s call basicConfig format=FORMAT level=INFO class ChatUdpServer begin function __init__ self ip=string 127.0.0.1 port=9999 interval=10 begin comment 创建udp对象需要指明类型 set sock = call socket type=SOCK_DGRAM set...
import threading import socket import datetime import logging FORMAT = '%(asctime)s %(thread)d %(message)s' logging.basicConfig(format=FORMAT, level=logging.INFO) class ChatUdpServer: def __init__(self, ip='127.0.0.1', port=9999, interval=10): self.sock = socket.socket(type=socket.SOCK_DGRAM) #创建udp对象需要指明...
Python
zaydzuhri_stack_edu_python
function test_env_a self begin assert equal A string a end function
def test_env_a(self): self.assertEqual(self.settings.A, 'a')
Python
nomic_cornstack_python_v1
for friend in friends begin print format string Live long and prosper, {}. friend end print string Bye!
for friend in friends: print('Live long and prosper, {}.'.format(friend)) print('Bye!')
Python
zaydzuhri_stack_edu_python
function find_module self fullname path=none begin if fullname in names begin return self end end function
def find_module(self, fullname, path=None): if fullname in self.names: return self
Python
nomic_cornstack_python_v1
from tkinter import * from tkinter import ttk from tkinter import messagebox from random import randint , choice , shuffle import pyperclip import json comment ---------------------------- SEARCH PASSWORD ---------------------------------- # function find_password begin set search_word = get website_entry try begin wit...
from tkinter import * from tkinter import ttk from tkinter import messagebox from random import randint, choice, shuffle import pyperclip import json # ---------------------------- SEARCH PASSWORD ---------------------------------- # def find_password(): search_word = website_entry.get() try: with ope...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python function way str_arg begin call small_point_and_long_day str_arg print string work_early_week_at_day end function function small_point_and_long_day str_arg begin print str_arg end function if __name__ == string __main__ begin call way string place_or_child end
#! /usr/bin/env python def way(str_arg): small_point_and_long_day(str_arg) print('work_early_week_at_day') def small_point_and_long_day(str_arg): print(str_arg) if __name__ == '__main__': way('place_or_child')
Python
zaydzuhri_stack_edu_python
function edit_oedeploymentplan self *editoedeploymentplan_obj begin set MAX_CHAR = 255 set s2l = call get_s2l string Navigate to DeploymentPlan Page if not call _is_element_present ID_PAGE_LABEL begin call navigate end string Retrieve data from datasheet if type editoedeploymentplan_obj is DataObj begin set editoedeplo...
def edit_oedeploymentplan(self, *editoedeploymentplan_obj): MAX_CHAR = 255 s2l = ui_lib.get_s2l() """ Navigate to DeploymentPlan Page """ if not s2l._is_element_present(i3sDeploymentPlanPage.ID_PAGE_LABEL): navigate() """ Retrieve data from datasheet """ if type(editoedeploymentplan_obj...
Python
nomic_cornstack_python_v1
function Epilog self resources_were_displayed begin if not resources_were_displayed begin print string Listed 0 items. end end function
def Epilog(self, resources_were_displayed): if not resources_were_displayed: log.status.Print('Listed 0 items.')
Python
nomic_cornstack_python_v1
function genTopLevelDirCMakeListsFile self working_path subdirs files cfg begin string Generate top level CMakeLists.txt. :param working_path: current working directory :param subdirs: a list of subdirectories of current working directory. :param files: a list of files in current working directory. :return: the full pa...
def genTopLevelDirCMakeListsFile(self, working_path, subdirs, files, cfg): """ Generate top level CMakeLists.txt. :param working_path: current working directory :param subdirs: a list of subdirectories of current working directory. :param files: a list of files in current workin...
Python
jtatman_500k
import numpy as np comment clearly, 1st and 4th rows are linealy dependent set A = call matrix list list 2 1 3 list - 1 0 2 list 3 0 - 2 list 4 2 6
import numpy as np A = np.matrix([[2,1,3],[-1,0,2],[3,0,-2],[4,2,6]]) # clearly, 1st and 4th rows are linealy dependent
Python
zaydzuhri_stack_edu_python
function spawn_cleaning_error_handler e node begin call _spawn_error_handler e node CLEANING end function
def spawn_cleaning_error_handler(e, node): _spawn_error_handler(e, node, states.CLEANING)
Python
nomic_cornstack_python_v1
comment Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j]. comment If there is no solution possible, return -1. from sys import maxint function maximumGap arr begin set n = length arr set start = 0 set end = n - 1 set maximum = - maxint - 1 if n == 0 or n == 1 begin ret...
#Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j]. #If there is no solution possible, return -1. from sys import maxint def maximumGap(arr): n = len(arr) start = 0 end = n-1 maximum = -maxint-1 if n == 0 or n==1: return 0 while (start...
Python
zaydzuhri_stack_edu_python
function iterate_file fpath start=none stop=none step=none mmap_mode=none begin set slicer = call slice start stop step set tuple _ ext = call splitext fpath if ext == string .pkl begin set events = call load_pickle fpath end else if ext == string .npy begin try begin set events = load np fpath mmap_mode=mmap_mode end ...
def iterate_file(fpath, start=None, stop=None, step=None, mmap_mode=None): slicer = slice(start, stop, step) _, ext = splitext(fpath) if ext == '.pkl': events = load_pickle(fpath) elif ext == '.npy': try: events = np.load(fpath, mmap_mode=mmap_mode) except: ...
Python
nomic_cornstack_python_v1
function testTrainSplit self X y sessionId testSize=0.3 randomState=1 splitType=string stratified begin comment X = array(X) comment y = array(y) set sessionId = array sessionId end function
def testTrainSplit(self, X, y,sessionId, testSize=0.3, randomState = 1, splitType = 'stratified'): #X = array(X) #y = array(y) sessionId = np.array(sessionId)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding:utf-8 string #============================================================================= # FileName: ConnectionBase.py # Desc: tornado Transport class # Author: sunminghong # Email: allen.fantasy@gmail.com # HomePage: http://weibo.com/5d13 # Version: 0.0.1 # LastChange: 20...
#!/usr/bin/env python #coding:utf-8 ''' #============================================================================= # FileName: ConnectionBase.py # Desc: tornado Transport class # Author: sunminghong # Email: allen.fantasy@gmail.com # HomePage: http://weibo.com/5d13 # Version: 0.0.1...
Python
zaydzuhri_stack_edu_python
import boto3 function lambda_handler event context begin set iam_users = call client string iam set paginator = call get_paginator string list_users set count = 0 for pages in paginate paginator begin for users in pages at string Users begin print users at string UserName set count = count + 1 end end print string tota...
import boto3 def lambda_handler(event, context): iam_users=boto3.client('iam') paginator=iam_users.get_paginator('list_users') count=0 for pages in paginator.paginate(): for users in pages['Users']: print(users['UserName']) count +=1 print('total data in each page',...
Python
zaydzuhri_stack_edu_python
import pigpio from time import sleep import math function main begin comment BCM pin numbers set APWM = 12 set AIN1 = 4 set AIN2 = 17 set BPWM = 13 set BIN1 = 27 set BIN2 = 22 set count = 0 set m1_rate = 250 set m2_rate = 333 set PWM_RANGE = 1024 set left_direction = true set right_direction = true set left_direction_l...
import pigpio from time import sleep import math def main(): #BCM pin numbers APWM= 12 AIN1 = 4 AIN2 = 17 BPWM = 13 BIN1 = 27 BIN2 = 22 count = 0 m1_rate = 250 m2_rate = 333 PWM_RANGE = 1024 left_direction = True right_direction = True left_direction_last = True right_direction_last = True print("[*...
Python
zaydzuhri_stack_edu_python
import urllib.request url retrieve string https://github.com/git-for-windows/git/releases/download/v2.33.1.windows.1/Git-2.33.1-64-bit.exe string GitSetup.exe
import urllib.request urllib.request.urlretrieve('https://github.com/git-for-windows/git/releases/download/v2.33.1.windows.1/Git-2.33.1-64-bit.exe', 'GitSetup.exe')
Python
flytech_python_25k
function get_load_balancer_outbound_ports self begin comment read the original value passed by the command set load_balancer_outbound_ports = get raw_param string load_balancer_outbound_ports comment In create mode, try to read the property value corresponding to the parameter from the `mc` object. if decorator_mode ==...
def get_load_balancer_outbound_ports(self) -> Union[int, None]: # read the original value passed by the command load_balancer_outbound_ports = self.raw_param.get( "load_balancer_outbound_ports" ) # In create mode, try to read the property value corresponding to the parameter ...
Python
nomic_cornstack_python_v1
set n = integer input set new_list = list comprehension integer x * n for x in split input print new_list
n = int(input()) new_list = [int(x)*n for x in input().split()] print(new_list)
Python
zaydzuhri_stack_edu_python
function get_metrics self begin set world = world set build_stats = dictionary comprehension idx : dict string n_builds 0 for a in agents for builds in builds begin for build in builds begin set idx = build at string builder set build_stats at idx at string n_builds = build_stats at idx at string n_builds + 1 end end s...
def get_metrics(self): world = self.world build_stats = {a.idx: {"n_builds": 0} for a in world.agents} for builds in self.builds: for build in builds: idx = build["builder"] build_stats[idx]["n_builds"] += 1 out_dict = {} for a in wor...
Python
nomic_cornstack_python_v1
function align_coords self coords_list eps=0.03 min_sample=2 angle_thresh=90.0 copy_list=true begin if copy_list begin set coords_list = copy copy coords_list end comment dbscan = DBSCAN(eps=eps, min_samples=min_sample).fit( comment [coords.worldpos() for coords in coords_list]) call dbscan_coords coords_list eps min_s...
def align_coords(self, coords_list, eps=0.03, min_sample=2, angle_thresh=90., copy_list=True): if copy_list: coords_list = copy.copy(coords_list) # dbscan = DBSCAN(eps=eps, min_samples=min_sample).fit( # [coords.worldpos() for coords in coords_list]) ...
Python
nomic_cornstack_python_v1
function tag_count self begin return length unique_tags end function
def tag_count(self): return len(self.unique_tags)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment passing mutable datatype as argument to function, object unchanged
#!/usr/bin/python # passing mutable datatype as argument to function, object unchanged
Python
zaydzuhri_stack_edu_python
function __init__ self begin pass end function
def __init__(self): pass
Python
nomic_cornstack_python_v1
comment encoding: utf-8 comment 正则表达式 .不能匹配\n import re import requests function parse_page url begin set headers = dict string user-agent string Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36 set response = get requests url headers=headers set ...
# encoding: utf-8 # 正则表达式 .不能匹配\n import re import requests def parse_page(url): headers = { 'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36', } response = requests.get(url,headers=headers) text = respo...
Python
zaydzuhri_stack_edu_python
function DeleteObject self *args **kwargs begin pass end function
def DeleteObject(self, *args, **kwargs): pass
Python
nomic_cornstack_python_v1
comment python code to demonstrate working of reduce() comment importing functools for reduce() import functools comment initializing list set lis = list 1 3 5 6 2 comment using reduce to compute sum of list print string The sum of the list elements is : end=string print reduce lambda a b -> a + b lis comment using red...
# python code to demonstrate working of reduce() # importing functools for reduce() import functools # initializing list lis = [ 1 , 3, 5, 6, 2, ] # using reduce to compute sum of list print ("The sum of the list elements is : ",end="") print (functools.reduce(lambda a,b : a+b,lis)) # using reduce t...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment File: darwin_walk_demo.py comment Description: Executes walk_limit number of walks for the Darwin OP in gazebo comment and records the distance travelled and average height for each comment walk. The walking algorithm is the default one provided. comment Also plots and creates a dat...
#!/usr/bin/env python ############################################################################### # File: darwin_walk_demo.py # Description: Executes walk_limit number of walks for the Darwin OP in gazebo # and records the distance travelled and average height for each # walk. The walking...
Python
zaydzuhri_stack_edu_python
import math function magnitude_to_vector magnitude angle begin set x = magnitude * cos call radians angle set y = magnitude * sin call radians angle set z = 0 return tuple x y z end function set result = call magnitude_to_vector 5 90 print string The vector is { result }
import math def magnitude_to_vector(magnitude, angle): x = magnitude * math.cos(math.radians(angle)) y = magnitude * math.sin(math.radians(angle)) z = 0 return (x, y, z) result = magnitude_to_vector(5, 90) print(f"The vector is {result}")
Python
iamtarun_python_18k_alpaca
comment 204 单例 ####感觉这一类的也要单独刷 comment 212 空格替换 感觉题目出错了 class Solution begin comment @param {char[]} string: An array of Char comment @param {int} length: The true length of the string comment @return {int} The true length of new string function replaceBlank self string length begin comment Write your code here set a =...
#204 单例 ####感觉这一类的也要单独刷 #212 空格替换 感觉题目出错了 class Solution: # @param {char[]} string: An array of Char # @param {int} length: The true length of the string # @return {int} The true length of new string def replaceBlank(self, string, length): # Write your code here a = len(string) ...
Python
zaydzuhri_stack_edu_python
function post_process self env activity_log activity start_activity *args **kwargs begin comment Check if delay has been defined. If not no delay is added. if delay_factor is none begin return dict end else comment Check if given delay factor is a random variate. if delay_is_dist begin set dt = now - start_activity se...
def post_process( self, env, activity_log, activity, start_activity, *args, **kwargs ): # Check if delay has been defined. If not no delay is added. if self.delay_factor is None: return {} # Check if given delay factor is a random variate. elif self.delay_is_dist...
Python
nomic_cornstack_python_v1
function excludeRotatedSolutions grid_size solutions begin set pruned_solutions = list for sol in solutions begin if not call isRotation grid_size sol begin append pruned_solutions sol end end return pruned_solutions end function
def excludeRotatedSolutions(grid_size, solutions): pruned_solutions = [] for sol in solutions: if not isRotation(grid_size, sol): pruned_solutions.append(sol) return pruned_solutions
Python
nomic_cornstack_python_v1
string Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? #method1: use hash to record node #method2: fast and slow pointer comment Definition for singly-linked list. comment class ListNode(object): comment def __init__(self, x): comment self.val = x comment s...
''' Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? #method1: use hash to record node #method2: fast and slow pointer ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.ne...
Python
zaydzuhri_stack_edu_python
function get_context_data self begin try begin set img = call order_by string ? at 0 end comment maybe Photo.objects.filter(published = 'pub')[:200].order_by("?")[0] except IndexError begin set img = none end return dict string img img end function
def get_context_data(self): try: img = Photo.objects.all().order_by("?")[0] # maybe Photo.objects.filter(published = 'pub')[:200].order_by("?")[0] except IndexError: img = None return {'img': img}
Python
nomic_cornstack_python_v1
function plugin_name self begin return string yuicompressor end function
def plugin_name(self): return "yuicompressor"
Python
nomic_cornstack_python_v1
comment 1) Создать базу данных товаров, у товара есть: Категория (связанная comment таблица), название, есть ли товар в продаже или на складе, цена, кол-во comment единиц.Создать html страницу. На первой странице выводить ссылки на все comment категории, при переходе на категорию получать список всех товаров в comment ...
# 1) Создать базу данных товаров, у товара есть: Категория (связанная # таблица), название, есть ли товар в продаже или на складе, цена, кол-во # единиц.Создать html страницу. На первой странице выводить ссылки на все # категории, при переходе на категорию получать список всех товаров в # наличии ссылками, при клике на...
Python
zaydzuhri_stack_edu_python
comment #import required packages function main begin comment Importing Libraries import pandas as pd import numpy as np import math import matplotlib.pyplot as plt comment Sklearn from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_square...
# #import required packages def main(): # Importing Libraries import pandas as pd import numpy as np import math import matplotlib.pyplot as plt # Sklearn from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.metr...
Python
zaydzuhri_stack_edu_python
import numpy import sys import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import waveIO comment import pyaudio function create_wave freq t begin return 5000 * cos freq * 2 * pi * t end function function window_hanning wave_window begin comment get the values of a hanning curve. The wave window wil...
import numpy import sys import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import waveIO #import pyaudio def create_wave(freq,t): return 5000 * numpy.cos(freq * 2 * numpy.pi * t) def window_hanning(wave_window): #get the values of a hanning curve. The wave window will be multiplied by these ...
Python
zaydzuhri_stack_edu_python
function check_unique self cr uid ids context=none begin for rec in call browse cr uid ids context=context begin set domain = list tuple string name string = name tuple string part string = part tuple string id string != id set idss = search cr uid domain if idss begin raise call except_osv call _ string ERROR call _ s...
def check_unique(self, cr, uid, ids, context=None): for rec in self.browse(cr, uid, ids, context=context): domain = [('name', '=', rec.name),('part', '=', rec.part),('id','!=',rec.id)] idss = self.search(cr,uid, domain) if idss: raise osv...
Python
nomic_cornstack_python_v1
function remove feed_id begin set query = filter by query id=feed_id set f = first query comment check feed exists. if f is none begin call flash string Sorry, this feed does not exist string error return call redirect call url_for string feeds end comment Check user is the correct one. if not user_id == session at str...
def remove(feed_id): query = Feed.query.filter_by(id=feed_id) f = query.first() # check feed exists. if f is None: flash("Sorry, this feed does not exist", "error") return redirect(url_for("feeds")) # Check user is the correct one. if not f.user_id == session["user_id"]: ...
Python
nomic_cornstack_python_v1
from firebase import firebase as fb import piratedata import firebasemanager from tkinter import * import random function addnew begin comment create a new instance of pirate class set p = call Pirate comment get values out of boxes comment load into pirate set name = get nBox set ship = get sBox set fictional = get op...
from firebase import firebase as fb import piratedata import firebasemanager from tkinter import* import random def addnew(): #create a new instance of pirate class p = piratedata.Pirate() #get values out of boxes #load into pirate p.name = nBox.get() p.ship = sBox.get() p.fictio...
Python
zaydzuhri_stack_edu_python
import random from operator import add from operator import mul import numpy as np import pandas as pd import csv class QLearn begin function __init__ self actions epsilon=0.3 alpha=0.2 gamma=0.6 begin set q = dict set epsilon = epsilon set alpha = alpha set gamma = gamma set actions = actions end function function ge...
import random from operator import add from operator import mul import numpy as np import pandas as pd import csv class QLearn: def __init__(self, actions, epsilon=0.3, alpha=0.2, gamma=0.6): self.q = {} self.epsilon = epsilon self.alpha = alpha self.gamma = gamma self.act...
Python
zaydzuhri_stack_edu_python
function download_image_link self link dst begin debug format string downloading: "{}", to: "{}" link dst set response = get requests link stream=true with open dst string wb as f begin call copyfileobj raw f end end function
def download_image_link(self, link, dst): self.logger.debug('downloading: "{}", to: "{}"'.format(link, dst)) response = requests.get(link, stream=True) with open(dst, 'wb') as f: shutil.copyfileobj(response.raw, f)
Python
nomic_cornstack_python_v1
comment noqa: E501 function __init__ self pagination=none vehicle_stats=none begin set openapi_types = dict string pagination Pagination ; string vehicle_stats List at InlineResponse2005VehicleStats set attribute_map = dict string pagination string pagination ; string vehicle_stats string vehicleStats set _pagination =...
def __init__(self, pagination=None, vehicle_stats=None): # noqa: E501 self.openapi_types = { 'pagination': Pagination, 'vehicle_stats': List[InlineResponse2005VehicleStats] } self.attribute_map = { 'pagination': 'pagination', 'vehicle_stats': 've...
Python
nomic_cornstack_python_v1
function reverse_ns viewname api_version=none args=none kwargs=none **extra begin set api_version = api_version or DEFAULT_VERSION set request = call req_factory_factory string /api/%s/ % api_version set versioning_scheme = call DEFAULT_VERSIONING_CLASS set version = api_version return call drf_reverse viewname args=ar...
def reverse_ns(viewname, api_version=None, args=None, kwargs=None, **extra): api_version = api_version or api_settings.DEFAULT_VERSION request = req_factory_factory('/api/%s/' % api_version) request.versioning_scheme = api_settings.DEFAULT_VERSIONING_CLASS() request.version = api_version return drf_...
Python
nomic_cornstack_python_v1
class Solution extends object begin function findNNumber self nums1 nums2 n begin set len1 = length nums1 set len2 = length nums2 if len1 == 0 begin return nums2 at n - 1 end if len2 == 0 begin return nums1 at n - 1 end set x = 0 set t1 = 0 set t2 = 0 set result = 0 while x != n begin if t1 > len1 - 1 begin set result ...
class Solution(object): def findNNumber(self,nums1,nums2,n): len1=len(nums1) len2=len(nums2) if len1==0: return nums2[n-1] if len2==0: return nums1[n-1] x=0 t1=0 t2=0 result=0 while(x!=n): if t1>len1-1: result=nums2[t2] t2=t2+1 x+=1 continue if t2>len2-1:...
Python
zaydzuhri_stack_edu_python
import unittest import electioncount class ElectionCountTest extends TestCase begin function test_TrumpCount self begin set result = call ElectionCount string Trump assert equal result 33660 end function end class
import unittest import electioncount class ElectionCountTest(unittest.TestCase): def test_TrumpCount(self): result = electioncount.ElectionCount('Trump') self.assertEqual(result, 33660)
Python
zaydzuhri_stack_edu_python
function process_request api begin set begin = time comment multiprocessing completion signal set signal = call Value string i 0 comment several iterations of external requests until satisfied with response set i = 0 while i < ATTEMPTS and not value begin comment multiprocessing text file name nonce set api at string n...
def process_request(api): begin = time.time() # multiprocessing completion signal signal = Value("i", 0) # several iterations of external requests until satisfied with response i = 0 while (i < ATTEMPTS) and not signal.value: # multiprocessing text file name nonce api["nonce"] = ...
Python
nomic_cornstack_python_v1
function placeLimitOrder self *args **kwargs begin raise NotImplementedError end function
def placeLimitOrder(self, *args, **kwargs): raise NotImplementedError
Python
nomic_cornstack_python_v1
comment Definition for singly-linked list. comment class ListNode: comment def __init__(self, x): comment self.val = x comment self.next = None class Solution begin function addTwoNumbers self l1 l2 begin string :type l1: ListNode :type l2: ListNode :rtype: ListNode set result = call ListNode 0 set carry_on = 0 set las...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ result = ListNode(0) ...
Python
zaydzuhri_stack_edu_python
function gen_image posix_path_folder begin set extensions = list string bmp string dib string jpg string jpeg string jpe string png set extensions = list comprehension string *. + ext for ext in extensions for ext in extensions begin for posix_path in glob posix_path_folder ext begin set path_img = string posix_path se...
def gen_image(posix_path_folder): extensions = ['bmp', 'dib', 'jpg', 'jpeg', 'jpe', 'png'] extensions = ['*.' + ext for ext in extensions] for ext in extensions: for posix_path in posix_path_folder.glob(ext): path_img = str(posix_path) name_img = posix_path.name i...
Python
nomic_cornstack_python_v1
function mape self begin return decimal mean np absolute true - predicted / true * 100 end function
def mape(self) -> float: return float(np.mean(np.abs((self.true - self.predicted) / self.true)) * 100)
Python
nomic_cornstack_python_v1
string Atribuicao multipla EM JAVA,C,C++,C# E JAVASCRIPT PARA ATRIBUIRMOS A TROCA DOS VALORES DE VARIAVEL FAZEMOS DESSA FOMA: a = 10 b = 5 x = a a = b b = x print(a) print(b) comment troca os valores das variaveis set a = 10 set b = 5 set x = a set a = b set b = x print a print b print comment em Python utilizamos dess...
""" Atribuicao multipla EM JAVA,C,C++,C# E JAVASCRIPT PARA ATRIBUIRMOS A TROCA DOS VALORES DE VARIAVEL FAZEMOS DESSA FOMA: a = 10 b = 5 x = a a = b b = x print(a) print(b) """ #troca os valores das variaveis a = 10 b = 5 x = a a = b b = x print(a) print(b) print() #em Python utilizamos dessa f...
Python
zaydzuhri_stack_edu_python
function cosine_similarity self x y begin return dot x y / norm x * norm y end function
def cosine_similarity(self, x, y): return np.dot(x, y) / (np.linalg.norm(x) * np.linalg.norm(y))
Python
nomic_cornstack_python_v1
comment Author: Gabrielle Josephson comment Project 2 - Bloom Filter comment CS 370 - Introduction to Security, Oregon State University, Fall 2021 comment Sources: https://www.w3schools.com/python/python_file_write.asp , comment https://www.geeksforgeeks.org/get-current-timestamp-using-python/ from hashing import * fro...
# Author: Gabrielle Josephson # Project 2 - Bloom Filter # CS 370 - Introduction to Security, Oregon State University, Fall 2021 # Sources: https://www.w3schools.com/python/python_file_write.asp , # https://www.geeksforgeeks.org/get-current-timestamp-using-python/ from hashing import * from dict_actions import * impo...
Python
zaydzuhri_stack_edu_python
function find_cosine_angles begin comment Given angle set angle = 340 comment Calculate possible angles based on cosine properties comment cos(-20°) = cos(20°) set n1 = 20 comment Original angle set n2 = 340 comment Store valid angles in a list set valid_angles = list comment Append angles that satisfy the range condi...
def find_cosine_angles(): # Given angle angle = 340 # Calculate possible angles based on cosine properties n1 = 20 # cos(-20°) = cos(20°) n2 = 340 # Original angle # Store valid angles in a list valid_angles = [] # Append angles that satisfy the range condition if 0 <= n1 <= 360...
Python
dbands_pythonMath
set sample = string Hi,My name is ankit i have done my Btech from hbti kanpur in the year 2014 print sample + string i joined cognizant in the year 2015 set string1 = string Routhan print string1 at slice 2 : 6 : print string1 at - 6 print count sample string H 0 9 print is alpha sample print upper sample
sample='''Hi,My name is ankit i have done my Btech from hbti kanpur in the year 2014''' print(sample + " i joined cognizant in the year 2015") string1='Routhan' print(string1[2:6]) print(string1[-6]) print(sample.count('H',0,9)) print(sample.isalpha()) print(sample.upper())
Python
zaydzuhri_stack_edu_python
comment Should be loaded already from django.db import models comment Need to varify < or > for Date Field from datetime import date comment Needed for REGEX import re comment Create your models here. class UserManager extends Manager begin function registerValidation self postData begin set EMAIL_REGEX = compile strin...
from django.db import models # Should be loaded already from datetime import date # Need to varify < or > for Date Field import re # Needed for REGEX # Create your models here. class UserManager(models.Manager): def registerValidation(self, postData): EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-...
Python
zaydzuhri_stack_edu_python
comment IMPORTS ######################################################################### import math comment True = print info variables in console set console = list false comment CONSTANTS ### comment Paths set icon_path = string files/icon.png set font_path = string files/font.ttf set menu_bg_path = list string fil...
############################################################################ IMPORTS ######################################################################### import math ###############################################################################################################################################...
Python
zaydzuhri_stack_edu_python
comment Constructors and Destructors in Inheritance class Base begin function __init__ self begin print string Base Constructor end function end class class Derive extends Base begin function __init__ self begin call __init__ print string Derive Constructor end function end class set obj = call Derive
#Constructors and Destructors in Inheritance class Base: def __init__(self): print("Base Constructor") class Derive(Base): def __init__(self): super(Derive, self).__init__() print("Derive Constructor") obj=Derive()
Python
zaydzuhri_stack_edu_python
function target_delayed x seed instance begin sleep 1 return tuple x ^ 2 dict string key seed ; string instance instance end function
def target_delayed(x: float, seed: int, instance: str) -> tuple[float, dict]: time.sleep(1) return x**2, {"key": seed, "instance": instance}
Python
nomic_cornstack_python_v1
from tkinter import * import requests from bs4 import BeautifulSoup import html5lib import re from copy import copy set window = call Tk call geometry string 450x450 title window string Emails from the Link set entry1 = call StringVar function fetch begin try begin set url = get entry1 set r = get requests url set cont...
from tkinter import * import requests from bs4 import BeautifulSoup import html5lib import re from copy import copy window = Tk() window.geometry('450x450') window.title('Emails from the Link') entry1 = StringVar() def fetch(): try: url = entry1.get() r = requests.get(url) content = r....
Python
zaydzuhri_stack_edu_python
function incrementCountInNestedDict current diff begin for tuple key value in call iteritems begin if is instance value dict begin call incrementCountInNestedDict set default current key dict value end else begin set current at key = get current key 0 + value end end end function
def incrementCountInNestedDict(current, diff): for key, value in diff.iteritems(): if isinstance(value, dict): incrementCountInNestedDict(current.setdefault(key, {}), value) else: current[key] = current.get(key, 0) + value
Python
nomic_cornstack_python_v1
function test_correlation_metrics_daskda_same_npda a_dask b_dask dim weight_bool weights_cos_lat_dask metrics skipna has_nan begin set a = copy a_dask set b = copy b_dask set weights = copy weights_cos_lat_dask set tuple metric _ = metrics if has_nan begin set a = load a set a at 0 = nan set a = call chunk end comment ...
def test_correlation_metrics_daskda_same_npda( a_dask, b_dask, dim, weight_bool, weights_cos_lat_dask, metrics, skipna, has_nan ): a = a_dask.copy() b = b_dask.copy() weights = weights_cos_lat_dask.copy() metric, _ = metrics if has_nan: a = a.load() a[0] = np.nan a = a.ch...
Python
nomic_cornstack_python_v1
function current_index self begin return _current_index end function
def current_index(self) -> int: return self._current_index
Python
nomic_cornstack_python_v1
import sys function print_int_lists *args begin string "printing the list of integer set a = list comprehension i for i in range integer args at 0 print a return a end function if __name__ == string __main__ begin call print_int_lists argv at 1 end
import sys def print_int_lists(*args): """"printing the list of integer""" a = [i for i in range(int(args[0]))] print(a) return a if __name__ == '__main__': print_int_lists(sys.argv[1])
Python
zaydzuhri_stack_edu_python
function calculate_damage your_type opponent_type attack defense begin set win = list string fire string water string grass string electric set los = list string grass string fire string water string water set effectiveness = 1 if your_type == opponent_type begin set effectiveness = 0.5 end if your_type in win begin se...
def calculate_damage(your_type, opponent_type, attack, defense): win=["fire","water","grass","electric"] los=["grass","fire","water","water"] effectiveness=1 if your_type==opponent_type: effectiveness=0.5 if your_type in win: index=win.index(your_type) if opponent_type == los...
Python
zaydzuhri_stack_edu_python
from BlinkyTape import BlinkyTape import time import GlobalSettings as G function fade_channel channel blinky begin while keepGoing is false begin continue end while true begin comment fade up for t in call xrange 0 256 8 begin for x in range 0 150 begin if channel == 0 begin call sendPixel t 0 0 end else if channel ==...
from BlinkyTape import BlinkyTape import time import GlobalSettings as G def fade_channel(channel,blinky): while G.keepGoing is False: continue while True: #fade up for t in xrange(0,256,8): for x in range(0,150): if channel == 0: blinky....
Python
zaydzuhri_stack_edu_python
function list_exports self begin return list _id end function
def list_exports(self): return Export.list(self._id)
Python
nomic_cornstack_python_v1
function on_window_close self begin if rep_timer begin call stop end call stop return end function
def on_window_close(self): if self.rep_timer: self.rep_timer.stop() Simulator.stop() return
Python
nomic_cornstack_python_v1