code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function fit_transform self X y=none confounds=none begin if kind == string tangent and length X <= 1 begin comment Check that people are applying fit_transform to a group of comment subject comment We can only impose this in fit_transform, as it is legit to comment fit only on a single given reference point raise call...
def fit_transform(self, X, y=None, confounds=None): if self.kind == "tangent" and len(X) <= 1: # Check that people are applying fit_transform to a group of # subject # We can only impose this in fit_transform, as it is legit to # fit only on a single given referen...
Python
nomic_cornstack_python_v1
import keyboard import pyautogui from time import sleep import win32api , win32con comment pyautogui.mouseInfo() function click coords begin call SetCursorPos coords call mouse_event MOUSEEVENTF_LEFTDOWN 0 0 sleep 0.01 call mouse_event MOUSEEVENTF_LEFTUP 0 0 end function set pixel = tuple 1511 641 while true begin if c...
import keyboard import pyautogui from time import sleep import win32api, win32con # pyautogui.mouseInfo() def click(coords): win32api.SetCursorPos(coords) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0,0) sleep(0.01) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0,0) pixel =...
Python
zaydzuhri_stack_edu_python
function publish_pd_controllergoal self PDgoal8=none Samplecounter=none time_speed=1 soft_start=true begin if PDgoal8 != none begin set PDControllerGoal8Msg = PDgoal8 end else begin if currentlyActiveTrajectoryNumber is none begin return end if Samplecounter == none begin return end if Samplecounter < 0 begin return en...
def publish_pd_controllergoal(self,PDgoal8=None,Samplecounter = None, time_speed=1, soft_start=True ): if PDgoal8 != None: PDControllerGoal8Msg = PDgoal8 else: if self.currentlyActiveTrajectoryNumber is None: return if Samplecounter == None: ...
Python
nomic_cornstack_python_v1
import socket import datetime import argparse function time_request host request begin set s = call socket AF_INET SOCK_STREAM 0 set host = split host string : call connect tuple host at 0 integer host at 1 set time_start = now call send request call recv 1024 set time_end = now set diff = time_end - time_start return ...
import socket import datetime import argparse def time_request(host, request): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) host = host.split(':') s.connect((host[0], int(host[1]))) time_start = datetime.datetime.now() s.send(request) s.recv(1024) time_end = datetime.datetime.n...
Python
zaydzuhri_stack_edu_python
from docx import Document from docx.enum.text import WD_BREAK set fn = string C:\Users\Priyanshu Gupta\Desktop\Resume Extractor\experiment4.docx set document = call Document fn comment pn=1 comment import re comment for p in document.paragraphs: comment r=re.match('Chapter \d+',p.text) comment if r: comment print(r.gro...
from docx import Document from docx.enum.text import WD_BREAK fn=r"C:\Users\Priyanshu Gupta\Desktop\Resume Extractor\experiment4.docx" document = Document(fn) # pn=1 # import re # for p in document.paragraphs: # r=re.match('Chapter \d+',p.text) # if r: # print(r.group(),pn) # for run in p.runs: ...
Python
zaydzuhri_stack_edu_python
for i in n begin if integer i == 1 begin set temp = string One end if integer i == 2 begin set temp = string Two end if integer i == 3 begin set temp = string Three end if integer i == 4 begin set temp = string Four end if integer i == 5 begin set temp = string Five end if integer i == 6 begin set temp = string Six end...
for i in n: if int(i) == 1: temp = "One" if int(i) == 2: temp = "Two" if int(i) == 3: temp = "Three" if int(i) == 4: temp = "Four" if int(i) == 5: temp = "Five" if int(i) == 6: temp = "Six" if int(i) == 7: temp = "Seven" if int(i) =...
Python
zaydzuhri_stack_edu_python
function stepper_config self steps_per_revolution stepper_pins begin string Configure stepper motor prior to operation. This is a FirmataPlus feature. :param steps_per_revolution: number of steps per motor revolution :param stepper_pins: a list of control pin numbers - either 4 or 2 :returns: No return value set task =...
def stepper_config(self, steps_per_revolution, stepper_pins): """ Configure stepper motor prior to operation. This is a FirmataPlus feature. :param steps_per_revolution: number of steps per motor revolution :param stepper_pins: a list of control pin numbers - either 4 or 2 ...
Python
jtatman_500k
function read_code code begin set index = 0 while true begin set cmd = integer string code at index at slice - 2 : : set modes = list comprehension integer ch for ch in string code at index at slice : - 2 : set args = list 0 0 0 0 comment 1 argsument set total = 0 if cmd in list 1 2 7 8 begin set total = 3 end if cm...
def read_code(code): index = 0 while True: cmd = int(str(code[index])[-2:]) modes = [int(ch) for ch in str(code[index])[:-2]] args = [0, 0, 0, 0] # 1 argsument total = 0 if cmd in [1, 2, 7, 8]: total = 3 if cmd in [5, 6]: ...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment gzip 파일 읽기 by me import gzip set base = string comment binary mode로 읽음 with open string covid19.fasta.gz string rb as f begin for line in f begin if starts with decode line string utf-8 string > begin continue end else begin set base = base + strip decode line string utf-8 end end...
#! /usr/bin/env python # gzip 파일 읽기 by me import gzip base = "" with gzip.open("covid19.fasta.gz", "rb") as f: # binary mode로 읽음 for line in f: if line.decode("utf-8").startswith(">"): continue else: base += line.decode("utf-8").strip() d_result = {} for b in base: if ...
Python
zaydzuhri_stack_edu_python
comment importa o módulo random import random comment executa iteração para gerar números aleatórios for i in range 10 begin set x = random print x end
#importa o módulo random import random #executa iteração para gerar números aleatórios for i in range(10): x = random.random() print(x)
Python
zaydzuhri_stack_edu_python
comment Finds index where data set is no longer linear function critical_idx x y begin assert is instance x ndarray msg string Input should be numpy array assert is instance y ndarray msg string Input should be numpy array if shape at 0 != shape at 0 begin raise call ValueError format string x and y must have same firs...
def critical_idx(x, y): # Finds index where data set is no longer linear assert isinstance(x, np.ndarray), "Input should be numpy array" assert isinstance(y, np.ndarray), "Input should be numpy array" if x.shape[0] != y.shape[0]: raise ValueError("x and y must have same first dimension, but " ...
Python
nomic_cornstack_python_v1
function list_volume_access_groups self start_volume_access_group_id=OPTIONAL limit=OPTIONAL begin call _check_connection_type string list_volume_access_groups string Cluster set params = dict if start_volume_access_group_id is not none begin set params at string startVolumeAccessGroupID = start_volume_access_group_id...
def list_volume_access_groups( self, start_volume_access_group_id=OPTIONAL, limit=OPTIONAL,): self._check_connection_type("list_volume_access_groups", "Cluster") params = { } if start_volume_access_group_id is not None: params["startVolu...
Python
nomic_cornstack_python_v1
function gTimeRichness self minimum maximum begin set myList = list for i in range islandNr begin append myList mean st timeRichness at i at slice minimum : maximum : end return myList end function
def gTimeRichness(self, minimum, maximum): myList = [] for i in range(self.islandNr): myList.append(st.mean(self.timeRichness[i][minimum:maximum])) return myList
Python
nomic_cornstack_python_v1
import math function calc a b x begin return floor a * x / b - a * floor x / b end function function main begin set tuple A B N = list comprehension integer x for x in split input if N < B begin print call calc A B N end else begin print call calc A B B - 1 end end function if __name__ == string __main__ begin call mai...
import math def calc(a,b,x): return math.floor(a*x/b) - a*math.floor(x/b) def main(): A,B,N = [int(x) for x in input().split()] if N < B: print(calc(A,B,N)) else: print(calc(A,B,B-1)) if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
function proposal parameters proposal_jump=list 1 1 1 begin set new_vals = array list comprehension call rvs for tuple p_i jump_i in zip parameters proposal_jump return new_vals end function
def proposal(parameters, proposal_jump=[1, 1, 1]): new_vals = np.array([scipy.stats.norm(loc=p_i, scale=jump_i).rvs() for p_i, jump_i in zip(parameters, proposal_jump)]) return new_vals
Python
nomic_cornstack_python_v1
function allocate_available_id self begin if length molecule_list <= 0 begin comment Reset the ID to 1 when there are no more molecules set next_id = 1 end set next_id = next_id + 1 return next_id - 1 end function
def allocate_available_id ( self ): if len(self.molecule_list) <= 0: # Reset the ID to 1 when there are no more molecules self.next_id = 1 self.next_id += 1 return ( self.next_id - 1 )
Python
nomic_cornstack_python_v1
function UpdateMaster self request timeout metadata=none with_call=false protocol_options=none begin raise call NotImplementedError end function
def UpdateMaster(self, request, timeout, metadata=None, with_call=False, protocol_options=None): raise NotImplementedError()
Python
nomic_cornstack_python_v1
function test_token_fetch_by_subtopic_unprivleged self begin call credentials HTTP_AUTHORIZATION=string Token + key set response = get client string /questions/by_subtopic/Topic 1/Subtopic 1/ format=string json set data = loads content at string results assert equal status_code HTTP_200_OK assert equal length data 1 as...
def test_token_fetch_by_subtopic_unprivleged(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.free_token.key) response = self.client.get('/questions/by_subtopic/Topic 1/Subtopic 1/', format='json') data = json.loads(response.content)['results'] self.assertEqual(response....
Python
nomic_cornstack_python_v1
function to_api in_dict int_keys=none date_keys=none bool_keys=none begin comment Cast all int_keys to int() if int_keys begin for in_key in int_keys begin if in_key in in_dict and get in_dict in_key none is not none begin set in_dict at in_key = integer in_dict at in_key end end end comment Cast all date_keys to datet...
def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None): # Cast all int_keys to int() if int_keys: for in_key in int_keys: if (in_key in in_dict) and (in_dict.get(in_key, None) is not None): in_dict[in_key] = int(in_dict[in_key]) # Cast all date_keys to datet...
Python
nomic_cornstack_python_v1
function pwd_keys self begin call sign_off call sign_on list string 2010 string OSHMKUFA end function
def pwd_keys(self): pos.sign_off() pos.sign_on(['2010', 'OSHMKUFA'])
Python
nomic_cornstack_python_v1
function convert_time_stamp_to_date content begin string Convert time stamp to date time format set start_time_stamp = get content string startTime set end_time_stamp = get content string endTime if start_time_stamp begin set start_time = string format time call utcfromtimestamp start_time_stamp // 1000 string %Y/%m/%d...
def convert_time_stamp_to_date(content): '''Convert time stamp to date time format''' start_time_stamp = content.get('startTime') end_time_stamp = content.get('endTime') if start_time_stamp: start_time = datetime.datetime.utcfromtimestamp(start_time_stamp // 1000).strftime("%Y/%m/%d %H:%M:%S") ...
Python
jtatman_500k
import os import graphviz import matplotlib.pyplot as plt import math from sklearn.metrics import confusion_matrix import numpy as np import pandas as pd from sklearn import tree from IPython.display import Image import pydotplus function partition x begin set createInd = dictionary set l = length x for i in range 0 l ...
import os import graphviz import matplotlib.pyplot as plt import math from sklearn.metrics import confusion_matrix import numpy as np import pandas as pd from sklearn import tree from IPython.display import Image import pydotplus def partition(x): createInd = dict() l = len(x) for i in range(0, l): ...
Python
zaydzuhri_stack_edu_python
function run self begin set running = true while running begin comment ARDUINO POLLING ################################### try begin print string DEBUG: running if debug == string n begin comment Arduino is connected set inp = read arduino end else begin set inp = string input string Enter Packet, Enter Key to skip. Ex...
def run(self): running = True while running: ################################### ARDUINO POLLING ################################### try: print("DEBUG: running") if self.debug == 'n': # Arduino is connected i...
Python
nomic_cornstack_python_v1
function test_13 begin seed 90 set f = several_quad_function set g = several_quad_gradient set d = 10 set P = 5 set lambda_1 = 1 set lambda_2 = 10 set tuple store_x0 matrix_combined = call function_parameters_several_quad P d lambda_1 lambda_2 set func_args = tuple P store_x0 matrix_combined set step = 1e-05 set point ...
def test_13(): np.random.seed(90) f = mt_obj.several_quad_function g = mt_obj.several_quad_gradient d = 10 P = 5 lambda_1 = 1 lambda_2 = 10 store_x0, matrix_combined = (mt_obj.function_parameters_several_quad (P, d, lambda_1, lambda_2)) func_args = P,...
Python
nomic_cornstack_python_v1
import httplib , urllib , base64 import json function getJson url begin comment Image to analyse (body of the request) set body = string {'URL': ' + url + string '} comment API request for Emotion Detection set headers = dict string Content-type string application/json comment Enter EMOTION API key set params = url enc...
import httplib, urllib, base64 import json def getJson(url): # Image to analyse (body of the request) body = '{\'URL\': \''+url+'\'}' # API request for Emotion Detection headers = {'Content-type': 'application/json',} params = urllib.urlencode({ 'subscription-key': 'ad946a803d384c379690cb42eff4e0ed',}) ...
Python
zaydzuhri_stack_edu_python
function unnameHuddle request begin set room_id : str = call getQueryValue request string id set huddle_id : str = call getQueryValue request string huddle_id call removed_huddle_name room_id huddle_id call updateStateCounter room_id set result : Dict = dictionary set map : Dict = call get_named_huddles_map room_id for...
def unnameHuddle(request) -> Response: room_id: str = helpers.getQueryValue(request, 'id') huddle_id: str = helpers.getQueryValue(request, 'huddle_id') rds.Room.removed_huddle_name(room_id, huddle_id) rds.Room.updateStateCounter(room_id) result:Dict = dict() map:Dict = rds.Room.get_named_huddle...
Python
nomic_cornstack_python_v1
comment Learning loops comment Use ":" this to inform compiler that you are using loop and line ends here for i in ab begin if i == 6 begin print string last element is found i end else begin print string Still Searching for the last item end end
# Learning loops for i in ab: # Use ":" this to inform compiler that you are using loop and line ends here if i==6: print("last element is found", i) else: print("Still Searching for the last item")
Python
zaydzuhri_stack_edu_python
import os import serial import httplib from socket import error as socket_error import json import time import RPi.GPIO as GPIO set headers = dict string Content-type string application/json comment send POST to interface.js
import os import serial import httplib from socket import error as socket_error import json import time import RPi.GPIO as GPIO headers={'Content-type' : 'application/json'} # send POST to interface.js
Python
zaydzuhri_stack_edu_python
function is_set self card1 card2 card3 begin if color + color + color % 3 == 0 and shape + shape + shape % 3 == 0 and shading + shading + shading % 3 == 0 and number + number + number % 3 == 0 begin return true end return false end function
def is_set(self, card1, card2, card3): if ( (card1.color + card2.color + card3.color) % 3 == 0 and (card1.shape + card2.shape + card3.shape) % 3 == 0 and (card1.shading + card2.shading + card3.shading) % 3 == 0 and (card1.number + card2.number + card3.number) % 3 ...
Python
nomic_cornstack_python_v1
string Author: WeiFan 2018011641 Aim: Generation and filtering of random numbers Data: 2020/6/17 import random import string function DataSampling datatype datarange num strlen=8 begin try begin set result = set if datatype is int begin while length result < num begin set it = iterate datarange set item = random intege...
''' Author: WeiFan 2018011641 Aim: Generation and filtering of random numbers Data: 2020/6/17 ''' import random import string def DataSampling(datatype,datarange,num,strlen=8): try: result=set() if datatype is int: while len(result)<num: it=iter(datarange) ...
Python
zaydzuhri_stack_edu_python
function test_returns_links_header self main begin comment setup set tuple testapp songService = main set expectedSongs = call createNSongs 50 call __mockGetList songService expectedSongs 50 comment test set rv = get testapp string /songs/ comment verification set actual = headers at string Link assert string <http://l...
def test_returns_links_header(self, main): # setup testapp, songService = main expectedSongs = createNSongs(50) self.__mockGetList(songService, expectedSongs, 50) # test rv = testapp.get('/songs/') # verification actual = rv.headers['Link'] assert ...
Python
nomic_cornstack_python_v1
string Screen scrape https://cloud.google.com/compute/pricing to get google pricing adapted from https://github.com/jupyterhub/zero-to-jupyterhub-k8s/blob/master/doc/ntbk/z2jh/cost.py import numpy as np import pandas as pd import re import requests from bs4 import BeautifulSoup as bs4 import locale comment import warni...
""" Screen scrape https://cloud.google.com/compute/pricing to get google pricing adapted from https://github.com/jupyterhub/zero-to-jupyterhub-k8s/blob/master/doc/ntbk/z2jh/cost.py """ import numpy as np import pandas as pd import re import requests from bs4 import BeautifulSoup as bs4 import locale #import warnings #...
Python
zaydzuhri_stack_edu_python
function keypad_string keys begin string Find the string that is created using a standard phone keypad >>> keypad_string("12345") 'adgj' >>> keypad_string("4433555555666") 'hello' >>> keypad_string("2022") 'a b' >>> keypad_string("") '' >>> keypad_string("111") '' >>> keypad_string("*") Traceback (most recent call last...
def keypad_string(keys: str) -> str: ''' Find the string that is created using a standard phone keypad >>> keypad_string("12345") 'adgj' >>> keypad_string("4433555555666") 'hello' >>> keypad_string("2022") 'a b' >>> keypad_string("") '' >>> keypad_string("111") '' >>>...
Python
zaydzuhri_stack_edu_python
import configparser import pyodbc set DEFAULT_SETTINGS = dict string driver string Microsoft Access Driver (*.mdb, *.accdb) ; string uid string admin ; string pwd string ; string systemdb string class Settings begin string Load settings from section from .ini file in module folder function __init__ s section ini_file...
import configparser import pyodbc DEFAULT_SETTINGS = { 'driver': r'Microsoft Access Driver (*.mdb, *.accdb)' , 'uid': r'admin' , 'pwd': r'' , 'systemdb': r'' } class Settings: ''' Load settings from section from .ini file in module folder ''' def __init__(s, section:str, ini_file:str='settings.ini' , encod...
Python
zaydzuhri_stack_edu_python
function id self value begin if not is instance value str begin raise call ValueError string ID must be string: { value } end if _id is not none begin raise call ValueError string Trying to reset id: { _id } with value: { value } end set _id = value end function
def id(self, value): if not isinstance(value, str): raise ValueError(f"ID must be string: {value}") if self._id is not None: raise ValueError(f"Trying to reset id: {self._id} with value: {value}") self._id = value
Python
nomic_cornstack_python_v1
for i in l1 begin if mt == 0 begin break end set q1 = mt // i set c1 = c1 + q1 set mt = mt - i * q1 end print c1
for i in l1: if mt==0: break q1=mt // i c1+=q1 mt=mt-i*q1 print(c1)
Python
zaydzuhri_stack_edu_python
function test_no_implicit_str_conv self begin comment NICE_TO_HAVE set code = string {0} + " things" set tuple typo good = tuple string 12 string str(12) set tuple bad_code good_code = call format_str code typo good call throws bad_code UNSUPPORTEDOPERAND call runs good_code end function
def test_no_implicit_str_conv(self): # NICE_TO_HAVE code = '{0} + " things"' typo, good = '12', 'str(12)' bad_code, good_code = format_str(code, typo, good) self.throws(bad_code, UNSUPPORTEDOPERAND) self.runs(good_code)
Python
nomic_cornstack_python_v1
comment FP Basics Eg 3.py string Main Game Loop ~~~~~~~~~~~~~~~~~~~~ while playing: get input from user move good guy move bad guys move other stuff check interactions draw scene delay This example shows that as soon as we add complexity to a game we need to start breaking our code down into procedures. The goal is for...
# FP Basics Eg 3.py ''' Main Game Loop ~~~~~~~~~~~~~~~~~~~~ while playing: get input from user move good guy move bad guys move other stuff check interactions draw scene delay This example shows that as soon as we add complexity to a game we ...
Python
zaydzuhri_stack_edu_python
comment A SUPPORT VECTOR MACHINE PROGRAM ######################## comment Importando pacotes import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys insert path 0 string modules/ import iplots as mfun comment --------------------------- LEITURA E VISUALIZAÇÃO ------------------------------# co...
################################################################################### ######################### A SUPPORT VECTOR MACHINE PROGRAM ######################## ################################################################################### #Importando pacotes import pandas as pd import numpy as np import m...
Python
zaydzuhri_stack_edu_python
function get_cookies self begin return decimal _curr_cookies end function
def get_cookies(self): return float(self._curr_cookies)
Python
nomic_cornstack_python_v1
function push self artifact version force=false user=none token=none prefix=none begin set creds = call getCredentials user=user token=token set artifactName = call getVersionedName version prefix=prefix set url = format ARTIFACT_PATH url=url repo=repo path=path file=artifactName set path = call ArtifactoryPath url key...
def push(self, artifact, version, force=False, user=None, token=None, prefix=None): creds = self.auth.getCredentials(user=user, token=token) artifactName = artifact.getVersionedName(version, prefix=prefix) url = ARTIFACT_PATH.format(url=self.url, repo=self.repo, path=self.path, file=artifactNa...
Python
nomic_cornstack_python_v1
class Person begin function __init__ self firstname lastname begin set firstname = firstname set lastname = lastname set id = none set movies = list end function function total_movies self begin return length movies end function end class
class Person: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname self.id = None self.movies = [] def total_movies(self): return len(self.movies)
Python
zaydzuhri_stack_edu_python
function __init__ self animal session begin set brain = prep_id set animal = animal set scan_ids = list comprehension id for scan in scan_runs set slides = all set czi_files = list comprehension file_name for slide in slides set slides_ids = list set counter_stains = list set session = session end function
def __init__(self, animal, session): self.brain = animal.prep_id self.animal = animal self.scan_ids = [scan.id for scan in self.animal.scan_runs] self.slides = session.query(Slide).filter(Slide.scan_run_id.in_(self.scan_ids)).all() self.czi_files = [slide.file_name for slide in s...
Python
nomic_cornstack_python_v1
comment !/opt/rh/rh-python36/root/usr/bin/python3 import math comment Faça um programa que calcule as raízes de uma equação do segundo grau, comment na forma ax2 + bx + c. comment O programa deverá pedir os valores de a, b e c e fazer as consistências, comment informando ao usuário nas seguintes situações: set run = in...
#!/opt/rh/rh-python36/root/usr/bin/python3 import math # Faça um programa que calcule as raízes de uma equação do segundo grau, # na forma ax2 + bx + c. # O programa deverá pedir os valores de a, b e c e fazer as consistências, # informando ao usuário nas seguintes situações: run=int(0) # a) Se o usuário informar o ...
Python
zaydzuhri_stack_edu_python
function get_socket self sessid=string begin string Return an existing or new client Socket. set socket = get sockets sessid if sessid and not socket begin comment you ask for a session that doesn't exist! return none end if socket is none begin set socket = call Socket self config set sockets at sessid = socket end el...
def get_socket(self, sessid=''): """Return an existing or new client Socket.""" socket = self.sockets.get(sessid) if sessid and not socket: return None # you ask for a session that doesn't exist! if socket is None: socket = Socket(self, self.config) ...
Python
jtatman_500k
function timestamp_p value begin comment check if the value has the expected type call string_p value set timeformat = string %Y-%m-%dT%H:%M:%S.%f try begin comment try to parse the input value string parse time value timeformat end except ValueError begin raise call Invalid format string invalid datetime value {value}...
def timestamp_p(value): # check if the value has the expected type string_p(value) timeformat = '%Y-%m-%dT%H:%M:%S.%f' try: # try to parse the input value datetime.datetime.strptime(value, timeformat) except ValueError: raise Invalid("invalid datetime value {value}".format(v...
Python
nomic_cornstack_python_v1
from flask import Flask , request , jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from flask_cors import CORS import os comment Init app set app = call Flask __name__ call CORS app set basedir = absolute path path directory name path __file__ comment Database set config at st...
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from flask_cors import CORS import os # Init app app = Flask(__name__) CORS(app) basedir = os.path.abspath(os.path.dirname(__file__)) # Database app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- print string ----------------------46-- comment простые function is_prime n begin if n == 2 or n == 3 begin return true end if n % 2 == 0 or n < 2 begin return false end comment only odd numbers for i in range 3 integer n ^ 0.5 + 1 2 begin if n % i == 0 begin retu...
# !/usr/bin/python3 # -*- coding: utf-8 -*- print(f'----------------------46--') def is_prime(n): # простые if n==2 or n==3: return True if n%2==0 or n<2: return False for i in range(3,int(n**0.5)+1,2): # only odd numbers if n%i==0: return False return True print() do...
Python
zaydzuhri_stack_edu_python
import fitdecode import json import numpy as np import os function saveJson obj begin with open string activities.json string w as outfile begin dump obj outfile end end function function decodeFitFile file name begin set power = list set obj = dict with call FitReader file as fit begin for frame in fit begin if is i...
import fitdecode import json import numpy as np import os def saveJson(obj): with open('activities.json', 'w') as outfile: json.dump(obj, outfile) def decodeFitFile(file, name): power = [] obj = {} with fitdecode.FitReader(file) as fit: for frame in fit: if isinstance(frame...
Python
zaydzuhri_stack_edu_python
function is_1d_iterable x begin comment transform into a numpy array try begin set x = call asarray x dtype=string float64 end except ValueError begin return false end comment squeeze any extraneous dimensions set x = squeeze x return ndim == 1 end function
def is_1d_iterable(x): try: # transform into a numpy array x = np.asarray(x, dtype="float64") except ValueError: return False x = x.squeeze() # squeeze any extraneous dimensions return x.ndim == 1
Python
nomic_cornstack_python_v1
comment download from urllib.request import urlopen from bs4 import BeautifulSoup import pyexcel set url = string http://s.cafef.vn/bao-cao-tai-chinh/VNM/IncSta/2017/3/0/0/ket-qua-hoat-dong-kinh-doanh-cong-ty-co-phan-sua-viet-nam.chn set cafef_content = decode read url open url string utf8 comment ROI comment xml,xhtml...
#download from urllib.request import urlopen from bs4 import BeautifulSoup import pyexcel url ='http://s.cafef.vn/bao-cao-tai-chinh/VNM/IncSta/2017/3/0/0/ket-qua-hoat-dong-kinh-doanh-cong-ty-co-phan-sua-viet-nam.chn' cafef_content = urlopen(url).read().decode('utf8') #ROI soup = BeautifulSoup(cafef_content, 'html.par...
Python
zaydzuhri_stack_edu_python
function lammps_cp_files job begin set lmps_submit_path = string ../../src/engine_input/lammps/VU_scripts/submit.pbs set lmps_run_path = string ../../src/engine_input/lammps/input_scripts/in.* set msg = string cp { lmps_submit_path } { lmps_run_path } ./ return msg end function
def lammps_cp_files(job): lmps_submit_path = "../../src/engine_input/lammps/VU_scripts/submit.pbs" lmps_run_path = "../../src/engine_input/lammps/input_scripts/in.*" msg = f"cp {lmps_submit_path} {lmps_run_path} ./" return msg
Python
nomic_cornstack_python_v1
function prep_image self begin call prep_image set centerx = screen_width // 2 set centery = screen_height // 2 - height call prep_image set centerx = screen_width // 2 set centery = screen_height // 2 + height end function
def prep_image(self): self.title.prep_image() self.title.image_rect.centerx = (self.config.screen_width // 2) self.title.image_rect.centery = (self.config.screen_height // 2) - self.title.image_rect.height self.subtitle.prep_image() self.subtitle.image_rect.centerx = (self.config...
Python
nomic_cornstack_python_v1
import graphlab as gl import numpy as np import math set sales = call SFrame string kc_house_data.gl set sales at string floors = as type sales at string floors int function get_numpy_data frame_data features output begin set frame_data at string constant = 1 set features = list string constant + features set feature_s...
import graphlab as gl import numpy as np import math sales = gl.SFrame('kc_house_data.gl') sales['floors'] = sales['floors'].astype(int) def get_numpy_data(frame_data, features, output): frame_data['constant'] = 1 features = ['constant'] + features feature_sframe = gl.SFrame() for feature in features:...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None class Solution begin function lowestCommonAncestor self root p q begin set p = p set q = q comment BST: every node on the left is smaller on the node ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': self.p = p self.q...
Python
zaydzuhri_stack_edu_python
string " for i in speedList:#依次为8 6 4 2 sameSpeedCarListLength = len(sameSpeedCarsInfo[i])#统计当前速度相同的车辆的个数 carNumEachSlice = sameSpeedCarListLength / sliceNum#同一速度同一时间片车辆的个数 carNumber = 0 for j in range(sliceNum): realPlanTime = (maxSpeed / i) * 35 * ((minWeight + j * cutOffLine) / maxWeight) + timeStamp carCount = 0 fo...
"""" for i in speedList:#依次为8 6 4 2 sameSpeedCarListLength = len(sameSpeedCarsInfo[i])#统计当前速度相同的车辆的个数 carNumEachSlice = sameSpeedCarListLength / sliceNum#同一速度同一时间片车辆的个数 carNumber = 0 for j in range(sliceNum): realPlanTime = (maxSpeed / i) * 35 * ((...
Python
zaydzuhri_stack_edu_python
function es_grafana_datasources self begin comment pylint: disable=bare-except set headers = dict string Content-type string application/json ; string Accept string application/json set url = call es_grafana_url string /api/datasources try begin set response = get requests url headers=headers end except any begin error...
def es_grafana_datasources(self): # pylint: disable=bare-except headers = {"Content-type": "application/json", "Accept": "application/json"} url = self.es_grafana_url("/api/datasources") try: response = requests.get(url, headers=headers) except: ...
Python
nomic_cornstack_python_v1
import csv with open string teamTest.csv string r as csv_file begin comment DictReader => it is used for key as header and column in pair set csv_reader = dict reader csv_file for line in csv_reader begin print line end with open string newTestcreateTab.csv string w as new_file begin set csv_writer = writer new_file de...
import csv with open('teamTest.csv','r') as csv_file: csv_reader = csv.DictReader(csv_file) #DictReader => it is used for key as header and column in pair for line in csv_reader: print(line) with open('newTestcreateTab.csv','w') as new_file: csv_writer = csv.writer(new_file,d...
Python
zaydzuhri_stack_edu_python
string https://www.codewars.com/kata/51675d17e0c1bed195000001 function solution digits begin set biggest = 0 if length digits > 5 begin for i in range length digits begin if integer digits at slice i : i + 5 : > biggest begin set biggest = integer digits at slice i : i + 5 : end end end return biggest end function
"""https://www.codewars.com/kata/51675d17e0c1bed195000001""" def solution(digits): biggest = 0 if len(digits) > 5: for i in range(len(digits)): if int(digits[i:i + 5]) > biggest: biggest = int(digits[i:i + 5]) return biggest
Python
zaydzuhri_stack_edu_python
function __repr__ self begin return string Scrape <Success: { string not failed } > end function
def __repr__(self) -> str: return f"Scrape <Success: {str(not self.failed)}>"
Python
nomic_cornstack_python_v1
from turtle import * comment turtle graphic call tracer 0 1 set BOK = 30 set SX = - 100 set SY = 0 function kwadrat x y kolor begin call fillcolor kolor call pu call goto SX + x * BOK SY + y * BOK call pd call begin_fill for i in range 4 begin call fd BOK call rt 90 end call end_fill end function function kolko x y kol...
from turtle import * ##################################################### # turtle graphic ##################################################### tracer(0,1) BOK = 30 SX = -100 SY = 0 def kwadrat(x, y, kolor): fillcolor(kolor) pu() goto(SX + x * BOK, SY + y * BOK) pd() begin_fill() for i in range(4): ...
Python
zaydzuhri_stack_edu_python
function performGetValue self quant options=dict begin if name == string Frequency begin set value = call ask string FR set value = decimal strip strip strip value string FR string HZ end else if name == string Power begin comment value = self.as('LEOA;K') set value = decimal strip strip strip value string LE string DM...
def performGetValue(self, quant, options={}): if quant.name == 'Frequency': value = self.ask('FR') value = float(value.strip().strip('FR').strip('HZ')) elif quant.name == 'Power': # value = self.as('LEOA;K') value = float(value.strip().strip('LE').strip('D...
Python
nomic_cornstack_python_v1
function _deploy_cmd self data_receiver connection cmd begin comment enter in command mode call _send_cmd connection cmd comment expect undefined number of answers try begin while true begin call _receive_and_log data_receiver connection end end except timeout begin pass end end function
def _deploy_cmd(self, data_receiver, connection, cmd): # enter in command mode self._send_cmd(connection, cmd) # expect undefined number of answers try: while True: self._receive_and_log(data_receiver, connection) except socket.timeout: p...
Python
nomic_cornstack_python_v1
function make_great magician_names begin for name in range length magician_names begin set magician_names at name = magician_names at name + string the Great end end function
def make_great(magician_names): for name in range(len(magician_names)): magician_names[name] += ' the Great'
Python
nomic_cornstack_python_v1
comment Python program to insert element in binary tree class newNode begin function __init__ self data begin set key = data set left = none set right = none end function end class string Inorder traversal of a binary tree function inorder temp begin set st = list set res = list set curr = temp while curr begin appen...
# Python program to insert element in binary tree class newNode(): def __init__(self, data): self.key = data self.left = None self.right = None """ Inorder traversal of a binary tree""" def inorder(temp): st = [] res = [] curr = temp while(curr): ...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import logging import os import numpy import cv2 import scipy import scipy.interpolate import matplotlib import matplotlib.pyplot class samples extends object begin function case01 self begin debug string 生成[1, 8]的等差数列: comment 从1到8 生成8个点的等差数据列 set x = linear space 1 8 8 print x print strin...
# -*- coding:utf-8 -*- import logging import os import numpy import cv2 import scipy import scipy.interpolate import matplotlib import matplotlib.pyplot class samples(object): def case01(self): logging.debug('生成[1, 8]的等差数列:') x = numpy.linspace(1, 8, 8) # 从1到8 生成8个点的等差数据列 print(x) print('\n') logging.debu...
Python
zaydzuhri_stack_edu_python
function name_that_shape begin comment Create string that finds shape name by number of sides input by user. set side = call raw_input string Please enter the number of sides: if side == string 3 begin print string triangle end else if side == string 4 begin print string quadrilateral end else if side == string 5 begin...
def name_that_shape(): # Create string that finds shape name by number of sides input by user. side = raw_input("Please enter the number of sides:") if side == "3": print("triangle") elif side == "4": print("quadrilateral") elif side == "5": print("pentagon") elif side == "...
Python
nomic_cornstack_python_v1
function test_invalid_arguments self parse_input tmpdir begin set program = call dedent string name CustomOperation version 0.0 float alpha = 0.3423 Coherent({alpha}, sqrt(pi)) | 0 MeasureFock() | 0 set filename = join tmpdir string test.xbb with open filename string w as f begin write f program end set test_include = ...
def test_invalid_arguments(self, parse_input, tmpdir): program = textwrap.dedent( """ name CustomOperation version 0.0 float alpha = 0.3423 Coherent({alpha}, sqrt(pi)) | 0 MeasureFock() | 0 """ ) filename = tmpd...
Python
nomic_cornstack_python_v1
function mpow a d n begin set res = 1 while d > 0 begin if d ? 1 begin set res = res * a % n end set a = a * a % n set d = d // 2 end return res end function function gcd a b begin return if expression b == 0 then a else call gcd b a % b end function function exgcd a b begin if b == 0 begin return tuple 1 0 end set tup...
def mpow(a, d, n): res = 1 while d > 0: if d&1: res = res * a % n a = a*a%n d = d//2 return res def gcd(a, b): return a if b==0 else gcd(b, a%b) def exgcd(a, b): if b==0: return 1,0 x, y=exgcd(b, a%b) return y, x-(a//b)*y
Python
zaydzuhri_stack_edu_python
while a >= 1 begin print a set a = a - 1 end
while (a>=1): print(a) a=a-1
Python
zaydzuhri_stack_edu_python
function build_test_dataset x begin set tuple x_test clips_per_sample = tuple list list for sample in x begin append clips_per_sample length sample for clip in sample begin append x_test clip end end return tuple array x_test clips_per_sample end function
def build_test_dataset(x: List[List[NpArray]]) -> Tuple[NpArray, List[int]]: x_test, clips_per_sample = [], [] for sample in x: clips_per_sample.append(len(sample)) for clip in sample: x_test.append(clip) return np.array(x_test), clips_per_sample
Python
nomic_cornstack_python_v1
function fov data begin comment rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data) set pos_x = x set pos_y = y set pos_z = z set q_0 = x set q_1 = y set q_2 = z set q_3 = w comment Currently considering orientation with a 3D axis but available data is for only 2D string T_AL = [[q_0**2+q_1**2-q_2**2-q_3**2 ...
def fov(data): #rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data) pos_x = data.position.x pos_y = data.position.y pos_z = data.position.z q_0 = data.orientation.x q_1 = data.orientation.y q_2 = data.orientation.z q_3 = data.orientation.w #Currently considering orien...
Python
nomic_cornstack_python_v1
comment this is a template for you to write a csv file import csv comment create a file to open comment 'w' = write mode comment new line = blank with open string name your csv file string w newline=string as fp begin comment create var set a = writer fp delimiter=string , set data = list list string Name string Age li...
#this is a template for you to write a csv file import csv # create a file to open # 'w' = write mode # new line = blank with open('name your csv file', 'w', newline = '') as fp: # create var a = csv.writer(fp, delimiter = ',') data = [['Name', 'Age'], ['Blair', '24'], ['Natalie', ...
Python
zaydzuhri_stack_edu_python
function f begin set tuple n m = map int split input set l = list generator expression tuple map int split input for _ in range n sort l key=lambda e -> tuple 0 6 3 2 at e at 0 * e at 1 reverse=true set tuple last r = tuple list 0 * 4 0 for tuple i tuple w c in enumerate l begin if m < w begin break end set m = m - w s...
def f(): n, m = map(int, input().split()) l = list(tuple(map(int, input().split())) for _ in range(n)) l.sort(key=lambda e: (0, 6, 3, 2)[e[0]] * e[1], reverse=True) last, r = [0] * 4, 0 for i, (w, c) in enumerate(l): if m < w: break m -= w r += c last[w] =...
Python
jtatman_500k
import csv import locale import dutil import sqlite3 comment Declare these dictionaries so they have global scope comment Item count indexed by item name set countDict = dict comment Item total sales indexed by item name set salesDict = dict comment The next four dictionaries are for breaking down sales comment by ca...
import csv import locale import dutil import sqlite3 # Declare these dictionaries so they have global scope # Item count indexed by item name countDict = {} # Item total sales indexed by item name salesDict = {} # The next four dictionaries are for breaking down sales # by category. The item name is prefixed with the...
Python
zaydzuhri_stack_edu_python
function normmax X begin set X = X - call nanmin X return X / call nanmax X end function
def normmax(X): X = X-np.nanmin(X) return X/np.nanmax(X)
Python
nomic_cornstack_python_v1
function display_score ap iou_ratio begin for class_name in keys ap begin print string ---------------------- print string Class + class_name + string - AP: + string round ap at class_name 2 end print string ###################### print string mAP@IoU + string round iou_ratio * 100 + string score: + string round decima...
def display_score(ap, iou_ratio): for class_name in ap.keys(): print('----------------------') print ('Class ' + class_name + ' - AP: ' + str(round(ap[class_name], 2))) print('######################') print ('mAP@IoU' + str(round(iou_ratio * 100)) + ' score: ' + str(round((float(sum(ap.values()))) / max(1,...
Python
nomic_cornstack_python_v1
function empty self begin return length _tiles == 0 end function
def empty(self): return len(self._tiles) == 0
Python
nomic_cornstack_python_v1
function update self dt begin update call super dt set _tospawn = _tospawn + pps * dt set color = colors at integer age * 20 % length colors comment print(int(self.age*20) % len(self.colors)) comment print(self._time) set _time = _time + dt set ptype = TriangleParticle set angle = uniform - 0.25 0.25 set speed = - unif...
def update(self, dt): super().update(dt) self._tospawn += self.pps * dt color = self.colors[int(self.age*20) % len(self.colors)] #print(int(self.age*20) % len(self.colors)) #print(self._time) self._time += dt ptype = TriangleParticle angle = uniform(-0.25...
Python
nomic_cornstack_python_v1
function test_sync_all_accounts_teams_deleted_account_during_sync self begin comment Create five test accounts set accounts = list comprehension call create for i in range 5 comment Create two teams to assign to some of the accounts set teams = list comprehension call create for i in range 2 set team = teams at 0 set e...
def test_sync_all_accounts_teams_deleted_account_during_sync(self): # Create five test accounts accounts = [Account.objects.create() for i in range(5)] # Create two teams to assign to some of the accounts teams = [Team.objects.create() for i in range(2)] accounts[0].team = teams[...
Python
nomic_cornstack_python_v1
from DeckClass import Deck from CardShuffle import card_shuffle from CardClass import Card from SQLiteClass import SQLite from ImageProcessing import square_set from CoreTarot import Tarot function deck_create_test begin set new_deck = call Deck string thoth 33333 call create set second_card = card_list at 1 return new...
from DeckClass import Deck from CardShuffle import card_shuffle from CardClass import Card from SQLiteClass import SQLite from ImageProcessing import square_set from CoreTarot import Tarot def deck_create_test(): new_deck = Deck('thoth', 33333) new_deck.create() second_card = new_deck.card_list[1] retur...
Python
zaydzuhri_stack_edu_python
function multicoil_cg x_in y nu x0 mask S n niter begin set x = x0 set x_zf_sum = call A_H y mask S comment [:,mask.flatten()] set r = nu * x_zf_sum + x_in - nu * call A_H call A x mask S mask S - n * x set p = r set rtr_old = call vdot flatten r flatten r for i in range 0 niter begin set Ap = nu * call A_H call A p ma...
def multicoil_cg(x_in,y,nu,x0,mask,S,n,niter): x = x0 x_zf_sum = A_H(y,mask,S) # [:,mask.flatten()] r = (nu*x_zf_sum) + x_in - (nu*A_H(A(x,mask,S),mask,S)) - (n*x) p = r rtr_old = np.vdot(r.flatten(),r.flatten()) for i in range(0,niter): Ap = (nu*A_H(A(p,mask,S),mask,S)) + (...
Python
nomic_cornstack_python_v1
import cherrypy import search import thread call start_new_thread crawl tuple string http://en.wikipedia.org/wiki/George_Washington set form = string <form action='query' method='GET'> query: <input type='text' name='search_string' autofocus> relevance: <input type='number' name='rel'> popularity: <input type='number' ...
import cherrypy import search import thread thread.start_new_thread(search.crawl, ("http://en.wikipedia.org/wiki/George_Washington",)) form = "<form action='query' method='GET'> \ query: <input type='text' name='search_string' autofocus> \ relevance: <input type='number' name='rel'> \ popularity: <input type...
Python
zaydzuhri_stack_edu_python
import hashlib import operator import os import pathlib import struct import typing as tp from pyvcs.objects import hash_object class GitIndexEntry extends NamedTuple begin comment @see: https://github.com/git/git/blob/master/Documentation/technical/index-format.txt set ctime_s : int set ctime_n : int set mtime_s : int...
import hashlib import operator import os import pathlib import struct import typing as tp from pyvcs.objects import hash_object class GitIndexEntry(tp.NamedTuple): # @see: https://github.com/git/git/blob/master/Documentation/technical/index-format.txt ctime_s: int ctime_n: int mtime_s: int mtime_...
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self key begin set key = key set next = none end function end class class LinkedList begin function __init__ self begin set head = none end function function append self new_data begin set new_node = call Node new_data if head == none begin set head = new_node return end set last = he...
class Node: def __init__(self, key): self.key = key self.next = None class LinkedList: def __init__(self): self.head = None def append(self, new_data): new_node = Node(new_data) if self.head == None: self.head = new_node return last ...
Python
zaydzuhri_stack_edu_python
function series r n=none begin set sum = 0 set lim = 1 / 1 - r try begin comment Returner sum med r og n for i in range n + 1 begin set sum = sum + r ^ i end end except any begin comment Returner konvergerende sum set i = 0 while true begin set sum = sum + r ^ i set i = i + 1 if sum > lim - tol begin break end end prin...
def series(r, n=None): sum = 0 lim = 1/(1 - r) try: # Returner sum med r og n for i in range(n + 1): sum += r**i except: # Returner konvergerende sum i = 0 while True: sum += r**i i += 1 if(sum > lim - tol): break; print('For å være innenfor totalgrensen {0} kjørte løkken {1} ganger'.format(...
Python
zaydzuhri_stack_edu_python
comment chce 2.5 sekundy f=200 wiec biere n=500 comment wielkość okna analizy set N = 500 comment Filter requirements. comment rzad order set order = 10 comment sample rate, Hz set fs = 199 comment desired cutoff frequency of the filter, Hz set cutoff = 15 comment Get the filter coefficients so we can check its frequen...
# chce 2.5 sekundy f=200 wiec biere n=500 # wielkość okna analizy N = 500 # Filter requirements. order = 10 # rzad order fs = 199 # sample rate, Hz cutoff = 15 # desired cutoff frequency of the filter, Hz # Get the filter coefficients so we can check its frequency response. # 200 hz def butter_lowpass(cutoff, fs...
Python
zaydzuhri_stack_edu_python
import sqlite3 from src.Item import Item from src.Player import Player set database_name = string game class SQLLoader begin set __instance = none decorator staticmethod function get_instance begin if __instance is none begin set __instance = call SQLLoader end return __instance end function function __init__ self begi...
import sqlite3 from src.Item import Item from src.Player import Player database_name = 'game' class SQLLoader: __instance = None @staticmethod def get_instance(): if SQLLoader.__instance is None: SQLLoader.__instance = SQLLoader() return SQLLoader.__instance def __init_...
Python
zaydzuhri_stack_edu_python
function detect_column_renamings self table_differences begin string Try to find columns that only changed their names. :type table_differences: TableDiff set rename_candidates = dict for tuple added_column_name added_column in items added_columns begin for removed_column in values removed_columns begin if length call...
def detect_column_renamings(self, table_differences): """ Try to find columns that only changed their names. :type table_differences: TableDiff """ rename_candidates = {} for added_column_name, added_column in table_differences.added_columns.items(): for rem...
Python
jtatman_500k
comment -*- coding: utf-8 -*- comment @Author : LiWayne comment @Time : 2020/11/21 from requests.packages.urllib3.exceptions import InsecureRequestWarning import requests import json class Avatar_Changer begin function __init__ self config begin set data = dict string username config at string DATA at string username ;...
# -*- coding: utf-8 -*- # @Author : LiWayne # @Time : 2020/11/21 from requests.packages.urllib3.exceptions import InsecureRequestWarning import requests import json class Avatar_Changer: def __init__(self, config): self.data = { 'username': config['DATA']['username'], 'email':...
Python
zaydzuhri_stack_edu_python
function removeTempMedia pathname begin try begin remove os pathname return true end except Exception begin print string Failed to remove temp file "%s" % pathname return false end end function
def removeTempMedia(pathname): try: os.remove(pathname) return True except Exception: print('Failed to remove temp file "%s"' % pathname) return False
Python
nomic_cornstack_python_v1
comment -*- coding: utf8 -*- string 初始化命令 from env import STATIC_PATH from env import accept_type , translate_type from env import os , shutil function InitCommand args begin set info = string smat.py init --<参数>=<参数值> --<参数>=<参数值> <应用名称> 支持的参数 type ---- 创建的应用类型,目前支持[command_app, web_app, common_app, dock_app] 默认类型为web...
# -*- coding: utf8 -*- """ 初始化命令 """ from ..env import STATIC_PATH from ..env import accept_type, translate_type from ..env import os, shutil def InitCommand(args): info = """ smat.py init --<参数>=<参数值> --<参数>=<参数值> <应用名称> 支持的参数 type ---- 创建的应用类型,目前支持[command_app, web_app, common_app, dock_app] 默认类型为web_app """...
Python
zaydzuhri_stack_edu_python
string There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up)...
''' There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), ...
Python
zaydzuhri_stack_edu_python
function test_create_doc_obj self begin set doc_obj = call create_doc_obj msg set expected_doc = deep copy doc set expected_doc at string _id = doc at string @uuid assert true is instance doc_obj DocumentObj assert equal doc_id doc at string @uuid assert equal collection doc at string collection assert equal data expec...
def test_create_doc_obj(self): doc_obj = create_doc_obj(self.msg) expected_doc = copy.deepcopy(self.doc) expected_doc['_id'] = self.doc['@uuid'] self.assertTrue(isinstance(doc_obj, DocumentObj)) self.assertEqual(doc_obj.doc_id, self.doc['@uuid']) self.assertEqual(doc_obj....
Python
nomic_cornstack_python_v1
comment a={'a','b','c',1,2,3,'a'} comment print(a) comment a.add('hyderabad') comment print(a) comment # a.add([1]) comment print(a) comment b={} comment print(type(b)) comment c=set() comment print(type(c)) comment a.update('vizag',{11,12,13,14}) comment print(a) comment # a.remove(21) comment # print(a) comment a.dis...
# a={'a','b','c',1,2,3,'a'} # print(a) # a.add('hyderabad') # print(a) # # a.add([1]) # print(a) # b={} # print(type(b)) # c=set() # print(type(c)) # a.update('vizag',{11,12,13,14}) # print(a) # # a.remove(21) # # print(a) # a.discard(21) # print(a) #Union,Intersection,difference,symmetric_difference a={5...
Python
zaydzuhri_stack_edu_python
import numpy as np comment import image from computer from IPython.display import Image set matrix_arr = array list list 3 4 5 list 6 7 8 list 9 5 1 print matrix_arr print matrix_arr at 1 print matrix_arr at 0 at 2 print matrix_arr at tuple 0 2 set i = call Image filename=string /Users/tungvm/mypict.png i
import numpy as np from IPython.display import Image # import image from computer matrix_arr = np.array([[3, 4, 5], [6, 7, 8], [9, 5, 1]]) print(matrix_arr) print(matrix_arr[1]) print(matrix_arr[0][2]) print(matrix_arr[0, 2]) i = Image(filename = "/Users/tungvm/mypict.png") i
Python
zaydzuhri_stack_edu_python
function test_get_amazon_search_result begin with call mock as m begin get m string https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias=sporting&page=1&field-keywords=oakley text=string <div id='test'>Wieners!</div> set soup = call get_amazon_search_result string Sports & Outdoors string Oakley assert text == st...
def test_get_amazon_search_result(): with requests_mock.mock() as m: m.get('https://www.amazon.com/s/ref=nb_sb_noss_1?' 'url=search-alias=sporting&page=1&field-keywords=oakley', text="<div id='test'>Wieners!</div>") soup = searcher.get_amazon_search_result('Sports & Outd...
Python
nomic_cornstack_python_v1
function deleteFTPSecret self request context begin call set_code UNIMPLEMENTED call set_details string Method not implemented! raise call NotImplementedError string Method not implemented! end function
def deleteFTPSecret(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
Python
nomic_cornstack_python_v1
function add_action_boolean self action_name default callback begin set action = call new_stateful action_name none call new_boolean default call connect string change-state callback call add_action action end function
def add_action_boolean(self, action_name, default, callback): action = Gio.SimpleAction().new_stateful(action_name, None, \ GLib.Variant.new_boolean(default)) action.connect('change-state', callback) self.add_action(action)
Python
nomic_cornstack_python_v1
function price_from_vol_LN self vol f K T_expiry payoff=string Call begin set d1 = 1 / vol * square root T_expiry * log f / K + 0.5 * vol ^ 2 * T_expiry set d2 = d1 - vol * square root T_expiry set CallPrice = f * call cdf d1 - K * call cdf d2 if payoff == string Call begin return CallPrice end else if payoff == string...
def price_from_vol_LN(self, vol, f, K, T_expiry, payoff='Call'): d1 = 1 / ( vol * np.sqrt( T_expiry ) ) * ( np.log( f / K ) + ( 0.5 * vol ** 2 ) * T_expiry ) d2 = d1 - vol * np.sqrt( T_expiry ) CallPrice = (f * norm.cdf( d1 ) - K * norm.cdf( d2 )) if payoff == "Call...
Python
nomic_cornstack_python_v1