code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function decrypt_vigenere ciphertext keyword begin set plaintext = string set new_keyword = string for i in range length ciphertext begin set num_word = ordinal ciphertext at i while length ciphertext > length new_keyword begin set new_keyword = new_keyword + keyword end set num_key = ordinal new_keyword at i if num_...
def decrypt_vigenere(ciphertext, keyword): plaintext = '' new_keyword = '' for i in range(len(ciphertext)): num_word = ord(ciphertext[i]) while len(ciphertext) > len(new_keyword): new_keyword += keyword num_key = ord(new_keyword[i]) if num_key <= 90: n...
Python
nomic_cornstack_python_v1
function read_data filename index epochs loss seconds begin with open filename as f begin for line in f begin if string images in line begin set words = split line set idx = integer words at 0 at slice : - 1 : if idx > index begin append seconds decimal words at 6 append loss decimal words at 2 append epochs idx end e...
def read_data(filename,index,epochs,loss,seconds): with open(filename) as f: for line in f: if 'images' in line: words = line.split() idx = int(words[0][:-1]) if idx> index: seconds.append(float(words[6])) lo...
Python
zaydzuhri_stack_edu_python
comment 3. Reading in to Pandas ## import pandas as pd set loans_2007 = read csv string loans_2007.csv print length columns head loans_2007 comment 5. First group of columns ## drop loans_2007 list string id string member_id string funded_amnt string funded_amnt_inv string grade string sub_grade string emp_title string...
## 3. Reading in to Pandas ## import pandas as pd loans_2007 = pd.read_csv('loans_2007.csv') print(len(loans_2007.columns)) loans_2007.head() ## 5. First group of columns ## loans_2007.drop(['id', 'member_id', 'funded_amnt', 'funded_amnt_inv', 'grade', 'sub_grade', 'emp_title', 'issue_d'], axis=1,...
Python
zaydzuhri_stack_edu_python
function merge_communities_qds adj c begin comment Array of unique community labels set unique_clusters = unique c comment Tracks the nodes in each community set dict_bool = dict comment Tracks the clusters that are connected to each community set dict_connected = dict for label in unique_clusters begin comment Track...
def merge_communities_qds(adj, c): # Array of unique community labels unique_clusters = np.unique(c) # Tracks the nodes in each community dict_bool = {} # Tracks the clusters that are connected to each community dict_connected = {} for label in unique_clusters: # Track the nodes ...
Python
nomic_cornstack_python_v1
function extract_timeperiod request begin set data = keys data if string start_date in data and string end_date in data begin set start_date = string parse time data at string start_date date_format set end_date = string parse time data at string end_date date_format end else if string start_date in data begin set star...
def extract_timeperiod(request): data = request.data.keys() if 'start_date' in data and 'end_date' in data: start_date = datetime.strptime(request.data['start_date'], date_format) end_date = datetime.strptime(request.data['end_date'], date_format) elif 'start_date' in data: start_da...
Python
nomic_cornstack_python_v1
function nmonths_features sales_df col_name num_months quantiles begin assert num_months >= 1 set columns = list string sum string min string max + list comprehension format string {}_q q for q in quantiles set columns = list comprehension format string {}_{}M_{} col_name num_months c for c in columns comment For fast ...
def nmonths_features(sales_df, col_name, num_months, quantiles): assert num_months >= 1 columns = ['sum', 'min', 'max'] + ['{}_q'.format(q) for q in quantiles] columns = ['{}_{}M_{}'.format(col_name, num_months, c) for c in columns] # For fast processing values = sales_df[col_name].values indic...
Python
nomic_cornstack_python_v1
function milp montecarlo_country decimals=1 begin import pulp import numpy as np comment End Ranking Forecast After Regular Season set model = call LpProblem string LpMinimize set variable_names = list set lowBound_dict = dictionary set upBound_dict = dictionary set teams = sorted list keys montecarlo_country set pos...
def milp(montecarlo_country,decimals = 1): import pulp import numpy as np # End Ranking Forecast After Regular Season model = pulp.LpProblem("", pulp.LpMinimize) variable_names = [] lowBound_dict = dict() upBound_dict = dict() teams = sorted(list(montecarlo_country.keys())) ...
Python
zaydzuhri_stack_edu_python
comment coding = utf-8 comment Author:XiaoFei comment Date:2021/3/10 16:20 print string 陈志霏 print string 春眠不觉晓, 处处闻啼鸟, 夜来风雨声, 花落知多少。 print string 春眠不觉晓,处处闻啼鸟,夜来风雨声,花落知多少。 set name = input string 请输入你的用户: set pwd = input string 请输入你的用户: print name + string 用户欢迎登录 set a = decimal input string 请输入第一个数字: set b = decimal in...
# coding = utf-8 # Author:XiaoFei # Date:2021/3/10 16:20 print("陈志霏") print('''春眠不觉晓, 处处闻啼鸟, 夜来风雨声, 花落知多少。''') print("春眠不觉晓,处处闻啼鸟,夜来风雨声,花落知多少。") name=input("请输入你的用户:") pwd=input("请输入你的用户:") print(name+"用户欢迎登录") a=float(input("请输入第一个数字:")) b=float(input("请输入第二个数字:")) print(a,"+",b,"=",a+b)
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np comment load img set img = call imread string Resources/trump.jpg set tuple width height = tuple 250 350 set pts1 = call float32 list list 227 93 list 430 136 list 162 379 list 370 426 comment left top,right top,left bottom,right bottom set pts2 = call float32 list list 0 0 list width 0 li...
import cv2 import numpy as np img = cv2.imread("Resources/trump.jpg") # load img width, height = 250, 350 pts1 = np.float32([[227, 93], [430, 136], [162, 379],[ 370, 426]]) # left top,right top,left bottom,right bottom pts2 = np.float32([[0, 0], [width, 0], [0, height], [width, height]]) matrix =...
Python
zaydzuhri_stack_edu_python
import utils comment Compute sum of perimeters of all almost equilateral triangles with integer area and perimeter < 10^9 comment Using Heron's formula, we can figure out that we need (3s+-1)(s-+1) to be a perfect square, where s is the repeated side comment After some rearranging we can restate the problem: comment Fo...
import utils # Compute sum of perimeters of all almost equilateral triangles with integer area and perimeter < 10^9 # Using Heron's formula, we can figure out that we need (3s+-1)(s-+1) to be a perfect square, where s is the repeated side # After some rearranging we can restate the problem: # For all x of the form 2^a...
Python
zaydzuhri_stack_edu_python
function transform self corpus begin for conv_id in conversations begin set conv = call get_conversation conv_id for utt in call iter_utterances begin if text != none begin set tokenized = call word_tokenize lower text set invocations = 0 set length = length tokenized set pol_words = list for token in tokenized begin ...
def transform(self, corpus: Corpus): for conv_id in corpus.conversations: conv = corpus.get_conversation(conv_id) for utt in conv.iter_utterances(): if utt.text != None: tokenized = word_tokenize(utt.text.lower()) invocatio...
Python
nomic_cornstack_python_v1
function compare_data_in_fits file1 file2 begin set hdu1 = open file1 set hdu2 = open file2 set identical = all close hdu1 close hdu2 return identical end function
def compare_data_in_fits(file1, file2): hdu1 = pyfits.open(file1) hdu2 = pyfits.open(file2) identical = (hdu1[0].data == hdu2[0].data).all() hdu1.close() hdu2.close() return identical
Python
nomic_cornstack_python_v1
function SetNetBlendDirectionData self Direction=defaultNamedNotOptArg InfluenceType=defaultNamedNotOptArg TrimCurves=defaultNamedNotOptArg BlendClosed=defaultNamedNotOptArg SplitSurfaces=defaultNamedNotOptArg begin set ret = call InvokeTypes 124 LCID 1 tuple 9 0 tuple tuple 2 1 tuple 2 1 tuple 2 1 tuple 11 1 tuple 11 ...
def SetNetBlendDirectionData(self, Direction=defaultNamedNotOptArg, InfluenceType=defaultNamedNotOptArg, TrimCurves=defaultNamedNotOptArg, BlendClosed=defaultNamedNotOptArg , SplitSurfaces=defaultNamedNotOptArg): ret = self._oleobj_.InvokeTypes(124, LCID, 1, (9, 0), ((2, 1), (2, 1), (2, 1), (11, 1), (11, 1)),Direc...
Python
nomic_cornstack_python_v1
function build_window self begin comment Size config call geometry string 750x500 call minsize 600 400 set main_frame = call Frame window call pack fill=string both set top_frame = call Frame main_frame call pack side=string top fill=string x set bottom_frame = call Frame main_frame call pack side=string bottom fill=st...
def build_window(self): # Size config self.window.geometry('750x500') self.window.minsize(600, 400) main_frame = tk.Frame(self.window) main_frame.pack(fill="both") top_frame = tk.Frame(main_frame) top_frame.pack(side="top", fill="x") bottom_frame = tk.F...
Python
nomic_cornstack_python_v1
for _ in range M begin set tuple row direction count = map int split input set newArray = list 0 * N set row = row - 1 comment 왼쪽으로 if direction == 0 begin for i in range N begin if i - count < 0 begin set position = N - absolute i - count end else begin set position = absolute i - count % N end set newArray at positio...
for _ in range(M): row, direction, count = map(int, input().split()) newArray = [0]*N row -= 1 #왼쪽으로 if direction == 0: for i in range(N): if (i - count) < 0: position = N - abs(i-count) else: position = abs(i-count) % N new...
Python
zaydzuhri_stack_edu_python
comment Exercício Python 63: Escreva um programa que leia um número N inteiro qualquer comment e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. Exemplo: print format string Os {} primeiros números da sequência de Fibonacci: n end=string print format string {}, {}, fi f end=string...
# Exercício Python 63: Escreva um programa que leia um número N inteiro qualquer # e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. Exemplo: print('Os {} primeiros números da sequência de Fibonacci: '.format(n), end='') print('\033[32m{}\033[m, \033[32m{}\033[m, '.format(fi, f), end='') while n...
Python
zaydzuhri_stack_edu_python
string Jerame Kim 1/25/2019 Program name: assignment_3 Three separate programs that use Lists, Loops, and Nested Lists comment part1 print join string directory list comment part2 set a = list 1 1 2 3 4 8 13 21 34 55 89 set b = list 1 2 3 4 5 6 7 8 9 10 11 34 12 13 set common_items = list set b_length = length b for ...
""" Jerame Kim 1/25/2019 Program name: assignment_3 Three separate programs that use Lists, Loops, and Nested Lists """ #part1 print("\n".join(dir(list))) #part2 a = [1, 1, 2, 3, 4, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 34, 12, 13] common_items=[] b_length = len(b) for i in range(0, ...
Python
zaydzuhri_stack_edu_python
class SpaceAge extends object begin set ORBITAL_PERIOD = dict string earth 1 ; string mercury 0.2408467 ; string venus 0.61519726 ; string mars 1.8808158 ; string jupiter 11.862615 ; string saturn 29.447498 ; string uranus 84.016846 ; string neptune 164.79132 function __init__ self seconds begin set seconds = seconds s...
class SpaceAge(object): ORBITAL_PERIOD = { 'earth' :1, 'mercury':0.2408467, 'venus':0.61519726, 'mars':1.8808158, 'jupiter':11.862615, 'saturn':29.447498, 'uranus':84.016846, 'neptune':164.79132 } def __init__(self, seconds): self.seconds = seconds self.earthY...
Python
zaydzuhri_stack_edu_python
import time call clock set tri = list comprehension list comprehension integer n for n in split s for s in read lines open string triangle.txt for row in range length tri - 1 0 - 1 begin for col in range 0 row begin set tri at row - 1 at col = tri at row - 1 at col + max tri at row at col tri at row at col + 1 end end
import time time.clock() tri = [[int(n) for n in s.split()] for s in open('triangle.txt').readlines()] for row in range(len(tri)-1, 0, -1): for col in range(0, row): tri[row-1][col] += max(tri[row][col], tri[row][col+1])
Python
zaydzuhri_stack_edu_python
function get_verb_prep_counts self begin set verb_prep_counts = dictionary for i in call xrange length tokens begin if call is_verb poss at i begin set verb = lemmas at i comment empty verb if strip verb == string begin continue end set has_prep_child = false for j in call xrange length tokens begin if parents at j ==...
def get_verb_prep_counts(self): verb_prep_counts = dict() for i in xrange(len(self.tokens)): if self.is_verb(self.poss[i]): verb = self.lemmas[i] if verb.strip() == '': # empty verb continue has_prep_child = False ...
Python
nomic_cornstack_python_v1
import sys set inp = read line stdin function coffeeLike inp begin set li = list inp if length li >= 6 begin if li at 2 == li at 3 and li at 4 == li at 5 begin print string Yes end else begin print string No end end else begin print string No end end function call coffeeLike inp
import sys inp=sys.stdin.readline() def coffeeLike(inp): li=list(inp) if(len(li)>=6): if (li[2]==li[3]) and (li[4]==li[5]): print("Yes") else: print("No") else: print("No") coffeeLike(inp)
Python
zaydzuhri_stack_edu_python
function on_ping self data begin string Called when the client pings our websocket connection. We proxy it to the backend. debug format string jupyter_server_proxy: on_ping: {} data call _record_activity if has attribute self string ws begin call write_ping data end end function
def on_ping(self, data): """ Called when the client pings our websocket connection. We proxy it to the backend. """ self.log.debug('jupyter_server_proxy: on_ping: {}'.format(data)) self._record_activity() if hasattr(self, 'ws'): self.ws.protocol.write...
Python
jtatman_500k
function test_dup_fields_merge self mock_track_factory tmp_session begin set track1 = call mock_track_factory set track2 = call mock_track_factory set track_num = track_num add tmp_session track1 merge call get_existing tmp_session merge track2 end function
def test_dup_fields_merge(self, mock_track_factory, tmp_session): track1 = mock_track_factory() track2 = mock_track_factory() track2.track_num = track1.track_num tmp_session.add(track1) track2.album_obj.merge(track2.album_obj.get_existing(tmp_session)) tmp_session.merge(...
Python
nomic_cornstack_python_v1
from firebase import firebase from app import app from flask import render_template , request , session import urllib2 from bs4 import BeautifulSoup from score import * from home import * decorator call route string /leaderboard/ function leaderboard begin comment imported firebase database where all the scores and use...
from firebase import firebase from app import app from flask import render_template, request, session import urllib2 from bs4 import BeautifulSoup from score import * from home import * @app.route('/leaderboard/') def leaderboard(): # imported firebase database where all the scores and usernames are stored db_curso...
Python
zaydzuhri_stack_edu_python
from soccersimulator import SoccerTeam , Simulation , show_simu , Strategy from module.strategies import * comment Creation d'une equipe set pyteam = call SoccerTeam name=string PyTeam set thon = call SoccerTeam name=string ThonTeam comment Strategie qui ne fait rien add pyteam string Mil call FonceurStrategy comment S...
from soccersimulator import SoccerTeam, Simulation, show_simu, Strategy from module.strategies import * ## Creation d'une equipe pyteam = SoccerTeam(name="PyTeam") thon = SoccerTeam(name="ThonTeam") pyteam.add("Mil",FonceurStrategy()) #Strategie qui ne fait rien thon.add("FonS",Milieu()) #Strategie aleatoire pytea...
Python
zaydzuhri_stack_edu_python
function show_flags self begin for row in board begin for tile in row begin if bomb begin set flagged = true end end end end function
def show_flags(self): for row in self.board: for tile in row: if tile.bomb: tile.flagged = True
Python
nomic_cornstack_python_v1
string Given list of patterns with wild carts (*), you need to determine which one of these pattern matches the given path. Wildcard can be replaced by any word/char In case of tie: prefer the pattern whose leftmost wildcard appears in a field further to the right Patterns are ',' separated and paths are '/' separated....
''' Given list of patterns with wild carts (*), you need to determine which one of these pattern matches the given path. Wildcard can be replaced by any word/char In case of tie: prefer the pattern whose leftmost wildcard appears in a field further to the right Patterns are ',' separated a...
Python
zaydzuhri_stack_edu_python
string 描述 使用turtle库,绘制一个八边形。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬ 注意:这是一个自动评阅题目,请补充"编程模板"中横线内容。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬ 输出示例 八边形效果如下: comment OctagonDraw.py import turtle as t call pensize ...
''' 描述 使用turtle库,绘制一个八边形。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬ 注意:这是一个自动评阅题目,请补充"编程模板"中横线内容。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬ 输出示例 八边形效果如下: ''' #OctagonDraw.py import turtle...
Python
zaydzuhri_stack_edu_python
string https://docs.google.com/document/d/1_rs5BXklnLqGS6g6eAjevVHsPafv4PXDCi_dAM2b7G0/edit?pli=1 import cookielib import urllib2 import simplejson set API_URL = string http://api.yousee.tv/rest set API_KEY = string HCN2BMuByjWnrBF4rUncEfFBMXDumku7nfT3CMnn set AREA_TVGUIDE = string tvguide class YouSeeApi extends objec...
""" https://docs.google.com/document/d/1_rs5BXklnLqGS6g6eAjevVHsPafv4PXDCi_dAM2b7G0/edit?pli=1 """ import cookielib import urllib2 import simplejson API_URL = 'http://api.yousee.tv/rest' API_KEY = 'HCN2BMuByjWnrBF4rUncEfFBMXDumku7nfT3CMnn' AREA_TVGUIDE = 'tvguide' class YouSeeApi(object): COOKIE_JAR = cookielib...
Python
zaydzuhri_stack_edu_python
function update_xml_element self begin string Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element if not has attribute self string xml_element begin set xml_element = call Element name nsmap=NSMAP end clear xml_element if has attribute self strin...
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) ...
Python
jtatman_500k
import numpy as np import matplotlib.pyplot as plt import pandas as pd import numpy.polynomial.polynomial as poly comment Suicide vs education comment load data frames set dfSuicide = read csv string suicide-death-rates.csv set dfEducation = read csv string mean-years-of-schooling.csv comment Choose data from year 2017...
import numpy as np import matplotlib.pyplot as plt import pandas as pd import numpy.polynomial.polynomial as poly ##################################### # Suicide vs education ##################################### # load data frames dfSuicide = pd.read_csv('suicide-death-rates.csv') dfEducation = pd.read_csv('mean-yea...
Python
zaydzuhri_stack_edu_python
class Solution begin function __init__ self X Y costs fixed begin set X = X set Y = Y set costs = costs set fixed = fixed end function function copy self begin return call type self copy X copy Y copy costs copy fixed end function end class
class Solution(): def __init__(self, X, Y, costs, fixed): self.X = X self.Y = Y self.costs = costs self.fixed = fixed def copy(self): return type(self)( self.X.copy(), self.Y.copy(), self.costs.copy(), self.fixed.copy() ...
Python
zaydzuhri_stack_edu_python
comment Sequence Types set party = string Spring_Break set food = list string pizza string wings string cake string chips string BBQ set drinks = tuple string soda string water string juice string tea set rsvps = list 1 2 3 5 2 4 2 6 8 2 5 1 8 2 comment Common Sequence Operations print string in function set x = string...
#Sequence Types party='Spring_Break' food=['pizza', 'wings', 'cake', 'chips', 'BBQ'] drinks=('soda', 'water', 'juice', 'tea') rsvps=[1, 2, 3, 5, 2, 4, 2, 6, 8, 2, 5, 1, 8, 2] #Common Sequence Operations print('in function') x = 'wings' in food print(x) y = 'beer' in drinks print(y) z = 'B' in p...
Python
zaydzuhri_stack_edu_python
function prime_factors_sum n divisor=2 result=0 begin if n <= 1 begin return result end else if n % divisor == 0 begin return call prime_factors_sum n // divisor divisor result + divisor end else begin return call prime_factors_sum n divisor + 1 result end end function set n = 123456789 set result = call prime_factors_...
def prime_factors_sum(n, divisor=2, result=0): if n <= 1: return result elif n % divisor == 0: return prime_factors_sum(n // divisor, divisor, result + divisor) else: return prime_factors_sum(n, divisor + 1, result) n = 123456789 result = prime_factors_sum(n) print(result)
Python
jtatman_500k
function __init__ __self__ arn=none description=none destination_cidr_block=none destination_port_range=none protocol=none rule_action=none rule_number=none source_cidr_block=none source_port_range=none traffic_direction=none traffic_mirror_filter_id=none begin if arn is not none begin set __self__ string arn arn end i...
def __init__(__self__, *, arn: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, destination_cidr_block: Optional[pulumi.Input[str]] = None, destination_port_range: Optional[pulumi.Input['TrafficMirrorFilterRuleDestin...
Python
nomic_cornstack_python_v1
from sympy import plot_implicit function plot2Variables functions begin string This function plot a list of 2 functions in implicit form to facilitate finding a good point for X^0 Parameters: functions = List of fuctions in they implicit form print string ---------Plotting--------- set initialPoint = decimal input stri...
from sympy import plot_implicit def plot2Variables(functions): """This function plot a list of 2 functions in implicit form to facilitate finding a good point for X^0 Parameters: functions = List of fuctions in they implicit form """ print('---------Plotting---------') initialPoint=float(input('Insert a lower ...
Python
zaydzuhri_stack_edu_python
function build_all_datasets cfg tokenizer train_valid_test_num_samples begin set train_dataset = call RetroQAFineTuneDataset get train_ds string file_name tokenizer get train_ds string answer_only_loss pad_id get train_ds string seq_length get train_ds string add_bos get train_ds string add_eos train_valid_test_num_sam...
def build_all_datasets( cfg, tokenizer, train_valid_test_num_samples, ): train_dataset = RetroQAFineTuneDataset( cfg.train_ds.get('file_name'), tokenizer, cfg.train_ds.get('answer_only_loss'), tokenizer.pad_id, cfg.train_ds.get('seq_length'), cfg.train_ds.get('add...
Python
nomic_cornstack_python_v1
string Created on 2019 M10 31 @author: Sheldon Van Middelkoop string ----------------------------------------------------------------------------------------------------------------------- Importing Libraries ---------------------------------------------------------------------------------------------------------------...
''' Created on 2019 M10 31 @author: Sheldon Van Middelkoop ''' """ ----------------------------------------------------------------------------------------------------------------------- Importing Libraries ----------------------------------------------------------------------------------------------------------------...
Python
zaydzuhri_stack_edu_python
set name = input print string While we seem to disagree on this issue, { name } , I respect your opinion and look forward to further discussion!
name = input() print(f"While we seem to disagree on this issue, {name}, I respect your opinion and look forward to further discussion!")
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- comment Python is very slow, takes 50x time of c_test1.c function is_prime n begin set i = 2 while i < n begin if n % i == 0 begin return false end set i = i + 1 end return true end function set count = 1 set i = 2 set n_max = 100000 while i <= n_max begin if call ...
#!/usr/bin/python # -*- coding: utf-8 -*- # Python is very slow, takes 50x time of c_test1.c def is_prime(n): i = 2 while i < n: if n % i == 0: return False i += 1 return True count = 1 i = 2 n_max = 100000 while i <= n_max: if is_prime(i): count += 1 i += 1
Python
zaydzuhri_stack_edu_python
function pos self begin if _name is none begin return none end return split _name string . at 1 end function
def pos(self): if self._name is None: return None return self._name.split('.')[1]
Python
nomic_cornstack_python_v1
function slice_video video_name index_file intro outro begin set clip_c = call VideoFileClip video_name if intro or outro begin set intro_clip = call VideoFileClip string videos/thedojo_intro.mp4 set outro_clip = call VideoFileClip string videos/thedojo_outro.mp4 end set duration = duration print duration set timestamp...
def slice_video(video_name, index_file, intro, outro): clip_c = VideoFileClip(video_name) if intro or outro: intro_clip = VideoFileClip("videos/thedojo_intro.mp4") outro_clip = VideoFileClip("videos/thedojo_outro.mp4") duration = clip_c.duration print(duration) timestamps = [] ...
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[848]: import numpy as np import pandas as pd import random from collections import defaultdict from scipy.sparse import csr_matrix from sklearn.decomposition import TruncatedSVD from sklearn.preprocessing import Normalizer from sklearn.neighbors import NearestNeighbors import matplotlib...
# coding: utf-8 # In[848]: import numpy as np import pandas as pd import random from collections import defaultdict from scipy.sparse import csr_matrix from sklearn.decomposition import TruncatedSVD from sklearn.preprocessing import Normalizer from sklearn.neighbors import NearestNeighbors import matplotlib.pyplot a...
Python
zaydzuhri_stack_edu_python
function incr self name amount=1 begin return call format_inline string INCRBY name amount end function
def incr(self, name, amount=1): return self.format_inline('INCRBY', name, amount)
Python
nomic_cornstack_python_v1
import tkinter from tkinter import * set root = call Tk call geometry string 500x500+100+100 title root string Canvas call minsize width=400 height=400 call maxsize width=600 height=500 comment DEFINIG A CANVAS##################### class _Can begin function __init__ self bg master=none begin set master = master set bg ...
import tkinter from tkinter import* root = Tk() root.geometry('500x500+100+100') root.title('Canvas') root.minsize(width = 400, height = 400) root.maxsize(width = 600, height = 500) ###################DEFINIG A CANVAS##################### class _Can(): def __init__(self, bg, master=None): ...
Python
zaydzuhri_stack_edu_python
from sortedcontainers import SortedDict from transaction import verify_transaction import json comment transaction pool class Pool extends object begin set pool = list function __init__ self begin pass end function function push self transaction begin append pool transaction comment True stand for success return true ...
from sortedcontainers import SortedDict from transaction import verify_transaction import json # transaction pool class Pool(object): pool = [] def __init__(self): pass def push(self,transaction): self.pool.append(transaction) # True stand for success return True ...
Python
zaydzuhri_stack_edu_python
function Set self *args begin return call itkRGBPixelUC_Set self *args end function
def Set(self, *args): return _itkRGBPixelPython.itkRGBPixelUC_Set(self, *args)
Python
nomic_cornstack_python_v1
import bottle import datetime import pytz decorator call route string /zone function select_zone begin set head = string <html> <head> <title>Zone Selector</title> </head> <body> set body = string <p>Show me the time in:</p> <form action="zone" method="post"> <select name="zones" multiple="multiple"> <option value="Eur...
import bottle import datetime import pytz @bottle.route('/zone') def select_zone(): head="<html> <head> <title>Zone Selector</title> </head> <body> " body="""<p>Show me the time in:</p> <form action="zone" method="post"> <select name="zones" multiple="multiple"> <option value="Europe/Istanbul">Ista...
Python
zaydzuhri_stack_edu_python
function reconstruction_loss self begin return _reconstruction_loss end function
def reconstruction_loss(self): return self._reconstruction_loss
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 from collections import defaultdict import sys function parse_input file_path begin with open file_path as f begin set source = integer strip read line f set sink = integer strip read line f set graph = default dictionary list for line in read lines f begin set tuple a b dist = map int spl...
#!/usr/bin/env python3 from collections import defaultdict import sys def parse_input(file_path): with open(file_path) as f: source = int(f.readline().strip()) sink = int(f.readline().strip()) graph = defaultdict(list) for line in f.readlines(): a, b, dist = map(int, l...
Python
zaydzuhri_stack_edu_python
import numpy as np set a = ones tuple 20 30 set b = ones tuple 20 30 set c = a * b print shape
import numpy as np a=np.ones((20,30)) b=np.ones((20,30)) c=a*b print(c.shape)
Python
zaydzuhri_stack_edu_python
function fit self X y=none begin set X = call _check_X X if handle_unknown not in list string error string ignore begin set template = string handle_unknown should be either 'error' or 'ignore', got %s raise call ValueError template % handle_unknown end if hashing_dim is not none and not is instance hashing_dim int beg...
def fit(self, X, y=None): X = self._check_X(X) if self.handle_unknown not in ["error", "ignore"]: template = "handle_unknown should be either 'error' or " "'ignore', got %s" raise ValueError(template % self.handle_unknown) if (self.hashing_dim is not None) and (not isins...
Python
nomic_cornstack_python_v1
function initializePatches win expInfo begin set patchClock = call Clock set ISI = call StaticPeriod win=win screenHz=expInfo at string frameRate name=string ISI set patch1 = call GratingStim win=win name=string patch1 units=string cm tex=string sin mask=string raisedCos ori=0 pos=list 0 0 size=10 sf=0.4 phase=0.0 colo...
def initializePatches(win, expInfo): patchClock = core.Clock() ISI = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI') patch1 = visual.GratingStim(win=win, name='patch1',units='cm', tex='sin', mask='raisedCos', ori=0, pos=[0,0], size=10, sf=0.4, phase=0.0, c...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment --- set FILE = string Data.csv comment --- import csv comment --- function get_field field begin string Get values of a field set obj = open FILE newline=string set reader = dict reader obj delimiter=string , set values = list for row in reader begin append values row at field end...
#!/usr/bin/env python3 #--- FILE = "Data.csv" #--- import csv #--- def get_field(field): """ Get values of a field """ obj = open(FILE, newline = "") reader = csv.DictReader(obj, delimiter = ",") values = [] for row in reader: values.append(row[field]) obj.close() return...
Python
zaydzuhri_stack_edu_python
comment Alex wang @ 20170512 function ifelse weight begin set body = if expression weight > 120 then string fat else string thin print body end function function test_cnumerate begin print string test enumerate......... set str_list = list string one string two string three string four for tuple i str in enumerate str_...
## Alex wang @ 20170512 def ifelse(weight): body = "fat" if weight > 120 else "thin" print(body) def test_cnumerate(): print("test enumerate.........") str_list = ["one", "two", "three", "four"] for i, str in enumerate(str_list): print("{}\t{}".format(i, str)) def test_zip(): print(...
Python
zaydzuhri_stack_edu_python
comment noqa: E501 function __init__ self object_info=none implementation_reference=none package=none method=none default_args=none data_parameters=none assessment_types=none version=none begin set swagger_types = dict string object_info ObjectInfo ; string implementation_reference ObjectReference ; string package str ...
def __init__(self, object_info: ObjectInfo=None, implementation_reference: ObjectReference=None, package: str=None, method: str=None, default_args: object=None, data_parameters: MetricDataParameters=None, assessment_types: List[str]=None, version: str=None): # noqa: E501 self.swagger_types = { 'obj...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sat Jan 12 11:13:11 2019 @author: 29132 import scipy.io as scio import numpy as np from Findclosedata import findClosestCentroids from calcenter import computeCentroids from runkmeans import runkMeans import matplotlib.image as mpimg from kMeansInit import kMeansInitCentr...
# -*- coding: utf-8 -*- """ Created on Sat Jan 12 11:13:11 2019 @author: 29132 """ import scipy.io as scio import numpy as np from Findclosedata import findClosestCentroids from calcenter import computeCentroids from runkmeans import runkMeans import matplotlib.image as mpimg from kMeansInit import kMeans...
Python
zaydzuhri_stack_edu_python
function _get_trajopt_obj self plan active_ts=none begin if active_ts == none begin set active_ts = tuple 0 horizon - 1 end set tuple start end = active_ts set traj_objs = list for param in values params begin if param not in _param_to_ll begin continue end if _type in list string Robot string Can begin for attr_name ...
def _get_trajopt_obj(self, plan, active_ts=None): if active_ts == None: active_ts = (0, plan.horizon-1) start, end = active_ts traj_objs = [] for param in plan.params.values(): if param not in self._param_to_ll: continue if param._type ...
Python
nomic_cornstack_python_v1
function retrieve_body self retrieve_url timeout=120 begin comment Firstly Login call login set url = call parse_url retrieve_url set headers = copy headers set headers at string Accept-Encoding = string gzip try begin set response = get requests url verify=false headers=headers timeout=timeout set encoding = string UT...
def retrieve_body(self, retrieve_url, timeout=120): # Firstly Login self.login() url = self.parse_url(retrieve_url) headers = self.headers.copy() headers["Accept-Encoding"] = 'gzip' try: response = requests.get(url, verify=False, headers=headers, timeout=tim...
Python
nomic_cornstack_python_v1
function is_started self begin return _started end function
def is_started(self): return self._started
Python
nomic_cornstack_python_v1
import cv2 import math comment 导入所需要的库: import numpy as np from datetime import datetime import argparse import matplotlib.pyplot as plt comment 图像的读取 set img = call imread string dujuan_1.jpg comment 灰度图像的读取 set gray = call cvtColor img COLOR_BGR2GRAY comment 修改原图的尺寸 set fx = 0.3 set fy = 0.3 set image = call resize i...
import cv2 import math # 导入所需要的库: import numpy as np from datetime import datetime import argparse import matplotlib.pyplot as plt # 图像的读取 img = cv2.imread("dujuan_1.jpg") # 灰度图像的读取 gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # 修改原图的尺寸 fx = 0.3 fy = 0.3 image = cv2.resize(img, dsize=None, fx=fx, fy=fy, interpolati...
Python
zaydzuhri_stack_edu_python
import random import pandas import locale from operator import itemgetter call set_option string display.width 1000 call setlocale LC_ALL string set VALUE_SMALLEST_DENOM = 5 set NUM_DENOMS = 10 set NUM_ITEMS = 30 comment used for converting a bidders index to a name comment 65 means bidder 0 is named A, bidder 1 is nam...
import random import pandas import locale from operator import itemgetter pandas.set_option('display.width', 1000) locale.setlocale( locale.LC_ALL, '' ) VALUE_SMALLEST_DENOM = 5 NUM_DENOMS = 10 NUM_ITEMS = 30 # used for converting a bidders index to a name # 65 means bidder 0 is named A, bidder 1 is named B, etc. B...
Python
zaydzuhri_stack_edu_python
function makeLazyEquation begin comment Make some variables set tuple v1 v2 v3 v4 v5 v6 v7 = call _makeArgs 7 comment Make some operations set mult = call MultiplicationOperator set plus = call AdditionOperator set minus = call SubtractionOperator set pow = call ExponentiationOperator set exp = call ExponentiationOpera...
def makeLazyEquation(): # Make some variables v1, v2, v3, v4, v5, v6, v7 = _makeArgs(7) # Make some operations mult = literals.MultiplicationOperator() plus = literals.AdditionOperator() minus = literals.SubtractionOperator() pow = literals.ExponentiationOperator() exp = literals.Expon...
Python
nomic_cornstack_python_v1
comment Vamsi Desu comment GT username: vdesu7 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn import metrics from sklearn.model_selection import validation_curve , GridSearchCV f...
# Vamsi Desu # GT username: vdesu7 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn import metrics from sklearn.model_selection import validation_curve, GridSearchCV from sklearn...
Python
zaydzuhri_stack_edu_python
comment Copyright(C) 2018 刘珅珅 comment Environment: python 3.6.4 comment Date: 2018.4.24 comment 通用函数 comment 不知道函数名和参数 function tracer func *args **kargs begin print string call func: __name__ return call func *args keyword kargs end function function func1 a b c d begin return a + b + c + d end function function func2...
# Copyright(C) 2018 刘珅珅 # Environment: python 3.6.4 # Date: 2018.4.24 # 通用函数 # 不知道函数名和参数 def tracer(func, *args, **kargs): print("call func: ", func.__name__) return func(*args, **kargs) def func1(a, b, c, d): return a + b + c + d def func2(a, b): return a * b print(tracer(func1, 1, 2, c=3, d=4)...
Python
zaydzuhri_stack_edu_python
function evaluate_trajs cost states controls begin set N = shape at 0 set T = shape at 1 set costs = zeros N for tuple i tuple x u in enumerate zip states controls begin for t in range T begin set costs at i = costs at i + call stage_cost x at t u at t end set costs at i = costs at i + call terminal_cost x at T end ret...
def evaluate_trajs(cost, states, controls): N = states.shape[0] T = controls.shape[1] costs = np.zeros(N) for i, (x, u) in enumerate(zip(states, controls)): for t in range(T): costs[i] += cost.stage_cost(x[t],u[t]) costs[i] += cost.terminal_cost(x[T]) return costs
Python
nomic_cornstack_python_v1
function test_default_configuration_file self begin set root_path = __HERE__ call load_configuration app assert equal config at string SECRET_KEY string supersecret end function
def test_default_configuration_file(self): self.app.config.root_path = __HERE__ load_configuration(self.app) self.assertEqual(self.app.config["SECRET_KEY"], "supersecret")
Python
nomic_cornstack_python_v1
string Functions for cleansing the data files for the heart disease final project. import logging import pandas as pd import pickle from pathlib import Path import numpy as np set LOGGER = call getLogger __name__ function get_clean_df raw_path=string clean_path=string infer use_cache=true raw_only=false begin string I...
"""Functions for cleansing the data files for the heart disease final project. """ import logging import pandas as pd import pickle from pathlib import Path import numpy as np LOGGER = logging.getLogger(__name__) def get_clean_df(raw_path = '', clean_path="infer", use_...
Python
zaydzuhri_stack_edu_python
function perform_create self serializer begin save end function
def perform_create(self, serializer): serializer.save()
Python
nomic_cornstack_python_v1
function addAttribute self attr begin pass end function
def addAttribute(self, attr): pass
Python
nomic_cornstack_python_v1
import cv2 import numpy as np import PIL from PIL import Image set img = open string black_white.jpg set tuple width height = size print width height set img1 = zeros tuple 339 509 3 uint8 set img1 = call rectangle img1 tuple 200 0 tuple 300 100 tuple 255 255 255 - 1 set img2 = call imread string black_white.jpg commen...
import cv2 import numpy as np import PIL from PIL import Image img = PIL.Image.open("black_white.jpg") width, height = img.size print(width, height) img1 = np.zeros((339,509,3), np.uint8) img1 = cv2.rectangle(img1, (200,0), (300,100), (255,255,255), -1) img2 = cv2.imread("black_white.jpg") # bitAnd = cv...
Python
zaydzuhri_stack_edu_python
from skimage import io import sys import numpy as np comment n_channles = 4 if length argv < 3 begin print string Usage: print string python3 merge.py file_1 file_2 ... file_n print string Description: print string merges file_1, file_2, ..., file_n into output.jpg print string merges *_sem.png files into output_sem.pn...
from skimage import io import sys import numpy as np #n_channles = 4 if len(sys.argv) < 3: print("Usage: ") print("python3 merge.py file_1 file_2 ... file_n") print("Description:") print("merges file_1, file_2, ..., file_n into output.jpg") print("merges *_sem.png files into output_sem.png") s...
Python
zaydzuhri_stack_edu_python
import hashlib import os import random import sys import time import xml.etree.ElementTree as ET from utils import extract_spectrogram_windows import tensorflow as tf try begin from urllib import urlretrieve end except any begin from urllib.request import urlretrieve end class DataProvider begin function __init__ self ...
import hashlib import os import random import sys import time import xml.etree.ElementTree as ET from utils import extract_spectrogram_windows import tensorflow as tf try: from urllib import urlretrieve except: from urllib.request import urlretrieve class DataProvider: def __init__(self, download_folder=...
Python
zaydzuhri_stack_edu_python
function test_index_events_fail self begin set response = get client string /v1/events assert equal status_code 500 end function
def test_index_events_fail(self): response = self.client.get('/v1/events') self.assertEqual(response.status_code, 500)
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- import logging set _logger = call getLogger __name__ comment 现在有多个字典或者映射,你想将它们从逻辑上合并为一个单一的映射后执行某些操作, 比如查找值或者检查某些键是否存在。 set a = dict string x 1 ; string z 3 set b = dict string y 2 ; string z 4 from collections import ChainMap comment 一个 ChainMap 接受多个字典并将它们在逻辑上变为一个字典。 然后,这些字典并不是真的合并在一起了, Cha...
# -*- coding:utf-8 -*- import logging _logger = logging.getLogger(__name__) # 现在有多个字典或者映射,你想将它们从逻辑上合并为一个单一的映射后执行某些操作, 比如查找值或者检查某些键是否存在。 a = {'x': 1, 'z': 3 } b = {'y': 2, 'z': 4 } from collections import ChainMap # 一个 ChainMap 接受多个字典并将它们在逻辑上变为一个字典。 然后,这些字典并不是真的合并在一起了, ChainMap 类只是在内部创建了一个容纳这些字典的列表 c = ChainMap(a,b) ...
Python
zaydzuhri_stack_edu_python
function test_contourf begin set mp = call MapPlot sector=string iowa nocaption=true call contourf array range - 94 - 89 array range 40 45 array range 5 array range 5 clevlabels=list string a string b string c string d string e return fig end function
def test_contourf(): mp = MapPlot(sector="iowa", nocaption=True) mp.contourf( np.arange(-94, -89), np.arange(40, 45), np.arange(5), np.arange(5), clevlabels=["a", "b", "c", "d", "e"], ) return mp.fig
Python
nomic_cornstack_python_v1
function print_regions regions begin from tabulate import tabulate set headers = list string Region string numServers string numRealms string numPlayers set table = list comprehension list k v at string numServers v at string numRealms v at string numPlayers for tuple k v in sorted items regions print call tabulate tab...
def print_regions(regions): from tabulate import tabulate headers = ["Region", "numServers", "numRealms", "numPlayers"] table = [[k, v["numServers"], v["numRealms"], v["numPlayers"]] for k, v in sorted(regions.items())] print(tabulate(table, headers, tablefmt="rst"))
Python
nomic_cornstack_python_v1
import random import string set length = 10 set chars = ascii_letters + digits set password = join string generator expression random choice chars for i in range length print password
import random import string length = 10 chars = string.ascii_letters + string.digits password = ''.join(random.choice(chars) for i in range(length)) print(password)
Python
flytech_python_25k
function _get_local_id self begin return __local_id end function
def _get_local_id(self): return self.__local_id
Python
nomic_cornstack_python_v1
function confidence_score self predicts confidence begin set predict_classes = reshape tf predicts at tuple slice : : slice : : slice : : slice 18 : - 1 : list Batch_Size cell_size cell_size num_class set confidence = call tile confidence list 1 1 1 num_class set class_speci_conf_score = call multiply predict...
def confidence_score(self, predicts, confidence): predict_classes = tf.reshape(predicts[:, :, :, 18:-1], [self.Batch_Size, self.cell_size, self.cell_size, self.num_class]) confidence = tf.tile(confidence, [1, 1, 1, self.num_class]) class_speci_conf_score = tf.multiply(predict_classes, confidenc...
Python
nomic_cornstack_python_v1
function today begin return call datestamp now end function
def today(): return datestamp(now())
Python
nomic_cornstack_python_v1
from keras.preprocessing.text import Tokenizer import pandas as pd from keras.utils import to_categorical from sklearn.model_selection import train_test_split from keras import models , layers import pickle set tokenizer = call Tokenizer set nama_file = string D:\resa\D\KULIAH\S2\Semester 1\python\mlNN_1\datasetSMS\dat...
from keras.preprocessing.text import Tokenizer import pandas as pd from keras.utils import to_categorical from sklearn.model_selection import train_test_split from keras import models, layers import pickle tokenizer = Tokenizer() nama_file = "D:\\resa\\D\\KULIAH\\S2\\Semester 1\\python\\mlNN_1\\datasetSMS\\dataset.csv...
Python
zaydzuhri_stack_edu_python
function __getNewWallet self begin comment get the public and private key set privateKey = call __getNewPrivateKey set publicKey = call __getNewPublicKey privateKey comment create the dictionary containing the public and private key set walletKeySet = dict string private_key decode call hexlify call exportKey format=st...
def __getNewWallet(self)->dict: # get the public and private key privateKey = self.__getNewPrivateKey() publicKey = self.__getNewPublicKey(privateKey) # create the dictionary containing the public and private key walletKeySet = { 'private_key': binascii.hexlify(priva...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import rospy import time from std_msgs.msg import UInt32MultiArray , Char class Arduino extends object begin function __init__ self min_distance=0.12 max_distance=0.9 lidar_queue_size=10 claw_queue_size=10 begin set min_distance = min_distance set max_distance = max_distance set mid = 0.5 *...
#!/usr/bin/env python import rospy import time from std_msgs.msg import UInt32MultiArray, Char class Arduino(object): def __init__(self, min_distance=0.12, max_distance=0.9, lidar_queue_size=10, claw_queue_size=10): self.min_distance = mi...
Python
zaydzuhri_stack_edu_python
comment ------------------------------------------------------------- comment Main REGEX TELEFONES comment --------------------------------------------------------- from TelefonesBr import TelefonesBr set telefone = input string Digite o número do seu celular com DDD e o código do seu país: set telefone_objeto = call T...
# ------------------------------------------------------------- # Main REGEX TELEFONES # --------------------------------------------------------- from TelefonesBr import TelefonesBr telefone = input( "Digite o número do seu celular com DDD e o código do seu país: " ) telefone_objeto = TelefonesBr(telefone) pri...
Python
zaydzuhri_stack_edu_python
function run list_of_goals result_folder general_and=false general_or=false no_clusters=false clusters_origianl=false clusters_mutex=false complete=true begin for g in list_of_goals begin print g end set controller_generated_and = false set trivial_and = false set controller_generated_or = false set trivial_or = false ...
def run(list_of_goals: List[CGTGoal], result_folder: str, general_and=False, general_or=False, no_clusters=False, clusters_origianl=False, clusters_mutex=False, complete=True): for g in list_of_goals: print(g) controller_generated_and = False trivial_...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from typing import List , Tuple , Dict , Set , TypeVar , Any , Optional , Iterable from collections import defaultdict from dungeon_lib import roomGraph4 as roomGraph set A = call TypeVar string A class Queue begin function __init__ self begin set queue : List at A = list end function funct...
#!/usr/bin/env python from typing import List, Tuple, Dict, Set, TypeVar, Any, Optional, Iterable from collections import defaultdict from dungeon_lib import roomGraph4 as roomGraph A = TypeVar('A') class Queue: def __init__(self): self.queue: List[A] = list() def enqueue(self, a: A): self.qu...
Python
zaydzuhri_stack_edu_python
comment coding:iso-8859-9 Trke comment p_13502.py: try-raise ile hazr veya zel istisna frlatp except Exception'la yakalama rnei. try begin raise call SyntaxError string Afedersiniz, kendi hatam!.. end except Exception as ist begin print ist end print string Program devam ediyor... print string - * 75 string sep=string...
# coding:iso-8859-9 Trke # p_13502.py: try-raise ile hazr veya zel istisna frlatp except Exception'la yakalama rnei. try: raise SyntaxError ("Afedersiniz, kendi hatam!..") except Exception as ist: print (ist) print ("Program devam ediyor...") print ("-"*75, "\n", sep="") #-------------------------------------...
Python
zaydzuhri_stack_edu_python
function score self word context begin set context = call check_context context set context_freqdist = ngrams at context set word_count = context_freqdist at word set context_count = call N return word_count + k / context_count + k_norm end function
def score(self, word, context): context = self.check_context(context) context_freqdist = self.ngrams[context] word_count = context_freqdist[word] context_count = context_freqdist.N() return (word_count + self.k) / \ (context_count + self.k_norm)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import os import csv set starting_dir = get current directory function csvstuff begin print format string Starting in directory: {} starting_dir change directory starting_dir set testdata_fname = string data/testdata.csv with open testdata_fname as csv_f begin set csvreader = reader csv_f ...
#!/usr/bin/env python3 import os import csv starting_dir = os.getcwd() def csvstuff(): print("Starting in directory: {}".format(starting_dir)) os.chdir(starting_dir) testdata_fname = 'data/testdata.csv' with open(testdata_fname) as csv_f: csvreader = csv.reader(csv_f) for row in csvrea...
Python
zaydzuhri_stack_edu_python
for z in range integer input begin set tuple l k = map int split input set s = 0 if k > l begin print string Case + string z + 1 + string : 0 end else if k == l begin print string Case + string z + 1 + string : 1 end else begin if l <= 4 begin set n = 1 end else begin set n = l - 4 + 1 end for i in range n + 1 0 - 1 be...
for z in range(int(input())): l,k=map(int,input().split()) s=0 if k>l: print("Case "+str(z+1)+": 0") elif k==l: print("Case "+str(z+1)+": 1") else: if l<=4: n=1 else: n=(l-4)+1 for i in range(n+1,0,-1): if i-k>0: ...
Python
zaydzuhri_stack_edu_python
function get_rating_count self from_admin=false begin set rate_score = call get_score self return rate_score end function
def get_rating_count(self, from_admin = False): rate_score = Ratings.objects.get_score(self) return rate_score
Python
nomic_cornstack_python_v1
function get_local_attribute_value self attr_name begin set op = call get_attribute_set_cmd attr_name if op is not none and source != string inheritance begin return new_value end else begin return none end end function
def get_local_attribute_value(self, attr_name): op = self.get_attribute_set_cmd(attr_name) if op is not None and op.source != 'inheritance': return op.new_value else: return None
Python
nomic_cornstack_python_v1
import sys import random set len_away = 10 set f = open string pagesave.txt string r set lines = read lines f close f set count = 0 set line = lines at 538 set line = split line string <span set teams = list set counts = list for a in line begin if string class="name" in a and string class="state" not in a and string...
import sys import random len_away = 10 f = open('pagesave.txt','r') lines = f.readlines() f.close() count = 0 line = lines[538] line = line.split("<span") teams = [] counts = [] for a in line: if "class=\"name\"" in a and "class=\"state\"" not in a and "class=\"name\"><a></a></span>" not in a: if "class=\"name\">R...
Python
zaydzuhri_stack_edu_python
function setEditorData self editor index begin set m = model try begin if call column == column begin set txt = data m index DisplayRole call setEditText txt end else begin comment use default call setEditorData self editor index end end except any begin pass end end function
def setEditorData(self, editor, index): m = index.model() try: if index.column() == self.column: txt = m.data(index, Qt.DisplayRole) editor.setEditText(txt) else: # use default QItemDelegate.setEditorData(self, edito...
Python
nomic_cornstack_python_v1
function gen_free_energy distribution spread=2.0 location=0.0 size=1 begin if lower distribution == string gaussian begin set f_true = call normal loc=location scale=spread size=size end else if lower distribution == string cauchy begin from scipy.stats import cauchy set f_true = call rvs loc=location scale=spread size...
def gen_free_energy(distribution, spread=2.0, location=0.0, size=1): if distribution.lower() == 'gaussian': f_true = np.random.normal(loc=location, scale=spread, size=size) elif distribution.lower() == 'cauchy': from scipy.stats import cauchy f_true = cauchy.rvs(loc=location, scale=sprea...
Python
nomic_cornstack_python_v1
function create_json fl name begin set obj = dumps fl indent=4 with open string new_json/ { name } .json string w as outfile begin write outfile obj end return end function
def create_json(fl, name): obj = json.dumps(fl, indent=4) with open(f"new_json/{name}.json", "w") as outfile: outfile.write(obj) return
Python
nomic_cornstack_python_v1
function calculateSalary begin set hrs = call raw_input string Enter Hours: set h = decimal hrs if h <= 40 begin set salary = h * 10.5 end else begin set salary = 40 * 10.5 + h - 40 * 10.5 * 1.5 end print salary end function
def calculateSalary(): hrs = raw_input("Enter Hours:") h = float(hrs) if h <= 40: salary = h*10.5 else: salary = 40*10.5 + (h-40)*(10.5*1.5) print(salary)
Python
zaydzuhri_stack_edu_python
function parallel_blast db query evalue=1e-50 p_id=100 cpus=- 1 out=string hit.hits begin set outfmt_str = string qseqid sseqid pident evalue qcovs qlen length set args = list string blastn string -db db string -query string - string -evalue string evalue string -perc_identity string p_id string -outfmt string 6 %s % o...
def parallel_blast(db, query, evalue=1E-50, p_id=100, cpus=-1, out='hit.hits'): outfmt_str = 'qseqid sseqid pident evalue qcovs qlen length' args = ['blastn', '-db', db, '-query', '-', '-evalue', str(evalue), '-perc_identity', str(p_id), '-outfmt', "6 %s" % outfmt_str] with shelve.open(query) as...
Python
nomic_cornstack_python_v1
function __init__ self access_token=none begin set access_token = access_token end function
def __init__(self, access_token=None): self.access_token = access_token
Python
nomic_cornstack_python_v1