code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function pearson_correlation self array1 array2 begin set n = length array1 set x_times_y = 0 set x_sq = 0 set y_sq = 0 for i in range n begin set x_min_mean = array1 at i - mean self array1 set y_min_mean = array2 at i - mean self array2 set x_times_y = x_times_y + x_min_mean * y_min_mean set x_sq = x_sq + x_min_mean ...
def pearson_correlation(self, array1, array2): n = len(array1) x_times_y = 0 x_sq = 0 y_sq = 0 for i in range(n): x_min_mean = array1[i] - self.mean(array1) y_min_mean = array2[i] - self.mean(array2) x_times_y += x_min_mean * y_min_mean ...
Python
nomic_cornstack_python_v1
set person = dict string name string John Doe ; string age 30 ; string location string New York ; string occupation string Software Engineer ; string hobbies list string reading string playing guitar string hiking ; string education dict string school string ABC University ; string degree string Computer Science ; stri...
person = { "name": "John Doe", "age": 30, "location": "New York", "occupation": "Software Engineer", "hobbies": ["reading", "playing guitar", "hiking"], "education": { "school": "ABC University", "degree": "Computer Science", "graduation_year": 2015 }, "languages"...
Python
greatdarklord_python_dataset
comment Chellz Mini Project - IITM BUNKER from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.opt...
# Chellz Mini Project - IITM BUNKER from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options i...
Python
zaydzuhri_stack_edu_python
comment Definition for an interval. comment class Interval: comment def __init__(self, s=0, e=0): comment self.start = s comment self.end = e class Solution begin function merge self intervals begin set lst = list comprehension tuple start end for s in intervals sort lst if not lst begin return lst end set ends = list ...
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def merge(self, intervals: List[Interval]) -> List[Interval]: lst = [(s.start,s.end) for s in intervals] lst.sort() if not lst: ret...
Python
zaydzuhri_stack_edu_python
function construct_global_ctx self begin call construct_global_ctx set gtx = gtx set rc = rc if string groups in needed_dbs begin set pi_id = call get_pi_id rc end set coll = string { TARGET_COLL } try begin if not database begin set database = databases at 0 at string name end end except any begin pass end set colls =...
def construct_global_ctx(self): super().construct_global_ctx() gtx = self.gtx rc = self.rc if "groups" in self.needed_dbs: rc.pi_id = get_pi_id(rc) rc.coll = f"{TARGET_COLL}" try: if not rc.database: rc.database = rc.databases[0]["n...
Python
nomic_cornstack_python_v1
function create movie begin set mname = get movie string mname none set mgenre = get movie string mgenre none set mdatereleased = get movie string mdatereleased none set mruntime = get movie string mruntime none if movie at string mname not in list comprehension movie at 1 at string mname for movie in items MOVIES and ...
def create(movie: dict): mname = movie.get("mname", None) mgenre = movie.get("mgenre", None) mdatereleased = movie.get("mdatereleased", None) mruntime = movie.get("mruntime", None) if ( movie["mname"] not in [movie[1]["mname"] for movie in MOVIES.items()] and mname is not None )...
Python
nomic_cornstack_python_v1
function forward self batch action_scores **kw begin if is instance action_scores tuple begin comment handle case of multiple return values from model; we assume comment scores are the first element in this case. set tuple action_scores _ = action_scores end comment TODO: Implement the entropy-based loss for the action...
def forward(self, batch: TrainBatch, action_scores, **kw): if isinstance(action_scores, tuple): # handle case of multiple return values from model; we assume # scores are the first element in this case. action_scores, _ = action_scores # TODO: Implement the entropy-b...
Python
nomic_cornstack_python_v1
async function test_light_no_on_off aresponses begin comment Handle to run asserts on request in async function response_handler request begin string Response handler for this test. set data = await json request assert data == dict string numberOfLights 1 ; string lights list dict string brightness 50 return call Respo...
async def test_light_no_on_off(aresponses: ResponsesMockServer) -> None: # Handle to run asserts on request in async def response_handler(request: ClientResponse) -> Response: """Response handler for this test.""" data = await request.json() assert data == { "numberOfLights"...
Python
nomic_cornstack_python_v1
import numpy as np import os import librosa import soundfile as sf from pathlib import Path import pickle import random function getGloVector glove_vectors_file=string glove.6B.50d.txt begin set glove_wordmap = dict with open glove_vectors_file string r encoding=string utf8 as glove begin for line in glove begin set t...
import numpy as np import os import librosa import soundfile as sf from pathlib import Path import pickle import random def getGloVector(glove_vectors_file = "glove.6B.50d.txt"): glove_wordmap = {} with open(glove_vectors_file, "r", encoding="utf8") as glove: for line in glove: name, vector = tuple(lin...
Python
zaydzuhri_stack_edu_python
import csv set filelist = input string Enter .txt file containing filenames set fileNames = list set fields = open filelist string r with fields begin set files = reader fields for row in files begin append fileNames row at 0 at slice : - 1 : end end print fileNames
import csv filelist = input("Enter .txt file containing filenames\n") fileNames = [] fields = open(filelist, 'r') with fields: files = csv.reader(fields) for row in files: fileNames.append(row[0][:-1]) print (fileNames)
Python
zaydzuhri_stack_edu_python
from django.core.management.base import BaseCommand , CommandError from fplcornerapp.models import Player_Weekly_Stat , Player_Last_Six_Stat class Command extends BaseCommand begin set help = string Updates the table that shows stats for the last 6 games. it checks one by one. The players that are already in that table...
from django.core.management.base import BaseCommand, CommandError from fplcornerapp.models import Player_Weekly_Stat, Player_Last_Six_Stat class Command(BaseCommand): help = 'Updates the table that shows stats for the last 6 games.' \ ' it checks one by one. The players that are already in that table'\ ...
Python
zaydzuhri_stack_edu_python
function allow_tagging_in_send_and_correct self allow_tagging_in_send_and_correct begin set _allow_tagging_in_send_and_correct = allow_tagging_in_send_and_correct end function
def allow_tagging_in_send_and_correct(self, allow_tagging_in_send_and_correct): self._allow_tagging_in_send_and_correct = allow_tagging_in_send_and_correct
Python
nomic_cornstack_python_v1
function _is_move_valid self start goal begin set moves = 0 for tuple x y in zip start goal begin if y != x and x == 0 begin set moves = moves + 1 end else if y != x begin return false end end return moves == 1 end function
def _is_move_valid( self, start: tuple[int, int, int], goal: tuple[int, int, int] ) -> bool: moves = 0 for x, y in zip(start, goal): if y != x and x == 0: moves += 1 elif y != x: return False return moves == 1
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment coding = UTF-8 set list1 = list for i in range 1 1001 begin set list1 = list1 + list i end set list1 = list1 + list 100 set sum1 = sum list1 set sum2 = sum range 1 1001 set num = sum1 - sum2 print string 重复的数字是: num
#!/usr/bin/python3 # coding = UTF-8 list1 = [] for i in range(1, 1001): list1 += [i] list1 = list1 + [100] sum1 = sum(list1) sum2 = sum(range(1, 1001)) num = sum1 - sum2 print('重复的数字是:', num)
Python
zaydzuhri_stack_edu_python
import time from base_page import BasePage from locators import BasePageLocators class BasketPage extends BasePage begin function guest_can_open_basket_page self begin set basket_button_on_main_page = call find_element *BasePageLocators.BASKET_BUTTON call click sleep 1 end function function basket_is_empty self begin a...
import time from .base_page import BasePage from .locators import BasePageLocators class BasketPage(BasePage): def guest_can_open_basket_page(self): basket_button_on_main_page = self.browser.find_element(*BasePageLocators.BASKET_BUTTON) basket_button_on_main_page.click() time.sleep(1) ...
Python
zaydzuhri_stack_edu_python
from categories import * import requests import json class Reminder begin decorator classmethod function parse cls text begin set parts = split text string @ if length parts != 2 begin set parts = split text string at if length parts != 2 begin raise exception string Invalid reminder syntax "%s" % text end end set item...
from categories import * import requests import json class Reminder: @classmethod def parse(cls, text): parts = text.split('@') if len(parts) != 2: parts = text.split(' at ') if len(parts) != 2: raise Exception('Invalid reminder syntax "%s"' % text) ...
Python
zaydzuhri_stack_edu_python
import pandas as pd comment Assuming 'df' is your DataFrame set df = drop missing df axis=1 how=string any
import pandas as pd # Assuming 'df' is your DataFrame df = df.dropna(axis=1, how='any')
Python
flytech_python_25k
import random class Board begin string Represents the board of tic-tac-toe set ROW_LEN = 3 set COL_LEN = 3 set POSITIONS = tuple tuple 0 0 0 1 0 2 tuple 1 0 1 1 1 2 tuple 2 0 2 1 2 2 tuple 0 0 1 0 2 0 tuple 0 1 1 1 2 1 tuple 0 2 1 2 2 2 tuple 0 0 1 1 2 2 tuple 0 2 1 1 2 0 function __init__ self begin string Checker is ...
import random class Board(): '''Represents the board of tic-tac-toe''' ROW_LEN = 3 COL_LEN = 3 POSITIONS = ((0, 0, 0, 1, 0, 2), (1, 0, 1, 1, 1, 2), (2, 0, 2, 1, 2, 2), (0, 0, 1, 0, 2, 0), (0, 1, 1, 1, 2, 1), (...
Python
zaydzuhri_stack_edu_python
comment This program takes an integer as input and returns the Syracruse comment Sequence printed in an organized list. comment Author: Joseph Prostko comment Project: Assignment 2: Python; Question 3 comment Version: October 2019 function main begin comment The user is prompted to enter an integer value. print string ...
# This program takes an integer as input and returns the Syracruse # Sequence printed in an organized list. # Author: Joseph Prostko # Project: Assignment 2: Python; Question 3 # Version: October 2019 def main(): # The user is prompted to enter an integer value. print("This program outputs a Sy...
Python
zaydzuhri_stack_edu_python
function add value begin global score set score = score + value end function function get begin return score end function function empty begin global score set score = 0 end function
def add(value): global score score = score + value def get(): return score def empty(): global score score = 0
Python
zaydzuhri_stack_edu_python
import turtle set num_legs = integer input string Enter number of legs: set turn_angle = 360 / num_legs set leg_length = 50 set wn = call Screen set t = call Turtle call hideturtle for step in range num_legs begin call forward leg_length backward t leg_length call left turn_angle end call exitonclick
import turtle num_legs = int(input("Enter number of legs: ")) turn_angle = 360 / num_legs leg_length = 50 wn = turtle.Screen() t = turtle.Turtle() t.hideturtle() for step in range(num_legs): t.forward(leg_length) t.backward(leg_length) t.left(turn_angle) wn.exitonclick()
Python
zaydzuhri_stack_edu_python
function add_three_to_five_numbers a b c x=1 y=2 begin string Returns sum of given arguments. :param a: float. :param b: float. :param c: float. :param x: float. :param y: float. :return: float. return a + b + c + x + y end function print call add_three_to_five_numbers 1 2 3 0
def add_three_to_five_numbers(a, b, c, x=1, y=2): """ Returns sum of given arguments. :param a: float. :param b: float. :param c: float. :param x: float. :param y: float. :return: float. """ return a + b + c + x + y print(add_three_to_five_numbers(1,2,3,0)) ...
Python
zaydzuhri_stack_edu_python
function reverse self transformed_point index=none begin return exp call asarray transformed_point end function
def reverse(self, transformed_point, index=None): return numpy.exp(numpy.asarray(transformed_point))
Python
nomic_cornstack_python_v1
import math function difference_in_minutes timestamp1 timestamp2 begin set difference = timestamp2 - timestamp1 return floor difference / 60 end function comment 2021-01-01 00:00:00 set timestamp1 = 1609459200 comment 2021-01-01 00:30:00 set timestamp2 = 1609461000 set difference = call difference_in_minutes timestamp1...
import math def difference_in_minutes(timestamp1, timestamp2): difference = timestamp2 - timestamp1 return math.floor(difference / 60) timestamp1 = 1609459200 # 2021-01-01 00:00:00 timestamp2 = 1609461000 # 2021-01-01 00:30:00 difference = difference_in_minutes(timestamp1, timestamp2) print(difference) #...
Python
jtatman_500k
function getSchema begin set yamlFile = join path directory name path __file__ string schema.yml set schema = none with open yamlFile string r as f begin set schema = call loadYaml f end assert is instance schema dict assert string __version__ in schema return schema end function
def getSchema(): yamlFile = os.path.join(os.path.dirname(__file__), 'schema.yml') schema = None with open(yamlFile, 'r') as f: schema = util.loadYaml(f) assert isinstance(schema, dict) assert '__version__' in schema return schema
Python
nomic_cornstack_python_v1
from collections import deque set q = deque maxlen=3 append q 1 append q 2 append q 3 print q append q 4 append q 5 print q comment ----------------------------- set q = deque append q 1 append q 2 append q 3 print q call appendleft 4 print q append q 5 print q call popleft print q
from collections import deque q = deque(maxlen=3) q.append(1) q.append(2) q.append(3) print(q) q.append(4) q.append(5) print(q) # ----------------------------- q = deque() q.append(1) q.append(2) q.append(3) print(q) q.appendleft(4) print(q) q.append(5) print(q) q.popleft() print(q)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Authors: Hung-Hsin Chen <chenhh@par.cse.nsysu.edu.tw> License: GPL v2 status: AC difficulty: 1 https://uva.onlinejudge.org/external/8/846.pdf The length of a step must be non-negative and can be by one bigger than, equal to, or by one smaller than the length of the previous step 0 s...
# -*- coding: utf-8 -*- """ Authors: Hung-Hsin Chen <chenhh@par.cse.nsysu.edu.tw> License: GPL v2 status: AC difficulty: 1 https://uva.onlinejudge.org/external/8/846.pdf The length of a step must be non-negative and can be by one bigger than, equal to, or by one smaller than the length of the previous step 0 step, ...
Python
zaydzuhri_stack_edu_python
from ics import Calendar comment Employee scheduling logic here
from ics import Calendar # Employee scheduling logic here
Python
flytech_python_25k
function _decreasing_int_to_arg level params begin set magnitude = level / _AUGMENTATION_MAX_LEVEL * params at 1 return tuple params at 0 - integer magnitude end function
def _decreasing_int_to_arg(level: int, params: Tuple[int, int]) -> Tuple[int]: magnitude = (level / _AUGMENTATION_MAX_LEVEL) * params[1] return (params[0] - int(magnitude),)
Python
nomic_cornstack_python_v1
function title self begin return get pulumi self string title end function
def title(self) -> pulumi.Input[str]: return pulumi.get(self, "title")
Python
nomic_cornstack_python_v1
function test_strip_atom_stereochemistry self begin set mol = call from_smiles string CCC[N@@](C)CC set nitrogen_idx = list comprehension molecule_atom_index for atom in atoms if symbol == string N at 0 assert stereochemistry == string S call strip_atom_stereochemistry smarts=string [N+0X3:1](-[*])(-[*])(-[*]) assert s...
def test_strip_atom_stereochemistry(self): mol = Molecule.from_smiles("CCC[N@@](C)CC") nitrogen_idx = [ atom.molecule_atom_index for atom in mol.atoms if atom.element.symbol == "N" ][0] assert mol.atoms[nitrogen_idx].stereochemistry == "S" mol.strip_atom_stereochemi...
Python
nomic_cornstack_python_v1
function ransac data tolerance=0.5 max_iterations=100 confidence=0.95 begin comment use a matrix to go along with the homography function set data = call matrix data set iterations = 0 set best_model = none set best_count = 0 set best_indices = none comment if we reached the maximum iteration while iterations < max_ite...
def ransac(data, tolerance=0.5, max_iterations=100, confidence=0.95): # use a matrix to go along with the homography function data = np.matrix(data) iterations = 0 best_model = None best_count = 0 best_indices = None # if we reached the maximum iteration while iterations < max_iteratio...
Python
nomic_cornstack_python_v1
import Football.football_data_parse as fdp from rgbmatrix import graphics function logo oc logo offset=0 brightness=30 / 100 begin set logo = call imageParser logo tuple 32 32 set pl = call pixel_list for x in range 32 begin for y in range 32 begin call SetPixel x + offset y pl at x at y at 0 * brightness pl at x at y ...
import Football.football_data_parse as fdp from rgbmatrix import graphics def logo(oc, logo, offset=0, brightness=30/100): logo = fdp.imageParser(logo, (32,32)) pl = logo.pixel_list() for x in range(32): for y in range(32): oc.SetPixel(x+offset, y, pl[x][y][0]*brightness, pl[x][y][1]*br...
Python
zaydzuhri_stack_edu_python
function should_retry begin with patch string homeassistant.components.stream._should_retry return_value=false as mock_should_retry begin yield mock_should_retry end end function
def should_retry() -> Generator[Mock, None, None]: with patch( "homeassistant.components.stream._should_retry", return_value=False ) as mock_should_retry: yield mock_should_retry
Python
nomic_cornstack_python_v1
function fidelity qState1 qState2 begin return absolute dot call conj qState1 qState2 end function
def fidelity(qState1, qState2): return np.abs(np.dot(np.conj(qState1), qState2))
Python
nomic_cornstack_python_v1
comment Testing the Genome class from src.genome import Genome function test_init begin string Test that the __init__ method of a genome sets up the correct number of input and output nodes. (connections between them are initialised randomly). set genome = call Genome 4 5 assert length call get_node_ids layer=string in...
# Testing the Genome class from src.genome import Genome def test_init(): """ Test that the __init__ method of a genome sets up the correct number of input and output nodes. (connections between them are initialised randomly). """ genome = Genome(4, 5) assert len(genome.get_node_ids(layer=...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import os import signal import time import sys function receiveSignal signum frame begin if p == 0 begin print string child recieved signum exit 0 end else begin print string parent here end end function call signal 2 receiveSignal set p = call fork print string beginning prorgram p if p ==...
#!/usr/bin/env python import os import signal import time import sys def receiveSignal(signum, frame): if(p==0): print("child recieved", signum) sys.exit(0) else: print("parent here") signal.signal(2,receiveSignal) p = os.fork() print("beginning prorgram",p) if(p==0): print("child PID is:", os.getpid()) w...
Python
zaydzuhri_stack_edu_python
function search self query begin comment Sanity check assert type query is str comment Parse the query into a list of words set query = call parse_query query comment Print information about the query print string ====> QUERY ANALYSIS <==== print string ----> Are query terms indexed? for word in query begin if word in ...
def search(self, query): # Sanity check assert(type(query) is str) # Parse the query into a list of words query = self.parser.parse_query(query) # Print information about the query print("====> QUERY ANALYSIS <====") print("----> Are query terms indexed?") ...
Python
nomic_cornstack_python_v1
async function async_step_zone self user_input=dict begin set _errors = dict if user_input is not none begin update _data user_input return call async_create_entry title=string data=_data end return await call _show_options_form user_input end function
async def async_step_zone(self, user_input={}): self._errors = {} if user_input is not None: self._data.update(user_input) return self.async_create_entry(title="", data=self._data) return await self._show_options_form(user_input)
Python
nomic_cornstack_python_v1
function getRegisteredModelDetail 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 getRegisteredModelDetail(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 press_long self hold_time element=none config=none x_cord=none y_cord=none begin if config begin call perform end else if element begin call perform end else if x_cord begin call perform end else begin error string Either element or co-ordinates must be given for long press! end sleep 2 end function
def press_long(self, hold_time, element=None, config=None, x_cord=None, y_cord=None): if config: self.touch.long_press(x=config[element]['x'], y=config[element]['y'], duration=hold_time).release().perform() elif element: ...
Python
nomic_cornstack_python_v1
class NumberSequence begin function __init__ self start=0 begin set current = start end function function next self begin set current = current set current = current + 1 return current end function end class
class NumberSequence: def __init__(self, start=0): self.current = start def next(self): current = self.current self.current += 1 return current
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import multiprocessing import time import os function normalizeData week begin set prev_time = time print string Week { week } | Started script | { round time - prev_time 4 } s set prev_time = time set track_df = reset index read csv string ./data/week { week } .csv low_memory=fal...
import pandas as pd import numpy as np import multiprocessing import time import os def normalizeData(week): prev_time = time.time() print(f"Week{week} | Started script | {round(time.time()-prev_time, 4)} s") prev_time = time.time() track_df = pd.read_csv(f"./data/week{week}.csv", low_mem...
Python
zaydzuhri_stack_edu_python
function _parse wd begin set tuple trees tree sequences probs rates = tuple list none list list list set tuple ancestors aps = tuple dict dict set tuple rst rs = tuple join path wd string rst join path wd string rates if is file path rst begin with open rst as f begin for line in f begin set line = strip line if ...
def _parse(wd): trees, tree, sequences, probs, rates = [], None, [], [], [] ancestors, aps = {}, {} rst, rs = os.path.join(wd, 'rst'), os.path.join(wd, 'rates') if os.path.isfile(rst): with open(rst) as f: for line in f: line = line.strip() if lin...
Python
nomic_cornstack_python_v1
function verifyFile self fixtureList begin call writeList fixtureFile fixtureList set observed = call readList fixtureFile assert equal observed fixtureList string %s does not equal %s % tuple observed fixtureList end function
def verifyFile(self, fixtureList): fileops.writeList(self.fixtureFile, fixtureList) observed = fileops.readList(self.fixtureFile) self.assertEqual(observed, fixtureList, "%s does not equal %s" % (observed, fixtureList))
Python
nomic_cornstack_python_v1
comment Ryan Jones comment 1/22/18 set fullname = input string Your full name: set tuple firstname lastname = split fullname set age = integer input string Enter your age: print string Your first name has length firstname string letters. print string Your last name has length lastname string letters. set nextyear = age...
#Ryan Jones #1/22/18 fullname= input( 'Your full name: ') firstname, lastname = fullname.split() age= int(input( 'Enter your age: ')) print( 'Your first name has',(len(firstname)), 'letters.') print( 'Your last name has',(len(lastname)), 'letters.') nextyear= (age++1) print( 'Next year you will be',(nextyear), 'years ...
Python
zaydzuhri_stack_edu_python
function test_missing_multiple_tokens self begin call helper_test_evaluate_raises string A or (B and (C and not D)) expected_exc_type=MissingSymbolError A=0 D=1 end function
def test_missing_multiple_tokens(self): self.helper_test_evaluate_raises( 'A or (B and (C and not D))', expected_exc_type=MissingSymbolError, A=0, D=1)
Python
nomic_cornstack_python_v1
function cross_val_score self X y return_incumbent_score=false begin return cross val score X=X y=y return_incumbent_score=return_incumbent_score end function
def cross_val_score(self, X, y, return_incumbent_score=False): return super().cross_val_score(X=X, y=y, return_incumbent_score=return_incumbent_score)
Python
nomic_cornstack_python_v1
comment below uses extra space function arrange A begin set arr = list set i = 0 while i < length A begin set j = A at i append arr A at j set i = i + 1 end return arr end function comment below uses less space and applies index logic to manipulate given array function re_arrange A begin set i = 0 set length = length ...
# below uses extra space def arrange(A): arr = [] i = 0 while i < len(A): j = A[i] arr.append(A[j]) i += 1 return arr # below uses less space and applies index logic to manipulate given array def re_arrange(A): i = 0 length = len(A) while i < length: ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt set rho = 7850 set E = 2.1 * 10 ^ 11 set L = 1.49 set d = 1.38 * 10 ^ - 2 set I = pi * d ^ 4 / 64 set A = pi * d ^ 2 / 4 set a = array list 1.875 4.694 7.855 10.996 set frec = a ^ 2 * square root E * I / rho * A * L ^ 4 / 2 * pi print string Primeras frecuencias normal...
import numpy as np import matplotlib.pyplot as plt rho = 7850 E = 2.1*10**11 L = 1.49 d = 1.38*10**-2 I = np.pi*d**4/64 A = np.pi*d**2/4 a = np.array([1.875, 4.694, 7.855, 10.996]) frec = a**2*np.sqrt(E*I/(rho*A*L**4))/(2*np.pi) print('Primeras frecuencias normales') for i in range(len(frec)): print(f'f{i + 1} =...
Python
zaydzuhri_stack_edu_python
from Extract_a_given_number_of_randomly_selected_elements_from_a_list_23 import extract_random_elements_limit set newlist = list string a string b string c string d string e string f string g string h print call extract_random_elements_limit length newlist newlist
from Extract_a_given_number_of_randomly_selected_elements_from_a_list_23 import extract_random_elements_limit newlist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] print(extract_random_elements_limit(len(newlist), newlist))
Python
zaydzuhri_stack_edu_python
class CommandParser begin function __init__ self command begin set command = command end function function can_parse self text begin return split text at 0 == command end function function _parse self text begin return split text end function function first_arg text begin return split text at 1 end function end class
class CommandParser(): def __init__(self, command): self.command = command def can_parse(self, text): return text.split()[0] == self.command def _parse(self, text): return text.split() def first_arg(text): return text.split()[1]
Python
zaydzuhri_stack_edu_python
function perform_clustering self kwargs begin set num_of_nodes = row_length set num_of_clusters = 0 set elements_per_cluster = 0 set max_num_of_clusters = 0 try begin set num_of_clusters = kwargs at string num_clusters set elements_per_cluster = max 1 num_of_nodes / num_of_clusters end except KeyError begin try begin s...
def perform_clustering(self, kwargs): num_of_nodes = self.condensed_matrix.row_length num_of_clusters = 0 elements_per_cluster = 0 max_num_of_clusters = 0 try: num_of_clusters = kwargs["num_clusters"] elements_per_cluster = max(1, num_of_nodes / num_of_clu...
Python
nomic_cornstack_python_v1
function set_tacticalRespawnInProgress self oldValue begin debug format string set_tacticalRespawnInProgress: id = {0}, {1}, old value: {2} id tacticalRespawnInProgress oldValue if tacticalRespawnInProgress begin call onTacticalRespawnBegin end else begin call fireCondition FINISHED_FLAG end end function
def set_tacticalRespawnInProgress(self, oldValue): logger.debug('set_tacticalRespawnInProgress: id = {0}, {1}, old value: {2}'.format(self.id, self.tacticalRespawnInProgress, oldValue)) if self.tacticalRespawnInProgress: self.onTacticalRespawnBegin() else: self._tacticalR...
Python
nomic_cornstack_python_v1
import sys from Bio import SeqIO set handle = argv at 1 for seqRec in parse SeqIO handle string fasta begin set DNA = seq end function ReverseComplement DNA begin set result = string for i in range length DNA - 1 - 1 - 1 begin if DNA at i == string A begin set result = result + string T end else if DNA at i == string ...
import sys from Bio import SeqIO handle = sys.argv[1] for seqRec in SeqIO.parse(handle,'fasta'): DNA = seqRec.seq def ReverseComplement(DNA): result = "" for i in range(len(DNA) - 1, -1, -1): if (DNA[i] == "A"): result += "T" elif (DNA[i] == "T"): res...
Python
zaydzuhri_stack_edu_python
function split_all reference sep begin string Splits a given string at a given separator or list of separators. :param reference: The reference to split. :param sep: Separator string or list of separator strings. :return: A list of split strings set parts = call partition_all reference sep return list comprehension p f...
def split_all(reference, sep): """ Splits a given string at a given separator or list of separators. :param reference: The reference to split. :param sep: Separator string or list of separator strings. :return: A list of split strings """ parts = partition_all(reference, sep) return [p ...
Python
jtatman_500k
function numberCovert num begin if num == string - begin return none end else if num at - 1 == string % begin return decimal num at slice : - 1 : / 100 end else if num at - 1 == string B begin return decimal num at slice : - 1 : * 1000000000 end else if num at - 1 == string M begin return decimal num at slice : - 1 ...
def numberCovert(num): if num == '-': return None elif num[-1] == '%': return float(num[:-1]) / 100 elif num[-1] == 'B': return float(num[:-1]) * 1000000000 elif num[-1] == 'M': return float(num[:-1]) * 1000000 elif num[-1] == 'K': return float(num[:-1]) * 100...
Python
nomic_cornstack_python_v1
from time import sleep import sys import pygame as P from word import Word from letter import Letter comment from TypeTest import TypeTest import Globals as G from menuItem import MenuItem from gameMenu import GameMenu call init function typing begin set loop = true set startOver = true set screen = call set_mode tuple...
from time import sleep import sys import pygame as P from word import Word from letter import Letter #from TypeTest import TypeTest import Globals as G from menuItem import MenuItem from gameMenu import GameMenu P.init() def typing(): loop = True startOver = True screen = P.display.set_mode((G.D_WIDTH,G....
Python
zaydzuhri_stack_edu_python
function order_history request pk begin set get_user_sql = string SELECT * FROM auth_user WHERE id = %s set user = call raw get_user_sql list pk at 0 set get_orders_sql = string SELECT * FROM website_order WHERE customerOrder_id = %s AND paymentOrder_id != %s set orders = call raw get_orders_sql list id 1 set order_tot...
def order_history(request, pk): get_user_sql = ''' SELECT * FROM auth_user WHERE id = %s ''' user = User.objects.raw(get_user_sql, [pk])[0] get_orders_sql = ''' SELECT * FROM website_order WHERE customerOrder_id = %s AND paymentOrder_id != %s ''' orders = Order.o...
Python
nomic_cornstack_python_v1
function add self params begin if length params < 2 begin return end set x = reg_dct at params at 0 set y = reg_dct at params at 1 set reg_dct at params at 0 = x + y % 2 ^ 32 end function
def add(self, params): if len(params) < 2: return x = self.reg_dct[params[0]] y = self.reg_dct[params[1]] self.reg_dct[params[0]] = (x + y) % (2** 32)
Python
nomic_cornstack_python_v1
class node begin comment WILL ALWAYS CONTAIN ALL NODES, INCLUDING EMPTY MERGING NODES [NAMEOFNODE->OBJ] set NAME_TO_OBJ = dict comment WILL ALWAYS STORE ROOT OF A NODE [OBJECTS STORED, NOT NAME] set COMPONENTS = list comment NAME -> BINARY_SEQ set NAME_TO_BITS = dict function __init__ self parent left_child name rig...
class node(): NAME_TO_OBJ = {} #WILL ALWAYS CONTAIN ALL NODES, INCLUDING EMPTY MERGING NODES [NAMEOFNODE->OBJ] COMPONENTS = [] #WILL ALWAYS STORE ROOT OF A NODE [OBJECTS STORED, NOT NAME] NAME_TO_BITS = {} #NAME -> BINARY_SEQ def __init__(self, parent, left_child, name, right_child, f): self.par...
Python
zaydzuhri_stack_edu_python
string # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children if children is not None else [] class Solution begin function diameter self root begin string :type root: 'Node' :rtype: int comment for each node, the length of diameter is: comment max(diam...
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children if children is not None else [] """ class Solution: def diameter(self, root: 'Node') -> int: """ :type root: 'Node' :rtype: int """ ...
Python
zaydzuhri_stack_edu_python
function findfib n begin if n == 1 begin return 1 end else if n == 2 begin return 1 end else begin return call findfib n - 1 + call findfib n - 2 end end function function main begin set x = integer input print call findfib x % 10007 end function if __name__ == string __main__ begin call main end string def printfib(n)...
def findfib(n): if n==1: return 1 elif n==2: return 1 else: return findfib(n-1)+findfib(n-2) def main(): x=int(input()) print(findfib(x)%10007) if __name__ == '__main__': main() """def printfib(n): a,b=1,2 for i in range(1,n): print("{0}个fib数是:{1}".format...
Python
zaydzuhri_stack_edu_python
from datetime import date set maioridade = 0 set menoridade = 0 for c in range 1 8 begin set atual = year set nascimento = integer input string Por favor, digite o ano de nascimento da { c } ° pessoa: set idade = atual - nascimento if idade < 21 begin set menoridade = menoridade + 1 end else if idade >= 21 begin set ma...
from datetime import date maioridade = 0 menoridade = 0 for c in range(1, 8): atual = date.today().year nascimento = int(input(f'Por favor, digite o ano de nascimento da {c}° pessoa: ')) idade = atual - nascimento if idade < 21: menoridade += 1 elif idade >= 21: maioridade += 1 print...
Python
zaydzuhri_stack_edu_python
function is_anonymous self begin return get pulumi self string is_anonymous end function
def is_anonymous(self) -> Optional[bool]: return pulumi.get(self, "is_anonymous")
Python
nomic_cornstack_python_v1
comment !/bin/env python string Takes a maf file and returns a fasta Usage: mafToFasta.py <inputMaf> outputFasta import sys class mafAttributes extends object begin function __init__ self mafLine begin set line = split mafLine try begin set type = line at 0 try begin set label = line at 1 end except ValueError begin se...
#!/bin/env python '''Takes a maf file and returns a fasta Usage: mafToFasta.py <inputMaf> outputFasta ''' import sys class mafAttributes(object): def __init__(self,mafLine): line=mafLine.split() try: self.type=line[0] try: self.label=line[1] exc...
Python
zaydzuhri_stack_edu_python
string This file reads in the plays from the 2019-20 NBA season. It then groups the plays based on shot type and team. The 3-point percentage, field goal percentage, and effective field goal percentage of each team is calculated. These statistics are then correlated with wins for each team and whether each team made th...
'''This file reads in the plays from the 2019-20 NBA season. It then groups the plays based on shot type and team. The 3-point percentage, field goal percentage, and effective field goal percentage of each team is calculated. These statistics are then correlated with wins for each team and whether each team made the pl...
Python
zaydzuhri_stack_edu_python
function calMove playerLocation nextLocation begin set move_vector = tuple call subtract nextLocation playerLocation for MOVE in DIRECTION_TO_CALCULATION begin if move_vector == DIRECTION_TO_CALCULATION at MOVE begin return MOVE end end return string Not right end function
def calMove(playerLocation, nextLocation): move_vector = tuple(np.subtract(nextLocation, playerLocation)) for MOVE in DIRECTION_TO_CALCULATION: if move_vector == DIRECTION_TO_CALCULATION[MOVE]: return MOVE return "Not right"
Python
nomic_cornstack_python_v1
function test_questions_category self begin comment call for endpoint to get response and load data set res = get call client string /categories/4/questions set data = loads data set questions = all comment check the status of the response and the message assert equal status_code 200 assert equal data at string success...
def test_questions_category(self): #call for endpoint to get response and load data res = self.client().get('/categories/4/questions') data = json.loads(res.data) # questions=db.session.query(Question).filter(Question.category==4).all() #check the status of the respons...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python string files objects can be created manually, and may also be returned from various calls. files are created manually with the built in open method. set f = open string names.txt comment read content into memory set content = read f comment read 10 bytes into memory set content2 = read f 10 str...
#!/usr/bin/python ''' files objects can be created manually, and may also be returned from various calls. files are created manually with the built in open method. ''' f=open('names.txt') content=f.read() # read content into memory content2=f.read(10) # read 10 bytes into memory ''' invoking read moves an internal...
Python
zaydzuhri_stack_edu_python
function MirgateUserData 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 MirgateUserData(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
import os from collections import defaultdict class TransMatrix extends object begin function __init__ self folder_path number_state begin string :param folder_path: the integrated file generated by info_integrate :param number_state: set trans = call init_trans number_state call build_trans_matrix folder_path end func...
import os from collections import defaultdict class TransMatrix(object): def __init__(self,folder_path,number_state): ''' :param folder_path: the integrated file generated by info_integrate :param number_state: ''' self.trans = self.init_trans(number_state) self.bui...
Python
zaydzuhri_stack_edu_python
function clean_details self id_ begin set details = call send string get_clean_record list id_ set res = list for rec in details begin append res call CleaningDetails rec end return res end function
def clean_details(self, id_: int) -> List[CleaningDetails]: details = self.send("get_clean_record", [id_]) res = list() for rec in details: res.append(CleaningDetails(rec)) return res
Python
nomic_cornstack_python_v1
comment pragma: no cover function pytest_configure begin print string Starting server app start PROC sleep 1 if exitcode is not none begin exit format string Failed to start the server, exit code {} Logs are in logs/server.log exitcode return end call create_generated_client end function
def pytest_configure() -> None: # pragma: no cover print("Starting server app") PROC.start() time.sleep(1) if PROC.exitcode is not None: pytest.exit("Failed to start the server, exit code {}\nLogs are in logs/server.log".format(PROC.exitcode)) return create_generated_client()
Python
nomic_cornstack_python_v1
function test_init self begin try begin call VeilRestPaginator name=string name ordering=string ordering limit=10 offset=5 end except TypeError begin raise call AssertionError end try else begin assert true end try begin call VeilRestPaginator name=123 ordering=string ordering limit=10 offset=5 end except TypeError beg...
def test_init(self): try: VeilRestPaginator(name='name', ordering='ordering', limit=10, offset=5) except TypeError: raise AssertionError() else: assert True try: VeilRestPaginator(name=123, ordering='ordering', limit=10, offset=5) e...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[23]: import numpy as np import cv2 import pandas as pd import os comment In[7]: comment creating skeleton of the Yolov3 using weights and its configration set net = call readNet string G://flicker_dataset//Yoloweights for cloth detection//yolov3-df2_15000.we...
#!/usr/bin/env python # coding: utf-8 # In[23]: import numpy as np import cv2 import pandas as pd import os # In[7]: # creating skeleton of the Yolov3 using weights and its configration net = cv2.dnn.readNet("G://flicker_dataset//Yoloweights for cloth detection//yolov3-df2_15000.weights", "G://flicker_dataset//...
Python
zaydzuhri_stack_edu_python
import collections class Solution extends object begin function containVirus self grid begin string :type grid: List[List[int]] :rtype: int function around r c t=none begin for d in tuple - 1 1 begin for tuple rr cc in tuple tuple r + d c tuple r c + d begin if 0 <= rr < m and 0 <= cc < n and t == none or grid at rr at...
import collections class Solution(object): def containVirus(self, grid): """ :type grid: List[List[int]] :rtype: int """ def around(r,c,t=None): for d in (-1,1): for (rr,cc) in ((r+d,c), (r,c+d)): if 0<=rr<m and 0<=cc<n and (t ...
Python
zaydzuhri_stack_edu_python
function dest_repo_tree dest_repo_no_tree begin set repo = dest_repo_no_tree comment Create and commit a file set fpath = join path working_dir string something.txt with open fpath string w as f begin write f string Mundul vult decipi, ergo decipiatur. end add index list fpath commit index string Dummy commit yield rep...
def dest_repo_tree(dest_repo_no_tree): repo = dest_repo_no_tree # Create and commit a file fpath = os.path.join(repo.working_dir, "something.txt") with open(fpath, "w") as f: f.write("Mundul vult decipi, ergo decipiatur.") repo.index.add([fpath]) repo.index.commit("Dummy commit") y...
Python
nomic_cornstack_python_v1
from tkinter import * from PIL import ImageTk , Image from tkinter import messagebox from tkinter import filedialog function main begin comment just as in flutter, everything is a widget. We begin with the root widget set root = call Tk comment geometry can define the dimensions of the window call geometry string 1000x...
from tkinter import * from PIL import ImageTk, Image from tkinter import messagebox from tkinter import filedialog def main(): # just as in flutter, everything is a widget. We begin with the root widget root = Tk() # geometry can define the dimensions of the window root.geometry("1000x800") # appl...
Python
zaydzuhri_stack_edu_python
from Classes.Voz import Voz from Bot import Bot from Constantes import FuncoesConst as fc from Classes import Navegador set CODIGO_FUNCAO = string --func class Main begin function __init__ self begin set bot = call Bot true set voz = call Voz set retorno = string while true begin set ultimoTermo = retorno set nome = i...
from Classes.Voz import Voz from Bot import Bot from Constantes import FuncoesConst as fc from Classes import Navegador CODIGO_FUNCAO = "--func" class Main: def __init__(self): bot = Bot(True) voz = Voz() retorno = "" while True: ultimoTermo = retorno nome ...
Python
zaydzuhri_stack_edu_python
string 列表的其他操作 set a_list = list 1 2.0 string a true set b_list = list 3 2 9 4 11 comment 列表脚本操作符:可以使用+号组合列表,*号重复列表 print a_list + a_list print a_list * 2 comment 判断元素是否在列表中 print string a in a_list comment 获得列表长度 print string 列表长度:%d % length a_list comment 统计元素在列表中出现的次数,True的值也是1 print string 列表中1出现的次数 %d % count a_l...
""" 列表的其他操作 """ a_list = [1, 2.0, 'a', True] b_list = [3, 2, 9, 4, 11] # 列表脚本操作符:可以使用+号组合列表,*号重复列表 print(a_list + a_list) print(a_list * 2) # 判断元素是否在列表中 print('a' in a_list) # 获得列表长度 print('列表长度:%d' % len(a_list)) # 统计元素在列表中出现的次数,True的值也是1 print('列表中1出现的次数 %d' % a_list.count(1)) # 统计最大值,最小值,列表元素类型需要为数字 print('列表中的...
Python
zaydzuhri_stack_edu_python
class TreeNode begin function __init__ self val begin set val = val set parent = none set left = none set right = none end function function setLeft self l_val begin set leftnode = call TreeNode l_val set left = leftnode if leftnode begin set parent = self end end function function setRight self r_val begin set rightno...
class TreeNode: def __init__(self, val): self.val = val self.parent = None self.left = None self.right = None def setLeft(self, l_val): leftnode = TreeNode(l_val) self.left = leftnode if leftnode: leftnode.parent = self def setRight(self, r_val): rightnode = TreeNode(r_val) self.right = right...
Python
zaydzuhri_stack_edu_python
function loss_characteristic self begin return _loss_characteristic end function
def loss_characteristic(self): return self._loss_characteristic
Python
nomic_cornstack_python_v1
function all_keys_for_usage_flags self begin yield from call all_keys_for_usage_flags yield from call generate_keys_for_usage_flags test_implicit_usage=false end function
def all_keys_for_usage_flags(self) -> Iterator[StorageTestData]: yield from super().all_keys_for_usage_flags() yield from self.generate_keys_for_usage_flags(test_implicit_usage=False)
Python
nomic_cornstack_python_v1
function convert_unix_timestamp_to_datetime_str unix_ts begin set timestamp = call utcfromtimestamp unix_ts return string format time timestamp string %Y-%m-%dT%H:%M:%S.%fZ end function
def convert_unix_timestamp_to_datetime_str(unix_ts): timestamp = datetime.utcfromtimestamp(unix_ts) return timestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
Python
nomic_cornstack_python_v1
function updated_on self begin return _updated_on end function
def updated_on(self): return self._updated_on
Python
nomic_cornstack_python_v1
function print_test begin global ask answer correct ask_modify answer_modify ball true_answer false_answer for i in range 0 length ask begin set n = string i + 1 append ask_modify split ask at i string - append answer_modify split answer at i string - print n + string . + join string ask_modify at i print string print...
def print_test(): global ask, answer, correct, ask_modify, answer_modify, ball, true_answer, false_answer for i in range(0, len(ask)): n = str(i + 1) ask_modify.append(ask[i].split('-')) answer_modify.append(answer[i].split('-')) print(n + '. ' + ' '.join(ask_modify[i])) print('') print('\n'.join(answer_m...
Python
zaydzuhri_stack_edu_python
function Scan client table callback begin function _OnScan retry_cb count result begin for item in items begin if col_names begin set item = dictionary list comprehension tuple k v for tuple k v in items item if k in col_names end call pprint item end if last_key begin call retry_cb last_key count + length items end el...
def Scan(client, table, callback): def _OnScan(retry_cb, count, result): for item in result.items: if options.options.col_names: item = dict([(k, v) for k, v in item.items() if k in options.options.col_names]) pprint.pprint(item) if result.last_key: retry_cb(result.last_key, c...
Python
nomic_cornstack_python_v1
from solve_suiting_words import solve_suited_words function nice_print total_score solution all_results also_print_all_found_words begin print string Total Score: %d % total_score for tuple i tuple score word in enumerate solution start=1 begin print string %d) %s = %d % tuple i word score end if also_print_all_found_w...
from solve_suiting_words import solve_suited_words def nice_print(total_score, solution, all_results, also_print_all_found_words): print('Total Score: %d' % total_score) for i, (score, word) in enumerate(solution, start=1): print('%d) %s = %d' % (i, word, score)) if also_print_all_found_words: ...
Python
zaydzuhri_stack_edu_python
from copy import deepcopy class Cell begin function __init__ self row col begin set row = row set col = col set values = list string 1 string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9 end function function __str__ self begin return string Row: + string row + string |Column: + string col + string ...
from copy import deepcopy class Cell: def __init__(self, row, col): self.row = row self.col = col self.values = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] def __str__(self): return 'Row: ' + str(self.row) + '|Column: ' + str(self.col) + '|Values: ' + str(self.values) clas...
Python
zaydzuhri_stack_edu_python
function test_memoryCheckerFailsPassword self begin return call assertFailure call requestAvatarId badPass UnauthorizedLogin end function
def test_memoryCheckerFailsPassword(self): return self.assertFailure(self.checker.requestAvatarId(self.badPass), error.UnauthorizedLogin)
Python
nomic_cornstack_python_v1
function test_x_list self begin with assert raises TypeError as x_error begin set obj1 = call Square 1 list 1 2 3 4 end assert equal string x must be an integer string exception end function
def test_x_list(self): with self.assertRaises(TypeError) as x_error: obj1 = Square(1, [1, 2, 3, 4]) self.assertEqual('x must be an integer', str(x_error.exception))
Python
nomic_cornstack_python_v1
async function can_run self ctx begin string |coro| Checks if the command can be executed by checking all the predicates inside the :attr:`.checks` attribute. Parameters ----------- ctx: :class:`.Context` The ctx of the command currently being invoked. Raises ------- :class:`CommandError` Any command error that was rai...
async def can_run(self, ctx): """|coro| Checks if the command can be executed by checking all the predicates inside the :attr:`.checks` attribute. Parameters ----------- ctx: :class:`.Context` The ctx of the command currently being invoked. Raises ...
Python
jtatman_500k
function setBaseName self name begin return call setSubItem - 1 name end function
def setBaseName(self, name): return self.setSubItem(-1, name)
Python
nomic_cornstack_python_v1
function destroy self begin remove tree base_location end function
def destroy(self): shutil.rmtree(self.base_location)
Python
nomic_cornstack_python_v1
function jointureTraficLigne rhv_grp_hors_123 affect_finale_cat4 cpt_perm_cat4 begin comment il faut vérifier que pour chaque troncon, les comptages sont bien au nombre de deux, ou concerne une voie unique. pour les autres on multiplie par ddeux la valeur de trafic comment jointure entre les comptage et ligne spour sav...
def jointureTraficLigne(rhv_grp_hors_123,affect_finale_cat4,cpt_perm_cat4): #il faut vérifier que pour chaque troncon, les comptages sont bien au nombre de deux, ou concerne une voie unique. pour les autres on multiplie par ddeux la valeur de trafic #jointure entre les comptage et ligne spour savoir si un co...
Python
nomic_cornstack_python_v1
function _set_releasever cfg log begin set releasever = call get_cfg_option_str cfg string repo_releasever if not releasever begin info string No releasever provided, leaving yum.conf unchanged. return end info string Setting yum releasever to %s releasever set statinfo = call stat YUMCONF with open YUMCONF as conf beg...
def _set_releasever(cfg, log): releasever = util.get_cfg_option_str(cfg, 'repo_releasever') if not releasever: log.info("No releasever provided, leaving yum.conf unchanged.") return log.info('Setting yum releasever to %s', releasever) statinfo = os.stat(YUMCONF) with open(YUMCONF) ...
Python
nomic_cornstack_python_v1
function get self request *args **kwargs begin set province_id = get GET string id none set province = call get_object_or_404 Province id=province_id set cities = filter province=province set serializer = call CitySerializer cities many=true return call Response data status=HTTP_200_OK end function
def get(self, request, *args, **kwargs): province_id = request.GET.get('id', None) province = get_object_or_404(Province, id=province_id) cities = City.objects.filter(province=province) serializer = CitySerializer(cities, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
Python
nomic_cornstack_python_v1
string - Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos Dólares ela pode comprar. Considere: US$1,00 = R$3,27 set real = decimal input string Digite um valor em R$: set us = real / 3.27 print format string Com R${:.2f} voce pode comprar US${:.2f} real us
""" - Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos Dólares ela pode comprar. Considere: US$1,00 = R$3,27 """ real = float(input('Digite um valor em R$: ')) us = real / 3.27 print('Com R${:.2f} voce pode comprar US${:.2f}'.format(real, us))
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Fri Nov 03 23:21:44 2017 @author: jsx 读取指定目录下 的txt(仅有一列)文件,并将其转化为一个数据矩阵, 然后再将之转化为bmp图片,另存在一个新的目录下 import numpy import os from PIL import Image function fileProcess filePath begin set files = list directory filePath for file in files begin if is directory path file begin c...
# -*- coding: utf-8 -*- """ Created on Fri Nov 03 23:21:44 2017 @author: jsx 读取指定目录下 的txt(仅有一列)文件,并将其转化为一个数据矩阵, 然后再将之转化为bmp图片,另存在一个新的目录下 """ import numpy import os from PIL import Image def fileProcess(filePath): files = os.listdir(filePath) for file in files: if os.path.isdir(file): conti...
Python
zaydzuhri_stack_edu_python