code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import random
import os
set playList = dict
comment playList ={ 1: "titulo cancion", 2: "titulo cancion" ... }
string libreria = {"California_Uber_Alles": {"track-number": 3, "artist": "Dead Kennedys", "album": "Dead Kennedys", "location":"/home/ulises/Micarpeta/proyectos/Ejercicios_Pyhton/biblioteca/California_Uber_A... | import random
import os
playList = {}
# playList ={ 1: "titulo cancion", 2: "titulo cancion" ... }
"""libreria = {"California_Uber_Alles":
{"track-number": 3, "artist": "Dead Kennedys", "album": "Dead Kennedys", "location":"/home/ulises/Micarpeta/proyectos/Ejercicios_Pyhton/biblioteca/California_Uber_A... | Python | zaydzuhri_stack_edu_python |
function config self
begin
return _config
end function | def config(self) -> argparse.Namespace:
return self._config | Python | nomic_cornstack_python_v1 |
function test x y
begin
print x
print y
end function
comment test(y=2,x=1) 關鍵字參數,與位置參數順序無關
comment test(1,2) 位置參數與形式參數一一對應
call test 3 y=2
print string -------
function test x y z
begin
print x
print y
print z
end function
call test 3 z=2 y=6 | def test(x,y):
print(x)
print(y)
#test(y=2,x=1) 關鍵字參數,與位置參數順序無關
#test(1,2) 位置參數與形式參數一一對應
test(3,y=2)
print('-------')
def test(x,y,z):
print(x)
print(y)
print(z)
test(3,z=2,y=6)
| Python | zaydzuhri_stack_edu_python |
function log_deltas self scm_bytes nvme_bytes prefix=none
begin
info string - %s=%s (%d Bytes) if expression prefix is none then string scm_delta else format string {}_scm_delta prefix call bytes_to_human scm_bytes scm_bytes
info string - %s=%s (%d Bytes) if expression prefix is none then string nvme_delta else format ... | def log_deltas(self, scm_bytes, nvme_bytes, prefix=None):
self.log.info(
"\t- %s=%s (%d Bytes)",
"scm_delta" if prefix is None else "{}_scm_delta".format(prefix),
bytes_to_human(scm_bytes),
scm_bytes)
self.log.info(
"\t- %s=%s (%d Bytes)",
... | Python | nomic_cornstack_python_v1 |
import numpy as np
from math import log , sqrt
import matplotlib.pyplot as plt
function ln x
begin
return log absolute x
end function
function centi x
begin
return x / 100.0
end function
function micro x
begin
return x / 1000000.0
end function
comment UNIVERSAL CONSTANT
set u_over_4pi = 1e-07
function run_sim getty_mas... | import numpy as np
from math import log, sqrt
import matplotlib.pyplot as plt
def ln(x):
return log(abs(x))
def centi(x):
return x / 100.0
def micro(x):
return x / 1000000.0
u_over_4pi = 1e-7 # UNIVERSAL CONSTANT
def run_sim(getty_mass, rail_separation, rail_width, rail_thickness, projectile_thickness, ... | Python | zaydzuhri_stack_edu_python |
function player board
begin
set count = 0
for item in board
begin
for i in range length item
begin
if item at i == X
begin
set count = count + 1
end
else
if item at i == O
begin
set count = count - 1
end
else
begin
continue
end
end
end
if count == 0
begin
return X
end
if count != 0
begin
return O
end
end function | def player(board):
count = 0
for item in board:
for i in range(len(item)):
if item[i] == X:
count += 1
elif item[i] == O:
count -= 1
else:
continue
if count == 0:
return (X)
if count != 0:
return ... | Python | nomic_cornstack_python_v1 |
import logging
import psutil
import os
from win32com.client import Dispatch
comment this variable is used for local module only.
comment On the project level,
set logger = call getLogger __name__
comment list of signals to record during scenario test generation
set signals_to_record = list
class ToolOneControl extends... | import logging
import psutil
import os
from win32com.client import Dispatch
# this variable is used for local module only.
# On the project level,
logger = logging.getLogger(__name__)
# list of signals to record during scenario test generation
signals_to_record = []
class ToolOneControl(object):
"... | Python | zaydzuhri_stack_edu_python |
import math
class Item
begin
function __init__ self name desc effect
begin
set name = name
set desc = desc
set effect = effect
end function
function give self monster
begin
if items at 0 is empty
begin
set items at 0 = self
end
else
if length items == 2 and items at 1 is empty
begin
set items at 1 = self
end
end functi... | import math
class Item:
def __init__(self, name, desc, effect):
self.name = name
self.desc = desc
self.effect = effect
def give(self, monster):
if monster.items[0] is empty:
monster.items[0] = self
elif len(monster.items) == 2 and monster.items[1] is empty:... | Python | zaydzuhri_stack_edu_python |
function max_index arr
begin
set max_value = arr at 0
set max_index = 0
for i in range 1 length arr
begin
if arr at i > max_value
begin
set max_index = i
set max_value = arr at i
end
end
return max_index
end function | def max_index(arr):
max_value = arr[0]
max_index = 0
for i in range(1, len(arr)):
if arr[i] > max_value:
max_index = i
max_value = arr[i]
return max_index
| Python | flytech_python_25k |
import urllib
set text = open string /Users/johnkoretoff/code/udacity/programming-foundations-with-python/scan-text.rtf
set content = read text
set url_place = url open string http://isithackday.com/arrpi.php?text= + content
set response = read url_place
print response
close url_place
close | import urllib
text = open("/Users/johnkoretoff/code/udacity/programming-foundations-with-python/scan-text.rtf")
content = text.read()
url_place = urllib.urlopen("http://isithackday.com/arrpi.php?text="+content)
response = url_place.read()
print(response)
url_place.close()
text.close
| Python | zaydzuhri_stack_edu_python |
function run self
begin
clear axs at 0 at 0
call simulate params=params plt=plt callback=callback home=home work=work positions=initial_positions stopping_t=150
end function | def run(self):
self.axs[0][0].clear()
simulate(params=self.params,plt=plt,callback=self.callback,home=self.home,work=self.work, positions=self.initial_positions, stopping_t=150) | Python | nomic_cornstack_python_v1 |
import random
import math
import multiprocessing
import sys
import os
import json
class BoggleDie extends object
begin
function __init__ self letters
begin
set letters = letters
set face = random choice letters
end function
decorator staticmethod
function all_dice test_board=false
begin
if test_board == true
begin
retu... | import random
import math
import multiprocessing
import sys
import os
import json
class BoggleDie(object):
def __init__(self, letters):
self.letters = letters
self.face = random.choice(letters)
@staticmethod
def all_dice(test_board=False):
if test_board == True:
return ... | Python | zaydzuhri_stack_edu_python |
function countPrimes num
begin
if num <= 1
begin
return 0
end
set primes = list 2
set x = 3
while x <= num
begin
for y in primes
begin
if x % y == 0
begin
set x = x + 2
continue
end
end
append primes x
set x = x + 2
end
return length primes
end function
set num_primes = call countPrimes 100
print string Number of prime... | def countPrimes(num):
if num <= 1:
return 0
primes = [2]
x = 3
while x <= num:
for y in primes:
if x % y == 0:
x += 2
continue
primes.append(x)
x += 2
return len(primes)
num_primes = countPrimes(100)
pr... | Python | jtatman_500k |
from urllib import quote_plus
import re
from super_dt_parser import safe_dt_parse
from posting_class import Posting
from posting_scraper import PostingScraper
from sys import stderr
from urlparse import urlsplit , urlunsplit
import traceback
set __author__ = string mcs
class UpworkScraper extends PostingScraper
begin
s... | from urllib import quote_plus
import re
from super_dt_parser import safe_dt_parse
from posting_class import Posting
from posting_scraper import PostingScraper
from sys import stderr
from urlparse import urlsplit, urlunsplit
import traceback
__author__ = 'mcs'
class UpworkScraper(PostingScraper):
_job_search_res... | Python | zaydzuhri_stack_edu_python |
comment Find the sum of the digits in the number 100!
from math import log , pow , ceil
function FindFactorialDigitSum
begin
comment Create a list of the factors of 100! and 101.
set facList = list range 1 102
comment Find all pairs of numbers, one with a factor of 2
comment the other with a factor of 5 and divide them... | # Find the sum of the digits in the number 100!
from math import log, pow, ceil
def FindFactorialDigitSum():
# Create a list of the factors of 100! and 101.
facList = list(range(1, 102))
# Find all pairs of numbers, one with a factor of 2
# the other with a factor of 5 and divide them each by
# their respective... | Python | zaydzuhri_stack_edu_python |
from redis import Redis
set redis_connection = call Redis decode_responses=true
comment przypisanie własnych wartości
set klucz = string jagoda
set wartosc = 24
comment odczytanie wartości
set klucz wartosc
print get redis_connection klucz
comment zwiększenie o 240
print call incr klucz 240
comment odjęcie 2400
print c... | from redis import Redis
redis_connection = Redis(decode_responses=True)
# przypisanie własnych wartości
klucz ="jagoda"
wartosc =24
# odczytanie wartości
redis_connection.set(klucz, wartosc)
print(redis_connection.get(klucz))
# zwiększenie o 240
print(redis_connection.incr(klucz,240))
# odjęcie 2400... | Python | zaydzuhri_stack_edu_python |
import random
set n = 10
set lst = list comprehension call randrange 1 101 for _ in range n
set sum_lst = sum lst
print string Random list: lst
print string Sum of the list: sum_lst | import random
n = 10
lst = [random.randrange(1, 101) for _ in range(n)]
sum_lst = sum(lst)
print("Random list: ", lst)
print("Sum of the list: ", sum_lst) | Python | jtatman_500k |
function move_to self destination
begin
set params = dict string destination project_folder_id
call _perform_empty string POST string /project-folders/%s/move % project_folder_id params=params
end function | def move_to(self, destination):
params = {
"destination": destination.project_folder_id
}
self.client._perform_empty("POST", "/project-folders/%s/move" % self.project_folder_id, params=params) | Python | nomic_cornstack_python_v1 |
string Abundant, deficient and perfect number classifications
from itertools import accumulate , chain , groupby , product
from functools import reduce
from math import floor , sqrt
from operator import mul
comment deficientPerfectAbundantCountsUpTo :: Int -> (Int, Int, Int)
function deficientPerfectAbundantCountsUpTo ... | '''Abundant, deficient and perfect number classifications'''
from itertools import accumulate, chain, groupby, product
from functools import reduce
from math import floor, sqrt
from operator import mul
# deficientPerfectAbundantCountsUpTo :: Int -> (Int, Int, Int)
def deficientPerfectAbundantCountsUpTo(n):
'''Co... | Python | zaydzuhri_stack_edu_python |
function do_logout client
begin
set url = AUTH_URL + string logout/
set resp = post url
set status_code = integer status_code
assert status_code in list 200 302
debug string logout successful
end function | def do_logout(client):
url = AUTH_URL + "logout/"
resp = client.post(url)
status_code = int(resp.status_code)
assert status_code in [200, 302]
logger.debug("logout successful") | Python | nomic_cornstack_python_v1 |
import statistics
function convert_to_letter_grade grade
begin
if grade < 0 or grade > 100
begin
return string Error: Invalid Grade
end
else
if grade >= 90
begin
return string A
end
else
if grade >= 80
begin
return string B
end
else
if grade >= 70
begin
return string C
end
else
if grade >= 60
begin
return string D
end
... | import statistics
def convert_to_letter_grade(grade):
if grade < 0 or grade > 100:
return "Error: Invalid Grade"
elif grade >= 90:
return "A"
elif grade >= 80:
return "B"
elif grade >= 70:
return "C"
elif grade >= 60:
return "D"
else:
return "F"
... | Python | jtatman_500k |
comment ! /usr/bin/env python3
string @author: Simon Haile This program creates a tensorflow graph with varying configurations. Our program support both classification and regression problems. Users can specify the number of hidden layers in their network as well as the shape of the hidden layers. Users can choose to u... | #! /usr/bin/env python3
"""
@author: Simon Haile
This program creates a tensorflow graph with varying configurations.
Our program support both classification and regression problems.
Users can specify the number of hidden layers in their network as
well as the shape of the hidden layers. Users can choose to use miniba... | Python | zaydzuhri_stack_edu_python |
function list_directory self path
begin
try
begin
set list = list directory path
end
except OSError
begin
call send_error NOT_FOUND string No permission to list directory
return none
end
sort list key=lambda a -> lower a
debug string Listing directory %s % list
set r = list
try
begin
set displaypath = unquote path err... | def list_directory(self, path):
try:
list = os.listdir(path)
except OSError:
self.send_error(
HTTPStatus.NOT_FOUND,
"No permission to list directory")
return None
list.sort(key=lambda a: a.lower())
logging.debug("Listing... | Python | nomic_cornstack_python_v1 |
function set_goal
begin
set form = call GoalForm
set is_add_goal = true
if call validate_on_submit
begin
set goal = call Goal title=data motivation=data acceptance_criteria=data reward=data frequency=data frequency_activity_type=data duration_activity_type=data duration=data distance_activity_type=data distance=data us... | def set_goal():
form = GoalForm()
is_add_goal = True
if form.validate_on_submit():
goal = Goal(title=form.title.data, motivation=form.motivation.data,
acceptance_criteria=form.acceptance_criteria.data,
reward=form.reward.data,
frequency=for... | Python | nomic_cornstack_python_v1 |
function search cls name=none biomass_remaining=none sample_type=none barcode=none project=none primer_set=none sample_set=none protocol=none
begin
comment Make sure at least one argument passed
if all list comprehension x is none for x in list name biomass_remaining sample_type barcode project primer_set sample_set pr... | def search(cls, name=None, biomass_remaining=None, sample_type=None,
barcode=None, project=None, primer_set=None, sample_set=None,
protocol=None):
# Make sure at least one argument passed
if all([x is None for x in [name, biomass_remaining, sample_type,
... | Python | nomic_cornstack_python_v1 |
function prompt_yes_or_no question yes_text=string Yes no_text=string No has_to_match_case=false enter_empty_confirms=true default_is_yes=false deselected_prefix=string selected_prefix=string [31m>[0m abort_value=none char_prompt=true
begin
comment type: str
comment type: str
comment type: str
comment type: bool
com... | def prompt_yes_or_no(
question, # type: str
yes_text = 'Yes', # type: str
no_text = 'No', # type: str
has_to_match_case = False, # type: bool
enter_empty_confirms = True, # type: bool
default_is_yes = False, # type: bool
deselected_prefix = ' ', # t... | Python | nomic_cornstack_python_v1 |
function NAM self GPH tname
begin
comment raise type error if tname is not a string
if not is instance tname str
begin
raise call TypeError string tname must be a string
end
comment raise type error if GPH is not an iris cube
if not is instance GPH Cube
begin
raise call TypeError string GPH must be an iris cube
end
com... | def NAM(self, GPH, tname):
# raise type error if tname is not a string
if not isinstance(tname, str):
raise TypeError("tname must be a string")
# raise type error if GPH is not an iris cube
if not isinstance(GPH, iris.cube.Cube):
raise TypeError("GPH must be an iris cube")
# add extra t... | Python | nomic_cornstack_python_v1 |
function stop_observing observed observer signal=string post_save
begin
set observed_item = call get_for observed observer signal
delete
end function | def stop_observing(observed, observer, signal='post_save'):
observed_item = ObservedItem.objects.get_for(observed, observer, signal)
observed_item.delete() | Python | nomic_cornstack_python_v1 |
import numpy as nm
import pandas as pd
string PCA 操作流程: 去平均值,即每一位特征减去各自的平均值 计算协方差矩阵 计算协方差矩阵的特征值与特征向量 对特征值从大到小排序 保留最大的个特征向量 将数据转换到个特征向量构建的新空间中 选择主成分的个数
comment 计算均值并求协方差矩阵
function zero_mean datamat
begin
comment 按列求均值,求每一维的特征平均值 axis=0 对各列求均值, axis=1 对各行求均值
set mean_val = mean nm datamat axis=0
set new_data = datamat -... | import numpy as nm
import pandas as pd
'''PCA 操作流程: 去平均值,即每一位特征减去各自的平均值
计算协方差矩阵
计算协方差矩阵的特征值与特征向量
对特征值从大到小排序
保留最大的个特征向量
将数据转换到个特征向量构建的新空间中
选择主成分的个数
'''
def zero_mean(datamat): # 计算均值并求协方差矩阵
mean_val = nm.mean(datamat, axis=0) # 按列求均值,求每一维的特征平均值 axis=0... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
set aa = string ../data/000001.xlsx
comment 设置数据显示的列数和宽度
call set_option string display.max_columns 500
call set_option string display.width 1000
comment 解决数据输出时列名不对齐的问题
call set_option string display.unicode.ambiguous_as_wide true
call set_option s... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
aa =r'../data/000001.xlsx'
#设置数据显示的列数和宽度
pd.set_option('display.max_columns',500)
pd.set_option('display.width',1000)
#解决数据输出时列名不对齐的问题
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
d... | Python | zaydzuhri_stack_edu_python |
from urllib.request import urlopen
from bs4 import BeautifulSoup
function scrape_wikipedia_page url
begin
comment Retrieve the page
set html = url open url
comment Create an instance of the bs4 parser
set soup = call BeautifulSoup html string html.parser
comment Extract content from the page
set page_content = find all... | from urllib.request import urlopen
from bs4 import BeautifulSoup
def scrape_wikipedia_page(url):
# Retrieve the page
html = urlopen(url)
# Create an instance of the bs4 parser
soup = BeautifulSoup(html, 'html.parser')
# Extract content from the page
page_content = soup.find_all('p')
page_... | Python | flytech_python_25k |
function test_fav_remove self
begin
call login_example_user
comment add two posts to favorites, and remove one
set test_urls = list string /1/wolf-mustache-fap-umami/favorite/ string /11/etsy-austin/favorite/ string /11/etsy-austin/unfavorite/
for url in test_urls
begin
get driver format string {0}{1} live_server_url u... | def test_fav_remove(self):
self.login_example_user()
# add two posts to favorites, and remove one
test_urls = ['/1/wolf-mustache-fap-umami/favorite/',
'/11/etsy-austin/favorite/',
'/11/etsy-austin/unfavorite/']
for url in test_urls:
self.driver.get('{0}... | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import gc
from sklearn.preprocessing import LabelEncoder , MinMaxScaler
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import roc_auc_score , precision_recall_curve , roc_curve , average_precision_score
from keras.models im... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import gc
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import roc_auc_score, precision_recall_curve, roc_curve, average_precision_score
from keras.models impo... | Python | zaydzuhri_stack_edu_python |
function update_to_v27 config_dict
begin
set service_map_v2 = dict string weewx.wxengine.StdTimeSynch string prep_services ; string weewx.wxengine.StdConvert string process_services ; string weewx.wxengine.StdCalibrate string process_services ; string weewx.wxengine.StdQC string process_services ; string weewx.wxengine... | def update_to_v27(config_dict):
service_map_v2 = {'weewx.wxengine.StdTimeSynch' : 'prep_services',
'weewx.wxengine.StdConvert' : 'process_services',
'weewx.wxengine.StdCalibrate' : 'process_services',
'weewx.wxengine.StdQC' : 'process_servi... | Python | nomic_cornstack_python_v1 |
comment 165. Merge Two Sorted Lists
comment 中文English
comment Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
comment Example
comment Example 1:
comment Input: list1 = null, li... | # 165. Merge Two Sorted Lists
# 中文English
# Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
#
# Example
# Example 1:
# Input: list1 = null, list2 = 0->3->3->null
# Output: 0-... | Python | zaydzuhri_stack_edu_python |
if x == 1
begin
comment indented four spaces
print string x is 1.
end
else
begin
print string x is NOT 1.
end
set floatv = decimal 55 | if x == 1:
# indented four spaces
print("x is 1.")
else:
print("x is NOT 1.")
floatv = float(55) | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
from decimal import Decimal
import requests
function convert amount cur_from cur_to date requests
begin
set url = string http://www.cbr.ru/scripts/XML_daily.asp?date_req=
comment Использовать переданный requests
set response = get requests url + date
set soap = call BeautifulSoup content s... | from bs4 import BeautifulSoup
from decimal import Decimal
import requests
def convert(amount, cur_from, cur_to, date, requests):
url = 'http://www.cbr.ru/scripts/XML_daily.asp?date_req='
response = requests.get(url+date) # Использовать переданный requests
soap = BeautifulSoup(response.content, 'lxml')
... | Python | zaydzuhri_stack_edu_python |
function userVisitVec df cuttime cat_name tau_visit
begin
comment only unique coupons are being counted
set df1 = call drop_duplicates list string VIEW_COUPON_ID_hash
set dict_cat = dict
if cat_name == string GENRE_NAME
begin
set dict_cat = genreDict
end
else
begin
set dict_cat = capsuleDict
end
set catNum = length ke... | def userVisitVec(df, cuttime, cat_name, tau_visit):
df1 = df.drop_duplicates(['VIEW_COUPON_ID_hash']) # only unique coupons are being counted
dict_cat = {}
if cat_name == 'GENRE_NAME':
dict_cat = genreDict
else:
dict_cat = capsuleDict
catNum = len(dict_cat.keys())
col_num = ca... | Python | nomic_cornstack_python_v1 |
from django.http import HttpResponse
from Words.models import Word
from datetime import datetime
import pytz
import calendar
function worddb_add user word
begin
set word1 = call Word user=user word=word
save
end function
function worddb_get user
begin
comment init
set item = list
set time = list
comment select * from... | from django.http import HttpResponse
from Words.models import Word
from datetime import datetime
import pytz
import calendar
def worddb_add(user,word):
word1 = Word(user=user,word=word)
word1.save()
def worddb_get(user):
#init
item = []
time = []
# select * from
list = Word.objects.filt... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Fri Jul 20 15:25:03 2018 @author: mayritaspring
from sklearn import metrics
function measure_performance X y clf show_accuracy=true show_classification_report=true show_confusion_matrix=true show_roc_auc=true show_mae=true
begin
set y_pred = ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 20 15:25:03 2018
@author: mayritaspring
"""
from sklearn import metrics
def measure_performance(X,y,clf, show_accuracy=True, show_classification_report=True, show_confusion_matrix=True, show_roc_auc = True, show_mae = True):
y_pred = clf.pred... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import requests
from config import API_ID , API_VERSION , API_URL
class VKAPIWrapper extends object
begin
string An easy wrapper for store VK credentials/wrap API call
function _params self method_params
begin
string Create dict of parameters which should be passed into url
set params = di... | # -*- coding: utf-8 -*-
import requests
from config import API_ID, API_VERSION, API_URL
class VKAPIWrapper(object):
"""
An easy wrapper for store VK credentials/wrap API call
"""
def _params(self, method_params):
"""
Create dict of parameters which should be passed into url
"... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf8 -*-
comment author : Lenovo
comment date: 2018/10/8
comment 用于控制进入数量的锁
comment 场景 文件分为读和写 读可以允许右多个线程读 但是写的时候只能允许一个线程写
comment 在这里应该巩固一下操作系统中的生产者消费者问题
import threading
import time
from queue import Queue
comment semaphore内部使用了condition条件变量实现
class Spider extends Thread
begin
function __init__ sel... | #-*- coding:utf8 -*-
#author : Lenovo
#date: 2018/10/8
#用于控制进入数量的锁
#场景 文件分为读和写 读可以允许右多个线程读 但是写的时候只能允许一个线程写
#在这里应该巩固一下操作系统中的生产者消费者问题
import threading
import time
from queue import Queue
#semaphore内部使用了condition条件变量实现
class Spider(threading.Thread):
def __init__(self,url,sem):
super(Spider, self).__init__(... | Python | zaydzuhri_stack_edu_python |
function test_senses self
begin
set babau = call fromId 165
set actual = get babau string senses
set expected = string Darkvision 60 ft., Telepathy 100 ft.
assert equal actual expected
comment no senses?
set locathah = call fromId 463
set actual = get locathah string senses
set expected = string -
assert equal actual e... | def test_senses(self):
babau = statblock.Statblock.fromId(165)
actual = babau.get('senses')
expected = u'Darkvision 60 ft., Telepathy 100 ft.'
self.assertEqual(actual, expected)
# no senses?
locathah = statblock.Statblock.fromId(463)
actual = locathah.get('senses... | Python | nomic_cornstack_python_v1 |
function set_alarms self name
begin
comment Special treatment for fan sensors
if string Fan in name
begin
set sensor_type = SENSOR_NAMES at name
for alarm_level in keys FAN_ALARMS
begin
set attribute sensors at sensor_type alarm_level FAN_ALARMS at alarm_level
end
set alarms_valid = true
end
else
comment Special treatm... | def set_alarms(self, name):
# Special treatment for fan sensors
if "Fan" in name:
sensor_type = SENSOR_NAMES[name]
for alarm_level in FAN_ALARMS.keys():
setattr(self.sensors[sensor_type], alarm_level, FAN_ALARMS[alarm_level])
self.sensors[sensor_type].... | Python | nomic_cornstack_python_v1 |
comment asc2.py
for i in range 0 256
begin
set c = character i
print string [ i string = c string ] end=string
if i % 7 == 0
begin
print
end
end | #asc2.py
for i in range (0,256):
c = chr(i)
print("[",i,"=",c, "]",end="")
if (i % 7 == 0):
print()
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
if __name__ == string __main__
begin
from sys import argv
set argc = length argv - 1
set argString = string argument
if argc != 1
begin
set argString = argString + string s
end
else
begin
set argString = argString + string
end
if argc != 0
begin
set argString = argString + string :
end
else
b... | #!/usr/bin/python3
if __name__ == "__main__":
from sys import argv
argc = len(argv) - 1
argString = "argument"
if argc != 1:
argString += "s"
else:
argString += ""
if argc != 0:
argString += ":"
else:
argString += "."
print("{} {}".format(argc, argString)... | Python | zaydzuhri_stack_edu_python |
function get_attrs self
begin
return _attrs
end function | def get_attrs(self):
return self._attrs | Python | nomic_cornstack_python_v1 |
function test_subclass_user self
begin
assert true is subclass __class__ BaseModel true
end function | def test_subclass_user(self):
self.assertTrue(issubclass(self.user.__class__, BaseModel), True) | Python | nomic_cornstack_python_v1 |
import psycopg2
function runSql query connection_info
begin
try
begin
comment gitben database_config.txt-be elmenteni zet a stringet
set connect_str = connection_info
set conn = call connect connect_str
set autocommit = true
set cursor = call cursor
execute cursor query
return call fetchall
end
except Exception as e
be... | import psycopg2
def runSql(query, connection_info):
try:
# gitben database_config.txt-be elmenteni zet a stringet
connect_str = connection_info
conn = psycopg2.connect(connect_str)
conn.autocommit = True
cursor = conn.cursor()
cursor.execute(query)
return cur... | Python | zaydzuhri_stack_edu_python |
function getOutputNames self
begin
if not proxy
begin
set proxy = call service string ALVisionRecognition
end
return call getOutputNames
end function | def getOutputNames(self):
if not self.proxy:
self.proxy = self.session.service("ALVisionRecognition")
return self.proxy.getOutputNames() | Python | nomic_cornstack_python_v1 |
function generate_feature_stack image features_specification=none
begin
set image = call push image
comment default features
if features_specification is none
begin
set blurred = call gaussian_blur image sigma_x=2 sigma_y=2 sigma_z=2
set edges = call sobel blurred
set stack = list image blurred edges
return stack
end
i... | def generate_feature_stack(image, features_specification : Union[str, PredefinedFeatureSet] = None):
image = cle.push(image)
# default features
if features_specification is None:
blurred = cle.gaussian_blur(image, sigma_x=2, sigma_y=2, sigma_z=2)
edges = cle.sobel(blurred)
stack = ... | Python | nomic_cornstack_python_v1 |
function get_point self index
begin
raise call NotImplementedError
end function | def get_point(self, index):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
if salario > 1250
begin
set aumento = salario * 1 + 10 / 100
end
else
begin
set aumento = salario * 1 + 15 / 100
end
print format string {}Seu novo salário é de R${:.2f} string [1;36m aumento | if salario > 1250 :
aumento = salario * (1 + 10 / 100)
else:
aumento = salario * (1 + 15 / 100)
print('{}Seu novo salário é de R${:.2f}'.format('\033[1;36m' ,aumento))
| Python | zaydzuhri_stack_edu_python |
function forward_pass self scene images_range
begin
raise call NotImplementedError
end function | def forward_pass(self, scene, images_range):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function on_finish self
begin
set _keepalive = false
if build
begin
comment if we have a build, tell it to stop watching
call stop
end
end function | def on_finish(self):
self._keepalive = False
if self.build:
# if we have a build, tell it to stop watching
self.build.stop() | Python | nomic_cornstack_python_v1 |
import requests
import bs4
import re
comment configuration for natas18
set USERNAME = string natas18
set PASSWORD = string xvKIqDjy4OPv7wCRgDlmj0pFsCsDjhdP
set URL = string http://natas18.natas.labs.overthewire.org/
set AUTH = call HTTPBasicAuth USERNAME PASSWORD
set session = call Session
set auth = AUTH
comment get t... | import requests
import bs4
import re
# configuration for natas18
USERNAME = 'natas18'
PASSWORD = 'xvKIqDjy4OPv7wCRgDlmj0pFsCsDjhdP'
URL = 'http://natas18.natas.labs.overthewire.org/'
AUTH = requests.auth.HTTPBasicAuth(USERNAME, PASSWORD)
session = requests.Session()
session.auth = AUTH
# get the challenge content
r... | Python | zaydzuhri_stack_edu_python |
string Перестановка - это упорядоченная выборка объектов. К примеру, 3124 является одной из возможных перестановок из цифр 1, 2, 3 и 4. Если все перестановки приведены в порядке возрастания или алфавитном порядке, то такой порядок будем называть словарным. Словарные перестановки из цифр 0, 1 и 2 представлены ниже: 012 ... | """
Перестановка - это упорядоченная выборка объектов.
К примеру, 3124 является одной из возможных перестановок из цифр 1, 2, 3 и 4.
Если все перестановки приведены в порядке возрастания или алфавитном порядке, то такой порядок будем называть словарным.
Словарные перестановки из цифр 0, 1 и 2 представлены ниже:
... | Python | zaydzuhri_stack_edu_python |
from time import sleep
from rich.console import Console
set console = call Console
set tasks = list comprehension string Successfully launched! for n in range 1 2
with call status string [bold green]Launch DDos please wait a few seconds ...[/bold green] as status
begin
while tasks
begin
set task = pop tasks 0
sleep 5
l... | from time import sleep
from rich.console import Console
console = Console()
tasks = [f"Successfully launched! " for n in range(1, 2)]
with console.status("[bold green]Launch DDos please wait a few seconds ...[/bold green]") as status:
while tasks:
task = tasks.pop(0)
sleep(5)
console.log(f... | Python | zaydzuhri_stack_edu_python |
set word = string Python
set variations = list lower word upper word capitalize word
comment Replace with the actual file name
set filename = string textfile.txt
set count = 0
with open filename string r as file
begin
for line in file
begin
set line = strip line
if any generator expression variant in line for variant i... | word = "Python"
variations = [word.lower(), word.upper(), word.capitalize()]
filename = "textfile.txt" # Replace with the actual file name
count = 0
with open(filename, "r") as file:
for line in file:
line = line.strip()
if any(variant in line for variant in variations):
print(line)
... | Python | greatdarklord_python_dataset |
import matplotlib.pyplot as plt
set f = open string score string r
set x = list comprehension decimal n for n in split strip read f
histogram x bins=15
show | import matplotlib.pyplot as plt
f = open("score", "r")
x = [float(n) for n in f.read().strip().split()]
plt.hist(x, bins = 15)
plt.show()
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[1]:
from keras.preprocessing.image import ImageDataGenerator , array_to_img , img_to_array , load_img
comment In[2]:
set datagen = call ImageDataGenerator rotation_range=40 width_shift_range=0.2 height_shift_range=0.2 shear_range=0.2 zoom_range=0.2 horizonta... | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
# In[2]:
datagen = ImageDataGenerator(
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
... | Python | zaydzuhri_stack_edu_python |
import argparse
import time
import DatabaseFactory
import CurveGenerator
import KeywordsClusterer
import KeywordsUtil
import math
import Conf
comment clusterKeywords
comment -d / -dbtype database product:
comment [MySQL, PostgreSQL, AsterixDB]
comment -t / -table target table name
comment -p / -percentage sample percen... | import argparse
import time
import DatabaseFactory
import CurveGenerator
import KeywordsClusterer
import KeywordsUtil
import math
import Conf
###########################################################
# clusterKeywords
#
# -d / -dbtype database product:
# [MySQL, PostgreSQL, AsterixDB]
# -t / -... | Python | zaydzuhri_stack_edu_python |
string Created on 9/02/2017 @author: ElDelPelo
function multiplicacion m n
begin
if m == 0 or n == 0
begin
return 0
end
else
begin
return m + call multiplicacion m n - 1
end
end function | '''
Created on 9/02/2017
@author: ElDelPelo
'''
def multiplicacion(m,n):
if m==0 or n==0:
return 0;
else:
return m + multiplicacion(m, n-1)
| Python | zaydzuhri_stack_edu_python |
function supports_asset_query self
begin
pass
end function | def supports_asset_query(self):
pass | Python | nomic_cornstack_python_v1 |
import os
import numpy as np
import matplotlib.image as mpimg
function rgb2gray image_rgb
begin
if length shape == 3
begin
set image_gray = 0.2989 * image_rgb at tuple slice : : slice : : 0 + 0.587 * image_rgb at tuple slice : : slice : : 1 + 0.114 * image_rgb at tuple slice : : slice : : 2
end
else
b... | import os
import numpy as np
import matplotlib.image as mpimg
def rgb2gray(image_rgb):
if len(image_rgb.shape)==3:
image_gray = 0.2989*image_rgb[:,:,0]+0.5870*image_rgb[:,:,1]+0.1140*image_rgb[:,:,2]
else:
image_gray = image_rgb
if np.max(image_gray)<1:
image_gray = image_gray*255.
... | Python | zaydzuhri_stack_edu_python |
async function send_msg conn msg drain=true
begin
write writer call _preprocess_msg msg
if drain
begin
await call drain
end
debug string Message sent: { msg }
end function | async def send_msg(conn: Connection, msg: str, drain: bool = True) -> None:
conn.writer.write(_preprocess_msg(msg))
if drain:
await conn.writer.drain()
logger.debug(f"Message sent: {msg}") | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import re
import urllib
import urlparse
import requests
set url = string http://thegradcafe.com/survey/index.php?q=stanford+management+science&t=a&pp=250&o=d&p=
set start_url = string http://thegradcafe.com/survey/index.php?q=stanford+management+science&t=a&o=&p=1
comment don't want to vis... | from bs4 import BeautifulSoup
import re
import urllib
import urlparse
import requests
url = "http://thegradcafe.com/survey/index.php?q=stanford+management+science&t=a&pp=250&o=d&p="
start_url = "http://thegradcafe.com/survey/index.php?q=stanford+management+science&t=a&o=&p=1"
#don't want to visit any page twice
urls ... | Python | zaydzuhri_stack_edu_python |
function sum_of_primes lst
begin
set primes = list
for num in lst
begin
if num > 100 and num < 1000
begin
set is_prime = true
for i in range 2 integer num ^ 0.5 + 1
begin
if num % i == 0
begin
set is_prime = false
break
end
end
if is_prime
begin
append primes num
end
end
end
if length primes == 0
begin
return 0
end
el... | def sum_of_primes(lst):
primes = []
for num in lst:
if num > 100 and num < 1000:
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.a... | Python | greatdarklord_python_dataset |
function test_gams_connector_in_active_constraint self
begin
set m = call ConcreteModel
set b1 = call Block
set b2 = call Block
set x = variance
set x = variance
set c = call Connector
add c x
set c = call Connector
add c x
set c = call Constraint expr=c == c
set o = call Objective expr=x
with assert raises RuntimeErro... | def test_gams_connector_in_active_constraint(self):
m = ConcreteModel()
m.b1 = Block()
m.b2 = Block()
m.b1.x = Var()
m.b2.x = Var()
m.b1.c = Connector()
m.b1.c.add(m.b1.x)
m.b2.c = Connector()
m.b2.c.add(m.b2.x)
m.c = Constraint(expr=m.b1.c... | Python | nomic_cornstack_python_v1 |
function there_is_an_other_string_with_content string
begin
set string at string content = string с каким-то контентом
end function | def there_is_an_other_string_with_content(string):
string['content'] = u"с каким-то контентом" | Python | nomic_cornstack_python_v1 |
function cast self
begin
if call validate
begin
if string blueprint in data
begin
comment A single blueprint
set obj = call Blueprint
set versionCode = versionCode
set data = data
return obj
end
else
if string blueprint-book in data
begin
comment A book of blueprints
set obj = call BlueprintBook
set versionCode = versi... | def cast(self):
if self.validate():
if 'blueprint' in self.data:
# A single blueprint
obj = Blueprint.Blueprint()
obj.versionCode = self.versionCode
obj.data = self.data
return obj
elif 'blueprint-book' in se... | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
from random import choice , uniform , random , sample , randint
set DEB = false
set IMPR = false
function nameRegion r
begin
if r == 0 or r == 9
begin
return string RS
end
else
if r == 1
begin
return string ALL
end
else
if r == 2
begin
return string NOTHING
end
else
if r == 3
begi... | import numpy as np
import pandas as pd
from random import choice, uniform, random, sample, randint
DEB = False
IMPR = False
def nameRegion(r):
if r == 0 or r == 9:
return 'RS'
elif r == 1:
return 'ALL'
elif r == 2:
return 'NOTHING'
elif r == 3:
return 'DOWN'
elif r == 4:
return 'UP'
elif r == 5:
ret... | Python | zaydzuhri_stack_edu_python |
function get_layers self
begin
extend ll DataLayers
if AxisLayer is not none
begin
append ll AxisLayer
end
if LabelLayer is not none
begin
append ll LabelLayer
end
return ll
end function | def get_layers(self):
ll.extend(self.DataLayers)
if self.AxisLayer is not None:
ll.append(self.AxisLayer)
if self.LabelLayer is not None:
ll.append(self.LabelLayer)
return ll | Python | nomic_cornstack_python_v1 |
function has_composed_rpm_bulid_libs self
begin
return version_info >= tuple 4 9 0
end function | def has_composed_rpm_bulid_libs(self):
return self.version_info >= (4, 9, 0) | Python | nomic_cornstack_python_v1 |
function wdrvire b5 b7 alpha=0.01
begin
set t1 = alpha * b7 - b5 / alpha * b7 + b5
set WDRVIRE = t1 + 1 - alpha / 1 + alpha
return WDRVIRE
end function | def wdrvire(b5, b7, alpha=0.01):
t1 = (alpha * b7 - b5) / (alpha * b7 + b5)
WDRVIRE = t1 + ((1 - alpha) / (1 + alpha))
return WDRVIRE | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
comment 搜狗细胞词库转txt
import glob
import os
import struct
from config import HERE , DICTIONARY_PATH , SOGOU_LEXICON_PATH , CUSTOM_DICTIONARY_PATH
function load_sogou_lexicon path
begin
comment 加载搜狗细胞词库
set files = glob glob string %s/*.scel % path
for f in files
begin
yield f
end
end function
... | # -*- coding:utf-8 -*-
# 搜狗细胞词库转txt
import glob
import os
import struct
from config import HERE, DICTIONARY_PATH, SOGOU_LEXICON_PATH, CUSTOM_DICTIONARY_PATH
def load_sogou_lexicon(path):
# 加载搜狗细胞词库
files = glob.glob(r'%s/*.scel' % path)
for f in files:
yield f
def read_utf16_str(f, offset=-1, ... | Python | zaydzuhri_stack_edu_python |
function transduceFcn self inpFcn nSteps=list
begin
set lstOutputs = list
comment Loop and apply the inputs
for i in nSteps
begin
try
begin
append lstOutputs step self call inpFcn i
end
except any
begin
append lstOutputs none
print string Step function failed, for index: i
end
end
return lstOutputs
end function | def transduceFcn(self, inpFcn, nSteps=[]):
lstOutputs = list()
# Loop and apply the inputs
for i in nSteps:
try:
lstOutputs.append(self.step(inpFcn(i)))
except:
lstOutputs.append(None)
print('Step function failed, for index:... | Python | nomic_cornstack_python_v1 |
function read self extra_files=none
begin
set default_config_file = expand user path join path string ~ RC_FILE
if not filenames
begin
set filenames = list default_config_file
end
if extra_files
begin
extend filenames extra_files
end
set parser = config parser
set existing = false
for filename in filenames
begin
if exi... | def read(self, extra_files=None):
default_config_file = os.path.expanduser(os.path.join('~', RC_FILE))
if not self.filenames:
self.filenames = [default_config_file]
if extra_files:
self.filenames.extend(extra_files)
self.parser = configparser.ConfigParser()
... | Python | nomic_cornstack_python_v1 |
import asyncio
from collections.abc import AsyncIterable , Mapping
import re
from typing import Tuple , Dict
async function run_cmd cmd
begin
set buf = b''
set ps = await call create_subprocess_shell cmd stdout=PIPE stderr=PIPE
while true
begin
set out = call create_task read stdout 1024
set err = call create_task read... | import asyncio
from collections.abc import AsyncIterable, Mapping
import re
from typing import Tuple, Dict
async def run_cmd(cmd: str) -> AsyncIterable:
buf = b''
ps = await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
while True:
out = asyn... | Python | zaydzuhri_stack_edu_python |
import urllib3
import json
import time
from weather.models import ForecastModel
set open_weather_key = string e4f710f948b2defa7ebb874a2e804d4a
function get_weather_data city
begin
set table_dict = dict
set temperature_dict = dict
set result_json = dict
set pressure_list = list
set temperature_list = list
set http ... | import urllib3
import json
import time
from weather.models import ForecastModel
open_weather_key = 'e4f710f948b2defa7ebb874a2e804d4a'
def get_weather_data(city):
table_dict = {}
temperature_dict = {}
result_json = {}
pressure_list = []
temperature_list = []
http = urllib3.PoolManager()
a... | Python | zaydzuhri_stack_edu_python |
string Created on Sep 14, 2017 @author: anand
from french_count import french_count , prepare_input
set f = call french_count | '''
Created on Sep 14, 2017
@author: anand
'''
from french_count import french_count, prepare_input
f= french_count() | Python | zaydzuhri_stack_edu_python |
function predict self states actions
begin
string YOUR CODE HERE
return run list predicted_states feed_dict=dict states states ; actions actions
end function | def predict(self, states, actions):
""" YOUR CODE HERE """
return self.sess.run([self.predicted_states], feed_dict = {self.states:states, self.actions:actions}) | Python | nomic_cornstack_python_v1 |
function reject_on_error self reject_on_error
begin
set _reject_on_error = reject_on_error
end function | def reject_on_error(self, reject_on_error):
self._reject_on_error = reject_on_error | Python | nomic_cornstack_python_v1 |
import binascii , base64
set test = string Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal
set key = string ICE
comment takes ascii string, ascii key
function xor_key str1 key
begin
comment convert both to arrays of hex values
set array = bytearray decode call hexlify str1 string hex
set byte... | import binascii, base64
test = """Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal"""
key = "ICE"
#takes ascii string, ascii key
def xor_key(str1, key):
#convert both to arrays of hex values
array = bytearray(binascii.hexlify(str1).decode("hex"))
bytearr = bytearray(binascii.hexl... | Python | zaydzuhri_stack_edu_python |
comment while循环,条件满足就执行下面的任务不满足就重复知道满足设定的条件
comment 设定一个正确答案
set zqda = string 漫橘长
comment 课程已经学习到第10讲
comment 提示用户输入正确答案
set name = input string 请输入姓名:
comment 当条件为真时执行下面code
while true
begin
if name == zqda
begin
comment 符合条件时跳出循环体
break
end
set name = input string 抱歉。错误,请重新输入:
end
print string 哎哟!帅哦。
print string 你真... | #while循环,条件满足就执行下面的任务不满足就重复知道满足设定的条件
zqda = '漫橘长'#设定一个正确答案
# 课程已经学习到第10讲
name = input('请输入姓名:')#提示用户输入正确答案
while True:#当条件为真时执行下面code
if name == zqda:
break #符合条件时跳出循环体
name = input('抱歉。错误,请重新输入:')
print('哎哟!帅哦。')
print('你真是漫橘长心中的蛔虫!')
#for 循环没懂,后续补
#了不起的循环
age =... | Python | zaydzuhri_stack_edu_python |
string Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict.
function get_month
begin
while true
begin
set month = input string введите номер месяца (от 1 до 12) или пустую строку, чтобы отменить вво... | """
Пользователь вводит месяц в виде целого числа от 1 до 12.
Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
Напишите решения через list и через dict.
"""
def get_month():
while True:
month = input('введите номер месяца (от 1 до 12) или пустую строку, чтобы отменить ввод: ')
... | Python | zaydzuhri_stack_edu_python |
from random import randint
from functools import reduce
comment select a random outcome from an 'oracle' list
function get_rand oracle
begin
return oracle at random integer 0 length oracle - 1
end function
comment select a random outcome from a weighted 'oracle' list
comment oracle = {
comment 3: ['common'],
comment 2:... | from random import randint
from functools import reduce
# select a random outcome from an 'oracle' list
def get_rand(oracle):
return oracle[randint(0, len(oracle)-1)]
# select a random outcome from a weighted 'oracle' list
# oracle = {
# 3: ['common'],
# 2: ['uncommon'],
# 1: ['rare'],
# }
def get_wrand(ora... | Python | zaydzuhri_stack_edu_python |
comment 25-01-2012
comment additional exercises 3, question 1
comment sample solution
print string Squared Numbers
print string This program asks the user for a number and then prints out
print string the squares of all numbers between 1 and the entered number
print
set number = integer input string Please enter a numb... | #25-01-2012
#additional exercises 3, question 1
#sample solution
print("Squared Numbers")
print("This program asks the user for a number and then prints out")
print("the squares of all numbers between 1 and the entered number")
print()
number = int(input("Please enter a number: "))
print()
for eachNumber in range(numb... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
comment Preprocessing
function preprocessing test
begin
if list values != list string timestamp string value
begin
set columns = list string timestamp string value
end
end function
comment Calculate EMA
function EMA bdp n
begin
set emaResult = list
set j = 1
set sma = sum / n
set... | import pandas as pd
import numpy as np
###Preprocessing
def preprocessing(test):
if list(test.columns.values) != ["timestamp", "value"]:
test.columns = ["timestamp", "value"]
###Calculate EMA
def EMA(bdp, n):
emaResult = []
j = 1
sma = bdp[:n].value.sum()/n
alpha = 2 / float(1 + n)
f... | Python | zaydzuhri_stack_edu_python |
function sampling_rate self
begin
string Return the sampling rate.
with call open_if_needed mode=string r as cnt
begin
return get cnt key at 1
end
end function | def sampling_rate(self):
"""
Return the sampling rate.
"""
with self.container.open_if_needed(mode='r') as cnt:
return cnt.get(self.key)[1] | Python | jtatman_500k |
import boto3
comment Customizable variables:
set temp = call splitlines
for security_group_id in temp
begin
set profile = string dev
print security_group_id
comment security_group_id = raw_input("Enter security group id : ")
set region = string ap-southeast-1
comment Start a session, specifying profile credentials and ... | import boto3
### Customizable variables:
temp = open('sg.txt','r').read().splitlines()
for security_group_id in temp:
profile = "dev"
print(security_group_id)
#security_group_id = raw_input("Enter security group id : ")
region = "ap-southeast-1"
####
# Start a session, specifying profile credentials and r... | Python | zaydzuhri_stack_edu_python |
import tkinter
if __name__ == string __main__
begin
set root = call Tk
title root string Window
call geometry string 400x500
set label = grid row=0 column=0
set label = grid row=0 column=4
set label = grid row=5 column=0
call mainloop
end | import tkinter
if __name__=="__main__":
root = tkinter.Tk()
root.title("Window")
root.geometry("400x500")
label = tkinter.Label(root, text="hello").grid(row=0, column=0)
label = tkinter.Label(root, text="hello2").grid(row=0, column=4)
label = tkinter.Label(root, text="hello3").grid(row=5, colu... | Python | zaydzuhri_stack_edu_python |
import sys
for line in stdin
begin
set line = right strip line + string
set ln = split line string
write stdout right strip line + string + string max integer ln at 4 integer ln at 1 + string + string min integer ln at 5 integer ln at 2 + string + string integer ln at 5 - integer ln at 4 + string + string integer ... | import sys
for line in sys.stdin:
line=line.rstrip() + "\n"
ln=line.split("\t")
sys.stdout.write( line.rstrip() + "\t" + str(max(int(ln[4]),int(ln[1])) ) + "\t" + str( min( int(ln[5]),int(ln[2]) ) ) + "\t" + str(int(ln[5]) - int(ln[4]) ) + "\t" + str(int(ln[2]) - int(ln[1]) ) + "\n" )
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import argparse
import itertools
from dotlib import Graph , to_dot
function parse_args
begin
set parser = call ArgumentParser description=string Generate a G(n, r, s) graph - a graph of all r-sized subsets of {1..n} intersecting by s elements
call add_argument string set_size metavar=strin... | #!/usr/bin/env python3
import argparse
import itertools
from dotlib import Graph, to_dot
def parse_args():
parser = argparse.ArgumentParser(description='Generate a G(n, r, s) graph - a graph of all r-sized subsets '
'of {1..n} intersecting by s elements')
parser.add_argum... | Python | zaydzuhri_stack_edu_python |
from pynput import *
import serial
set v = string
while true
begin
set port_name = input string Enter the BT port :
set confirm = input string confirm ? [y/n] :
if lower confirm == string y or lower port_name == string yes
begin
try
begin
set seri = call Serial port_name 9600
print string _________Serial Port Conected... | from pynput import *
import serial
v = ""
while True:
port_name = input("Enter the BT port :")
confirm = input("confirm ? [y/n] :")
if confirm.lower() == "y" or port_name.lower() == "yes":
try:
seri = serial.Serial(port_name,9600)
print("\n_________Serial Port Conected !__________\n")
break
except:
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
from __future__ import print_function
from collections import defaultdict
import sys
import json
import re
import string
set DATAFILE = string ../dic/pos_mapping.txt
set results = default dictionary list
function add_line line
begin
set tokens = split string line
set key = tokens at 0
set v... | #!/usr/bin/env python
from __future__ import print_function
from collections import defaultdict
import sys
import json
import re
import string
DATAFILE = "../dic/pos_mapping.txt"
results = defaultdict(list)
def add_line(line):
tokens = string.split(line)
key = tokens[0]
val = tokens[1]
results[key] = v... | Python | zaydzuhri_stack_edu_python |
function InsertSplitLineProject self IsDirectional=defaultNamedNotOptArg FlipDir=defaultNamedNotOptArg
begin
return call InvokeTypes 65816 LCID 1 tuple 24 0 tuple tuple 11 1 tuple 11 1 IsDirectional FlipDir
end function | def InsertSplitLineProject(self, IsDirectional=defaultNamedNotOptArg, FlipDir=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(65816, LCID, 1, (24, 0), ((11, 1), (11, 1)),IsDirectional
, FlipDir) | Python | nomic_cornstack_python_v1 |
comment for wget and tar
import os
comment load files
import cPickle
comment arrays
import numpy as np
comment to select proportion of false data
import random
comment absolute value
import math
comment set a seed so that the results are consistent
seed 1 | import os # for wget and tar
import cPickle # load files
import numpy as np # arrays
import random # to select proportion of false data
import math # absolute value
random.seed(1) # set a seed so that the results are consistent
| Python | zaydzuhri_stack_edu_python |
set nums = range 1 11 1
set odd_squares = list comprehension x * x for x in nums if x % 2
print string Sum of odd squares is %d % sum odd_squares | nums = range(1, 11, 1)
odd_squares = [x * x for x in nums if x % 2]
print('Sum of odd squares is %d' % sum(odd_squares))
| Python | zaydzuhri_stack_edu_python |
function clean_vcf_output orig_file clean_fn config name=string clean
begin
string Provide framework to clean a file in-place, with the specified clean function.
set tuple base ext = call splitext_plus orig_file
set out_file = format string {0}-{1}{2} base name ext
if not call file_exists out_file
begin
with open orig_... | def clean_vcf_output(orig_file, clean_fn, config, name="clean"):
"""Provide framework to clean a file in-place, with the specified clean
function.
"""
base, ext = utils.splitext_plus(orig_file)
out_file = "{0}-{1}{2}".format(base, name, ext)
if not utils.file_exists(out_file):
with open(... | Python | jtatman_500k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.