code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function methodsKN
begin
return call render_template string methodsKN.html year=year
end function | def methodsKN():
return render_template(
'methodsKN.html',
year=datetime.now().year,
) | Python | nomic_cornstack_python_v1 |
function add_raw_annotation binary_addr text inline=false priority=none
begin
append annotations at binary_addr call Annotation text inline priority
end function | def add_raw_annotation(binary_addr, text, inline=False, priority=None):
annotations[binary_addr].append(Annotation(text, inline, priority)) | Python | nomic_cornstack_python_v1 |
function quickSort arr
begin
function partition arr left right
begin
set pivot = arr at right
set i = left - 1
for j in range left right
begin
if arr at j <= pivot
begin
set i = i + 1
set tuple arr at i arr at j = tuple arr at j arr at i
end
end
set tuple arr at i + 1 arr at right = tuple arr at right arr at i + 1
retu... | def quickSort(arr):
def partition(arr, left, right):
pivot = arr[right]
i = left - 1
for j in range(left, right):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[right] = arr[right], arr[i+1]
return i + 1
... | Python | jtatman_500k |
function prepare_database mongo_uri db_name
begin
global db client
if client is not none
begin
return tuple client db
end
set client = call MongoClient mongo_uri
set db = client at db_name
call create_zlib_collection db string users
call ensure_index db string users string created_at ASCENDING
return tuple client db
en... | def prepare_database(mongo_uri, db_name):
global db, client
if client is not None:
return client, db
client = pymongo.MongoClient(mongo_uri)
db = client[db_name]
create_zlib_collection(db, "users")
ensure_index(db, 'users', 'created_at', pymongo.ASCENDING)
return client, db | Python | nomic_cornstack_python_v1 |
function ph_water self ph_water
begin
set _ph_water = ph_water
end function | def ph_water(self, ph_water):
self._ph_water = ph_water | Python | nomic_cornstack_python_v1 |
function start_acq self session params=none
begin
if params is none
begin
set params = dict
end
set f_sample = get params string sampling_frequency 2.5
set sleep_time = 1 / f_sample - 0.01
with call acquire_timeout 0 job=string acq as acquired
begin
if not acquired
begin
warn format string Could not start acq because ... | def start_acq(self, session, params=None):
if params is None:
params = {}
f_sample = params.get('sampling_frequency', 2.5)
sleep_time = 1/f_sample - 0.01
with self.lock.acquire_timeout(0, job='acq') as acquired:
if not acquired:
self.log.warn("Co... | Python | nomic_cornstack_python_v1 |
function upgrade_1_0_to_1_1 setuptool
begin
call runAllImportStepsFromProfile string profile-quintagroup.plonegooglesitemaps:upgrade_1_0_to_1_1
end function | def upgrade_1_0_to_1_1(setuptool):
setuptool.runAllImportStepsFromProfile('profile-quintagroup.plonegooglesitemaps:upgrade_1_0_to_1_1') | Python | nomic_cornstack_python_v1 |
import random
class Game extends object
begin
set count_player = 1
function __init__ self graphic
begin
set graphic = graphic
end function
decorator staticmethod
function display_instruct
begin
string print the game instruction. :return:
end function
print string Wellcome to game seabattle ship play you can in 2 stages... | import random
class Game(object):
count_player = 1
def __init__(self, graphic):
self.graphic = graphic
@staticmethod
def display_instruct():
"""
print the game instruction.
:return:
"""
print("""
Wellcome to game seabattle ship
play you ... | Python | zaydzuhri_stack_edu_python |
function divide_string sentence
begin
set parts = split sentence string
return parts
end function
function sort_words words
begin
return sorted words
end function
function upper_word word
begin
return upper word
end function
function lower_word word
begin
return lower word
end function
function sort_sentence sentence
b... | def divide_string(sentence):
parts = sentence.split(' ')
return parts
def sort_words(words):
return sorted(words)
def upper_word(word):
return word.upper()
def lower_word(word):
return word.lower()
def sort_sentence(sentence):
words = divide_string(sentence)
return sort_words(words)
#se... | Python | zaydzuhri_stack_edu_python |
function create_returns_tear_sheet factor_data long_short=true group_neutral=false by_group=false
begin
string Creates a tear sheet for returns analysis of a factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values ... | def create_returns_tear_sheet(factor_data,
long_short=True,
group_neutral=False,
by_group=False):
"""
Creates a tear sheet for returns analysis of a factor.
Parameters
----------
factor_data : pd.DataFrame - M... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Created on Fri Feb 5 16:13:43 2021 @author: v-mpurvis
comment Gets Lineup Rotations from Basketball Monster
set base_url = string https://basketballmonster.com/DepthCharts.aspx
import pandas as pd
import os
from bs4 import BeautifulSoup
import requests
from selenium import webdriver... | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 5 16:13:43 2021
@author: v-mpurvis
"""
# Gets Lineup Rotations from Basketball Monster
base_url = 'https://basketballmonster.com/DepthCharts.aspx'
import pandas as pd
import os
from bs4 import BeautifulSoup
import requests
from selenium import webdrive... | Python | zaydzuhri_stack_edu_python |
function auto_excerpt self
begin
from ebdata.textmining.treeutils import make_tree
set tree = call make_tree html
if rss_full_entry
begin
from ebdata.templatemaker.textlist import html_to_paragraph_list
set paras = call html_to_paragraph_list tree
end
else
begin
if strip_noise
begin
from ebdata.templatemaker.clean impo... | def auto_excerpt(self):
from ebdata.textmining.treeutils import make_tree
tree = make_tree(self.html)
if self.seed.rss_full_entry:
from ebdata.templatemaker.textlist import html_to_paragraph_list
paras = html_to_paragraph_list(tree)
else:
if sel... | Python | nomic_cornstack_python_v1 |
function print_triangle rows order
begin
if order == string ascending
begin
set spaces = rows - 1
set asterisks = 1
set step = - 1
end
else
begin
set spaces = 0
set asterisks = rows
set step = 1
end
for _ in range rows
begin
print string * spaces + string * * asterisks
set spaces = spaces + step
set asterisks = asteri... | def print_triangle(rows, order):
if order == "ascending":
spaces = rows - 1
asterisks = 1
step = -1
else:
spaces = 0
asterisks = rows
step = 1
for _ in range(rows):
print(" " * spaces + "*" * asterisks)
spaces += step
asterisks -= step... | Python | jtatman_500k |
function checkSurroundings self
begin
set surfs = list comprehension x for x in overlapping_sprites if x in surfaces
if length surfs == 1
begin
if left < left - 1
begin
set dx = 1
end
else
if right > right + 1
begin
set dx = - 1
end
end
end function | def checkSurroundings(self):
surfs = [x for x in self.overlapping_sprites if x in self.game.surfaces]
if len(surfs) == 1:
if self.left < surfs[0].left - 1:
self.dx = 1
elif self.right > surfs[0].right + 1:
self.dx = -1 | Python | nomic_cornstack_python_v1 |
function test_hikizan self
begin
set value1 = 2
set value2 = 12
set expected = - 10
set actual = call hikizan value1 value2
assert equal expected actual
end function | def test_hikizan(self):
value1 = 2
value2 = 12
expected = -10
actual = keisan.hikizan(value1, value2)
self.assertEqual(expected, actual) | Python | nomic_cornstack_python_v1 |
function _compute_total_seven_rolls self
begin
for rec in self
begin
if thousands_per_roll
begin
set total_seven_rolls = thousands_per_roll * 7
end
end
end function | def _compute_total_seven_rolls(self):
for rec in self:
if rec.thousands_per_roll:
rec.total_seven_rolls = rec.thousands_per_roll * 7 | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
class printStuffs
begin
function printJointAngle self txtfile digit_to_plot data_path
begin
set j1List = list
set j2List = list
set j3List = list
set indexList = list
comment read a row in every 10 rows, starting from the row =(digit_to_plot)
for line in re... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class printStuffs():
def printJointAngle(self, txtfile, digit_to_plot, data_path):
j1List=[]
j2List=[]
j3List=[]
indexList=[]
for line in open(data_path+txtfile, "r").readlines()[digit_to_plot::10]: #... | Python | zaydzuhri_stack_edu_python |
function load_json path name
begin
if string .json not in name
begin
set name = name + string .json
end
with open join path path name string r as json_file
begin
return load json json_file
end
end function | def load_json(path, name):
if '.json' not in name:
name += '.json'
with open(os.path.join(path, name), 'r') as json_file:
return json.load(json_file) | Python | nomic_cornstack_python_v1 |
from players.weight_player import TileWeightPlayer
from players.minmoves_player import MinMovesPlayer
from task import *
from curriculum import *
from tqdm import tqdm
import numpy as np
import scipy.stats as stats
from reversi import ReversiState
from pathlib import Path
import matplotlib.pyplot as plt
import argparse... | from players.weight_player import TileWeightPlayer
from players.minmoves_player import MinMovesPlayer
from task import *
from curriculum import *
from tqdm import tqdm
import numpy as np
import scipy.stats as stats
from reversi import ReversiState
from pathlib import Path
import matplotlib.pyplot as plt
import argparse... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function wiggleMaxLength self nums
begin
string :type nums: List[int] :rtype: int
comment DP
if not nums
begin
return 0
end
set asc = list 1 * length nums
set dec = list 1 * length nums
for i in range 1 length nums
begin
for j in range i
begin
if nums at j < nums at i
begin
set asc a... | class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# DP
if not nums:
return 0
asc = [1] * len(nums)
dec = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
... | Python | zaydzuhri_stack_edu_python |
import os
import pathlib
import urllib
import urllib.request
import shutil
import random
import zipfile
set TEMP_FILENAME = string tmp.zip
function download_data out_path csv_filename url force=false
begin
string downloads the data to the specified out_path
set dir_path = call Path out_path
make directory dir_path exis... | import os
import pathlib
import urllib
import urllib.request
import shutil
import random
import zipfile
TEMP_FILENAME = "tmp.zip"
def download_data(out_path, csv_filename, url, force=False):
""" downloads the data to the specified out_path """
dir_path = pathlib.Path(out_path)
dir_path.mkdir(exist_ok... | Python | zaydzuhri_stack_edu_python |
import sys
set n = integer strip read line stdin
for i in range n
begin
set m = integer strip read line stdin
set players = list
for j in range m
begin
set tuple value name = split read line stdin
append players tuple integer value name
end
sort players key=lambda x -> tuple x at 0 x at 1 reverse=true
print players at... | import sys
n = int(sys.stdin.readline().strip())
for i in range(n):
m = int(sys.stdin.readline().strip())
players = []
for j in range(m):
value, name = sys.stdin.readline().split()
players.append((int(value), name))
players.sort(key=lambda x: (x[0], x[1]), reverse=True)
print(play... | Python | zaydzuhri_stack_edu_python |
function get_file_states self
begin
set states = dict
for file in call get_files
begin
set states at call get_path = call get_file_state file
end
return states
end function | def get_file_states(self):
states = {}
for file in self.app.get_files():
states[file.get_path()] = self.get_file_state(file)
return states | Python | nomic_cornstack_python_v1 |
string Britni Canale SoftDev1 pd6 K8 -- Fill Yer Flask 2018-09-19
from flask import Flask
set app = call Flask __name__
decorator call route string /
comment creating home page of web page
function hello_world
begin
return string <!DOCTYPE html><html><head><title>BRITNI CANALE</title></head><body><h1> This is a website... | '''Britni Canale
SoftDev1 pd6
K8 -- Fill Yer Flask
2018-09-19'''
from flask import Flask
app = Flask(__name__)
@app.route("/") ##creating home page of web page
def hello_world():
return "<!DOCTYPE html><html><head><title>BRITNI CANALE</title></head><body><h1> This is a website that contains some information</h1... | Python | zaydzuhri_stack_edu_python |
function integrate func a b dt=0.001
begin
set area = 0.0
while a < b
begin
set area = area + call func a + 0.5 * dt * dt
set a = a + dt
end
return area
end function | def integrate(func: Integrable, a: float, b: float, dt: float=0.001) -> float:
area = 0.0
while a < b:
area += func(a + 0.5 * dt) * dt
a += dt
return area | Python | nomic_cornstack_python_v1 |
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons , make_circles , make_classification
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm impor... | import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import ... | Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
comment 会话拥有并管理程序运行时的所有资源
import tensorflow as tf
set mat1 = call constant list list 3 3
set mat2 = call constant list list 2 list 2
set product = matrix multiply mat1 mat2
comment 模式1
comment 当程序因为异常退出时,关闭会话的函数可能就不会被执行从而导致资源泄漏
comment sess = tf.Session() # 创建会话
comment print(sess.run(product)) # 执... | # coding:utf-8
# 会话拥有并管理程序运行时的所有资源
import tensorflow as tf
mat1 = tf.constant([[3, 3]])
mat2 = tf.constant([[2],
[2]])
product = tf.matmul(mat1, mat2)
# 模式1
# 当程序因为异常退出时,关闭会话的函数可能就不会被执行从而导致资源泄漏
# sess = tf.Session() # 创建会话
# print(sess.run(product)) # 执行运算
# sess.close() # 关闭会话
# 模式2
# 为了解决异常退出... | Python | zaydzuhri_stack_edu_python |
comment Jordan Lemite
comment CSMC 140-2
comment p3.16
set string1 = input string word:
set string2 = input string word:
set string3 = input string word:
if string1 >= string2 and string2 >= string3
begin
print string1 string2 string3
end
else
if string2 < string1
begin
print string2 string1
end
else
if string3 > strin... | #Jordan Lemite
#CSMC 140-2
#p3.16
string1 = input("word: ")
string2 = input("word: ")
string3 = input("word: ")
if string1 >= string2 and string2 >= string3 :
print(string1,string2,string3)
elif string2 < string1 :
print(string2,string1)
elif string3 > string2 :
print(string3,string2)
elif string1 > stri... | Python | zaydzuhri_stack_edu_python |
from rest_framework import serializers
from ext.rest_framework.serializers import BaseModelSerializer
from models import Person , User
class PersonSerializer extends BaseModelSerializer
begin
set school = call PrimaryKeyRelatedField read_only=true
set first_name = call CharField
set surname = call CharField
set full_na... | from rest_framework import serializers
from ext.rest_framework.serializers import BaseModelSerializer
from .models import Person, User
class PersonSerializer(BaseModelSerializer):
school = serializers.PrimaryKeyRelatedField(read_only=True)
first_name = serializers.CharField()
surname = serializers.CharField()
... | Python | zaydzuhri_stack_edu_python |
function Move self request context
begin
call set_code UNIMPLEMENTED
call set_details string Method not implemented!
raise call NotImplementedError string Method not implemented!
end function | def Move(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string ITS 3210 Introduction to Scripting Languages Governor's State University Adam Balauskas Assignment 3 This program should receive two filenames from the user from the command line arguments used when launching the script, and copy the first file into the second. Use the file provided ... | #!/usr/bin/env python
"""
ITS 3210 Introduction to Scripting Languages
Governor's State University
Adam Balauskas
Assignment 3
This program should receive two filenames from the user from the command line arguments
used when launching the script, and copy the first file into the second. Use the file
provided (infile.... | Python | zaydzuhri_stack_edu_python |
function remove_duplicate_words text
begin
set words = list
for word in split text
begin
if not words or word != words at - 1
begin
append words word
end
end
return join string words
end function
set text = string The the quick brown fox fox jumps over the lazy dog dog
set text = call remove_duplicate_words text
prin... | def remove_duplicate_words(text):
words = []
for word in text.split():
if not words or word != words[-1]:
words.append(word)
return " ".join(words)
text = "The the quick brown fox fox jumps over the lazy dog dog"
text = remove_duplicate_words(text)
print(text) | Python | jtatman_500k |
from project.technology.technology import Technology
string The Laptop class should have the following attributes: • memory – float • memory_taken – float The class should have method install_software(software, software_memory): • check if you have memory to install the software and return the memory left after the ins... | from project.technology.technology import Technology
"""
The Laptop class should have the following attributes:
• memory – float
• memory_taken – float
The class should have method install_software(software, software_memory):
• check if you have memory to install the software and return the memory left afte... | Python | zaydzuhri_stack_edu_python |
try
begin
set fhandler = open fname
end
except any
begin
print string Bad file name, please input valid, like mbox-short.txt
call quit
end
set count = 0
for line in fhandler
begin
set line = right strip line
if not starts with line string From
begin
continue
end
set line = split line
print line at 1
set count = count +... | try:
fhandler = open(fname)
except:
print("Bad file name, please input valid, like mbox-short.txt")
quit()
count = 0
for line in fhandler:
line = line.rstrip()
if not line.startswith('From '):
continue
line = line.split()
print(line[1])
count = count + 1
print('There were',cou... | Python | zaydzuhri_stack_edu_python |
function parse_prefix s
begin
comment Task 7.3.1
comment Base Case 1: empty string
if s == string
begin
comment TODO check what they want
return tuple call Term string string
end
set cur_token = s at 0
comment Base Case 2: s is a variable
if call is_variable cur_token
begin
return call get_variable s
end
comment Base... | def parse_prefix(s: str) -> Tuple[Term, str]:
# Task 7.3.1
# Base Case 1: empty string
if s == '':
return Term(''), '' # TODO check what they want
cur_token = s[0]
# Base Case 2: s is a variable
if is_variable(cur_token):
return get_vari... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment Overplot transcription results on the original image.
import argparse
import pickle
from PIL import Image
import matplotlib
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.patches
import numpy
set par... | #!/usr/bin/env python
# Overplot transcription results on the original image.
import argparse
import pickle
from PIL import Image
import matplotlib
from matplotlib.backends.backend_agg import \
FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.patches
import numpy
p... | Python | zaydzuhri_stack_edu_python |
function available self
begin
return _available
end function | def available(self):
return self._available | Python | nomic_cornstack_python_v1 |
function get_explanatory_variable self
begin
return _explanatory_variables at 0
end function | def get_explanatory_variable(self):
return self._explanatory_variables[0] | Python | nomic_cornstack_python_v1 |
function compute_gradients images model class_index **extra
begin
set num_classes = shape at 1
set expected_output = ones list 1 14 14 14 1
comment if gt is not None:
comment expected_output = gt
comment else:
comment expected_output = tf.one_hot([class_index] * images.shape[0], num_classes)
comment import ipdb; ipdb.s... | def compute_gradients(images, model, class_index, **extra):
num_classes = model.output.shape[1]
expected_output = tf.ones([1, 14, 14, 14, 1])
#if gt is not None:
# expected_output = gt
#else:
# expected_output = tf.one_hot([class_index] * images.shape[0], num_cla... | Python | nomic_cornstack_python_v1 |
function get_payment self money from_person
begin
set _bill = _bill + money
print string { self } received $ { money } from { from_person }
end function | def get_payment(self, money: float, from_person: Waiter):
self._bill += money
print(f'{self} received ${money} from {from_person}') | Python | nomic_cornstack_python_v1 |
function db_read_sequences_test
begin
set json_data = open DB_INFO_TEST
set data = load json json_data
set sequences = keys data at string videos
return sequences
end function | def db_read_sequences_test():
json_data = open(__C.FILES.DB_INFO_TEST)
data = json.load(json_data)
sequences = data['videos'].keys()
return sequences | Python | nomic_cornstack_python_v1 |
string Claramente se puede ver que se está tratando con una lista enlazada, por lo que esta es la estructura de datos usada en este algoritmo.
class Alumno
begin
string Complejidad constructor, 3. Ya que se hacen tres declaraciones. En Big O sería O(1)
function __init__ self nombre edad nota
begin
set nombre = nombre
s... | """
Claramente se puede ver que se está tratando con una lista enlazada, por lo que esta
es la estructura de datos usada en este algoritmo.
"""
class Alumno:
"""
Complejidad constructor, 3. Ya que se hacen tres declaraciones.
En Big O sería O(1)
"""
def __init__(self, nombre, edad, n... | Python | zaydzuhri_stack_edu_python |
function queryUniprot accessionList resFormat=string xml
begin
set params = dict string from string ACC ; string to string ACC ; string format resFormat ; string query join string accessionList
return post string https://www.uniprot.org/uploadlists/ params
end function | def queryUniprot(accessionList, resFormat = "xml"):
params = {
'from': 'ACC',
'to': 'ACC',
'format': resFormat,
'query':' '.join(accessionList)
}
return requests.post('https://www.uniprot.org/uploadlists/', params) | Python | nomic_cornstack_python_v1 |
function max_retries self
begin
if not _max_retries
begin
return call integer call getenv string BACKOFF_DEFAULT_TRIES string 3
end
return _max_retries
end function | def max_retries(self):
if not self._max_retries:
return validators.integer(os.getenv('BACKOFF_DEFAULT_TRIES', '3'))
return self._max_retries | Python | nomic_cornstack_python_v1 |
function surface_force p N A
begin
set F_mag = p * A
set F_x = - F_mag * N at tuple slice : : 0
set F_y = - F_mag * N at tuple slice : : 1
set F_z = - F_mag * N at tuple slice : : 2
set F = T
return F
end function | def surface_force(p, N, A):
F_mag = p * A
F_x = -F_mag * N[:, 0]
F_y = -F_mag * N[:, 1]
F_z = -F_mag * N[:, 2]
F = np.array([F_x, F_y, F_z]).T
return F | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding : utf-8 -*-
comment OCR
class OCR extends object
begin
function __init__ self
begin
set processor = none
end function
function run self
begin
call crop
call touch
end function
end class
class Process extends object
begin
function crop self
begin
raise NotImplementedError
end ... | #!/usr/bin/python
# -*- coding : utf-8 -*-
# OCR
class OCR(object):
def __init__(self):
self.processor = None
def run(self):
self.processor.crop()
self.processor.touch()
class Process(object):
def crop(self):
raise NotImplementedError
def touch(self):
raise ... | Python | zaydzuhri_stack_edu_python |
from pprint import pprint
from collections import Counter
class InputValidator
begin
set vertexlabel_dict = none
set edgelabel_dict = none
set vertex_stats_list = none
set edge_stats_list = none
comment these arrays will store any vertexLabels and edgeLabels that do not belong in the schema
set invalid_vertex_labels = ... | from pprint import pprint
from collections import Counter
class InputValidator():
vertexlabel_dict = None
edgelabel_dict = None
vertex_stats_list = None
edge_stats_list = None
# these arrays will store any vertexLabels and edgeLabels that do not belong in the schema
invalid_vertex_labels = None
invalid_edges = ... | Python | zaydzuhri_stack_edu_python |
function backtrack result k R data L
begin
if k == length data
begin
comment print(R)
append L R at slice : :
end
else
begin
for i in range 0 length data
begin
if result at i == false
begin
append R data at i
set result at i = true
call backtrack result k + 1 R data L
set result at i = false
pop R
end
end
end
end fun... | def backtrack(result, k, R, data, L):
if k == len(data):
# print(R)
L.append(R[:])
else:
for i in range(0, len(data)):
if result[i] == False:
R.append(data[i])
result[i] = True
backtrack(result, k + 1, R, data, L)
... | Python | zaydzuhri_stack_edu_python |
function lyrics_to_vocab_idx lyrics vocab_index
begin
set input_vector = list comprehension get vocab_index word - 1 for word in lyrics
return tensor input_vector dtype=long
end function | def lyrics_to_vocab_idx(lyrics, vocab_index):
input_vector = [vocab_index.get(word, -1) for word in lyrics]
return torch.tensor(input_vector, dtype=torch.long) | Python | nomic_cornstack_python_v1 |
function execution_controls self
begin
return get pulumi self string execution_controls
end function | def execution_controls(self) -> pulumi.Output[Optional['outputs.RemediationConfigurationExecutionControls']]:
return pulumi.get(self, "execution_controls") | Python | nomic_cornstack_python_v1 |
function get_hierarchical_children self GenericParams context=none
begin
return call call_method string OntologyAPI.get_hierarchical_children list GenericParams _service_ver context
end function | def get_hierarchical_children(self, GenericParams, context=None):
return self._client.call_method('OntologyAPI.get_hierarchical_children',
[GenericParams], self._service_ver, context) | Python | nomic_cornstack_python_v1 |
function get_averages
begin
set averages_sql = string SELECT count(*) n, avg(avg_grade_lvl) avg_grade_lvl, avg(avg_sentences) avg_sentences FROM ( SELECT cookie_id, avg(avg_grade_lvl) avg_grade_lvl, avg(avg_sentences) avg_sentences FROM email_analysis_results GROUP BY cookie_id) a;
comment First result
return call runS... | def get_averages():
averages_sql = "SELECT count(*) n, avg(avg_grade_lvl) avg_grade_lvl, avg(avg_sentences) avg_sentences FROM ( SELECT cookie_id, avg(avg_grade_lvl) avg_grade_lvl, avg(avg_sentences) avg_sentences FROM email_analysis_results GROUP BY cookie_id) a;"
return runSQL(averages_sql)[0] # First result | Python | nomic_cornstack_python_v1 |
import numpy as np
from uncertainties import ufloat
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
set tuple f Uc = call genfromtxt string mess2.txt unpack=true
set U0 = 51.6
set U = Uc / U0
function h x m b
begin
return 1 / square root 1 + m ^ 2 * x ^ 2 + b
end function
set tuple params covarianc... | import numpy as np
from uncertainties import ufloat
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
f, Uc = np.genfromtxt('mess2.txt', unpack=True)
U0 = 51.6
U = Uc/U0
def h (x,m,b):
return 1/np.sqrt(1+m**2*x**2)+b
params, covariance_matrix = curve_fit(h, f, U)
x_plot = np.linspace(10, 10**... | Python | zaydzuhri_stack_edu_python |
function get_num_params self
begin
if num_params is none
begin
import inspect
set argspec = call getfullargspec call get_code
if varargs or varkw
begin
set num_params = - 1
end
else
begin
set num_params = length args
end
end
return num_params
end function | def get_num_params(self):
if self.num_params is None:
import inspect
argspec = inspect.getfullargspec(self.get_code())
if argspec.varargs or argspec.varkw:
self.num_params = -1
else:
self.num_params = len(argspec.args)
retur... | Python | nomic_cornstack_python_v1 |
function process_covid_dimension spark input_data covid19_lake output_data
begin
comment get filepath to dimensions
set covid_global_data = covid19_lake + string tableau-jhu/csv/COVID-19-Cases.csv
set covid_brazil_data = input_data + string COVID-19-Brazil.csv.gz
set brazil_provinces = input_data + string provinces_bra... | def process_covid_dimension(spark, input_data, covid19_lake, output_data):
# get filepath to dimensions
covid_global_data = covid19_lake + 'tableau-jhu/csv/COVID-19-Cases.csv'
covid_brazil_data = input_data + 'COVID-19-Brazil.csv.gz'
brazil_provinces = input_data + 'provinces_brazil.csv'
# ... | Python | nomic_cornstack_python_v1 |
function deltac self z
begin
set deltac0 = 3.0 * 12.0 * pi ^ 2.0 / 3.0 / 20.0 * 1.0 + 0.0123 * call log10 call om0z z
set deltac = deltac0 * call d1 0 / call d1 z
return deltac
end function | def deltac(self,z):
deltac0 = 3.*(12.*M.pi)**(2./3.)/20.*(1.+0.0123*M.log10(self.om0z(z)))
deltac = deltac0*self.d1(0)/self.d1(z)
return deltac | Python | nomic_cornstack_python_v1 |
import time
set s = time
set a = dict 0 1 ; 1 1
function fibo n
begin
if call has_key n
begin
return a at n
end
else
begin
set nw = call fibo n - 1 + call fibo n - 2
set a at n = nw
return nw
end
end function
set i = 1 | import time
s=time.time()
a={0:1,1:1}
def fibo(n):
if a.has_key(n):
return a[n]
else:
nw=fibo(n-1)+fibo(n-2)
a[n]=nw
return nw
i=1 | Python | zaydzuhri_stack_edu_python |
function message_ports_out self
begin
return call resource_mapper_sptr_message_ports_out self
end function | def message_ports_out(self):
return _my_lte_swig.resource_mapper_sptr_message_ports_out(self) | Python | nomic_cornstack_python_v1 |
comment Sist endret: 17.12.2019 21:46 by Alexandra Jahr Kolstad
import sys
import numpy as np
import matplotlib.pyplot as plt
comment 3D
from mpl_toolkits.mplot3d import Axes3D
comment 3D
import matplotlib as mpl
set dict = dict string Sun string #ffdf22 ; string Mercury string #d3d3d3 ; string Venus string #c04e01 ; s... | #Sist endret: 17.12.2019 21:46 by Alexandra Jahr Kolstad
import sys
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D #3D
import matplotlib as mpl #3D
dict = {"Sun":"#ffdf22" , "Mercury":"#d3d3d3" , "Venus":"#c04e01" , "Earth":"#197619" , "Mars":"#cf6e28" , "Jupiter":"#... | Python | zaydzuhri_stack_edu_python |
function friend_q_learning self time_steps alpha gamma
begin
comment gathered stats
set statistics = list
comment state joint action pair to record q-diff's
set q_stat = tuple q_stat_state DOWN STICK
comment Q-table
set Q = default dictionary lambda -> 1
comment time-step counter
set time_step_counter = 0
comment Star... | def friend_q_learning(self, time_steps, alpha, gamma):
# gathered stats
statistics = list()
# state joint action pair to record q-diff's
q_stat = (self.q_stat_state, Actions.DOWN, Actions.STICK)
# Q-table
Q = defaultdict(lambda: 1)
# time-step counter... | Python | nomic_cornstack_python_v1 |
for m in range 1 10
begin
for n in range 1 10
begin
print m string x n string = m * n
end
print
end | for m in range(1,10):
for n in range(1,10):
print (m,"x",n,"=",m*n)
print( ) | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import csv
import sqlite3
import time
import datetime
import random
set conn = call connect string new.db
set c = call cursor
set x = list
set y = list
set z = list
execute c string SELECT * FROM iot
set data = call fetchall
for row in data
begin
append x row at 0
append y row at 2
ap... | import matplotlib.pyplot as plt
import csv
import sqlite3
import time
import datetime
import random
conn = sqlite3.connect('new.db')
c = conn.cursor()
x = []
y = []
z = []
c.execute('SELECT * FROM iot')
data = c.fetchall()
for row in data:
x.append(row[0])
y.append(row[2])
z.append(row[3])
plt.subplot(... | Python | zaydzuhri_stack_edu_python |
import os
import requests
from BeautifulSoup import BeautifulSoup
from urllib2 import urlopen
from urllib2 import urlparse
import urllib
from datetime import datetime
set twitter = string https://www.twitter.com/
comment this will scrape the twitter handle for users
comment and returns a list with the names
function ge... | import os
import requests
from BeautifulSoup import BeautifulSoup
from urllib2 import urlopen
from urllib2 import urlparse
import urllib
from datetime import datetime
twitter = "https://www.twitter.com/"
# this will scrape the twitter handle for users
# and returns a list with the names
def getUsersFromUser(tHandle):... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
string 3<=len(A)<=100
function largestPerimeter self A
begin
sort A reverse=true
set c_default = 0
for i in range 2 call __len__
begin
if A at i + A at i - 1 > A at i - 2
begin
set c_default = sum A at slice i - 2 : i + 1 :
break
end
end
return c_default
end function
end class
comment 方法二改方法一尝试提速但速... | class Solution:
"""3<=len(A)<=100"""
def largestPerimeter(self, A: List[int]) -> int:
A.sort(reverse=True)
c_default = 0
for i in range(2,A.__len__()):
if A[i]+A[i-1]>A[i-2]:
c_default = sum(A[i-2:i+1])
break
return c_default
##########... | Python | zaydzuhri_stack_edu_python |
import csv
from matplotlib import pyplot as plt
from datetime import datetime
set filename = string 538impeachment.csv
with open filename as f
begin
set reader = reader f
set header_row = next reader
set tuple dates yes no = tuple list list list
for row in reader
begin
set current_date = string parse time row at 1 s... | import csv
from matplotlib import pyplot as plt
from datetime import datetime
filename = '538impeachment.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
dates, yes, no = [], [], [],
for row in reader:
current_date = datetime.strptime(row[1],'%m/%d/%Y' )
... | Python | zaydzuhri_stack_edu_python |
function merge_n_dictionnaries dicts
begin
set result = dicts at 0
for i in range 1 length dicts
begin
set result = call merge_2_dictionnaries result dicts at i
end
return result
end function | def merge_n_dictionnaries(dicts):
result = dicts[0]
for i in range(1, len(dicts)):
result = merge_2_dictionnaries(result, dicts[i])
return result | Python | nomic_cornstack_python_v1 |
function attach self name path
begin
with call begin as con
begin
call exec_driver_sql string ATTACH DATABASE { string path } AS { call _quote name }
end
end function | def attach(self, name: str, path: str | Path) -> None:
with self.begin() as con:
con.exec_driver_sql(f"ATTACH DATABASE {str(path)!r} AS {self._quote(name)}") | Python | nomic_cornstack_python_v1 |
from matplotlib import pyplot as plt
import cv2
import math
function plot_image img title=string fig_size=list 5 3
begin
figure figsize=fig_size
title plt title fontsize=12
axis string off
image show call cvtColor img COLOR_BGR2RGB
end function
function plot_matches img1 keypoints1 img2 keypoints2 matches fig_size=lis... | from matplotlib import pyplot as plt
import cv2
import math
def plot_image(img, title='', fig_size=[5, 3]):
plt.figure(figsize=fig_size)
plt.title(title, fontsize=12)
plt.axis('off')
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
def plot_matches(img1, keypoints1, img2, keypoints2, matches, fig_size=[15, 12]):
... | Python | zaydzuhri_stack_edu_python |
function transformCovariance self state Q
begin
set position = state at slice 0 : 3 :
set velocity = state at slice 3 : 6 :
comment Radial - In-track (actually, along track) - Cross-track
if _process_noise_frame == string RIC
begin
comment DCM from inertial to RIC
set DCM = zeros tuple 3 3
set r = position / norm pos... | def transformCovariance(self, state, Q):
position = state[0:3]
velocity = state[3:6]
if self._process_noise_frame == "RIC": # Radial - In-track (actually, along track) - Cross-track
DCM = np.zeros((3,3)) # DCM from inertial to RIC
r = position/np.linalg.norm(position)
... | Python | nomic_cornstack_python_v1 |
function refresh_query_builder_ops apps schema_editor
begin
for witem in all
begin
call set_query_builder_ops
save
end
end function | def refresh_query_builder_ops(apps, schema_editor):
for witem in Workflow.objects.all():
witem.set_query_builder_ops()
witem.save() | Python | nomic_cornstack_python_v1 |
function gate_pass self goal
begin
function rc_to_obj self goal
begin
string Add constant rc commands to depth and heading hold
set channels = call depth_heading_rc goal
set channels at xchannel = x_rc_vel
set yrc_cmd = call get_obj_y goal true
set channels at ychannel = yrc_cmd
return channels
end function
function is... | def gate_pass(self, goal):
def rc_to_obj(self, goal):
"""Add constant rc commands to depth and heading hold"""
channels = self.depth_heading_rc(goal)
channels[self.xchannel] = goal.x_rc_vel
yrc_cmd = self.get_obj_y(goal, True)
channels[self.ychannel] =... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import re
from des_struct import *
comment from unicode to hexadecimal
function from_unicode_to_hex text
begin
set hex_text = string
for i in text
begin
set hex_text = hex_text + string %02x % ordinal i
end
return hex_text
end function
comment from hexadecimal to binary
function from_hex_... | # -*- coding: utf-8 -*-
import re
from des_struct import *
# from unicode to hexadecimal
def from_unicode_to_hex(text):
hex_text = ""
for i in text:
hex_text += "%02x" % ord(i)
return hex_text
# from hexadecimal to binary
def from_hex_to_binary(num):
out_put = ""
lens = len(num)
len... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Time : 2017/12/11 上午11:15
comment @Author : LeonHardt
comment @File : cp_knn.py
import numpy as np
function ConformalPredictionKnn x_train x_test y_train k
begin
set y_train = reshape y_train tuple - 1 1
set all_label = reshape unique y_train tuple - 1... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/11 上午11:15
# @Author : LeonHardt
# @File : cp_knn.py
import numpy as np
def ConformalPredictionKnn(x_train, x_test, y_train, k):
y_train = y_train.reshape((-1, 1))
all_label = np.unique(y_train).reshape((-1, 1))
all_label_number = al... | Python | zaydzuhri_stack_edu_python |
comment Dictionary of numbers and words
set DAYS = dict 1 string one ; 2 string two ; 3 string three ; 4 string four ; 5 string five ; 6 string six ; 7 string seven ; 8 string eight ; 9 string nine ; 10 string ten
function num_to_str num
begin
if num in DAYS
begin
return DAYS at num
end
else
begin
return string invalid... | # Dictionary of numbers and words
DAYS = {
1:'one',
2:'two',
3:'three',
4:'four',
5:'five',
6:'six',
7:'seven',
8:'eight',
9:'nine',
10:'ten',
}
def num_to_str(num):
if num in DAYS:
return DAYS[num]
else:
return "invalid number"
if __name__ == '__main__'... | Python | iamtarun_python_18k_alpaca |
from src.constants.const import KEY_LEN , SEC_PARAM
from src.paillier.paillier_key import *
from decimal import *
import random
import secrets
function calc_g num
begin
string Calculates "g" :param num: In this case it is n :return: g = n + 1
comment Following the advice from the statement
return num + 1
end function
f... | from src.constants.const import KEY_LEN, SEC_PARAM
from src.paillier.paillier_key import *
from decimal import *
import random
import secrets
def calc_g(num):
"""
Calculates "g"
:param num: In this case it is n
:return: g = n + 1
"""
return num + 1 # Following the advice from the statement
... | Python | zaydzuhri_stack_edu_python |
string #M.31 Count All Palindromic Subsequence in a given String Find how many palindromic subsequence (need not necessarily be distinct) can be formed in a given string. Note that the empty string is not considered as a palindrome. Examples: Input : str = "abcd" Output : 4 Explanation :- palindromic subsequence are : ... | """
#M.31
Count All Palindromic Subsequence in a given String
Find how many palindromic subsequence (need not necessarily be distinct) can be formed in a given string. Note that the empty string is not considered as a palindrome.
Examples:
Input : str = "abcd"
Output : 4
Explanation :- palindromic subsequence are : "... | Python | zaydzuhri_stack_edu_python |
function text_replace_line text old new find=lambda old new -> old == new process=lambda _ -> _
begin
set res = list
set replaced = 0
set eol = call text_detect_eol text
for line in split text eol
begin
if find process line process old
begin
append res new
set replaced = replaced + 1
end
else
begin
append res line
end... | def text_replace_line(text, old, new, find=lambda old, new: old == new,
process=lambda _: _):
res = []
replaced = 0
eol = text_detect_eol(text)
for line in text.split(eol):
if find(process(line), process(old)):
res.append(new)
replaced += 1
e... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
set dataName = string output1.txt
comment input datastream from file and process to obtain data (eg strip away nonessential characters)
set data = list comprehension list comprehension decimal i for i in split line at slice 2 : -... | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
dataName = "output1.txt"
# input datastream from file and process to obtain data (eg strip away nonessential characters)
data = [ [float(i) for i in line[2:-6].split(',')] for line in open(dataName).read().split()]
#print(data)... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment 2014-03-16 #
comment modified 2014-03-19 #
comment modified 2019-07-18 #
comment modified 2020-10-24 #
comment modified 2020-10-25 #
comment modified 2020-10-27 #
comment Thermostatic control of energy consumption #
comment ## Python for Raspberry Pi ## #
comment Eric Adler <tonsofpcs@g... | #!/usr/bin/python
###############################################
# 2014-03-16 #
# modified 2014-03-19 #
# modified 2019-07-18 #
# modified 2020-10-24 #
# modified 2020-10-25 #
# modified 202... | Python | zaydzuhri_stack_edu_python |
function order_by_start self
begin
return call order_by string start_time
end function | def order_by_start(self):
return self.order_by("start_time") | Python | nomic_cornstack_python_v1 |
import pickle
from com.utils import load_t_d
function get_sentence_pairs dt_set min_len=5 max_len=350
begin
string 将数据集中的句子从中间切成一对句子 :param dt_set: train/test/dev :return: list of sentence sequence
set sentence_pair_list = list
set size = length dt_set
print string converting data...
comment print("size:",size)
for i ... | import pickle
from com.utils import load_t_d
def get_sentence_pairs(dt_set,min_len=5,max_len=350):
"""
将数据集中的句子从中间切成一对句子
:param dt_set: train/test/dev
:return: list of sentence sequence
"""
sentence_pair_list=[]
size=len(dt_set)
print("converting data...")
# print("size:",size)
... | Python | zaydzuhri_stack_edu_python |
import os
from pprint import pprint
import pygame
set SPRITES_DIR = join path directory name path real path path __file__ string .. string Resources string sprites
set sprites = dict
set sprite_speeds = dict
function LoadSprites
begin
print string Loading Sprites...
for tuple _ sprite_dirs _ in walk SPRITES_DIR
begin... | import os
from pprint import pprint
import pygame
SPRITES_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "Resources", "sprites")
sprites = {}
sprite_speeds = {}
def LoadSprites():
print("Loading Sprites...")
for _, sprite_dirs, _ in os.walk(SPRITES_DIR):
for sprite_name in spri... | Python | zaydzuhri_stack_edu_python |
while msg
begin
set word = split msg
for i in range 0 length word
begin
if word at i in words
begin
set words at word at i = words at word at i + 1
end
else
begin
set words at word at i = 1
end
end
set msg = input string Enter line:
end
for msg in sorted words
begin
print msg words at msg
end | while msg:
word = msg.split()
for i in range(0, len(word)):
if word[i] in words:
words[word[i]] = words[word[i]] + 1
else:
words[word[i]] = 1
msg = input("Enter line: ")
for msg in sorted(words):
print(msg, words[msg])
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
set test = 3
set test_res = 638
function part1 steps
begin
set state = list 0
set pos = 0
for cycle in range 1 2018
begin
set pos = pos + steps % length state + 1
set state = state at slice : pos : + list cycle + state at slice pos : :
end
return state at pos + 1 % length state
end fun... | #!/usr/bin/env python3
test = 3
test_res = 638
def part1(steps):
state = [0]
pos = 0
for cycle in range(1, 2018):
pos = (pos + steps) % len(state) + 1
state = state[:pos] + [cycle] + state[pos:]
return state[(pos + 1) % len(state)]
def part2(steps):
pos = 0
res = None
fo... | Python | zaydzuhri_stack_edu_python |
function get_ios_device_type udid
begin
try
begin
set out = call splitlines
if length out == 1
begin
return out at 0
end
end
except tuple OSError CalledProcessError
begin
pass
end
end function | def get_ios_device_type(udid):
try:
out = subprocess.check_output(
['ideviceinfo', '-k', 'ProductType', '-u', udid],
universal_newlines=True).splitlines()
if len(out) == 1:
return out[0]
except (OSError, subprocess.CalledProcessError):
pass | Python | nomic_cornstack_python_v1 |
function __init__ self name odds
begin
set _name = name
set _odds = odds
end function | def __init__(self, name, odds):
self._name = name
self._odds = odds | Python | nomic_cornstack_python_v1 |
function compute_stoch_least_squares_gradient y tx w
begin
set my = none
set mx = none
for tuple mmini_y mini_x in call batch_iter y tx batch_size=1
begin
set my = mmini_y
set mx = mini_x
end
return call compute_gradient my mx w
end function | def compute_stoch_least_squares_gradient(y, tx, w):
my=None
mx=None
for mmini_y,mini_x in batch_iter(y, tx, batch_size=1):
my=mmini_y
mx=mini_x
return compute_gradient(my, mx, w) | Python | nomic_cornstack_python_v1 |
import numpy as np
comment import time
class Neighbourhood
begin
function __init__ self reladresses
begin
string creates an instance of the class Parameters ---------- reladresses : list relative coordinates of the neighbours of the cell. Raises ---------- ValueError Te coordinates need to be of the same dimension. Typ... | import numpy as np
#import time
class Neighbourhood:
def __init__(self, reladresses : list) -> None:
'''
creates an instance of the class
Parameters
----------
reladresses : list
relative coordinates of the neighbours of the cell.
Raises
----... | Python | zaydzuhri_stack_edu_python |
function _get_vm hostname unlock=true allow_retired=false
begin
set object_id = get query dict string hostname any hostname starts with hostname + string . ; string servertype string vm list string object_id at string object_id
function vm_query
begin
return get query dict string object_id object_id VM_ATTRIBUTES
end f... | def _get_vm(hostname, unlock=True, allow_retired=False):
object_id = Query({
'hostname': Any(hostname, StartsWith(hostname + '.')),
'servertype': 'vm',
}, ['object_id']).get()['object_id']
def vm_query():
return Query({
'object_id': object_id,
}, VM_ATTRIBUTES).... | Python | nomic_cornstack_python_v1 |
function inputs self
begin
return list comprehension input x for x in values call GetInputList
end function | def inputs(self):
return [Input(x) for x in self._reference.GetInputList().values()] | Python | nomic_cornstack_python_v1 |
function celsius_to_fahrenheit celsius
begin
return celsius * 9 / 5 + 32
end function
function get_valid_temperature
begin
while true
begin
try
begin
set temperature = decimal input string Enter a temperature in Celsius (or 'q' to quit):
return temperature
end
except ValueError
begin
print string Invalid temperature. P... | def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def get_valid_temperature():
while True:
try:
temperature = float(input("Enter a temperature in Celsius (or 'q' to quit): "))
return temperature
except ValueError:
print("Invalid temperature. Ple... | Python | jtatman_500k |
import os
import json
import urllib
from bs4 import BeautifulSoup
from mutagen.mp3 import MP3
from mutagen.id3 import ID3 , APIC , error
function makeAlbumFile song_name
begin
set album_query = song_name + string album art
set count = 3
set album_art_div = none
while count
begin
set url = string https://www.google.com/... | import os
import json
import urllib
from bs4 import BeautifulSoup
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, error
def makeAlbumFile(song_name):
album_query = song_name + " album art"
count = 3
album_art_div = None
while count:
url = ("https://www.google.com/search?q=" + ur... | Python | zaydzuhri_stack_edu_python |
import os , string
function get_ifaces_list
begin
set hnd = popen string ip link list + string | + string sed -n -e 's/^[0-9]*: \([^:]*\):.*$/\1/p' string r
set ret = map strip read lines hnd
close hnd
return ret
end function
function get_iface_status iface
begin
set ret = call system string ip link list dev + iface + ... | import os, string
def get_ifaces_list ():
hnd = os.popen ("ip link list " +
"| " +
"sed -n -e 's/^[0-9]*: \\([^:]*\\):.*$/\\1/p'", "r")
ret = map(string.strip, hnd.readlines ())
hnd.close ()
return ret
def get_iface_status (iface):
ret = os.system ("ip link list dev " +... | Python | zaydzuhri_stack_edu_python |
function get_app_varieties_to_display self
begin
set available_app_varieties = call get_app_varieties
set to_display = list
for app_variety in app_varieties_to_display
begin
if app_variety in available_app_varieties
begin
append to_display app_variety
end
end
return to_display
end function | def get_app_varieties_to_display(self):
available_app_varieties = self.get_app_varieties()
to_display = []
for app_variety in self.app_varieties_to_display:
if app_variety in available_app_varieties:
to_display.append(app_variety)
return to_display | Python | nomic_cornstack_python_v1 |
function addNoise x y noise
begin
set n = length x
comment random angle in [0,2*pi[
set theta = random n * 2 * pi
comment random amplitude in [0,noise[
set d = random n * noise
set x = x + cos theta * d
set y = y + sin theta * d
end function | def addNoise(x,y,noise):
n = len(x)
theta = np.random.random(n)*(2*np.pi) # random angle in [0,2*pi[
d = np.random.random(n)*noise # random amplitude in [0,noise[
x += np.cos(theta)*d
y += np.sin(theta)*d | Python | nomic_cornstack_python_v1 |
function perspectiveDistanceRatioArray angal divisions
begin
comment ***if angal >= 0.25:
comment *** raise Exception, "angal must be less than 0.25"
set origin = call Point 0 0
set unitLength = 100
comment plot point under origin
set feetPoint = origin - call Point 0 unitLength
set vanishingDistance = unitLength / tan... | def perspectiveDistanceRatioArray(angal, divisions):
#***if angal >= 0.25:
#*** raise Exception, "angal must be less than 0.25"
origin = Point(0,0)
unitLength = 100
#plot point under origin
feetPoint = origin - Point(0, unitLength)
vanishingDistance = unitLength/math.tan(angal*tew... | Python | nomic_cornstack_python_v1 |
function reset_actor_positions actor_type=none possible=none
begin
if possible is none
begin
set available_zones = list comprehension i for i in keys Z if length thresholds > 0
end
else
begin
set available_zones = list possible
end
for a in A
begin
if actor_type in a
begin
set new_pos = random choice list cells
move ne... | def reset_actor_positions(actor_type = None, possible = None):
if possible is None:
available_zones = [i for i in Collection.Z.keys() if len(Collection.Z[i].thresholds) > 0]
else:
available_zones = list(possible)
for a in Actor.A:
if actor_type in a:
new_pos = random.choi... | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
import math
from datetime import date
import datetime as DT
function keyword_growth_rate_ranker kw_list_in=list string GAF timeframe_in=string today 5-y geo_in=string US span_in=10 delay_in=14
begin
set today = today
set current_day = string format time today string %Y-%m-%d
set t... | import numpy as np
import pandas as pd
import math
from datetime import date
import datetime as DT
def keyword_growth_rate_ranker(kw_list_in=['GAF'], timeframe_in='today 5-y', geo_in='US', span_in=10, delay_in=14):
today = date.today()
current_day = today.strftime("%Y-%m-%d")
two_week_ago = today - DT.t... | Python | zaydzuhri_stack_edu_python |
function attempts n
begin
comment always initilize a variable
set x = 0
comment condition
while x <= n
begin
print string attempt { string x }
comment increment the value so as not to get an infinite loop
set x = x + 1
end
print string done
end function
call attempts 5 | def attempts(n):
# always initilize a variable
x = 0
while x <= n: #condition
print(f"attempt {str(x)}")
x += 1 # increment the value so as not to get an infinite loop
print(f"done")
attempts(5)
| Python | zaydzuhri_stack_edu_python |
function test_validate_email_address self
begin
set test_data21 = dict string name string t3frcf ; string email_address string 5u.gmail.com ; string password string wqc ; string account_type string store_attendant
set response = post string /store-manager/api/v1/auth/signup content_type=string application/json data=dum... | def test_validate_email_address(self):
self.test_data21 = {"name": "t3frcf", "email_address": "5u.gmail.com", "password": "wqc",
"account_type": "store_attendant"}
response = self.test_app.post('/store-manager/api/v1/auth/signup', content_type="application/json",
... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.