code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import unittest import sys append path string .. comment TODO change that to something else from rounds import * class Test_Methods extends TestCase begin comment Testing adding a preference Happy path function test_whenDrinkNameValid_ShouldReturnTheSameName self begin comment Arrange set newRound = round string Christ...
import unittest import sys sys.path.append("..") from rounds import * #TODO change that to something else class Test_Methods(unittest.TestCase): #Testing adding a preference Happy path def test_whenDrinkNameValid_ShouldReturnTheSameName(self): # Arrange newRound = Round("Christos") n...
Python
zaydzuhri_stack_edu_python
from sarki import * print string ********************************************************* Şarkı Programına Hoşgeldiniz... İşlemler; 1. Şarkı Göster 2. Şarkı Sorgula 3. Şarkı Ekle 4. Şarkı Sil Çıkmak için 'q' ya basınız :) ********************************************************* set sarki = call Kitaplık while true be...
from sarki import * print("""********************************************************* Şarkı Programına Hoşgeldiniz... İşlemler; 1. Şarkı Göster 2. Şarkı Sorgula 3. Şarkı Ekle 4. Şarkı Sil Çıkmak için 'q' ya basınız :) *********************************************************""") sarki = Kitaplık() while Tru...
Python
zaydzuhri_stack_edu_python
import math while true begin try begin set number = decimal input string Введите число = end except ValueError begin comment Проверка на правельность ввода данных# print string Повелитель вы ввели неверный символ попробуйте еще раз =) continue end try begin set number1 = decimal input string Введите число = end except ...
import math while True: try: number = float(input('Введите число = ')) except ValueError: print('Повелитель вы ввели неверный символ попробуйте еще раз =)') #Проверка на правельность ввода данных# continue try: number1 = float(input('Введите число = ')) except Value...
Python
zaydzuhri_stack_edu_python
function check_companion_count context min_count=0 begin set json_data = call get_json_data context set path = string result/0/recommendation/companion set companions = call get_value_using_path json_data path assert length companions > integer min_count end function
def check_companion_count(context, min_count=0): json_data = get_json_data(context) path = "result/0/recommendation/companion" companions = get_value_using_path(json_data, path) assert len(companions) > int(min_count)
Python
nomic_cornstack_python_v1
function sum_range start end begin set sum = 0 for i in range start end + 1 begin set sum = sum + i end return sum end function comment Driver Code set start = 2 set end = 5 print call sum_range start end comment Result: 14
def sum_range(start, end): sum = 0 for i in range(start, end+1): sum += i return sum # Driver Code start = 2 end = 5 print(sum_range(start, end)) # Result: 14
Python
flytech_python_25k
function device self **kwargs begin return call api_request call _get_method_fullname string device kwargs end function
def device(self, **kwargs): return self.api_request(self._get_method_fullname("device"), kwargs)
Python
nomic_cornstack_python_v1
function test_handshakeAlive self begin set remainData = call handle_handshake string salive assert equal remainData string assert equal state string challenge assert equal call value string true end function
def test_handshakeAlive(self): remainData = self.proto.handle_handshake("\x00\x06salive") self.assertEqual(remainData, "") self.assertEqual(self.proto.state, "challenge") self.assertEqual(self.transport.value(), "\x00\x04true")
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 01/03/2017 9:55 AM comment @Author : Shuqi.qin comment @File : clusters.py comment @Software: PyCharm Community Edition from math import sqrt from PIL import Image , ImageDraw function readfile filename begin set lines = list comprehension line ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 01/03/2017 9:55 AM # @Author : Shuqi.qin # @File : clusters.py # @Software: PyCharm Community Edition from math import sqrt from PIL import Image, ImageDraw def readfile(filename): lines = [line for line in file(filename)] # First line is the col...
Python
zaydzuhri_stack_edu_python
import sys set input = readline set N = integer input set ans = 0 for n in range 1 N + 1 begin set ans = ans + 1 / n end print ans
import sys input = sys.stdin.readline N = int(input()) ans = 0 for n in range(1, N+1): ans += 1/n print(ans)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import sys from cclib.parser import ccopen import logging function spectra etens etoscs low=0.5 high=10.0 resolution=0.01 smear=0.04 begin string Return arrays of the energies and intensities of a Lorentzian-blurred spectrum set maxSlices = integer high - low / resolution + 1 set peaks = length...
#!/usr/bin/python import sys from cclib.parser import ccopen import logging def spectra(etens, etoscs, low = 0.5, high = 10.0, resolution = 0.01, smear = 0.04): """Return arrays of the energies and intensities of a Lorentzian-blurred spectrum""" maxSlices = int((high - low) / resolution) + 1 peaks = len(...
Python
zaydzuhri_stack_edu_python
function filter_strings lst n begin set filtered_lst = list for string in lst begin if any generator expression is lower char for char in string and any generator expression is upper char for char in string and length string >= n begin append filtered_lst string end end return filtered_lst end function set strings = l...
def filter_strings(lst, n): filtered_lst = [] for string in lst: if any(char.islower() for char in string) and any(char.isupper() for char in string) and len(string) >= n: filtered_lst.append(string) return filtered_lst strings = ["Hello", "WORLD", "Hello World", "123", "Abc123"] filte...
Python
jtatman_500k
import pandas as pd from datetime import datetime from pandas import Series from matplotlib import pyplot import matplotlib.pyplot as plt from math import sqrt import numpy as np comment Extracting data into pandas Dataframes. set inventory_positions = call from_csv string files/InventoryPosition.csv set products = cal...
import pandas as pd from datetime import datetime from pandas import Series from matplotlib import pyplot import matplotlib.pyplot as plt from math import sqrt import numpy as np #Extracting data into pandas Dataframes. inventory_positions = pd.DataFrame.from_csv("files/InventoryPosition.csv") products = pd.DataFrame....
Python
zaydzuhri_stack_edu_python
function attention_requested self message begin pass end function
def attention_requested(self, message): pass
Python
nomic_cornstack_python_v1
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status set CREATE_USER_URL = reverse string user:create set TOKEN_URL = reverse string user:token set ME_URL = reverse string user:me set U...
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status CREATE_USER_URL = reverse('user:create') TOKEN_URL = reverse('user:token') ME_URL = reverse('user:me') USER_MODEL = get_user_mode...
Python
zaydzuhri_stack_edu_python
function resolve_incident_commander_email db_session reporter_email incident_type incident_name incident_title incident_description page_commander begin set commander_service = commander_service set p = call get_active db_session=db_session plugin_type=string oncall comment page for high priority incidents comment we c...
def resolve_incident_commander_email( db_session: SessionLocal, reporter_email: str, incident_type: str, incident_name: str, incident_title: str, incident_description: str, page_commander: bool, ): commander_service = incident_type_service.get_by_name( db_session=db_session, name...
Python
nomic_cornstack_python_v1
for i in range n begin if d % a at i != 0 begin set ans = ans + d // a at i + 1 end else begin set ans = ans + d // a at i end end print ans + x
for i in range(n): if d % a[i] != 0: ans += d // a[i] + 1 else: ans += d // a[i] print(ans+x)
Python
zaydzuhri_stack_edu_python
function create_database self instance **attrs begin set instance = call _get_resource Instance instance return call _create Database instance_id=id keyword attrs end function
def create_database(self, instance, **attrs): instance = self._get_resource(_instance.Instance, instance) return self._create( _database.Database, instance_id=instance.id, **attrs )
Python
nomic_cornstack_python_v1
from typing import List from collections import deque class Solution begin function tribonacci self n begin set init = list 0 1 1 if n < 4 begin return init at n - 1 end set q = deque extend q init set s = 2 while n > 3 begin append q s set s = s + s set s = s - call popleft set n = n - 1 end return s % 2 ^ 31 end func...
from typing import List from collections import deque class Solution: def tribonacci(self, n: int) -> int: init = [0,1,1] if n < 4: return init[n-1] q = deque() q.extend(init) s = 2 while n > 3: q.append(s) s += s s -= ...
Python
zaydzuhri_stack_edu_python
function use_bump self yes=true begin set opts at string bump = yes end function
def use_bump(self, yes=True): self.opts['bump'] = yes
Python
nomic_cornstack_python_v1
function get_combined_model self begin set internal_model = call _check_internal_model call _get_internal_model if is instance internal_model Iterable begin comment This function needs to return a single instance of cuml.Base, comment even if the class is just a composite. raise call ValueError string Expected a single...
def get_combined_model(self): internal_model = self._check_internal_model(self._get_internal_model()) if isinstance(self.internal_model, Iterable): # This function needs to return a single instance of cuml.Base, # even if the class is just a composite. raise ValueEr...
Python
nomic_cornstack_python_v1
comment %load q03_xgboost/build.py comment Default imports from sklearn.model_selection import train_test_split from xgboost import XGBClassifier import pandas as pd from sklearn.metrics import accuracy_score import numpy as np comment load data set dataset = read csv string data/loan_clean_data.csv comment split data ...
# %load q03_xgboost/build.py # Default imports from sklearn.model_selection import train_test_split from xgboost import XGBClassifier import pandas as pd from sklearn.metrics import accuracy_score import numpy as np # load data dataset = pd.read_csv('data/loan_clean_data.csv') # split data into X and y X = dataset.iloc...
Python
zaydzuhri_stack_edu_python
function chiral_tag atom begin return call GetChiralTag end function
def chiral_tag(atom: Atom) -> ChiralType: return atom.GetChiralTag()
Python
nomic_cornstack_python_v1
import tweepy import csv from textblob import TextBlob set consumer_key = string BDMHBweQzZwimb1mN1C05gYsp set consumer_secret = string 4A3ryMWFIKvC2TYomOUppNNvAyZPrJAApLcLdQhAietfPwEEYE set access_token = string 863173256-8oym2WsCQb8V2XWJZp3CPBNfpiVxLrmfjNAjuBBE set access_token_secret = string X3fYTmoRevFv6R6x8OcN7Nd...
import tweepy import csv from textblob import TextBlob consumer_key = 'BDMHBweQzZwimb1mN1C05gYsp' consumer_secret = '4A3ryMWFIKvC2TYomOUppNNvAyZPrJAApLcLdQhAietfPwEEYE' access_token = '863173256-8oym2WsCQb8V2XWJZp3CPBNfpiVxLrmfjNAjuBBE' access_token_secret = 'X3fYTmoRevFv6R6x8OcN7NdNwhpWZ3cEK49doIHIdhVC7' ...
Python
zaydzuhri_stack_edu_python
function runtime_version self begin return get pulumi self string runtime_version end function
def runtime_version(self) -> Optional[str]: return pulumi.get(self, "runtime_version")
Python
nomic_cornstack_python_v1
function create_from_reflections cls params reflections crystal beam detector goniometer=none scan=none profile=none begin from dials.algorithms.profile_model.gaussian_rs.calculator import ProfileModelCalculator , ScanVaryingProfileModelCalculator comment Check the number of spots if not length reflections >= overall b...
def create_from_reflections( cls, params, reflections, crystal, beam, detector, goniometer=None, scan=None, profile=None, ): from dials.algorithms.profile_model.gaussian_rs.calculator import ( ProfileModelCalculator, ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment This node recieves /scan messages from the Lidar on the turtlebot, comment and publishes the minimum overall and individual wedge scans comment (corresponding to the robot's front, front left and right, comment side left and right, and back left and right). comment It computes the w...
#!/usr/bin/env python #This node recieves /scan messages from the Lidar on the turtlebot, #and publishes the minimum overall and individual wedge scans #(corresponding to the robot's front, front left and right, #side left and right, and back left and right). #It computes the wedge scans via python slicing. import ro...
Python
zaydzuhri_stack_edu_python
set nnn = integer input set k = 1 set n = nnn // 10 ^ k % 10 print n
nnn = int(input()) k = 1 n = (nnn // 10 ** k) % 10 print(n)
Python
zaydzuhri_stack_edu_python
function checkio number begin set FiBu = string Fizz Buzz set Fi = string Fizz set Bu = string Buzz if number <= 1000 begin if number % 3 == 0 and number % 5 == 0 begin print string Fizz Buzz return string FiBu end if number % 3 == 0 begin print string Fizz return string Fi end if number % 5 == 0 begin print string Buz...
def checkio(number: int) -> str: FiBu = 'Fizz Buzz' Fi = 'Fizz' Bu = 'Buzz' if number <= 1000: if number%3 == 0 and number%5 == 0: print('Fizz Buzz') return str(FiBu) if number%3 == 0: print('Fizz') return str(Fi) if num...
Python
zaydzuhri_stack_edu_python
function area self begin return _size * _size end function
def area(self): return self._size * self._size
Python
nomic_cornstack_python_v1
function E11 self begin return _E11 end function
def E11(self): return self._E11
Python
nomic_cornstack_python_v1
from Request import Request set request = call Request string NAME:(!продажи or !sales) comment .json() set response = call get_response set a = list for item in json response at string items begin append a string продажи in lower item at string name or string sales in lower item at string name end print status_code
from Request import Request request = Request('NAME:(!продажи or !sales)') response = request.get_response()#.json() a = [] for item in response.json()['items']: a.append('продажи' in item['name'].lower() or 'sales' in item['name'].lower()) print(response.status_code)
Python
zaydzuhri_stack_edu_python
from sklearn.cluster import AgglomerativeClustering , KMeans from sklearn.metrics import silhouette_score from sklearn.decomposition import PCA import pandas as pd import plotly.express as px import plotly.io as pio import tempfile set algs = dict 0 KMeans ; 1 AgglomerativeClustering comment Clustering function cluster...
from sklearn.cluster import AgglomerativeClustering, KMeans from sklearn.metrics import silhouette_score from sklearn.decomposition import PCA import pandas as pd import plotly.express as px import plotly.io as pio import tempfile algs = { 0: KMeans, 1: AgglomerativeClustering } #Clustering d...
Python
zaydzuhri_stack_edu_python
import numpy as np from detection_metrics.ap_accumulator import APAccumulator class MAP begin function __init__ self n_class pr_samples=11 overlap_threshold=0.5 begin string Running computation of average precision of n_class in a bounding box + classification task :param n_class: quantity of class :param pr_samples: q...
import numpy as np from detection_metrics.ap_accumulator import APAccumulator class MAP: def __init__(self, n_class, pr_samples=11, overlap_threshold=0.5): """ Running computation of average precision of n_class in a bounding box + classification task :param n_class: quantity o...
Python
zaydzuhri_stack_edu_python
import gym import math import time import random import numpy as np import pybullet import pybulletgym import pybullet_data import matplotlib.pyplot as plt from dqn_class import DQNAlgoAgent from vanilla_q import VanillaQAlgoAgent from fitted_q import FittedQAlgoAgent from sarsa import SarsaAlgoAgent comment env_var_na...
import gym import math import time import random import numpy as np import pybullet import pybulletgym import pybullet_data import matplotlib.pyplot as plt from dqn_class import DQNAlgoAgent from vanilla_q import VanillaQAlgoAgent from fitted_q import FittedQAlgoAgent from sarsa import SarsaAlgoAgent ...
Python
zaydzuhri_stack_edu_python
from prac_06.guitar import Guitar function main begin set name = string Gibson L-5 CES set year = 1922 set cost = 16035.4 set guitar = call Guitar name year cost print guitar print call get_age print call is_vintage print format string {} get_age() - Expected {}. Got {} name 96 call get_age end function call main
from prac_06.guitar import Guitar def main(): name = "Gibson L-5 CES" year = 1922 cost = 16035.40 guitar = Guitar(name, year, cost) print(guitar) print(guitar.get_age()) print(guitar.is_vintage()) print("{} get_age() - Expected {}. Got {}".format(guitar.name, 96, ...
Python
zaydzuhri_stack_edu_python
set tuple A B X Y = map int split input set P = X - A set Q = Y - B print string R * P + string U * Q + string L * P + string D * Q + string L + string U * Q + 1 + string R * P + 1 + string D + string R + string D * Q + 1 + string L * P + 1 + string U
A, B, X, Y = map(int, input().split()) P = X-A Q = Y-B print("R"*P+"U"*Q+"L"*P+"D"*Q+"L"+"U"*(Q+1)+"R"*(P+1)+"D"+\ "R"+"D"*(Q+1)+"L"*(P+1)+"U")
Python
jtatman_500k
string Useful for converting pydantic models into objects which can only accept json-like data; e.g. a database import logging from datetime import datetime from typing import Optional from fastapi import FastAPI , status from fastapi.encoders import jsonable_encoder from fastapi.logger import logger from pydantic impo...
""" Useful for converting pydantic models into objects which can only accept json-like data; e.g. a database """ import logging from datetime import datetime from typing import Optional from fastapi import FastAPI, status from fastapi.encoders import jsonable_encoder from fastapi.logger import logger from pydantic im...
Python
zaydzuhri_stack_edu_python
from math import trunc set n = decimal input string Digite um valor: set i = call trunc n print format string A parte inteira de {} é {} n i
from math import trunc n = float(input('Digite um valor: ')) i = trunc(n) print('A parte inteira de {} é {}'.format(n, i))
Python
zaydzuhri_stack_edu_python
function upload self file_name file_bytes file_type codetype begin set post_data = dict string username user_name ; string password pass_word ; string codetype codetype ; string appid appid ; string appkey appkey ; string timeout 60 ; string method string upload set files = dict string file tuple file_name file_bytes f...
def upload(self, file_name, file_bytes, file_type, codetype): post_data = { "username": self.user_name, "password": self.pass_word, "codetype": codetype, "appid": self.appid, "appkey": self.appkey, "timeout": 60, "method": "uplo...
Python
nomic_cornstack_python_v1
function sum self dim=none skipna=none min_count=none keep_attrs=none **kwargs begin return reduce sum dim=dim skipna=skipna min_count=min_count numeric_only=true keep_attrs=keep_attrs keyword kwargs end function
def sum( self, dim: Dims = None, *, skipna: bool | None = None, min_count: int | None = None, keep_attrs: bool | None = None, **kwargs: Any, ) -> Dataset: return self.reduce( duck_array_ops.sum, dim=dim, skipna=skipn...
Python
nomic_cornstack_python_v1
function write self msg begin write stream string %s % msg end function
def write(self, msg): self.stream.write("%s\0" % msg)
Python
nomic_cornstack_python_v1
function crossoverFunc parents size bits begin set children = zeros size call dtype string a6 for i in range 0 integer size / 2 begin set x_site = random integer 0 bits - 1 set x1 = parents at i set x2 = parents at size - i - 1 comment Crossover Probability = 60 percent if random integer 0 100 > 40 begin set ch1 = x1 a...
def crossoverFunc(parents, size, bits): children = np.zeros((size), np.dtype('a6')) for i in range(0, int(size/2)): x_site = np.random.randint(0, bits - 1) x1 = parents[i] x2 = parents[size - i - 1] if (np.random.randint(0, 100)) > 40 : # Crossover Probability = 60 percent ch1 = x1[0:x_site] + x2[x_site:b...
Python
nomic_cornstack_python_v1
function approved_repr id begin if id is none begin set repr_text = APPROVAL_PENDING end else if id == 0 begin set repr_text = APPROVED end else begin set row = get users id none if row begin set repr_text = t dist string Approved by %(first_name)s.%(last_name)s % dictionary first_name=row at string first_name at 0 las...
def approved_repr(id): if id is None: repr_text = APPROVAL_PENDING elif id == 0: repr_text = APPROVED else: row = users.get(id, None) if row: repr_text = T("Approved by %(first_name)s.%(last_name)s") % \ dict(fi...
Python
nomic_cornstack_python_v1
string Task : 0033_Looblike Author : Phumipat C. [MAGCARI] Language: Python Created : 30 May 2021 [11:58] Algo : Status : Finished set N = integer input set num = list comprehension integer x for x in split input set mapp = dictionary for x in num begin if x in mapp begin set mapp at x = mapp at x + 1 end else begin se...
""" Task : 0033_Looblike Author : Phumipat C. [MAGCARI] Language: Python Created : 30 May 2021 [11:58] Algo : Status : Finished """ N = int(input()) num = [int(x) for x in input().split()] mapp = dict() for x in num: if x in mapp: mapp[x]+=1 else: mapp[x] = 1 maxx = max([x for x in mapp.values()]) for x in s...
Python
zaydzuhri_stack_edu_python
function forward self users k=5 begin return call top_k_items_for_users users k end function
def forward(self, users, k = 5): return self.top_k_items_for_users(users, k)
Python
nomic_cornstack_python_v1
function __eq__ self other begin if not is instance other Dihedral begin raise call TypeError other string is not a Dihedral Group end return rot == rot and refl == refl end function
def __eq__(self, other): if not isinstance(other, Dihedral): raise TypeError(other, "is not a Dihedral Group") return self.rot==other.rot and self.refl==other.refl
Python
nomic_cornstack_python_v1
function pipupdate begin string Update all currently installed pip packages set packages = list comprehension d for d in working_set call string pip install --upgrade + join string packages end function
def pipupdate(): """ Update all currently installed pip packages """ packages = [d for d in pkg_resources.working_set] subprocess.call('pip install --upgrade ' + ' '.join(packages))
Python
jtatman_500k
function post self request *args **kwargs begin set form = call get_form if call is_valid begin return call form_valid form end else begin return call form_invalid form end end function
def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form)
Python
nomic_cornstack_python_v1
import os function find_files suffix path begin if not suffix or not path begin return end if path at slice - 2 : : == suffix begin print string path matched: path end else if is directory path path begin for file in list directory path begin call find_files suffix join path path file end end end function comment Tes...
import os def find_files(suffix, path): if not suffix or not path: return if path[-2:] == suffix: print("path matched: ", path) else: if os.path.isdir(path): for file in os.listdir(path): find_files(suffix, os.path.join(path, file)) # Tests print("Te...
Python
zaydzuhri_stack_edu_python
function add_peer self peerAddr networks=none begin if _debug begin call _debug string add_peer %r networks=%r peerAddr networks end comment see if this is already a peer if peerAddr in peers begin comment add the (new?) reachable networks if not networks begin set networks = list end else begin extend peers at peerAd...
def add_peer(self, peerAddr, networks=None): if _debug: BTR._debug("add_peer %r networks=%r", peerAddr, networks) # see if this is already a peer if peerAddr in self.peers: # add the (new?) reachable networks if not networks: networks = [] els...
Python
nomic_cornstack_python_v1
import random set high_score = none function start_game high_score begin print string Welcome to the NUMBER GUESSING GAME! set num = random integer 1 10 set count = 1 while num begin try begin set prompt = integer input string Enter a number between 1 and 10: if prompt > 10 or prompt < 1 begin print string Number must ...
import random high_score = None def start_game(high_score): print("Welcome to the NUMBER GUESSING GAME!") num = random.randint(1,10) count = 1 while num: try: prompt = int(input("Enter a number between 1 and 10: ")) if prompt > 10 or prompt < 1: print("Num...
Python
zaydzuhri_stack_edu_python
comment Sol 1 set arr = list for i in range 10 begin set n = integer input % 42 if n not in arr begin append arr n end end print length arr comment Sol 2 set arr = list for i in range 10 begin append arr integer input % 42 end print length set arr comment Sol 3 print length set comprehension integer input % 42 for i ...
# Sol 1 arr = [] for i in range(10): n = int(input()) % 42 if n not in arr: arr.append(n) print(len(arr)) # Sol 2 arr = [] for i in range(10): arr.append(int(input()) % 42) print(len(set(arr))) # Sol 3 print(len({int(input()) % 42 for i in range(10)}))
Python
zaydzuhri_stack_edu_python
function plot_distribution self begin comment Check to make sure that simulation has run previously. if not is instance simulated_return DataFrame begin call calc_cumulative_return end comment Use the `plot` function to create a probability distribution histogram of simulated ending prices comment with markings for a 9...
def plot_distribution(self): # Check to make sure that simulation has run previously. if not isinstance(self.simulated_return,pd.DataFrame): self.calc_cumulative_return() # Use the `plot` function to create a probability distribution histogram of simulated ending p...
Python
nomic_cornstack_python_v1
set tuple x y = map float split input set size = input set n = integer size set pd = x / y set prob_1st_defective = 1 - pd ^ 4 * pd print format string {:.3f} prob_1st_defective
x, y = map(float, input().split()) size = input() n = int(size) pd = x/y prob_1st_defective = (1-pd)**4 * pd print("{:.3f}".format(prob_1st_defective))
Python
zaydzuhri_stack_edu_python
function test_new_file_read_ok self begin comment File read is OK if version is new enough, or version cannot be parsed comment because it is non-int or has too many elements for ver in tuple string 1.3.2 string 1.3 string 0.0.4.3 string 0.0a begin set cif = string loop_ _audit_conform.dict_name _audit_conform.dict_ver...
def test_new_file_read_ok(self): # File read is OK if version is new enough, or version cannot be parsed # because it is non-int or has too many elements for ver in ('1.3.2', '1.3', '0.0.4.3', '0.0a'): cif = """ loop_ _audit_conform.dict_name _audit_conform.dict_version mmcif_pdbx.di...
Python
nomic_cornstack_python_v1
function first_level_from_bids bids_layout task_name process_name space_name=string MNI152NLin2009cAsym subjects=string all sessions=string all bold_suffix=string bold modulation_suffix=string modulation confound_suffix=string regressors img_filters=none t_r=none slice_time_ref=0.0 hrf_model=string glover drift_model=s...
def first_level_from_bids(bids_layout, task_name, process_name, space_name="MNI152NLin2009cAsym", subjects='all',sessions='all',bold_suffix="bold", modulation_suffix="modulation", confound_suffix="regressors", ...
Python
nomic_cornstack_python_v1
function create_labeled_pair img gt_center prop_center gt_radius scale begin set permitted_scales = list 32 64 128 256 if scale not in permitted_scales begin set msg = string scale { scale } not permitted. Please use one of: set msg = msg + string permitted_scales raise exception msg end set scale_factor = scale // 32 ...
def create_labeled_pair(img, gt_center, prop_center, gt_radius, scale): permitted_scales = [32, 64, 128, 256] if scale not in permitted_scales: msg = f"scale {scale} not permitted. Please use one of: " msg += str(permitted_scales) raise Exception(msg) scale_factor = scale//32 x_o...
Python
nomic_cornstack_python_v1
from decimal import Decimal from typing import Union function coerce_decimal x begin if type x is float begin set x = call Decimal x end return x end function
from decimal import Decimal from typing import Union def coerce_decimal(x: Union[float, Decimal]) -> Decimal: if type(x) is float: x = Decimal(x) return x
Python
zaydzuhri_stack_edu_python
function copy self other recursive=false ignore=none followlinks=true begin string copy: copy self to other @type other: URI @param other: the path to copy itself over. What will really happen depends on the backend. Note that file properties are only copied when self and other are located in the same backend, i.e. it ...
def copy(self, other, recursive=False, ignore=None, followlinks=True): """ copy: copy self to other @type other: URI @param other: the path to copy itself over. What will really happen depends on the backend. Note that file properties are only copied when ...
Python
jtatman_500k
function draw self begin for chunk in values chunks begin call draw end end function
def draw(self): for chunk in self.chunks.values(): chunk.draw()
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python string ======================= ANSI Screen Rendition ======================= Library to help you use ANSI graphics on text terminals, featuring cursor movement and color support. Usage ===== Clear screen:: >>> from ansi import clear >>> clear() Move cursor: >>> from ansi import cursor >>> ...
#! /usr/bin/env python ''' ======================= ANSI Screen Rendition ======================= Library to help you use ANSI graphics on text terminals, featuring cursor movement and color support. Usage ===== Clear screen:: >>> from ansi import clear >>> clear() Move cursor: >>> from ansi import...
Python
zaydzuhri_stack_edu_python
import pymongo comment Open connection set client = call MongoClient string mongodb://localhost:27017/ set db = client at string mydatabase comment Update document call update_one dict string name string John Doe dict string $set dict string age 28 comment Close connection close client
import pymongo # Open connection client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["mydatabase"] # Update document db.collection.update_one( {"name": "John Doe"}, {"$set": {"age": 28}} ) # Close connection client.close()
Python
jtatman_500k
function key_vault_key_id self begin return get pulumi self string key_vault_key_id end function
def key_vault_key_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "key_vault_key_id")
Python
nomic_cornstack_python_v1
from google.cloud import storage import logging import os import asyncio import json import feedparser from deepgram import Deepgram info string Starting podcast transcriber comment Keys for required environment variables; should match keys in .env.yaml. set ENV_TARGET_FEED_URL = string TARGET_FEED_URL set ENV_TRANSCRI...
from google.cloud import storage import logging import os import asyncio import json import feedparser from deepgram import Deepgram logging.info("Starting podcast transcriber") # Keys for required environment variables; should match keys in .env.yaml. ENV_TARGET_FEED_URL = 'TARGET_FEED_URL' ENV_TRANSCRIPTIONS_BUCKE...
Python
zaydzuhri_stack_edu_python
function attributes_for_template self begin set fields = call order_by string display_order if not fields begin return list end if not attributes begin warn string %s has fields in its schema, but no attributes! % self end comment Hopefully we can cope with an empty dict. comment return [] return list comprehension ca...
def attributes_for_template(self): fields = SchemaField.objects.filter(schema__id=self.schema_id).select_related().order_by('display_order') if not fields: return [] if not self.attributes: logger.warn("%s has fields in its schema, but no attributes!" % self) ...
Python
nomic_cornstack_python_v1
import pandas as pd set movies = read csv string movies.csv set scifi_movies = read csv string scifi_movies set action_movies = read csv string action_movies
import pandas as pd movies = pd.read_csv('movies.csv') scifi_movies = pd.read_csv('scifi_movies') action_movies = pd.read_csv('action_movies')
Python
zaydzuhri_stack_edu_python
async function async_post_request url data begin info string Fetching { url } with data { data } return await call run_in_executor executor post url data end function
async def async_post_request(url, data): logging.info(f"Fetching {url} with data {data}") return await event_loop.run_in_executor(executor, requests.post, url, data)
Python
nomic_cornstack_python_v1
function destroy self begin if popIval begin call pause set popIval = none end if downIval begin call pause set downIval = none end call removeNode pass end function
def destroy(self): if self.popIval: self.popIval.pause() self.popIval = None if self.downIval: self.downIval.pause() self.downIval = None self.removeNode() pass
Python
nomic_cornstack_python_v1
function mouseDragged self point delta begin pass end function
def mouseDragged(self, point, delta): pass
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Mon May 7 14:58:05 2018 @author: mlgkschm import csv from math import sqrt from warnings import warn comment Q: How do you guarrantee the state names are not misspelled? comment A: Use this dict to check harvester state names for validity set st = dict string off string o...
# -*- coding: utf-8 -*- """ Created on Mon May 7 14:58:05 2018 @author: mlgkschm """ import csv from math import sqrt from warnings import warn # Q: How do you guarrantee the state names are not misspelled? # A: Use this dict to check harvester state names for validity st = {'off': 'off', 'cold': 'cold...
Python
zaydzuhri_stack_edu_python
import sys set input = readline function main begin set i = integer input set j = integer input print if expression i % j == 0 then 0 else j - i % j end function if __name__ == string __main__ begin call main end
import sys input = sys.stdin.readline def main(): i = int(input()) j = int(input()) print(0 if i % j == 0 else j - i % j) if __name__ == "__main__": main()
Python
zaydzuhri_stack_edu_python
function append self serie timestamp data begin if count serie > maxItems - 1 begin for r in range count serie - maxItems + 1 begin remove serie call boxSets at 0 end end set quantiles = call quantile data list 0 0.25 0.5 0.75 1 * coefficient set boxSet = call QBoxSet *quantiles string { tm_sec } . { integer timestamp ...
def append(self, serie, timestamp, data): if serie.count() > self.maxItems - 1: for r in range(serie.count() - self.maxItems + 1): serie.remove(serie.boxSets()[0]) quantiles = np.quantile(data, [0, 0.25, 0.5, 0.75, 1]) * self.coefficient boxSet = QtCharts.QBoxSet( ...
Python
nomic_cornstack_python_v1
string array = [1,2,4,5,1] Find min difference of left and right sum of the array e.g. LS - RS 1 - 12 => 11 3 - 10 => 7 7 - 6 => 1 12 - 1 => 11 function min_diff sum index arr begin try begin print sum if length arr > 1 begin comment if index > 0: set divider = length arr // index set left = call min_diff sum + arr at ...
''' array = [1,2,4,5,1] Find min difference of left and right sum of the array e.g. LS - RS 1 - 12 => 11 3 - 10 => 7 7 - 6 => 1 12 - 1 => 11 ''' def min_diff(sum, index, arr): try: print(sum) if len(arr) > 1: #if index > 0: divider = len(arr) // index lef...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment ![](https://www.aquare.la/wp-content/uploads/unimed-bh.png) comment In[ ]: comment visualização de dados import matplotlib.pyplot as plt comment visualização de dados import seaborn as sns set color_codes=true comment linear algebra import numpy as np comment d...
#!/usr/bin/env python # coding: utf-8 # ![](https://www.aquare.la/wp-content/uploads/unimed-bh.png) # In[ ]: import matplotlib.pyplot as plt # visualização de dados import seaborn as sns # visualização de dados sns.set(color_codes=True) import numpy as np # linear algebra import pandas as pd # data processing, CSV...
Python
zaydzuhri_stack_edu_python
function db_for_write self model **hints begin if app_label == string auditoria begin return string logs end return none end function
def db_for_write(self, model, **hints): if model._meta.app_label == 'auditoria': return 'logs' return None
Python
nomic_cornstack_python_v1
function version self begin set data = string none yet if STARTED begin set data = get about string Version or get about string Installed Version or string DEMO set data = replace data string _ string . end return data end function
def version(self) -> str: data = "none yet" if self.STARTED: data = ( self.about.get("Version") or self.about.get("Installed Version") or "DEMO" ) data = data.replace("_", ".") return data
Python
nomic_cornstack_python_v1
function xdivy x y begin return call xdivy x y end function
def xdivy(x, y): return F.xdivy(x, y)
Python
nomic_cornstack_python_v1
function save self begin set updated_at = today save end function
def save(self): self.updated_at = datetime.today() models.storage.save()
Python
nomic_cornstack_python_v1
if opcao == 1 begin print string Você escolheu Coca-Cola end else if opcao == 2 begin print string Você escolheu Pepsi end else if opcao == 3 begin print string Você escolheu Guaraná end else if opcao == 4 begin print string Você escolheu Chá end else begin print string Opção inválida end
if opcao == 1: print('Você escolheu Coca-Cola') elif opcao == 2: print('Você escolheu Pepsi') elif opcao == 3: print('Você escolheu Guaraná') elif opcao == 4: print('Você escolheu Chá') else: print('Opção inválida')
Python
zaydzuhri_stack_edu_python
import nltk function get_synonyms sentence begin set output = list set words = call word_tokenize sentence for word in words begin set synonyms = list for syn in call synsets word begin for l in call lemmas begin append synonyms call name end end append output list set synonyms end end function
import nltk def get_synonyms(sentence): output = [] words = nltk.word_tokenize(sentence) for word in words: synonyms = [] for syn in wordnet.synsets(word): for l in syn.lemmas(): synonyms.append(l.name()) output.append(list(set(synonyms)))
Python
jtatman_500k
for s in seq begin set comp_seq = comp_seq + comp_data at s end print seq print comp_seq for i in range length seq begin set s = seq at i set cs = comp_seq at i set bond = string ≡ if s == string A or s == string T begin set bond = string = end print string { s } { bond } { cs } end
for s in seq: comp_seq+=comp_data[s] print(seq) print(comp_seq) for i in range(len(seq)): s=seq[i] cs=comp_seq[i] bond="≡" if s == "A" or s == "T": bond="=" print(f"{s}{bond}{cs}")
Python
zaydzuhri_stack_edu_python
function test_get_items_workspaces_get self begin pass end function
def test_get_items_workspaces_get(self): pass
Python
nomic_cornstack_python_v1
class ReachaNumber extends object begin comment 下面来说第二个 trick,这个是解题的关键,比如说目标值是4,那么如果我们一直累加步数, comment 直到其正好大于等于target时,有: comment 0 + 1 = 1 comment 1 + 2 = 3 comment 3 + 3 = 6 comment 第三步加上3,得到了6,超过了目标值4,超过了的距离为2,是偶数,那么实际上我们只要将加上距 comment 离为1的时候,不加1,而是加 -1,那么此时累加和就损失了2,那么正好能到目标值4,如下: comment 0 - 1 = -1 comment -1 + 2 =...
class ReachaNumber(object): # 下面来说第二个 trick,这个是解题的关键,比如说目标值是4,那么如果我们一直累加步数, # 直到其正好大于等于target时,有: # 0 + 1 = 1 # 1 + 2 = 3 # 3 + 3 = 6 # 第三步加上3,得到了6,超过了目标值4,超过了的距离为2,是偶数,那么实际上我们只要将加上距 # 离为1的时候,不加1,而是加 -1,那么此时累加和就损失了2,那么正好能到目标值4,如下: # 0 - 1 = -1 # -1 + 2 = 1 # 1 + 3 = 4 # 那么,我们...
Python
zaydzuhri_stack_edu_python
import sys import string if __name__ == string __main__ begin set mapping = dict set refInputString = string ejp mysljylc kd kxveddknmc re jsicpdrysi + string rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd + string de kr kd eoya kw aej tysr re ujdr lkgc jv set refOutputString = string our language is impossible to under...
import sys import string if __name__=='__main__': mapping = {} refInputString = "ejp mysljylc kd kxveddknmc re jsicpdrysi" + \ "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd" + \ "de kr kd eoya kw aej tysr re ujdr lkgc jv" refOutputString = "our language is impossible to understand" +\ ...
Python
zaydzuhri_stack_edu_python
function _NeedToReturnReferenceDiagnoser msg begin set regex = string In member function \'testing::internal::ReturnAction<R>.*\n(?P<file>.*):(?P<line>\d+):\s+instantiated from here\n.*gmock-actions\.h.*error: creating array with negative size set diagnosis = string %(file)s:%(line)s: You are using an Return() action i...
def _NeedToReturnReferenceDiagnoser(msg): regex = (r'In member function \'testing::internal::ReturnAction<R>.*\n' r'(?P<file>.*):(?P<line>\d+):\s+instantiated from here\n' r'.*gmock-actions\.h.*error: creating array with negative size') diagnosis = """%(file)s:%(line)s: You are using an Retur...
Python
nomic_cornstack_python_v1
function update self begin pass end function
def update(self): pass
Python
nomic_cornstack_python_v1
import tkinter as tk from tkinter import ttk import easygui import pandas as pd from time import strftime , sleep import visualizer import helper comment text set rtx3080text = string Running RTX 3080 Ebay Prices Visualizer! comment tkinter intialization and config set window = call Tk title window string Average Ebay ...
import tkinter as tk from tkinter import ttk import easygui import pandas as pd from time import strftime, sleep import visualizer import helper # text rtx3080text = "Running RTX 3080 Ebay Prices Visualizer!" # tkinter intialization and config window = tk.Tk() window.title("Average Ebay Prices") # window.geometry("6...
Python
zaydzuhri_stack_edu_python
function my_function n1 n2 begin if length n1 > length n2 begin print n1 end else if length n1 == length n2 begin print n1 n2 end end function set a = input string enter a text set b = input string enter a text call my_function a b
def my_function(n1,n2): if len(n1)>len(n2): print(n1) elif len(n1)==len(n2): print(n1,n2) a=input("enter a text") b=input("enter a text") my_function(a,b)
Python
zaydzuhri_stack_edu_python
function overwrite_forward_crossattention self begin for mod in block begin set attn = EncDecAttention set forward = call MethodType cross_attention_forward attn end end function
def overwrite_forward_crossattention(self): for mod in self.decoder.block: attn = mod.layer[1].EncDecAttention attn.forward = types.MethodType(cross_attention_forward, attn)
Python
nomic_cornstack_python_v1
function isAirx x y begin if call getBlock x y zp == 0 begin return true end else begin return false end end function
def isAirx(x, y): if mc.getBlock(x, y, zp) == 0: return True else: return False
Python
nomic_cornstack_python_v1
function format_angles *args begin set result = list for arg in args begin comment separate the sign and the magnitude set arg_value = absolute arg set arg_sign = arg / arg_value debug string format_angles: arg sign is %+d arg_sign debug string format_angles: arg value is %f arg_value comment get the integer degrees o...
def format_angles(*args): result = [] for arg in args: # separate the sign and the magnitude arg_value = abs(arg) arg_sign = arg/arg_value logger.debug("format_angles: arg sign is %+d", arg_sign) logger.debug("format_angles: arg value is %f", arg_value) # get the integer degrees or hours ...
Python
nomic_cornstack_python_v1
function _close self fd begin string Removes a file descriptor from the file descriptor list :rtype: int :param fd: the file descriptor to close. :return: C{0} on success. try begin close files at fd comment Keep track for SymbolicFile testcase generation append _closed_files files at fd set files at fd = none end exce...
def _close(self, fd): """ Removes a file descriptor from the file descriptor list :rtype: int :param fd: the file descriptor to close. :return: C{0} on success. """ try: self.files[fd].close() self._closed_files.append(self.files[fd]) # Ke...
Python
jtatman_500k
function get_inverted_index self begin return _inverted_index_cache end function
def get_inverted_index(self): return self._inverted_index_cache
Python
nomic_cornstack_python_v1
function build_footPivots self begin set mi_footModule = false set mi_ball = false set mi_ankle = false end function comment Find our foot comment ============================================================================
def build_footPivots(self): mi_footModule = False mi_ball = False mi_ankle = False #Find our foot #============================================================================
Python
nomic_cornstack_python_v1
function find_stop_near place_name begin return call get_nearest_station call get_lat_long place_name at 0 call get_lat_long place_name at 1 end function
def find_stop_near(place_name): return get_nearest_station(get_lat_long(place_name)[0],get_lat_long(place_name)[1])
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python2 comment -*- coding: utf-8 -*- string Created on Mon Feb 11 00:09:03 2019 @author: dweckler from tkinter import Tk , Label , Button , Entry , mainloop , filedialog , messagebox , Grid , Checkbutton , IntVar , END import os comment import tkSimpleDialog as simpledialog import matplotlib call...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Feb 11 00:09:03 2019 @author: dweckler """ from tkinter import Tk, Label, Button, Entry, mainloop, filedialog, messagebox, Grid, Checkbutton, IntVar, END import os #import tkSimpleDialog as simpledialog import matplotlib matplotlib.use('qt5agg') from ...
Python
zaydzuhri_stack_edu_python
function on_actionBon_de_Livaison_triggered self begin set bon_livraison = call Bon_Livraison engine show end function
def on_actionBon_de_Livaison_triggered(self): self.bon_livraison = Bon_Livraison(self.engine) self.bon_livraison.show()
Python
nomic_cornstack_python_v1
import pandas as pd from Constants.constants import PORTFOLIO_FILE_NAME class Data_Reader begin function read_excel path=string begin try begin set df = call read_excel path + PORTFOLIO_FILE_NAME + string .xlsx end except Exception as e begin print string Failed to read excel file print e return none end return df end ...
import pandas as pd from ..Constants.constants import PORTFOLIO_FILE_NAME class Data_Reader: def read_excel(path: str="") -> pd.DataFrame: try: df = pd.read_excel(path + PORTFOLIO_FILE_NAME + ".xlsx") except Exception as e: print("Failed to read excel file") ...
Python
zaydzuhri_stack_edu_python
function bonus GPA begin set bonus = 500000 set total = GPA * bonus return total end function set listGPA = list 3 2.7 2.5 4 for GPA in listGPA begin if GPA > 3 begin print string Selamat Anda Mendapatkan Bonus call bonus GPA end else begin print string Mohon Maaf, Anda Tidak Mendapatkan Bonus end end
def bonus(GPA): bonus = 500000 total = GPA*bonus return total listGPA = [3, 2.7, 2.5, 4] for GPA in listGPA: if GPA > 3: print("Selamat Anda Mendapatkan Bonus", bonus(GPA)) else: print("Mohon Maaf, Anda Tidak Mendapatkan Bonus")
Python
zaydzuhri_stack_edu_python
import pygame from pygame.locals import * import random import os set environ at string SDL_VIDEO_WINDOW_POS = string 0,0 import sys from threading import Thread comment car_thread=Thread(target=functionname,args=(arguments,)) comment car_thread.start() comment window=pygame.display.set_mode((858,624),RESIZABLE|HWSURFA...
import pygame from pygame.locals import * import random import os os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0" import sys from threading import Thread #car_thread=Thread(target=functionname,args=(arguments,)) #car_thread.start() #window=pygame.display.set_mode((858,624),RESIZABLE|HWSURFACE|DOUBLEBUF) window=pygame.displ...
Python
zaydzuhri_stack_edu_python