code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function connect self host begin set _app = call TestApp host end function
def connect(self, host): self._app = livetest.TestApp(host)
Python
nomic_cornstack_python_v1
function test_xkcd_fetch_old_image_deleted self begin comment first call get_xkcd comment second call get_xkcd comment third call get_xkcd set xkcd_images2 = list directory string images assert length xkcd_images2 == 2 assert starts with xkcd_images2 at 0 string xkcd assert starts with xkcd_images2 at 1 string xkcd end...
def test_xkcd_fetch_old_image_deleted(self): # first xkcd_fetch.get_xkcd() # second xkcd_fetch.get_xkcd() # third xkcd_fetch.get_xkcd() xkcd_images2 = os.listdir("images") assert len(xkcd_images2) == 2 assert xkcd_images2[0].startswith('xkcd')...
Python
nomic_cornstack_python_v1
function tabularize items fields header=true writer=stdout begin if not items begin raise call ValueError string empty items end set widths = list comprehension max generator expression length string get e field string for e in items for field in fields set widths = list comprehension max w length f for tuple w f in zi...
def tabularize(items, fields, header=True, writer=stdout): if not items: raise ValueError('empty items') widths = [max(len(str(e.get(field, ''))) for e in items) for field in fields] widths = [max(w, len(f)) for (w, f) in zip(widths, fields)] tpl = '%s\n' % (''.join('%%%ss' % (w + 1, ) for w in widths), ) ...
Python
nomic_cornstack_python_v1
function __init__ self begin set _que1 = list end function
def __init__(self): self._que1 = []
Python
nomic_cornstack_python_v1
function clear_stack self begin set stack at slice : : = list call debug_log string Clearing Stack add lights_to_update self end function
def clear_stack(self): self.stack[:] = [] self.debug_log("Clearing Stack") MatrixLight.lights_to_update.add(self)
Python
nomic_cornstack_python_v1
function as_sql self *args **kwargs begin string Overrides the :class:`SQLAggregateCompiler` method in order to prepend the necessary CTE syntax, as well as perform pre- and post- processing, including adding the extra CTE table and WHERE clauses. :param qn: :type qn: :return: :rtype: function _as_sql begin return call...
def as_sql(self, *args, **kwargs): """ Overrides the :class:`SQLAggregateCompiler` method in order to prepend the necessary CTE syntax, as well as perform pre- and post- processing, including adding the extra CTE table and WHERE clauses. :param qn: :type qn: :ret...
Python
jtatman_500k
function MacdonaldPolynomialsQ R q=none t=none begin return call cache_q R q t end function
def MacdonaldPolynomialsQ(R, q=None, t=None): return cache_q(R, q, t)
Python
nomic_cornstack_python_v1
function _init self **kwds begin set name = get kwds string name if name and not call has_key string name begin call set_name name end set characterID = get kwds string characterID none set myName = get kwds string myName string end function
def _init(self, **kwds): name = kwds.get('name') if name and not self.data.has_key('name'): self.set_name(name) self.characterID = kwds.get('characterID', None) self.myName = kwds.get('myName', u'')
Python
nomic_cornstack_python_v1
function disp *args **kwargs begin pass end function
def disp(*args, **kwargs) -> Any: pass
Python
nomic_cornstack_python_v1
function get_image begin set url = string http://skyview.gsfc.nasa.gov/cgi-bin/images set params = dictionary Position=string %s,%s % tuple source at string ra source at string dec Survey=val Return=string GIF set response = get requests url params=params stream=true with open rel string wb as out_file begin call copyf...
def get_image(): url = 'http://skyview.gsfc.nasa.gov/cgi-bin/images' params = dict(Position='%s,%s' % (source['ra'], source['dec']), Survey=source['survey'].val, Return='GIF') response = requests.get(url, params=params, stream=True) with open(files['image.gif'].rel, ...
Python
nomic_cornstack_python_v1
function predict self X threshold begin set scores = call anomaly_score X return call predict_from_anomaly_scores scores=scores threshold=threshold end function
def predict(self, X: np.ndarray, threshold: float) -> np.ndarray: scores = self.anomaly_score(X) return self.predict_from_anomaly_scores(scores=scores, threshold=threshold)
Python
nomic_cornstack_python_v1
from pydantic import BaseModel from typing import Text from datetime import datetime from uuid import UUID , uuid4 class Nota extends BaseModel begin set id : UUID set datetime_criacao : datetime set datetime_modificacao : datetime set anotacao : Text function __init__ __pydantic_self__ anotacao begin set dados_da_nota...
from pydantic import BaseModel from typing import Text from datetime import datetime from uuid import UUID, uuid4 class Nota(BaseModel): id: UUID datetime_criacao: datetime datetime_modificacao: datetime anotacao: Text def __init__(__pydantic_self__, anotacao: Text) -> None: dados_da_not...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render , get_object_or_404 import markdown comment Create your views here. from django.http import HttpResponse from models import Post , Category , Tag from comments.forms import CommentForm from django.views.generic import ListView , DetailView from django.utils.text import slugify from m...
from django.shortcuts import render, get_object_or_404 import markdown # Create your views here. from django.http import HttpResponse from .models import Post,Category,Tag from comments.forms import CommentForm from django.views.generic import ListView,DetailView from django.utils.text import slugify from markdown.exte...
Python
zaydzuhri_stack_edu_python
function optionCallback self button begin set functions = dict string save saveGame ; string load loadGame ; string exit_game exitGame set label = replace lower text string string _ try begin call end except KeyError begin pass end end function
def optionCallback(self, button): functions = {'save': self.saveGame, 'load': self.loadGame, 'exit_game': exitGame} label = button._w.original_widget.text.lower().replace(' ', '_') try: functions[label]() except KeyError: ...
Python
nomic_cornstack_python_v1
function new_state self state begin if string state not in index begin comment initial value 0 to new state set new_state = call Series data=list 0 * length actionSet index=actionSet name=string state comment the index is the columns name of the brain comment the name is the index name of the brain string append the ne...
def new_state(self,state): if str(state) not in self.brain.index: new_state = pd.Series(data=[0]*len(self.actionSet), # initial value 0 to new state index=self.actionSet, # the index is the columns name of the brain name=str(state)) ...
Python
nomic_cornstack_python_v1
if x1 % 2 != 0 begin print string { x1 - 2 } { x1 + 1 } end else begin print string { x1 - 1 } { x1 + 2 } end
if (x1 % 2 != 0): print(f'{x1 - 2} {x1 + 1}') else: print(f'{x1 - 1} {x1 + 2}')
Python
zaydzuhri_stack_edu_python
string Module containing Calculation class and subclasses required for GM. A single Calculation object serves the config line which is the main interface between user and gaussian string # method/basis opt(ts, calcfc, noeigen, tight) integral(grid=superfine) scf(maxcyc=256) freq string # method/basis irc(direction, cal...
"""Module containing Calculation class and subclasses required for GM. A single Calculation object serves the config line which is the main interface between user and gaussian""" '# method/basis opt(ts, calcfc, noeigen, tight) integral(grid=superfine) scf(maxcyc=256) freq' '# method/basis irc(direction, calcfc, ma...
Python
zaydzuhri_stack_edu_python
import datetime from sqlalchemy import create_engine , DATETIME from sqlalchemy.orm import sessionmaker comment fills up the db with a few basic things comment primarily for testing comment https://pythonspot.com/en/login-authentication-with-flask/ from tableDef import * set engine = call create_engine string sqlite://...
import datetime from sqlalchemy import create_engine,DATETIME from sqlalchemy.orm import sessionmaker #fills up the db with a few basic things #primarily for testing #https://pythonspot.com/en/login-authentication-with-flask/ from tableDef import * engine = create_engine('sqlite:///db/myStorage.db', echo=True) text ...
Python
zaydzuhri_stack_edu_python
function test_api_type_filtering api_client by_type by_state begin set response = get api_client path=string /breweries params=dict string by_type by_type ; string by_state by_state assert json response != list assert ok end function
def test_api_type_filtering(api_client, by_type, by_state): response = api_client.get(path='/breweries', params={'by_type': by_type, 'by_state': by_state}) assert response.json() != [] assert response.ok
Python
nomic_cornstack_python_v1
comment function for bubble sort function bubbleSort lst begin for _ in range length lst begin for j in range length lst - 1 begin if lst at j > lst at j + 1 begin set tuple lst at j lst at j + 1 = tuple lst at j + 1 lst at j end end end return lst end function comment function for insertion sort function insertionSort...
# function for bubble sort def bubbleSort(lst): for _ in range(len(lst)): for j in range(len(lst) - 1): if lst[j] > lst[j + 1]: lst[j], lst[j + 1] = lst[j + 1], lst[j] return lst # function for insertion sort def insertionSort(lst): for i in range(1, len(lst)): ...
Python
zaydzuhri_stack_edu_python
function cross_product v1 v2 begin return x * y - x * y end function
def cross_product(v1, v2): return v1.x * v2.y - v2.x * v1.y
Python
nomic_cornstack_python_v1
function modify self fd event begin call modify fd event end function
def modify(self, fd, event): self.epoll.modify(fd, event)
Python
nomic_cornstack_python_v1
string Ejemplo de uso del drop en una lista import sys from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class DropInList extends QListWidget begin function __init__ self begin call __init__ call setAcceptDrops true end function function dropEvent self QDropEvent begin set source_Widget...
""" Ejemplo de uso del drop en una lista """ import sys from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class DropInList(QListWidget): def __init__(self): super(DropInList,self).__init__() self.setAcceptDrops(True) def dropEvent(self, QDropEvent): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import rospy import tf import utm from sensor_msgs.msg import NavSatFix , Imu from nav_msgs.msg import Odometry from math import pi , radians , sqrt , sin , cos , atan2 comment Class to contain raw data of a state class State extends object begin function __init__ self begin set measured_la...
#!/usr/bin/env python import rospy import tf import utm from sensor_msgs.msg import NavSatFix, Imu from nav_msgs.msg import Odometry from math import pi, radians, sqrt, sin, cos, atan2 # Class to contain raw data of a state class State(object): def __init__(self): self.measured_lat = None self.measured_lng = N...
Python
zaydzuhri_stack_edu_python
function supports_book_hierarchy self begin return false end function
def supports_book_hierarchy(self): return False
Python
nomic_cornstack_python_v1
string file: raindrops.py language: python 3 author: Duc Phan - ddp3945@rit.edu description: Lab 3 - Raindrops import math import random import turtle as t function PEN_SIZE begin string Return the turtle's pen size return 1 end function function BOX_SIZE begin string Return the size of the bounding box return 540 end ...
""" file: raindrops.py language: python 3 author: Duc Phan - ddp3945@rit.edu description: Lab 3 - Raindrops """ import math import random import turtle as t def PEN_SIZE(): """Return the turtle's pen size""" return 1 def BOX_SIZE(): """Return the size of the bounding box""" return 540 def MAX_COO...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import os import datetime import pandas as pd import matplotlib.pyplot as plt import tushare as ts import time import sys function load_stocks date=none begin string 加载所有股票列表。 若列表文件‘stock-list.csv’不存在,则下载 :return: :rtype: DataFrame if date == none begin set today = now set date = string for...
# -*- coding:utf-8 -*- import os import datetime import pandas as pd import matplotlib.pyplot as plt import tushare as ts import time import sys def load_stocks(date=None): """ 加载所有股票列表。 若列表文件‘stock-list.csv’不存在,则下载 :return: :rtype: DataFrame """ if date == None: today = dat...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3.4 comment encoding: utf-8 string Created on 18-1-3 @author: Xu import requests import pandas import re from bs4 import BeautifulSoup function get_article url begin set res1 = get requests url set encoding = string utf-8 set soup1 = call BeautifulSoup text string html.parser set dic = dict ...
#!/usr/bin/env python3.4 # encoding: utf-8 """ Created on 18-1-3 @author: Xu """ import requests import pandas import re from bs4 import BeautifulSoup def get_article(url): res1 = requests.get(url) res1.encoding = 'utf-8' soup1 = BeautifulSoup(res1.text, 'html.parser') dic = {} dic['title'] = soup...
Python
zaydzuhri_stack_edu_python
set a = 4 set b = 2 set c = divide mod a b print c at 0 print c at 1 print c
a=4 b=2 c=divmod(a,b) print(c[0]) print(c[1]) print(c)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import xml.etree.cElementTree as ET from collections import defaultdict import re import pprint import os import json set INPUT_PATH = string input/rio-de-janeiro_brazil.osm comment INPUT_PATH = 'input/sample-100.osm' comment INPUT_PATH = 'input/sample-1000.osm...
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.cElementTree as ET from collections import defaultdict import re import pprint import os import json INPUT_PATH = 'input/rio-de-janeiro_brazil.osm' # INPUT_PATH = 'input/sample-100.osm' # INPUT_PATH = 'input/sample-1000.osm' OUTPUT_DIR = 'output' OUTPUT_PA...
Python
zaydzuhri_stack_edu_python
function dispatch self *args **kwargs begin return call dispatch *args keyword kwargs end function
def dispatch(self, *args, **kwargs): return super(MediaTalkListView, self).dispatch( *args, **kwargs )
Python
nomic_cornstack_python_v1
function validate_template template session=none begin info string Validating CloudFormation Template set client = call boto3_client service=string cloudformation session=session try begin set response = call validate_template TemplateBody=template return response end except ClientError as e begin raise call ClientErro...
def validate_template(template, session=None): logger.info("Validating CloudFormation Template") client = boto3_client(service='cloudformation', session=session) try: response = client.validate_template(TemplateBody=template) return response except ex.ClientError as e: raise ex....
Python
nomic_cornstack_python_v1
function parse_dest *args **kwargs begin set dest = get kwargs string dest if dest begin return dest end comment No explicit dest, so compute one based on the first long arg, or the short arg comment if that's all there is. set arg = next generator expression a for a in args if starts with a string -- args at 0 return ...
def parse_dest(*args, **kwargs): dest = kwargs.get("dest") if dest: return dest # No explicit dest, so compute one based on the first long arg, or the short arg # if that's all there is. arg = next((a for a in args if a.startswith("--")), args[0]) return arg.l...
Python
nomic_cornstack_python_v1
function match_grids self f begin if div == div begin return tuple values values div end if div > div begin return tuple values call interpolate div div end if div < div begin return tuple call interpolate div values div end end function
def match_grids(self, f): if self.div == f.div: return self.values, f.values, self.div if self.div > f.div: return self.values, f.interpolate(self.div), self.div if self.div < f.div: return self.interpolate(f.div), f.values, f.div
Python
nomic_cornstack_python_v1
function _raw_input message begin return call raw_input message end function
def _raw_input(message): return raw_input(message)
Python
nomic_cornstack_python_v1
import sys import os import logging import math from phase_space_generator.vectors import Vector , LorentzVector from phase_space_generator.vectors import LorentzVectorDict , LorentzVectorList set logger = call getLogger string MG5aMC_PythonMEs.PhaseSpaceGenerator class Dimension extends object begin string A dimension...
import sys import os import logging import math from phase_space_generator.vectors import Vector, LorentzVector from phase_space_generator.vectors import LorentzVectorDict, LorentzVectorList logger = logging.getLogger('MG5aMC_PythonMEs.PhaseSpaceGenerator') class Dimension(object): """ A dimension object specify...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np function read begin set data = read csv string C:/Users/Administrator/Documents/WeChat Files/wxid_tstamvlvsn8411/FileStorage/File/2021-08/数据/数据/all_chiller.csv usecols=list string 冷水机组冷冻供水温度 string 冷水机组冷冻回水温度 string 冷水机组负荷比 string cop comment datay = pd.read_csv('C:/Users/Administ...
import pandas as pd import numpy as np def read(): data = pd.read_csv('C:/Users/Administrator/Documents/WeChat Files/wxid_tstamvlvsn8411/FileStorage/File/2021-08/数据/数据/all_chiller.csv',usecols=['冷水机组冷冻供水温度', '冷水机组冷冻回水温度', '冷水机组负荷比','cop']) # datay = pd.read_csv('C:/Users/Administrator/Documents/WeChat Files/wx...
Python
zaydzuhri_stack_edu_python
comment !/bin/env python3 string https://www.hackerrank.com/challenges/py-the-captains-room INPUT: lines: 1: int K size of each group 2: unordered elements of the room number list Constraints: 1 < K < 1000 OUPUT: The Captain's room number function findCaptainsRoom r begin set uniq = set r for i in uniq begin if count r...
#!/bin/env python3 """ https://www.hackerrank.com/challenges/py-the-captains-room INPUT: lines: 1: int K size of each group 2: unordered elements of the room number list Constraints: 1 < K < 1000 OUPUT: The Captain's room number """ def findCaptainsRoom(r): uniq = set(r) for i in uniq: ...
Python
zaydzuhri_stack_edu_python
import sys import math set n = integer input set flag = false for i in range ceil n / 4 + 1 begin for j in range ceil n / 7 + 1 begin if n - 4 * i - 7 * j == 0 begin set flag = true end end end if expression flag then print string Yes else print string No
import sys import math n = int(input()) flag = False for i in range(math.ceil(n/4) + 1): for j in range(math.ceil(n/7) + 1): if n - (4*i) - (7*j) == 0: flag = True print("Yes") if flag else print("No")
Python
zaydzuhri_stack_edu_python
comment reliably restored by inspect function freeze_notify self begin pass end function
def freeze_notify(self): # reliably restored by inspect pass
Python
nomic_cornstack_python_v1
function get_values counter begin return list comprehension counter at key for key in call get_keys counter end function
def get_values(counter): return( [counter[key] for key in get_keys(counter) ] )
Python
nomic_cornstack_python_v1
comment append/create/sort/reverse_sort in agiven list set list = list string EWT string VLSI string VIR string ES print string the initial elements of the list are: print list append list string BIGDATA print string the elements of the list after appending are: print list insert list 3 string CL print string the eleme...
#append/create/sort/reverse_sort in agiven list list =["EWT","VLSI","VIR","ES"] print("the initial elements of the list are:\t") print(list) list.append('BIGDATA') print("the elements of the list after appending are:\t") print(list) list.insert(3,'CL') print("the elements of the list after inserting") print(list) print...
Python
zaydzuhri_stack_edu_python
function test_start_time_initialisation self begin assert equal start call datetime 2014 1 1 15 30 assert equal start call datetime 2014 1 1 16 30 end function
def test_start_time_initialisation(self): self.assertEqual( PomodoroCalculator(end='18:30').start, datetime(2014, 1, 1, 15, 30), ) self.assertEqual( PomodoroCalculator(end='18:30', start='16:30').start, datetime(2014, 1, 1, 16, 30), )
Python
nomic_cornstack_python_v1
function __init__ self begin try begin make directories output_path end except Exception as err begin error string Failed to create path { output_path } because { err } raise err end set queue = call QueueSimple output_path end function
def __init__(self): try: utils.makedirs(CONF.ssm.output_path) except Exception as err: LOG.error(f"Failed to create path {CONF.ssm.output_path} because {err}") raise err self.queue = dirq.QueueSimple.QueueSimple(CONF.ssm.output_path)
Python
nomic_cornstack_python_v1
function _eq_nodes_setup_node_set model node_set all_node_set renumber_nodes=false idtype=string int32 begin if length node_set > 1 begin warning string multi node_sets; n= { length node_set } end set node_list = list keys nodes set all_nids = array node_list dtype=idtype comment all_nids.sort() comment B - A comment t...
def _eq_nodes_setup_node_set(model: BDF, node_set: List[NDArrayNint], all_node_set: NDArrayNint, renumber_nodes: bool=False, idtype:str='int32') -> Tuple[NDArrayNint, NDArrayNint]: if len(node_set) > ...
Python
nomic_cornstack_python_v1
for n in sorted nums key=abs begin print n end
for n in sorted(nums, key = abs): print(n)
Python
zaydzuhri_stack_edu_python
function __init__ self tmpdir win_id=none fps=15 begin set tuple x y w h = call get_active_window_pos set x = x set y = y set width = w set height = h set fps = fps set tmpdir = tmpdir set screengrab = call Pixbuf COLORSPACE_RGB false 8 w h set _datafile = open tmpdir + string /data string w set headers = tuple w h cal...
def __init__(self, tmpdir, win_id=None, fps=15): x, y, w, h = self.get_active_window_pos() self.x = x self.y = y self.width = w self.height = h self.fps = fps self.tmpdir = tmpdir self.screengrab = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, w, h) ...
Python
nomic_cornstack_python_v1
function getPupil self image threshold=0 pupilMinimum=10 pupilMaximum=50 begin comment Create the output variable. set bestPupil = - 1 set bestProps = dict set ellipses = list set centers = list comment Create variables to plot the regression data. comment TIPS: You must select two blob properties and add their valu...
def getPupil(self, image, threshold=0, pupilMinimum=10, pupilMaximum=50): # Create the output variable. bestPupil = -1 bestProps = {} ellipses = [] centers = [] # Create variables to plot the regression data. # TIPS: You must select two blob properties and add...
Python
nomic_cornstack_python_v1
function clearView self begin debug string ShortestPathUI.clearView function started call setText string call setText string call setText string call setText string debug string ShortestPathUI.clearView function ended end function
def clearView(self): logging.debug("ShortestPathUI.clearView function started") self.fromLineEdit.setText("") self.toLineEdit.setText("") self.pathLineEdit.setText("") self.lengthLabel.setText("") logging.debug("ShortestPathUI.clearView function ended\n")
Python
nomic_cornstack_python_v1
from flask import Flask , request , redirect , render_template , session , flash from flask_sqlalchemy import SQLAlchemy set app = call Flask __name__ set config at string DEBUG = true set config at string SQLALCHEMY_DATABASE_URI = string mysql+pymysql://blogz:ellen@localhost:8889/blogz set config at string SQLALCHEMY_...
from flask import Flask, request, redirect, render_template, session, flash from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://blogz:ellen@localhost:8889/blogz' app.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(app) app....
Python
zaydzuhri_stack_edu_python
function get_band_info h5_info band_name begin set first_doy = next iterate h5_info with call File h5_info at first_doy string r as fid begin set ds = fid at band_name return tuple shape dictionary comprehension key : attrs at key for key in list string crs_wkt string geotransform end end function
def get_band_info(h5_info: Dict, band_name: str): first_doy = next(iter(h5_info)) with h5py.File(h5_info[first_doy], "r") as fid: ds = fid[band_name] return ds.shape, {key: ds.attrs[key] for key in ["crs_wkt", "geotransform"]}
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment cw07-05 set values = list with open string dane.txt string r as f begin for line in f begin try begin append values integer line end except any begin pass end end end print string Najmniejsza odczytana liczba to: min values
#!/usr/bin/env python3 # cw07-05 values = [] with open('dane.txt', 'r') as f: for line in f: try: values.append(int(line)) except: pass print('Najmniejsza odczytana liczba to:', min(values))
Python
zaydzuhri_stack_edu_python
function diffCloseLow self begin return close - low end function
def diffCloseLow(self): return self.close - self.low
Python
nomic_cornstack_python_v1
comment L8 PROBLEM 4 function yieldAllCombos items begin string Generates all combinations of N items into two bags, whereby each item is in one or zero bags. Yields a tuple, (bag1, bag2), where each bag is represented as a list of which item(s) are in each bag. set N = length items comment Enumerate the 3**N possible ...
# L8 PROBLEM 4 def yieldAllCombos(items): """ Generates all combinations of N items into two bags, whereby each item is in one or zero bags. Yields a tuple, (bag1, bag2), where each bag is represented as a list of which item(s) are in each bag. """ N = len(items) # Enumerate the 3**N possible ...
Python
zaydzuhri_stack_edu_python
for i in range N - 1 - 1 - 1 begin set a = - A at i at 0 - cnt % A at i at 1 set cnt = cnt + a end print cnt
for i in range(N-1,-1,-1): a = (-A[i][0]-cnt)%A[i][1] cnt += a print(cnt)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment encoding: utf-8 string @contact: 1650503480@qq.com @file: login_datas.py @time: 2021/6/1 15:03 comment 登录成功的数据 set user = tuple string nswe string 111111 comment 登录失败的数据- 用户名为空/密码为空/用户名格式不正确 set invalid_data = list dict string user string ; string password string 111111 ; string ch...
#!/usr/bin/env python # encoding: utf-8 ''' @contact: 1650503480@qq.com @file: login_datas.py @time: 2021/6/1 15:03 ''' # 登录成功的数据 user = ("nswe", "111111") # 登录失败的数据- 用户名为空/密码为空/用户名格式不正确 invalid_data = [ {"user": "", "password": "111111", "check": "账号或密码错误"}, {"user": "nswe", "password": "1111112qsda1", "chec...
Python
zaydzuhri_stack_edu_python
function cmu_syl word begin return length list comprehension ph for ph in phoneme_dict at word at 0 if strip ph ascii_letters end function
def cmu_syl(word: str) -> int: return len( [ph for ph in phoneme_dict[word][0] if ph.strip(string.ascii_letters)] )
Python
nomic_cornstack_python_v1
import json with open string ingredients.json as data_file begin set data = load json data_file end set category = keys data for i in range 0 length category - 1 begin set names = keys data at category at i set price = values data at category at i end
import json with open('ingredients.json') as data_file: data = json.load(data_file) category = data.keys() for i in range(0, len(category)-1): names = data[category[i]].keys() price = data[category[i]].values()
Python
zaydzuhri_stack_edu_python
function test_outright begin call _do_test string tests/resources/conduit/basta_bar.xpi test_conduittoolbar failure=true require_install=true set_type=PACKAGE_EXTENSION end function
def test_outright(): _do_test("tests/resources/conduit/basta_bar.xpi", conduit.test_conduittoolbar, failure=True, require_install=True, set_type=PACKAGE_EXTENSION)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import os import sys import numpy as np function display_result work_time send_time backends incomplete begin set work_time_p95 = integer call percentile work_time 95 set send_time_sorted_list = sorted send_time key=lambda i -> integer send_time at i reverse=true if length send_time_sorted_list...
#!/usr/bin/python import os import sys import numpy as np def display_result(work_time, send_time, backends, incomplete): work_time_p95 = int(np.percentile(work_time, 95)) send_time_sorted_list = sorted(send_time, key=lambda i: int(send_time[i]), reverse = True) if (len(send_time_sorted_list) >= 10): send_tim...
Python
zaydzuhri_stack_edu_python
import matplotlib as matplotlib import matplotlib.pyplot as plt import numpy as np seed 1000 set y = cumulative sum call standard_normal tuple 20 2 axis=0 figure figsize=tuple 10 60 comment If they have the same x-axis we can do it without any 'x' values plot y at tuple slice : : 0 lw=1.5 label=string 1st plot y at ...
import matplotlib as matplotlib import matplotlib.pyplot as plt import numpy as np np.random.seed(1000) y = np.random.standard_normal((20,2)).cumsum(axis=0) plt.figure(figsize=(10,60)) # If they have the same x-axis we can do it without any 'x' values plt.plot(y[:,0], lw = 1.5, label='1st') plt.plot(y[:,1], lw = 1.5...
Python
zaydzuhri_stack_edu_python
from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from sklearn.utils import shuffle from trainingData import TrainingData from logistic2 import sigmoid , cross_entropy set Data = call TrainingData set D = shape at 1 set W = randn D set b = 1 function forward X W b begin return sig...
from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from sklearn.utils import shuffle from trainingData import TrainingData from logistic2 import sigmoid, cross_entropy Data = TrainingData() D = Data.X.train.shape[1] W = np.random.randn(D) b = 1 def forward(X, W, b): return...
Python
zaydzuhri_stack_edu_python
import argparse comment 创建一个解析器 set parser = call ArgumentParser comment 添加解析参数 call add_argument string eho set args = call parse_args print eho
import argparse #创建一个解析器 parser = argparse.ArgumentParser() #添加解析参数 parser.add_argument("eho") args = parser.parse_args() print(args.eho)
Python
zaydzuhri_stack_edu_python
function following request user_id flag begin string Returns a list of actors that the user identified by ``user_id`` is following (eg who im following). set instance = call get_object_or_404 USER_MODEL pk=user_id set flag = flag or string return call render request string actstream/following.html dict string followin...
def following(request, user_id, flag): """ Returns a list of actors that the user identified by ``user_id`` is following (eg who im following). """ instance = get_object_or_404(USER_MODEL, pk=user_id) flag = flag or '' return render( request, 'actstream/following.html', ...
Python
jtatman_500k
for i in range 10 begin print 2 * i end
for i in range(10): print(2 * i)
Python
zaydzuhri_stack_edu_python
function maxTerritoryMarkerno self territoryno begin set result = call aggregate max string markerno return if expression result then result at string markerno__max else 1 end function
def maxTerritoryMarkerno(self, territoryno): result = Place.objects.filter(territoryno=territoryno).aggregate(Max('markerno')) return result['markerno__max'] if result else 1
Python
nomic_cornstack_python_v1
function read_lcat_original lcat_name begin set fname = call get_lcat_original_file lcat_name print string reading: fname return read fitsio fname lower=true end function
def read_lcat_original(lcat_name): fname=get_lcat_original_file(lcat_name) print("reading:",fname) return fitsio.read(fname, lower=True)
Python
nomic_cornstack_python_v1
function search_books search begin comment prepare search query url in required format set search_book_url = string https://www.gutenberg.org/ebooks/search/?query= set search_book_url = search_book_url + join string + split search string comment download page set soup = call download_page search_book_url return call ge...
def search_books(search) -> pd.DataFrame: # prepare search query url in required format search_book_url = "https://www.gutenberg.org/ebooks/search/?query=" search_book_url += "+".join(search.split(" ")) # download page soup = download_page(search_book_url) return get_book_links(soup)
Python
nomic_cornstack_python_v1
function planCartesianPath self startConfig goalPose stepSize linkName mustReachGoal=true begin call _preemptionCheck set startJS = call dictToJointState startConfig try begin set planResult = call _cartesianLinearPathPlanner move_group=call get_name link_name=linkName pose=goalPose start_config=startJS step_size=stepS...
def planCartesianPath(self, startConfig, goalPose, stepSize, linkName, mustReachGoal=True): self._preemptionCheck() startJS = utils.ArgumentsCollector.dictToJointState(startConfig) try: planResult = self._cartesianLinearPathPlanner(move_group=self._moveGroup.get_name(), ...
Python
nomic_cornstack_python_v1
function multiply_list l begin from functools import reduce return reduce lambda x y -> x * y l end function
def multiply_list(l): from functools import reduce return reduce((lambda x, y: x * y), l)
Python
jtatman_500k
function data_collection_endpoint self begin return get pulumi self string data_collection_endpoint end function
def data_collection_endpoint(self) -> str: return pulumi.get(self, "data_collection_endpoint")
Python
nomic_cornstack_python_v1
function mit2stn fp add_z=false connect_origin=false cap=true begin with open fp string r as f begin set jo = loads read f end set stnlist = list for inst in jo at string instances begin comment inst is an STP dict for tuple arr_name arr in items inst begin set stn = call _make_stn arr add_z connect_origin set name = ...
def mit2stn(fp: str, add_z=False, connect_origin=False, cap=True) -> list: with open(fp, "r") as f: jo = json.loads(f.read()) stnlist = [] for inst in jo["instances"]: # inst is an STP dict for arr_name, arr in inst.items(): stn = _make_stn(arr, add_z, connect_origin) ...
Python
nomic_cornstack_python_v1
function make_tree_info task indent=string last=true details=false abbr=true visited_tasks=none ignore_task_names=none begin return call make_task_info_as_tree_str task=task details=details abbr=abbr ignore_task_names=ignore_task_names end function
def make_tree_info(task: TaskOnKart, indent: str = '', last: bool = True, details: bool = False, abbr: bool = True, visited_tasks: Optional[Set[str]] = None, ignore_task_names: Optional[List[str]] = None) -...
Python
nomic_cornstack_python_v1
function push_prefix self pfx begin append _prefix_stack pfx set _prefix_str = join string _prefix_stack end function
def push_prefix(self, pfx): self._prefix_stack.append(pfx) self._prefix_str = ''.join(self._prefix_stack)
Python
nomic_cornstack_python_v1
import sys function Room_check H N begin set cont = 0 set s = 0 comment N이 머무르는 호수 파악 while true begin set cont = cont + 1 set s = s + H if N <= s begin break end end comment a : N이 머무르는 층수(N % H) comment cont : N이 머무르는 호수 set a = if expression N % H != 0 then N % H else H return print string %d%02d % tuple a cont end ...
import sys def Room_check(H, N): cont = 0 s = 0 # N이 머무르는 호수 파악 while True: cont += 1 s += H if N <= s: break # a : N이 머무르는 층수(N % H) # cont : N이 머무르는 호수 a = N % H if N % H != 0 else H return print("%d%02d" % (a, cont)) T = int(sys.stdin.readline()....
Python
zaydzuhri_stack_edu_python
function test_display_user_profile self begin with client as c begin with call session_transaction as sess begin set sess at CURR_USER_KEY = id end set resp = get client string /users/ { id } set html = call get_data as_text=true assert equal status_code 200 assert in string <form id="edit-user-form" class="user-form" ...
def test_display_user_profile(self): with self.client as c: with c.session_transaction() as sess: sess[CURR_USER_KEY] = self.testuser.id resp = self.client.get(f"/users/{self.testuser.id}") html = resp.get_data(as_text=True) self.assertEqual(res...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment Copyright (C) 2014 Bitergia comment This program is free software; you can redistribute it and/or modify comment it under the terms of the GNU General Public License as published by comment the Free Software Foundation; either version 3 of the License, or comment (at your option) an...
#!/usr/bin/env python # Copyright (C) 2014 Bitergia # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program...
Python
zaydzuhri_stack_edu_python
comment Weekly Tasks 3 comment Author: Louise Stafford comment Program that takes asks a user to input a string and outputs every second letter in reverse order comment TODO
# Weekly Tasks 3 # Author: Louise Stafford # Program that takes asks a user to input a string and outputs every second letter in reverse order # TODO
Python
zaydzuhri_stack_edu_python
function img2jpg folder_name prefix ids=none begin set path = absolute path path folder_name set files = list directory path for file in files begin set tuple prefix id suffix = call seperate_file_name file if suffix == string jpg begin continue end if ids is not none and id not in ids begin continue end set fullname =...
def img2jpg(folder_name, prefix, ids=None): path = os.path.abspath(folder_name) files = os.listdir(path) for file in files: prefix, id, suffix = utg.seperate_file_name(file) if suffix == 'jpg': continue if ids is not None and id not in ids: continue fu...
Python
nomic_cornstack_python_v1
function summarize_cfg_diffs delta stream begin set stanza_stats = default dictionary set set key_stats = default dictionary lambda -> default dictionary lambda -> default dictionary set set c = counter for op in delta begin set c at tag = c at tag + 1 if is instance location DiffStanza begin add stanza_stats at tag ...
def summarize_cfg_diffs(delta: List[DiffOp], stream: TextIO): stanza_stats = defaultdict(set) key_stats = defaultdict(lambda: defaultdict(lambda: defaultdict(set))) c = Counter() for op in delta: c[op.tag] += 1 if isinstance(op.location, DiffStanza): stanza_stats[op.tag].add(...
Python
nomic_cornstack_python_v1
function test_datagram_start_bit self begin set dt = call encode_datagram bytes list 1 set msgs = call datagram_to_frames dt source=0 comment Bit 7 is start bit. call assertBitSet id 7 call assertBitClear id 7 end function
def test_datagram_start_bit(self): dt = encode_datagram(bytes(), [1]) msgs = datagram_to_frames(dt, source=0) # Bit 7 is start bit. self.assertBitSet(next(msgs).id, 7) self.assertBitClear(next(msgs).id, 7)
Python
nomic_cornstack_python_v1
comment data preparation import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model set lines = call loadtxt string input/logisticR_data.csv delimiter=string , dtype=string str set x_total = as type lines at tuple slice : : slice 1 : 3 : string float set y_total = as type lines at tuple sli...
## data preparation import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model lines = np.loadtxt('input/logisticR_data.csv', delimiter = ',', dtype = 'str') x_total = lines[:, 1:3].astype('float') y_total = lines[:, 3].astype('float') pos_index = np.where(y_total == 1) neg_index =...
Python
zaydzuhri_stack_edu_python
function aliases self query=string begin set names = list for template in all begin for name in list key + aliases begin if query in name begin append names name end end end return names end function
def aliases(self, query=""): names = [] for template in self.all(): for name in [template.key] + template.aliases: if query in name: names.append(name) return names
Python
nomic_cornstack_python_v1
function __init__ self name=string uniformvelmodel begin call __init__ self name return end function
def __init__(self, name="uniformvelmodel"): SpatialDBObj.__init__(self, name) return
Python
nomic_cornstack_python_v1
comment coding: utf-8 from logging import getLogger , Formatter , FileHandler , DEBUG , INFO class Logger extends object begin set filename = string DEBUG.log set level = DEBUG set fmt = string %(asctime)s %(name)s %(levelname)s %(message)s function __init__ self name **kwargs begin if call has_key string filename begi...
# coding: utf-8 from logging import getLogger, Formatter, FileHandler, DEBUG, INFO class Logger(object): filename = "DEBUG.log" level = DEBUG fmt = "%(asctime)s %(name)s %(levelname)s %(message)s" def __init__(self, name, **kwargs): if kwargs.has_key("filename"): self.filen...
Python
zaydzuhri_stack_edu_python
comment If they do exist, then they are deleted for every user on the server. Also, a logfile comment is created which keeps a record of what has been deleted comment Deleted ... usually means that folder has been deleted comment Skipped ... usually means that that folder does not exist comment Every log will have a be...
# If they do exist, then they are deleted for every user on the server. Also, a logfile # is created which keeps a record of what has been deleted # # Deleted ... usually means that folder has been deleted # Skipped ... usually means that that folder does not exist # # Every log will have a beginning and ending timest...
Python
zaydzuhri_stack_edu_python
function _get_trader_dir temp_name begin set cwd = call cwd set temp_path = call joinpath temp_name comment If .vntrader folder exists in current working directory, comment then use it as trader running path. if exists temp_path begin return tuple cwd temp_path end comment Otherwise use home path of system. set home_pa...
def _get_trader_dir(temp_name: str) -> Tuple[Path, Path]: cwd = Path.cwd() temp_path = cwd.joinpath(temp_name) # If .vntrader folder exists in current working directory, # then use it as trader running path. if temp_path.exists(): return cwd, temp_path # Otherwise use home path of syst...
Python
nomic_cornstack_python_v1
function calcUnboundInterface self boundChain boundChainInterface unboundChain utils begin set unbound_interface_indices = call getMatchingStructure boundChain boundChainInterface unboundChain return call getSubsetOfSelection unboundChain unbound_interface_indices end function
def calcUnboundInterface(self, boundChain, boundChainInterface, unboundChain, utils): unbound_interface_indices = utils.getMatchingStructure(boundChain, boundChainInterface, unboundChain) return utils.getSubsetOfSelection(unboundChain, unbound_interface_indices)
Python
nomic_cornstack_python_v1
print string ===== AULA 6 ===== set n1 = integer input string Digite um valor set n2 = integer input string Digite outro set s = n1 + n2 print string A soma entre n1 string e n2 string vale s print format string A soma entre {} e {} vale {} n1 n2 s print string A soma entre { n1 } e { n2 } vale { s }
print('===== AULA 6 =====') n1 = int(input('Digite um valor')) n2 = int(input('Digite outro')) s = n1 + n2 print('A soma entre ' ,n1 ,'e',n2, 'vale', s) print('A soma entre {} e {} vale {}'.format(n1,n2,s)) print(f'A soma entre {n1} e {n2} vale {s}')
Python
zaydzuhri_stack_edu_python
function l2h_ndcg self n query_truth num_bins=5 begin if not is_query_level begin return 0.0 end if num_relevant == 0 begin return 1.0 end call sort_docs_by_price call sort_docs_by_price set lowest_price = price set highest_price = price if lowest_price == highest_price begin set highest_price = highest_price + 1 end s...
def l2h_ndcg(self, n, query_truth, num_bins=5): if not self.is_query_level: return 0.0 if query_truth.num_relevant == 0: return 1.0 query_truth.sort_docs_by_price() self.query_prediction.sort_docs_by_price() lowest_price = query_truth.relevant_do...
Python
nomic_cornstack_python_v1
function load_annotations self begin assert ends with ann_file string .pkl set data = call hload_pkl ann_file set video_infos = list for video_info in data begin set filename = video_info at string filename if data_prefix is not none begin set filename = join osp data_prefix filename end set video_info at string filen...
def load_annotations(self): assert self.ann_file.endswith('.pkl') data = hload_pkl(self.ann_file) video_infos = [] for video_info in data: filename = video_info['filename'] if self.data_prefix is not None: filename = osp.join(self.data_prefix, fil...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- set numbers = dict string 1 string yksi ; string 2 string kaksi ; string 3 string kolme ; string 4 string neljä ; string 5 string viisi ; string 6 string kuusi ; string 7 string seitsemän ; string 8 string kahdeksan ; string 9 string yhdeksän ; string 10 string...
#!/usr/bin/env python # -*- coding: utf-8 -*- numbers = {'1': u'yksi', '2': u'kaksi', '3': u'kolme', '4': u'neljä', '5': u'viisi', '6': u'kuusi', \ '7': u'seitsemän', '8': u'kahdeksan', '9': u'yhdeksän', '10': u'kymmenen'} for hundred in range(0, 11): if hundred == 0: sata = '' elif hundred ==...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Mar 10 23:48:27 2019 @author: Praison Joshua import math set testcase = integer input for i in range testcase begin set tuple n k = list comprehension integer x for x in split input set N = list set c = 0 set N = list map int split input for i in range n begin set su...
# -*- coding: utf-8 -*- """ Created on Sun Mar 10 23:48:27 2019 @author: Praison Joshua """ import math testcase=int(input()) for i in range(testcase): n,k=[int(x) for x in input().split()] N=[] c=0 N= list(map(int, input (). split ())) for i in ...
Python
zaydzuhri_stack_edu_python
for a in range 1 6 begin append savat input string { a } -mahsulotni kiriting: end for mahsulot in savat begin if mahsulot in mahsulotlar begin print string { mahsulot } dokonimizda bor end else begin print string { mahsulot } dokonimizda yoq end end
for a in range(1,6): savat.append(input(f'{a}-mahsulotni kiriting:')) for mahsulot in savat: if mahsulot in mahsulotlar: print(f'{mahsulot} dokonimizda bor') else: print(f'{mahsulot} dokonimizda yoq')
Python
zaydzuhri_stack_edu_python
from PIL import Image from multiprocessing import Pool import imghdr import glob , os , sys import tqdm comment DEFAULT_SIZE = (480, 480) set DEFAULT_SIZE = tuple 960 960 set IMAGE_TYPE = list string rgb string gif string pbm string pgm string ppm string tiff string rast string xbm string jpeg string bmp string png str...
from PIL import Image from multiprocessing import Pool import imghdr import glob, os, sys import tqdm # DEFAULT_SIZE = (480, 480) DEFAULT_SIZE = (960, 960) IMAGE_TYPE = ['rgb', 'gif', 'pbm', 'pgm', 'ppm', 'tiff', 'rast', 'xbm', 'jpeg', 'bmp', 'png', 'webp', 'exr'] def down_size(image_path, size=DEFAULT_SIZE): im = I...
Python
zaydzuhri_stack_edu_python
function home_remedies begin print string choose from the following problem print string 1.cold 2.cough 3.acidity 4.diarrhoea 5.vomitings 6.fever 7.blood pressure 8.allergies 9.stomach ache 10.diabetes 11.dehyration 12.food poisoning 13.itching 14.obesity 15.toothache set choice = integer input string Enter your choice...
def home_remedies(): print("choose from the following problem") print(" 1.cold\n 2.cough\n 3.acidity\n 4.diarrhoea\n 5.vomitings\n 6.fever \n 7.blood pressure\n 8.allergies\n 9.stomach ache\n 10.diabetes \n 11.dehyration\n 12.food poisoning\n 13.itching\n 14.obesity\n 15.toothache") choice=int(input("Ent...
Python
zaydzuhri_stack_edu_python
function supported_features self begin return SUPPORT_FLAGS end function
def supported_features(self): return SUPPORT_FLAGS
Python
nomic_cornstack_python_v1
function haversine_km lat1 lng1 lat2 lng2 begin return call haversine_rad lat1 lng1 lat2 lng2 * radius_km end function
def haversine_km(lat1, lng1, lat2, lng2): return haversine_rad(lat1, lng1, lat2, lng2) * radius_km
Python
nomic_cornstack_python_v1
function _construct_and_pickle_set_cover_input self possible_probes_grouped target_genomes_grouped begin set paths = list for tuple group_i tuple possible_probes target_genomes in enumerate zip possible_probes_grouped target_genomes_grouped begin comment Ensure that the input is a list set possible_probes = list possi...
def _construct_and_pickle_set_cover_input(self, possible_probes_grouped, target_genomes_grouped): paths = [] for group_i, (possible_probes, target_genomes) in enumerate(zip( possible_probes_grouped, target_genomes_grouped)): # Ensure that the input is a list ...
Python
nomic_cornstack_python_v1
comment Create a class named MyClass, class MyClass begin set x = 5 end class print MyClass comment Creating an object class MyClass begin set x = 5 end class set p1 = call MyClass print x comment Using the __init__() function to assign values for name and age class Person begin function __init__ self name age begin se...
# Create a class named MyClass, class MyClass: x = 5 print(MyClass) # Creating an object class MyClass: x = 5 p1 = MyClass() print(p1.x) # Using the __init__() function to assign values for name and age class Person: def __init__(self, name, age): self.name = name self.age = age ...
Python
zaydzuhri_stack_edu_python