code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import pandas as pd
from model.model_evaluation import ModelEvaluation
from datetime import datetime , timedelta
class GroundTruth extends object
begin
function fit self df
begin
set train_start_date = min df at string date
set train_end_date = max df at string date
set rate = decimal sum / decimal length df at string ... | import pandas as pd
from model.model_evaluation import ModelEvaluation
from datetime import datetime, timedelta
class GroundTruth(object):
def fit(self, df):
self.train_start_date = min(df['date'])
self.train_end_date = max(df['date'])
self.rate = float(df['count'].sum()) / float(len(df['c... | Python | zaydzuhri_stack_edu_python |
comment test file for binning function
import csv
from _functions import csv2dict
import random
comment populate master dictionary
function add2masterDict indict masterdict
begin
string Extend the MasterDictionary to contain all possible SNPs
for tuple element values in items indict
begin
set masterdict at element = li... | # test file for binning function
import csv
from _functions import csv2dict
import random
# populate master dictionary
def add2masterDict(indict, masterdict):
"""
Extend the MasterDictionary to contain all possible SNPs
"""
for element, values in indict.items():
masterdict[element] = []
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from bokeh.plotting import figure , show
function add_hist_plot x plot n_bins=100 x_range=none normalize=false norm=1.0 **kwargs
begin
if x_range is none
begin
set x_range = list min x max x
end
set tuple hist edges = call histogram x bins=n_bins range=x_range
set dx = edges at 1 - edges at 0
if norm... | import numpy as np
from bokeh.plotting import figure, show
def add_hist_plot(x, plot, n_bins=100, x_range=None, normalize=False, norm=1.0, **kwargs):
if x_range is None:
x_range = [min(x), max(x)]
hist, edges = np.histogram(x, bins=n_bins, range=x_range)
dx = edges[1] - edges[0]
if normalize:... | Python | zaydzuhri_stack_edu_python |
comment Functions for running an encryption or decryption.
comment The values of the two jokers.
set JOKER1 = 27
set JOKER2 = 28
function clean_message original_message
begin
string (str) -> str The function takes in a text message that only has one line of text and strips away any non-alphabet chacters and spaces, the... | # Functions for running an encryption or decryption.
# The values of the two jokers.
JOKER1 = 27
JOKER2 = 28
def clean_message(original_message):
'''(str) -> str
The function takes in a text message that only has one line of text and
strips away any non-alphabet chacters and spaces, then it converts all
... | Python | zaydzuhri_stack_edu_python |
import re
set VERSIONFILE = string myniftyapp/_version.py
set verstrline = read open VERSIONFILE string rt
set VSRE = string ^__version__ = ['\"]([^'\"]*)['\"]
set mo = search VSRE verstrline M
if mo
begin
set verstr = call group 1
end
else
begin
raise call RuntimeError string Unable to find version string in %s. % tup... | import re
VERSIONFILE="myniftyapp/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr = mo.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))
| Python | jtatman_500k |
function get_argument_groups parser
begin
set groups : Dict at tuple str Any = dict string __NO_TITLE__ list
set all_action_groups : List at _ArgumentGroup = list
for group in _action_groups
begin
set all_action_groups = all_action_groups + call collect_groups_recurse group
end
for group in all_action_groups
begin
if... | def get_argument_groups(
parser: argparse.ArgumentParser,
) -> Dict[str, argparse._ArgumentGroup]:
groups: Dict[str, Any] = {"__NO_TITLE__": []}
all_action_groups: List[argparse._ArgumentGroup] = []
for group in parser._action_groups:
all_action_groups += collect_groups_recurse(group)
for gr... | Python | nomic_cornstack_python_v1 |
for i in range test_case
begin
set count = 0
set tuple N M = map int split input string
set data = list map int split input string
set target = data at M
while true
begin
if data at 0 == max data
begin
set count = count + 1
if data at 0 == target
begin
print count
break
end
else
begin
pop data 0
end
end
else
begin
appe... | for i in range(test_case):
count = 0
N, M = map(int,input().split(' '))
data = list(map(int, input().split(' ')))
target = data[M]
while True:
if data[0] == max(data):
count += 1
if data[0] == target:
print(count)
break
else... | Python | zaydzuhri_stack_edu_python |
with open company at num string a as f
begin
write f complain
print string Ваша жалоба принятa.
end | with open(company[num], "a") as f:
f.write(complain)
print("\nВаша жалоба принятa.") | Python | zaydzuhri_stack_edu_python |
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
set x_train = call FloatTensor list list 1 list 2 list 3
set y_train = call FloatTensor list list 1 list 2 list 3
class LinearRegressionModel extends Module
begin
function __init__ self
begin
call __init__
set linear = linear 1 1
end func... | import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
x_train = torch.FloatTensor([[1],[2],[3]])
y_train = torch.FloatTensor([[1],[2],[3]])
class LinearRegressionModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(1,1)
def forward(self, ... | Python | zaydzuhri_stack_edu_python |
comment This Python 3 environment comes with many helpful analytics libraries installed
comment It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
comment For example, here's several helpful packages to load in
comment Input data files are available in the "../input/" directory.
co... | # This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
# Input data files are available in the "../input/" directory.
# For example, running t... | Python | zaydzuhri_stack_edu_python |
function init_func unicore_fuzz uc
begin
pass
end function | def init_func(unicore_fuzz, uc):
pass | Python | nomic_cornstack_python_v1 |
function __init__ self root size exclude_imagenet1k=true *args **kwargs
begin
call __init__ root *args keyword kwargs
set exclude_imagenet1k = exclude_imagenet1k
set shuffle_idxs = false
set size = size
if exclude_imagenet1k
begin
set samples = list comprehension s for s in samples if not any list comprehension idx in ... | def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs):
super(MyImageNet22K, self).__init__(root, *args, **kwargs)
self.exclude_imagenet1k = exclude_imagenet1k
self.shuffle_idxs = False
self.size = size
if exclude_imagenet1k:
self.... | Python | nomic_cornstack_python_v1 |
function last_run self
begin
return _last_run
end function | def last_run(self):
return self._last_run | Python | nomic_cornstack_python_v1 |
function save self datastore model
begin
add datastore model
flush datastore
return model
end function | def save(self, datastore, model):
datastore.add(model)
datastore.flush()
return model | Python | nomic_cornstack_python_v1 |
import string
from collections import Counter
try
begin
from nltk.corpus import stopwords
set stopwords = call words string english
end
except ImportError
begin
comment Manually define stopwords
set stopwords = list string the string and string is string a string an string in string of string on string to
end
function ... | import string
from collections import Counter
try:
from nltk.corpus import stopwords
stopwords = stopwords.words('english')
except ImportError:
stopwords = ['the', 'and', 'is', 'a', 'an', 'in', 'of', 'on', 'to'] # Manually define stopwords
def count_words(string):
string = string.lower()
string ... | Python | jtatman_500k |
function apply_template self **kwargs
begin
set query_params = dict string _actions string false ; string _links string true ; string _embedded string true
set path_params = dict
set headers = dict
set body = none
if string applicationId in kwargs
begin
set path_params at string applicationId = kwargs at string appli... | def apply_template(self, **kwargs):
query_params = {"_actions": "false", "_links": "true", "_embedded": "true"}
path_params = {}
headers = {}
body = None
if "applicationId" in kwargs:
path_params["applicationId"] = kwargs["applicationId"]
if "options" in kwa... | Python | nomic_cornstack_python_v1 |
function test_rshift_array_array_none_e2 self
begin
comment This version is expected to pass.
call rshift testarray1 testarray2
comment This is the actual test.
with assert raises TypeError
begin
call rshift badarray1 testarray2
end
end function | def test_rshift_array_array_none_e2(self):
# This version is expected to pass.
arrayfunc.rshift(self.testarray1, self.testarray2)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.rshift(self.badarray1, self.testarray2) | Python | nomic_cornstack_python_v1 |
try
begin
set no = integer input
set num1 = list map int split input
for y in num1
begin
if count num1 y == 1
begin
print y
end
end
end
except ValueError
begin
print string invalid
end | try:
no=int(input())
num1=list(map(int,input().split()))
for y in num1:
if num1.count(y)==1:
print(y)
except ValueError:
print("invalid")
| Python | zaydzuhri_stack_edu_python |
string Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You may not modify the values in the list's nodes, only nodes itself may be changed. Example 1: Given 1->2->3->4, reorder it to 1->4->2->3. Example 2: Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
class Solution extends obj... | """
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
"""
class Solution(object... | Python | zaydzuhri_stack_edu_python |
function load_tf_weights_in_bert_kernel model ckpt_path voc_size_diff
begin
try
begin
import re
import numpy as np
import tensorflow as tf
end
except ImportError
begin
error string Loading a TensorFlow model in DeepSpeed, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installati... | def load_tf_weights_in_bert_kernel(model, ckpt_path, voc_size_diff):
try:
import re
import numpy as np
import tensorflow as tf
except ImportError:
logger.error(
"Loading a TensorFlow model in DeepSpeed, requires TensorFlow to be installed. Please see "
"ht... | Python | nomic_cornstack_python_v1 |
function login self username=none password=none
begin
set service = string /api/account/login
set username = username or username
set password = password or password
assert username is not none
assert password is not none
debug string LOGIN USERNAME: %s username
set r = call _httpreq_json service string POST form=dicti... | def login(self, username=None, password=None):
service = '/api/account/login'
username = username or self.username
password = password or self.password
assert username is not None
assert password is not None
self.log.debug('LOGIN USERNA... | Python | nomic_cornstack_python_v1 |
comment Brute force, recursive only solution
comment def solveKnapsack(profits, weights, capacity):
comment return recursiveKnapsack(profits, weights, capacity, 0)
comment def recursiveKnapsack(profits, weights, capacity, currentIndex):
comment # base condition check
comment if capacity <= 0 or currentIndex >= len(prof... | # Brute force, recursive only solution
# def solveKnapsack(profits, weights, capacity):
# return recursiveKnapsack(profits, weights, capacity, 0)
# def recursiveKnapsack(profits, weights, capacity, currentIndex):
# # base condition check
# if capacity <= 0 or currentIndex >= len(profits):
# ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri May 11 10:54:24 2018 @author: Karan
set str = string This is a multi line string. This code challenge is to test your understanding about strings.You need to print some part of this string. From here print this text without manually counting the indexes.
set lst = cal... | # -*- coding: utf-8 -*-
"""
Created on Fri May 11 10:54:24 2018
@author: Karan
"""
str = """This is a multi line string. This code challenge is to
test your understanding about strings.You need to print some part of this string.
From here print this text without manually counting the indexes."""
lst = str.splitlines... | Python | zaydzuhri_stack_edu_python |
import os
print string +====================================+ ______________ | HDE Products | |______________| HeHeHeHeHeHeHe +====================================+ {1} Instalar ferramentas (Para kali linux apenas) {2} Info Do site completa
set ask = integer input string {Escolha} {>
if ask == string 1
begin
call syste... | import os
print("""
+====================================+
______________
| HDE Products |
|______________|
HeHeHeHeHeHeHe
+====================================+
{1} Instalar ferramentas (Para kali linux apenas)
{2} Info Do site completa
""")
ask = int(input(' {... | Python | zaydzuhri_stack_edu_python |
function _models_impl draw strat
begin
try
begin
return call draw strat at 0
end
except IntegrityError
begin
call reject
end
end function | def _models_impl(draw, strat):
try:
return draw(strat)[0]
except IntegrityError:
reject() | Python | nomic_cornstack_python_v1 |
string 给一个DNA字符串,找出所有长度超过10,切出现次数超过1次的子串。 @Author: Li Zenghui @Date: 2020-03-25 16:32
comment 方法1,长度为10, 按顺序遍历,固定长度为10,将字符串存入哈希表。最后统计次数大于1的key值
function find_repeat_substring s
begin
set end = length s - 10
set word_map = dict
for i in range end + 1
begin
set key = s at slice i : i + 10 :
if key not in keys word_map
... | """
给一个DNA字符串,找出所有长度超过10,切出现次数超过1次的子串。
@Author: Li Zenghui
@Date: 2020-03-25 16:32
"""
# 方法1,长度为10, 按顺序遍历,固定长度为10,将字符串存入哈希表。最后统计次数大于1的key值
def find_repeat_substring(s):
end = len(s)-10
word_map = {}
for i in range(end+1):
key = s[i:i+10]
if key not in word_map.keys():
word_map[... | Python | zaydzuhri_stack_edu_python |
function _rsplit value sep maxsplit=none
begin
set str_parts = split value sep
if maxsplit is not none and length str_parts > 1
begin
return list join str sep str_parts at slice : - maxsplit : + str_parts at slice - maxsplit : :
end
return str_parts
end function | def _rsplit(value, sep, maxsplit=None):
str_parts = value.split(sep)
if (maxsplit is not None) and (len(str_parts) > 1):
return [str.join(sep, str_parts[:-maxsplit])] + str_parts[-maxsplit:]
return str_parts | Python | nomic_cornstack_python_v1 |
for i in range 0 integer length rra
begin
set tot = tot * 10 + rra at i
end
print tot | for i in range(0,int(len(rra))):
tot=(tot*10)+rra[i]
print(tot)
| Python | zaydzuhri_stack_edu_python |
string Created on 2011-4-14 @author: Plato Sun
from dbobj import dbobj
class phone extends dbobj
begin
set table_name = string phone
set fields = string uid,phonebook_uid,name,companyname,title,mobile
set key = string uid
function __init__ self
begin
set uid = string
set phonebook_uid = string
set name = string
set ... | '''
Created on 2011-4-14
@author: Plato Sun
'''
from dbobj import dbobj
class phone(dbobj):
table_name = 'phone'
fields = 'uid,phonebook_uid,name,companyname,title,mobile'
key = 'uid'
def __init__(self):
self.uid = ''
self.phonebook_uid = ''
self.name = ''
self.compan... | Python | zaydzuhri_stack_edu_python |
from io import StringIO
import re
import inspect
from typing import Iterator , io , Union , Tuple , Any , List , Callable , Dict , Optional
class ParserError extends Exception
begin
pass
end class
class Identifier extends str
begin
pass
end class
class EOL
begin
pass
end class
set TokenType = Union at tuple Identifier ... | from io import StringIO
import re
import inspect
from typing import Iterator, io, Union, Tuple, Any, List, Callable, Dict, Optional
class ParserError(Exception):
pass
class Identifier(str): pass
class EOL: pass
TokenType = Union[Identifier, str, int, float, EOL]
# '\\{key}' from this map is replaced by accord... | Python | zaydzuhri_stack_edu_python |
comment Roman Goj
comment 25/11/2010
string This module contains functions to read electrode locations from pre-prepared text files and to plot a topographic map of scalp activity.
import csv
from numpy import cos , sin , abs , pi , array , append , copy , linspace , sqrt , mean
from numpy.random import uniform
from nu... | # Roman Goj
# 25/11/2010
"""
This module contains functions to read electrode locations from pre-prepared
text files and to plot a topographic map of scalp activity.
"""
import csv
from numpy import cos, sin, abs, pi, array, append, copy, linspace, sqrt, mean
from numpy.random import uniform
from numpy.ma import maske... | Python | zaydzuhri_stack_edu_python |
comment Repeated DNA Sequences
string All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to find all the 10-letter-long sequences (substrings) that occur more t... | # Repeated DNA Sequences
"""
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than onc... | Python | zaydzuhri_stack_edu_python |
function register_volumes static moving nBins=32 sampling_prop=none level_iters=list 100 50 2 sigmas=list 5.0 2.0 0 factors=list 8 3 1 params0=none static_grid2world=none moving_grid2world=none verbosity=2
begin
from dipy.align.imaffine import transform_centers_of_mass , MutualInformationMetric , AffineRegistration
fro... | def register_volumes(static, moving, nBins=32, sampling_prop=None,
level_iters=[100, 50, 2], sigmas=[5.0, 2.0, 0],
factors=[8, 3, 1], params0=None,
static_grid2world=None, moving_grid2world=None,
verbosity=2):
from dipy.align.imaffi... | Python | nomic_cornstack_python_v1 |
import flickrapi
from bs4 import BeautifulSoup
import urllib
import urllib2
import sys
from KEYS import api_key , api_secret
function downloadImg link
begin
set html = url open link
set soup = call BeautifulSoup html string lxml
comment mydiv= soup.findAll('div',{'class':'photo-notes-scrappy-view'})
set mydiv = find al... | import flickrapi
from bs4 import BeautifulSoup
import urllib
import urllib2
import sys
from KEYS import api_key,api_secret
def downloadImg(link):
html = urllib.urlopen(link)
soup = BeautifulSoup(html,"lxml")
#mydiv= soup.findAll('div',{'class':'photo-notes-scrappy-view'})
mydiv = soup.findAll('img',{'class':'main... | Python | zaydzuhri_stack_edu_python |
for player in players at slice : 3 :
begin
print player
end
print string The middle three players in my team are:
for player in players at slice 1 : 4 :
begin
print player
end
print string The last three players in my team are:
for player in players at slice - 3 : :
begin
print player
end | for player in players[:3]:
print(player)
print("The middle three players in my team are:")
for player in players[1:4]:
print(player)
print("The last three players in my team are:")
for player in players[-3:]:
print(player) | Python | zaydzuhri_stack_edu_python |
function GetMax self
begin
set dimension = call GetDimensionOfLandmarks
set maxValue = list decimal string -inf * dimension
for lmk in landmarkList
begin
for i in range dimension
begin
if lmk at i + 1 > maxValue at i
begin
set maxValue at i = lmk at i + 1
end
end
end
return maxValue
end function | def GetMax(self):
dimension = self.GetDimensionOfLandmarks()
maxValue = [float('-inf')]*dimension
for lmk in self.landmarkList:
for i in range(dimension):
if lmk[i+1] > maxValue[i]: maxValue[i] = lmk[i+1]
return maxValue | Python | nomic_cornstack_python_v1 |
comment INF103
comment danilo patrucco
comment exercise nr 1
class pet
begin
comment constructor ; it is instantly executed
function __init__ self name animal_type age
begin
set __name = name
set __animal_type = animal_type
set __age = age
end function
comment class method (setters)
function set_name self name
begin
se... | #INF103
#danilo patrucco
#exercise nr 1
class pet :
#constructor ; it is instantly executed
def __init__(self,name,animal_type,age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
#class method (setters)
def set_name (self,name):
self.__... | Python | zaydzuhri_stack_edu_python |
from django.db import models
from shop.models import Product
class Order extends Model
begin
set client = call CharField max_length=200
set delivery_address = call CharField max_length=200
function get_total_cost self
begin
set total_cost = sum generator expression call get_cost for item in all
return total_cost
end fu... | from django.db import models
from shop.models import Product
class Order(models.Model):
client = models.CharField(max_length=200)
delivery_address = models.CharField(max_length=200)
def get_total_cost(self):
total_cost = sum(item.get_cost() for item in self.item.all())
return total_cost
... | Python | zaydzuhri_stack_edu_python |
function test_commit self
begin
comment Same id, data and user_id
set id = call get_rand_string
add self id=id user_id=id data=id
comment Make sure the changes weren't commited.
set results = results
call assertEquals length results 0 string Changes to index shouldn't be visible without commiting, results:%s % call rep... | def test_commit(self):
# Same id, data and user_id
id = get_rand_string()
self.add(id=id, user_id=id, data=id)
# Make sure the changes weren't commited.
results = self.query(self.conn, "id:" + id).results
self.assertEquals(len(results), 0,
("Changes to index ... | Python | nomic_cornstack_python_v1 |
comment !usr/local/bin
import sys
import ast
import unittest
function brute_force a
begin
comment outer loop runs n-1 times
comment inner loop goes through n -i
set outcomes = list
for i in range 0 length a - 1
begin
comment buy at day [i]
set outcome = list
append outcome string Buy: + string a at i
for j in range i... | #!usr/local/bin
import sys
import ast
import unittest
def brute_force(a):
# outer loop runs n-1 times
# inner loop goes through n -i
#
outcomes = []
for i in range(0, len(a)-1):
# buy at day [i]
outcome = []
outcome.append('Buy:' + str(a[i]))
for j in range(i, len(a))... | Python | zaydzuhri_stack_edu_python |
function _getUnixGroup self name
begin
import grp
comment Try to get the group in list of all groups.
set group_found = false
for iterator in range 1000
begin
if group_found
begin
break
end
for group in call getgrall
begin
if group at 0 == name
begin
set group_found = true
break
end
end
sleep 0.1
end
if not group_found... | def _getUnixGroup(self, name):
import grp
# Try to get the group in list of all groups.
group_found = False
for iterator in range(1000):
if group_found:
break
for group in grp.getgrall():
if group[0] == name:
gr... | Python | nomic_cornstack_python_v1 |
function C self u
begin
if u == round u
begin
return round_cost
end
return sharp_cost
end function | def C(self, u):
if u == self.Round(u):
return self.round_cost
return self.sharp_cost | Python | nomic_cornstack_python_v1 |
function __iter__ self
begin
for kv_pair in _backing
begin
if kv_pair and not value is absent
begin
yield kv_pair
end
end
end function | def __iter__(self):
for kv_pair in self._backing:
if kv_pair and not kv_pair.value is Hashmap.absent:
yield kv_pair | Python | nomic_cornstack_python_v1 |
function ninserted self
begin
string Extract ninserted or nInserted counter if available (lazy).
if not _counters_calculated
begin
set _counters_calculated = true
call _extract_counters
end
return _ninserted
end function | def ninserted(self):
"""Extract ninserted or nInserted counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._ninserted | Python | jtatman_500k |
function prune self max_vocab
begin
assert max_vocab >= 1
set i2w = dictionary comprehension k : v for tuple k v in items i2w if k < max_vocab
set w2i = dictionary comprehension v : k for tuple k v in items i2w
call check_valid
end function | def prune(self, max_vocab):
assert max_vocab >= 1
self.i2w = {k: v for k, v in self.i2w.items() if k < max_vocab}
self.w2i = {v: k for k, v in self.i2w.items()}
self.check_valid() | Python | nomic_cornstack_python_v1 |
function get_layer_points self layer_idx contour_format=true
begin
comment TODO add code in item_points to convert circles into contours
if is instance layer_idx str
begin
set layer_idx = call get_layer_idx layer_idx
end
set layer = _obj at string layers at layer_idx
if contour_format
begin
set layer_points = list gene... | def get_layer_points(self, layer_idx, contour_format=True):
# TODO add code in item_points to convert circles into contours
if isinstance(layer_idx, str):
layer_idx = self.get_layer_idx(layer_idx)
layer = self._obj['layers'][layer_idx]
if contour_format:
layer_poi... | Python | nomic_cornstack_python_v1 |
from tkinter import *
from tkinter import messagebox
class Game
begin
function __init__ self
begin
comment Hauptfenster
set window = call Tk
title window string Tic-Tac-Toe
set clicks = none
set player = string X
set colors = dict string X string red ; string O string blue
set winners = tuple set literal string 00 stri... | from tkinter import *
from tkinter import messagebox
class Game:
def __init__(self):
# Hauptfenster
self.window = Tk()
self.window.title("Tic-Tac-Toe")
self.clicks = None
self.player = "X"
self.colors = {
"X": "red",
"O": "blue"
}... | Python | zaydzuhri_stack_edu_python |
comment -*- encoding: utf-8 -*-
from django.db import models
comment Create your models here.
class Instrumentos extends Model
begin
set TIPO_INSTRUMENTO = tuple tuple string Cu string Cuerda tuple string Vi string Viento tuple string Pe string Percusion tuple string Ot string Otros
set nombre = call CharField max_leng... | # -*- encoding: utf-8 -*-
from django.db import models
# Create your models here.
class Instrumentos(models.Model):
TIPO_INSTRUMENTO=(
("Cu","Cuerda"),
("Vi","Viento"),
("Pe","Percusion"),
("Ot","Otros"),
)
nombre=models.CharField(max_length=200)
tipo=models.CharField(max_length=200,choices=TIPO_INSTR... | Python | zaydzuhri_stack_edu_python |
function check_flags_and_score
begin
assert sentence_pairs_file or reference_file and candidate_file msg string Reference and candidate files not found, please specify a JSONL file or two text files.
if sentence_pairs_file
begin
set sentence_pairs_generator = call _json_generator sentence_pairs_file
end
else
begin
set ... | def check_flags_and_score():
assert FLAGS.sentence_pairs_file or (
FLAGS.reference_file and FLAGS.candidate_file
), ("Reference and candidate files not found, please specify a JSONL file or "
"two text files.")
if FLAGS.sentence_pairs_file:
sentence_pairs_generator = _json_generator(FLAGS.sentence... | Python | nomic_cornstack_python_v1 |
function create_audit_client self
begin
set host = PLATFORM_HOST
set port = PLATFORM_PORT
set token = PLATFORM_USER_TOKEN
set protocol = PLATFORM_DIGITAL_CLIENT_PROTOCOL
set audit_client = call AuditClient host=host port=port protocol=protocol token=token
info format string Audit Client created: {} list protocol host p... | def create_audit_client(self):
host = self.config.PLATFORM_HOST
port = self.config.PLATFORM_PORT
token = self.config.PLATFORM_USER_TOKEN
protocol = self.config.PLATFORM_DIGITAL_CLIENT_PROTOCOL
audit_client = AuditClient(
host=host, port=port, protocol=protoc... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment # Bias, Variance, and Least Squares #
comment In this chapter we will attempt to answer some general questions about estimators.
comment - How can we measure the accuracy of an estimator?
comment - What factors lead to error in estimation? Can we quantify them?... | #!/usr/bin/env python
# coding: utf-8
# # Bias, Variance, and Least Squares #
# In this chapter we will attempt to answer some general questions about estimators.
#
# - How can we measure the accuracy of an estimator?
# - What factors lead to error in estimation? Can we quantify them?
# - When we have two different ... | Python | zaydzuhri_stack_edu_python |
function create_channels self team_id body **kwargs
begin
comment type: str
comment type: "models.MicrosoftGraphChannel"
comment type: Any
comment type: (...) -> "models.MicrosoftGraphChannel"
comment type: ClsType["models.MicrosoftGraphChannel"]
set cls = pop kwargs string cls none
set error_map = dict 401 ClientAuthe... | def create_channels(
self,
team_id, # type: str
body, # type: "models.MicrosoftGraphChannel"
**kwargs # type: Any
):
# type: (...) -> "models.MicrosoftGraphChannel"
cls = kwargs.pop('cls', None) # type: ClsType["models.MicrosoftGraphChannel"]
error_map = {... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import RPi.GPIO as GPIO
import time
import sys
import dht11
from datetime import datetime
from sender import Sender
comment http://www.piddlerintheroot.com/dht11/
comment initialize GPIO
call setwarnings true
call setmode BCM
comment read data using pin 17
set instance = call DHT11 pin=17
comme... | #!/usr/bin/python
import RPi.GPIO as GPIO
import time
import sys
import dht11
from datetime import datetime
from sender import Sender
# http://www.piddlerintheroot.com/dht11/
# initialize GPIO
GPIO.setwarnings(True)
GPIO.setmode(GPIO.BCM)
# read data using pin 17
instance = dht11.DHT11(pin=17)
# Configure Sender
sen... | Python | zaydzuhri_stack_edu_python |
import pickle
import pandas as pd
import shapely.geometry as shp
import json
set thisRepo = string /home/mattdzugan/Documents/dev/Control Cities/
set interstates = load pickle open thisRepo + string data/interim/InterstatesWithCityIDs.p string rb
set voronoiResults = load pickle open thisRepo + string data/interim/Inte... | import pickle
import pandas as pd
import shapely.geometry as shp
import json
thisRepo = '/home/mattdzugan/Documents/dev/Control Cities/'
interstates = pickle.load(open(thisRepo+"data/interim/InterstatesWithCityIDs.p","rb"))
voronoiResults = pickle.load(open(thisRepo + "data/interim/InterstateVoronoi.p", "rb"))
cities... | Python | zaydzuhri_stack_edu_python |
function GetAllowedAndroidApplications args messages
begin
set allowed_applications = list
for application in get attribute args string allowed_application list or list
begin
set android_application = call V2AndroidApplication sha1Fingerprint=application at string sha1_fingerprint packageName=application at string pa... | def GetAllowedAndroidApplications(args, messages):
allowed_applications = []
for application in getattr(args, 'allowed_application', []) or []:
android_application = messages.V2AndroidApplication(
sha1Fingerprint=application['sha1_fingerprint'],
packageName=application['package_name'])
allow... | Python | nomic_cornstack_python_v1 |
function train self metergroup
begin
comment Inizialise stats and training data:
set stats = list
set onpower_train = call DataFrame columns=list string onpower
set offpower_train = call DataFrame columns=list string offpower
set duration_train = call DataFrame columns=list string duration
comment Calling train_on_chu... | def train(self, metergroup):
# Inizialise stats and training data:
self.stats = []
self.onpower_train = pd.DataFrame(columns=['onpower'])
self.offpower_train = pd.DataFrame(columns=['offpower'])
self.duration_train = pd.DataFrame(columns=['duration'])
# Calling train_on_... | Python | nomic_cornstack_python_v1 |
function correct_ibis ibis
begin
set peaks = cumulative sum np ibis
set peaks_corrected = call correct_peaks peaks 1
set ibis_corrected = call ediff1d peaks_corrected to_begin=0
set ibis_corrected at 0 = ibis_corrected at 1
return ibis_corrected
end function | def correct_ibis(ibis):
peaks = np.cumsum(ibis)
peaks_corrected = correct_peaks(peaks, 1)
ibis_corrected = np.ediff1d(peaks_corrected, to_begin=0)
ibis_corrected[0] = ibis_corrected[1]
return ibis_corrected | Python | nomic_cornstack_python_v1 |
comment encoding:utf-8
class SNode
begin
function __init__ self elem=none next_=none
begin
set elem = elem
set next_ = next_
end function
end class
comment 带空头结点的链栈,即栈顶结点是该空头结点的下一个结点
class LStack
begin
function __init__ self
begin
set S = call SNode
end function
function is_empty self
begin
return next_ == none
end fun... | #encoding:utf-8
class SNode:
def __init__(self, elem=None, next_ = None):
self.elem = elem
self.next_ = next_
# 带空头结点的链栈,即栈顶结点是该空头结点的下一个结点
class LStack:
def __init__(self):
self.S = SNode()
def is_empty(self):
return self.S.next_ == None
def push(self, X):
temp =... | Python | zaydzuhri_stack_edu_python |
function build_tokens_line self
begin
set logical = list
set comments = list
set length = 0
set prev_row = none
set prev_col = none
set mapping = none
for tuple token_type text start end line in tokens
begin
if token_type in SKIP_TOKENS
begin
continue
end
if not mapping
begin
set mapping = list tuple 0 start
end
if t... | def build_tokens_line(self):
logical = []
comments = []
length = 0
prev_row = prev_col = mapping = None
for token_type, text, start, end, line in self.tokens:
if token_type in SKIP_TOKENS:
continue
if not mapping:
m... | Python | nomic_cornstack_python_v1 |
function config_rules self
begin
return get pulumi self string config_rules
end function | def config_rules(self) -> Sequence['outputs.GetCompliancePacksPackConfigRuleResult']:
return pulumi.get(self, "config_rules") | Python | nomic_cornstack_python_v1 |
function copy_after self
begin
return get pulumi self string copy_after
end function | def copy_after(self) -> pulumi.Input[Union['CopyOnExpiryOptionArgs', 'CustomCopyOptionArgs', 'ImmediateCopyOptionArgs']]:
return pulumi.get(self, "copy_after") | Python | nomic_cornstack_python_v1 |
function hyperparameter_search args
begin
set hyper_config = dict string momentum random choice list 0.0 0.4 0.8 0.9 0.95 ; string lr call loguniform 0.001 0.1 ; string batch_size random choice list 8 16 32 64 ; string database database
set max_epochs = 20
set scheduler = call ASHAScheduler metric=string mean_accuracy ... | def hyperparameter_search(args):
hyper_config = {
"momentum": tune.choice([0.0, 0.4, 0.8, 0.9, 0.95]),
"lr": tune.loguniform(1e-3, 1e-1),
"batch_size": tune.choice([8, 16, 32, 64]),
"database": args.database
}
max_epochs = 20
scheduler = ASHAScheduler(
metric="me... | Python | nomic_cornstack_python_v1 |
function fibo
begin
set first = 1
set second = 2
set even_sum = 0
while first < 4000000
begin
set n = first + second
set first = second
set second = n
if n % 2 == 0
begin
set even_sum = even_sum + n
end
end
print even_sum + 2
end function
call fibo | def fibo():
first = 1
second = 2
even_sum = 0
while(first < 4000000):
n =first + second
first = second
second = n
if n % 2 == 0 :
even_sum += n
print(even_sum + 2)
fibo()
| Python | zaydzuhri_stack_edu_python |
import pandas as pd
from sqlalchemy import create_engine
set df = read csv string example.csv
comment write csv
to csv df string my_output.csv index=false
comment You could read from an excel file
comment conda install xlrd
comment pd.read_excel('!Excel_Sample.xlsx', sheetname='Sheet1')
comment df.to_excel('Excel_sampl... | import pandas as pd
from sqlalchemy import create_engine
df = pd.read_csv('example.csv')
# write csv
df.to_csv('my_output.csv', index=False)
# You could read from an excel file
# conda install xlrd
# pd.read_excel('!Excel_Sample.xlsx', sheetname='Sheet1')
# df.to_excel('Excel_sample2.xlsx')
# Read html tables
dat... | Python | zaydzuhri_stack_edu_python |
function get_user_collections
begin
return get session string restricted_collections set
end function | def get_user_collections():
return session.get('restricted_collections', set()) | Python | nomic_cornstack_python_v1 |
function _fix_phidp_from_kdp phidp kdp r gatefilter
begin
set kdp at gate_excluded = 0
set kdp at kdp < - 4 = 0
set kdp at kdp > 15 = 0
set interg = call cumtrapz kdp r axis=1
set phidp at tuple slice : : slice : - 1 : = interg / length r
return tuple phidp kdp
end function | def _fix_phidp_from_kdp(phidp, kdp, r, gatefilter):
kdp[gatefilter.gate_excluded] = 0
kdp[(kdp < -4)] = 0
kdp[kdp > 15] = 0
interg = integrate.cumtrapz(kdp, r, axis=1)
phidp[:, :-1] = interg / (len(r))
return phidp, kdp | Python | nomic_cornstack_python_v1 |
function property_details request property_id
begin
set property = call get_object_or_404 Property pk=property_id
set reserved_dates = list
set reserved_all = filter book_property=property book_check_in__gte=today
for reserved in reserved_all
begin
set delta = book_check_out - book_check_in
for i in range days + 1
beg... | def property_details(request, property_id):
property = get_object_or_404(Property, pk=property_id)
reserved_dates = []
reserved_all = Booking.objects.filter(book_property=property, book_check_in__gte=datetime.date.today())
for reserved in reserved_all:
delta = reserved.book_check_out - reserve... | Python | nomic_cornstack_python_v1 |
comment Incorporating the if statement with a boolean
set x = 10
set y = 4
if x % y == 0
begin
print true
end
else
begin
print false
end
comment While loop
set number = 1
while number < 4
begin
print number
if number == 4
begin
break
end
set number = number + 1
end
comment Incorporating the else statement in the while ... | # Incorporating the if statement with a boolean
x = 10
y = 4
if x % y == 0:
print (True)
else:
print (False)
# While loop
number = 1
while number < 4:
print (number)
if number == 4:
break
number = number + 1
# Incorporating the else statement in the while loop
number = 2
while number < 4... | Python | zaydzuhri_stack_edu_python |
function main_menu
begin
comment Reads the main menu graphics
set main_doc = open string Graphics\Main_menu.txt string rt encoding=string utf8
comment Prints and closes main menu txt document
set main_menu = read main_doc
close main_doc
print main_menu
set difficultiesrule_doc = open string Graphics\Difficultiesrule.tx... | def main_menu():
# Reads the main menu graphics
main_doc = open(
r"Graphics\Main_menu.txt",
"rt",
encoding="utf8",
)
# Prints and closes main menu txt document
main_menu = main_doc.read()
main_doc.close()
print(main_menu)
difficultiesrule_doc = open(
r"G... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment import the relevant libraries
import sys
import time
import pygame
import random
import os
import math
comment from pygame.locals import *
from Vec2d import Vec2d as Vec2d
comment define screen size
set SCREEN = tuple 640 480
comment control Frame Rate
set CLOCK = call Clock
set FPS = 1... | #!/usr/bin/python
# import the relevant libraries
import sys
import time
import pygame
import random
import os
import math
# from pygame.locals import *
from Vec2d import Vec2d as Vec2d
# define screen size
SCREEN = (640, 480)
# control Frame Rate
CLOCK = pygame.time.Clock()
FPS = 100
# define background musicfile
BA... | Python | zaydzuhri_stack_edu_python |
function read_gbq query project_id=string robusta-lab **kwargs
begin
return call read_gbq query project_id credentials=call _get_credentials_gbq keyword kwargs
end function | def read_gbq(query, project_id="robusta-lab", **kwargs):
return pandas_gbq.read_gbq(
query, project_id, credentials=_get_credentials_gbq(), **kwargs
) | Python | nomic_cornstack_python_v1 |
string Tools to work with units
import numpy as np
function c_SI_to_SIM concentration_mol_L sigma_in_meter exponent=1.0
begin
string convert concentration from SI to simulation
from simulation_tools import fundamental_constants
comment [sigma_per_meter] = sigma/m
set sigma_per_meter = 1.0 / sigma_in_meter
comment [sigm... | """Tools to work with units"""
import numpy as np
def c_SI_to_SIM(concentration_mol_L, sigma_in_meter, exponent=1.0):
""" convert concentration from SI to simulation"""
from simulation_tools import fundamental_constants
# [sigma_per_meter] = sigma/m
sigma_per_meter = 1.0 / sigma_in_meter
# [sigmacu... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import os
import view.game_view as gv
import view.snake_config_view as scv
import view.main_view as mv
from multiprocessing import Pipe
from const import *
from threading import Thread
function send_exit_msg queue
begin
set msg = call MsgType type=MSG_SNACK msgtype=CLOSE_DLG msg=call getpi... | # -*- coding: utf-8 -*-
import os
import view.game_view as gv
import view.snake_config_view as scv
import view.main_view as mv
from multiprocessing import Pipe
from const import *
from threading import Thread
def send_exit_msg(queue):
msg = MsgType(type=MsgType.MSG_SNACK, msgtype=MsgType.CLOSE_DLG, msg=os.getpid()... | Python | zaydzuhri_stack_edu_python |
import os
import logging
from openpyxl import load_workbook
from openpyxl import Workbook
comment from openpyxl.comments import Comment
comment from openpyxl.drawing.image import Image
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font , Color , PatternFill , Alignment
set logger = call getLo... | import os
import logging
from openpyxl import load_workbook
from openpyxl import Workbook
# from openpyxl.comments import Comment
# from openpyxl.drawing.image import Image
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font, Color, PatternFill, Alignment
logger = logging.getLogger('logger')... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set _categories : Dict = CATEGORIES
set _kaomoji : str = string
set _template : str = TEMPLATE
end function | def __init__(self) -> None:
self._categories: Dict = config.CATEGORIES
self._kaomoji: str = ""
self._template: str = config.TEMPLATE | Python | nomic_cornstack_python_v1 |
comment Q1
comment num1#num2#num3#num4#num5#num6#cpfApostador#numAposta#loterica
comment Subprograma
function armazenandoDadosAposta arquivo vals
begin
set dados = open arquivo string r
set linha = read line dados
comment print(linha)
if linha == string
begin
print string VAZIO – Nenhuma aposta registrada!!
end
set ar... | # Q1
# num1#num2#num3#num4#num5#num6#cpfApostador#numAposta#loterica
# Subprograma
def armazenandoDadosAposta(arquivo, vals):
dados = open(arquivo, "r")
linha = dados.readline()
# print(linha)
if linha == "":
print("VAZIO – Nenhuma aposta registrada!!")
array6 = []
array5 = []
array4 = []
array3 ... | Python | zaydzuhri_stack_edu_python |
for step in range 3
begin
print step + string : + names at step
end | for step in range(3):
print(step + " : " + names[step])
| Python | zaydzuhri_stack_edu_python |
comment 开发者:Lingyu
comment 开发时间:2020/12/1 21:25
print string -------------选择结构--------
comment 如果。。。就。。。
print string -------------单分支结构--------
set money = 1000
set s = decimal input string 您要取出的金额为:
comment 比较运算符,:加回车
if money >= s
begin
comment 以下均Tab,表示在if条件分支内
print string 交易成功
set money = money - s
print string 您... | # 开发者:Lingyu
# 开发时间:2020/12/1 21:25
print('-------------选择结构--------')
print('-------------单分支结构--------') # 如果。。。就。。。
money = 1000
s = float(input('您要取出的金额为:'))
if money >= s: # 比较运算符,:加回车
print('交易成功') # 以下均Tab,表示在if条件分支内
money = money - s
print('您的余额为:', money)
print('交易结束')
print('--... | Python | zaydzuhri_stack_edu_python |
function boundingBox self
begin
set it = iterate self
set result = call boundingBox
for dart in it
begin
set result = result ? call boundingBox
end
return result
end function | def boundingBox(self):
it = iter(self)
result = it.next().boundingBox()
for dart in it:
result |= dart.edge().boundingBox()
return result | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Jan 28 12:13:34 2020 @author: Akanksha
comment K-Nearest Neighbors (K-NN)
comment Importing the libraries
import json
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
comment from sklearn.pipeline import Pipeline
from collections import Counter
c... | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 12:13:34 2020
@author: Akanksha
"""
# K-Nearest Neighbors (K-NN)
# Importing the libraries
import json
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#from sklearn.pipeline import Pipeline
from collections import Counter
# Importin... | Python | zaydzuhri_stack_edu_python |
for x in N
begin
print x end=string
end | for x in N:
print(x, end="")
| Python | zaydzuhri_stack_edu_python |
function test_bad_command
begin
with raises AttributeError
begin
call Arguments token=string abc slug=TEST_SLUG tag=TEST_TAG command=string bad
end
end function | def test_bad_command():
with pytest.raises(AttributeError):
Arguments(token='abc', slug=TEST_SLUG, tag=TEST_TAG, command='bad') | Python | nomic_cornstack_python_v1 |
function setup args
begin
set cfg = call get_cfg
call merge_from_file config_file
call merge_from_list opts
call freeze
call default_setup cfg args
comment if you don't like any of the default setup, write your own setup code
return cfg
end function | def setup(args):
cfg = get_cfg()
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
default_setup(
cfg, args
) # if you don't like any of the default setup, write your own setup code
return cfg | Python | nomic_cornstack_python_v1 |
function handle_disconnected self
begin
if keepalive != none
begin
call cancel
set keepalive = none
end
if password == string guest and starts with username string Guest
begin
set username = string guest
end
set _completed_models = false
set _completed_tags = false
if not _manual_disconnect
begin
print string Disconnec... | def handle_disconnected(self):
if self.keepalive != None:
self.keepalive.cancel()
self.keepalive = None
if self.password == "guest" and self.username.startswith("Guest"):
self.username = "guest"
self._completed_models = False
self._completed_tag... | Python | nomic_cornstack_python_v1 |
function score uv_fits_path mdl_path stokes=string I bmaj=none
begin
set stokes = upper stokes
if stokes not in tuple string I string RR string LL
begin
raise exception string Only stokes I, RR or LL are supported!
end
if bmaj is not none
begin
set c = pi * bmaj * mas_to_rad ^ 2 / 4 * log 2
end
else
begin
set c = 1.0
e... | def score(uv_fits_path, mdl_path, stokes='I', bmaj=None):
stokes = stokes.upper()
if stokes not in ('I', 'RR', 'LL'):
raise Exception("Only stokes I, RR or LL are supported!")
if bmaj is not None:
c = (np.pi*bmaj*mas_to_rad)**2/(4*np.log(2))
else:
c = 1.0
# Loading test dat... | Python | nomic_cornstack_python_v1 |
for name in names
begin
set key = length name
if key not in d
begin
set d at key = list
end
append d at key name
end
print d
comment 1) Loop through the list of names
comment 2) Set the variable key to the length of the name
comment 3) If the length of that particular name being looped through at the moment does not a... | for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)
print(d)
# 1) Loop through the list of names
# 2) Set the variable key to the length of the name
# 3) If the length of that particular name being looped through at the moment does not already exist, set the value of that key to a... | Python | zaydzuhri_stack_edu_python |
from sqlalchemy.orm import relationship , sessionmaker
from sqlalchemy import create_engine
from database import *
set engine = call create_engine string sqlite:///crudlab.db
call create_all engine
set bind = engine
set DBSession = call sessionmaker bind=engine
set session = call DBSession
set hobbit = call Book title=... | from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
from database import *
engine = create_engine('sqlite:///crudlab.db')
Base.metadata.create_all(engine)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
hobbit = Book(
title = "The Hobbi... | Python | zaydzuhri_stack_edu_python |
function get_index self
begin
set index = call curselection at 0
return index
end function | def get_index(self):
index = self._listbox.curselection()[0]
return index | Python | nomic_cornstack_python_v1 |
function draw_shape_rounded_rectangle self rect xform colour
begin
for shape in call as_arcs_lines
begin
call get attribute self string draw_shape_%s % type shape xform colour
end
end function | def draw_shape_rounded_rectangle(self, rect, xform, colour):
for shape in rect.as_arcs_lines():
getattr(self, 'draw_shape_%s' % shape.type)(shape, xform, colour) | Python | nomic_cornstack_python_v1 |
function charger fichier
begin
string Charge le fichier spécifié. Parameters ---------- fichier : nom du fichier texte. Returns ------- texte : contenu du fichier texte.
with open fichier encoding=string utf-8 as file2read
begin
set texte = read file2read
return strip texte
end
end function
function enregistrer texte f... | def charger(fichier: str) -> str:
"""Charge le fichier spécifié.
Parameters
----------
fichier :
nom du fichier texte.
Returns
-------
texte : contenu du fichier texte.
"""
with open(fichier, encoding='utf-8') as file2read:
texte = file2read.read()
return te... | Python | zaydzuhri_stack_edu_python |
function getFeatures gdf
begin
import json
return list loads to json gdf at string features at 0 at string geometry
end function | def getFeatures(gdf):
import json
return [json.loads(gdf.to_json())['features'][0]['geometry']] | Python | nomic_cornstack_python_v1 |
string convergence.py version 1.
import os
comment for writing to excel sheets
import xlwt
comment for reading from excel sheets
import xlrd
import re
import numpy
import matplotlib.pyplot as plt
from clean import findSpeakers
function createSectionDicts filename convergence_path
begin
comment find number of words in t... | '''
convergence.py version 1.
'''
import os
import xlwt # for writing to excel sheets
import xlrd # for reading from excel sheets
import re
import numpy
import matplotlib.pyplot as plt
from clean import findSpeakers
def createSectionDicts(filename, convergence_path):
# find number of words in text
stream = ... | Python | zaydzuhri_stack_edu_python |
function setup user=string node3
begin
set user = user
set password = string icssda
end function | def setup(user='node3'):
env.user = user
env.password = 'icssda' | Python | nomic_cornstack_python_v1 |
function getCreatedTime self
begin
return get base string created_time list
end function | def getCreatedTime(self):
return self.base.get("created_time", []) | Python | nomic_cornstack_python_v1 |
comment Замена тэгов средствами BeautifulSoup'а
from bs4 import BeautifulSoup
with open string index.html as fp
begin
set soup = call BeautifulSoup fp
comment находим первый в очереди <span>. tag здесь нерезервированное слово.
set tag = span
comment меняем <span> на <div>
set name = string div
end
comment print(soup)
p... | #Замена тэгов средствами BeautifulSoup'а
from bs4 import BeautifulSoup
with open("index.html") as fp:
soup = BeautifulSoup(fp)
tag = soup.span #находим первый в очереди <span>. tag здесь нерезервированное слово.
tag.name = "div" #меняем <span> на <div>
#print(soup)
print(tag)
| Python | zaydzuhri_stack_edu_python |
import os
import re
set name_patten = string [(](.*?)[)]
set path_patten = string [\[](.*?)[\]]
with open string ./SUMMARY.md string r encoding=string utf-8 as f
begin
set names = find all read f
end
for name in names
begin
if name
begin
print name
end
end
comment f = open(name, 'w',encoding='utf-8')
comment f.close() | import os
import re
name_patten = r'[(](.*?)[)]'
path_patten = r'[\[](.*?)[\]]'
with open('./SUMMARY.md','r', encoding='utf-8') as f:
names = re.compile(name_patten).findall(f.read())
for name in names:
if name:
print(name)
# f = open(name, 'w',encoding='utf-8')
# f.close() | Python | zaydzuhri_stack_edu_python |
function intersection L1 L2
begin
set D = L1 at 0 * L2 at 1 - L1 at 1 * L2 at 0
set Dx = L1 at 2 * L2 at 1 - L1 at 1 * L2 at 2
set Dy = L1 at 0 * L2 at 2 - L1 at 2 * L2 at 0
if D != 0
begin
set x = Dx / D
set y = Dy / D
return tuple x y
end
else
begin
return false
end
end function | def intersection(L1, L2):
D = L1[0] * L2[1] - L1[1] * L2[0]
Dx = L1[2] * L2[1] - L1[1] * L2[2]
Dy = L1[0] * L2[2] - L1[2] * L2[0]
if D != 0:
x = Dx / D
y = Dy / D
return x, y
else:
return False | Python | nomic_cornstack_python_v1 |
from abstract_rule import AbstractRule , ResultRule
class LengthRule extends AbstractRule
begin
set MIN_LEN_FAILED = string Required minimum is nine char
function apply self str_pwd
begin
return if expression length str_pwd >= 9 and length str_pwd <= 20 then next str_pwd else call ResultRule false MIN_LEN_FAILED
end fu... | from .abstract_rule import AbstractRule, ResultRule
class LengthRule(AbstractRule):
MIN_LEN_FAILED = "Required minimum is nine char"
def apply(self, str_pwd: str) -> ResultRule:
return self.next(str_pwd) if len(str_pwd) >= 9 and len(str_pwd) <= 20 else ResultRule(False, self.MIN_LEN_FAILED)
| Python | zaydzuhri_stack_edu_python |
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
function check_events game_settings screen ship bullets stats play_button aliens sb
begin
string Respond to keypresses and mouse events :param sb: Scoreboard :param play_button: :param aliens: Alien :param stats: GameStats... | import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
def check_events(game_settings, screen, ship, bullets, stats, play_button,
aliens, sb):
"""Respond to keypresses and mouse events
:param sb: Scoreboard
:param play_button:
:param aliens:... | Python | zaydzuhri_stack_edu_python |
while i == 0
begin
set placa = input string Qual a placa do veículo (XXXXXXX)?
while placa != string
begin
set instante1 = integer input string Passou pela câmera 1 em qual instante (segundos)?
set instante2 = integer input string Passou pela câmera 2 em qual instante (segundos)?
comment m/s
set vel_media = dis_cam / ... | while i == 0:
placa = input("Qual a placa do veículo (XXXXXXX)? ")
while placa != (""):
instante1 = int(input("Passou pela câmera 1 em qual instante (segundos)?"))
instante2 = int(input("Passou pela câmera 2 em qual instante (segundos)?"))
vel_media = dis_cam/(instante2 - instante1) #m/s... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.