code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_bin_lims n max_value
begin
return linear space max_value // n max_value n dtype=int
end function | def get_bin_lims(n, max_value):
return np.linspace(max_value // n, max_value, n, dtype=int) | Python | nomic_cornstack_python_v1 |
comment This program reads data that describes a morphological paradigm.
comment The first line is a space-separated list of the affixes.
comment A line that begins "\pattern name" is the beginning of an inflectional pattern;
comment that ends only when another \pattern name2 is encountered.
comment Put "\end" at the e... | # This program reads data that describes a morphological paradigm.
# The first line is a space-separated list of the affixes.
# A line that begins "\pattern name" is the beginning of an inflectional pattern;
# that ends only when another \pattern name2 is encountered.
# Put "\end" at the end of each paradigm
# I shou... | Python | zaydzuhri_stack_edu_python |
function pre_compose self update
begin
set vector_quaternion_update = update at tuple Ellipsis slice 0 : 3 :
set trans_update = list update at tuple Ellipsis 3 update at tuple Ellipsis 4 update at tuple Ellipsis 5
set new_quaternion = quaternion + call quat_multiply_by_vec quaternion vector_quaternion_update
set trans... | def pre_compose(self, update):
vector_quaternion_update = update[..., 0:3]
trans_update = [update[..., 3], update[..., 4], update[..., 5]]
new_quaternion = (self.quaternion +
quat_multiply_by_vec(self.quaternion,
vector_quaternion... | Python | nomic_cornstack_python_v1 |
function main
begin
set expenses = list
with open string input.txt as f
begin
for line in f
begin
append expenses integer strip line
end
end
print call part1 expenses
print call part2 expenses
end function
function part1 expenses
begin
for i in range length expenses - 1
begin
for j in range i + 1 length expenses
begin
... | def main():
expenses = list()
with open('input.txt') as f:
for line in f:
expenses.append(int(line.strip()))
print(part1(expenses))
print(part2(expenses))
def part1(expenses):
for i in range(len(expenses)-1):
for j in range(i+1, len(expenses)):
if expenses[i] + expenses[j] == 2020:
... | Python | zaydzuhri_stack_edu_python |
function test_lucas n result
begin
from series import lucas
assert call lucas n == result
end function | def test_lucas(n, result):
from series import lucas
assert lucas(n) == result | Python | nomic_cornstack_python_v1 |
string 给定一个正整数 n,返回长度为 n 的所有可被视为可奖励的出勤记录的数量。 答案可能非常大,你只需返回结果mod 109 + 7的值。 学生出勤记录是只包含以下三个字符的字符串: 'A' : Absent,缺勤 'L' : Late,迟到 'P' : Present,到场 如果记录不包含多于一个'A'(缺勤)或超过两个连续的'L'(迟到),则该记录被视为可奖励的。 示例 1: 输入: n = 2 输出: 8 解释: 有8个长度为2的记录将被视为可奖励: "PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL" 只有"AA"不会被视为可奖励,因为缺勤次数超过一次。 来源:力扣(Lee... | """
给定一个正整数 n,返回长度为 n 的所有可被视为可奖励的出勤记录的数量。 答案可能非常大,你只需返回结果mod 109 + 7的值。
学生出勤记录是只包含以下三个字符的字符串:
'A' : Absent,缺勤
'L' : Late,迟到
'P' : Present,到场
如果记录不包含多于一个'A'(缺勤)或超过两个连续的'L'(迟到),则该记录被视为可奖励的。
示例 1:
输入: n = 2
输出: 8
解释:
有8个长度为2的记录将被视为可奖励:
"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"
只有"AA"不会被视为可奖励,因为缺勤次数超过一次。
来源:力扣(... | Python | zaydzuhri_stack_edu_python |
import sys
from collections import deque
set tuple R C = map int split read line stdin
set maze = list list 2 * C + 2
for _ in range R
begin
append maze list map int string 2 { strip read line stdin } 2
end
append maze list 2 * C + 2
set q = deque list
append q list tuple 1 1 1
set maze at 1 at 1 = 3
set break_flag = f... | import sys
from collections import deque
R, C = map(int, sys.stdin.readline().split())
maze = [[2]*(C+2)]
for _ in range(R):
maze.append(list(map(int, f'2{sys.stdin.readline().strip()}2')))
maze.append([2]*(C+2))
q = deque([])
q.append([(1,1,1)])
maze[1][1] = 3
break_flag = False
while len(q) != 0 and break_flag ... | Python | zaydzuhri_stack_edu_python |
from daisy.coordinate import Coordinate
from daisy.ext import pyklb
from daisy.roi import Roi
import glob
import json
import numpy as np
import os
class KlbAdaptor
begin
function __init__ self filename
begin
set files = glob glob filename
sort files
if length files == 0
begin
raise call IOError string no KLB files foun... | from daisy.coordinate import Coordinate
from daisy.ext import pyklb
from daisy.roi import Roi
import glob
import json
import numpy as np
import os
class KlbAdaptor():
def __init__(self, filename):
self.files = glob.glob(filename)
self.files.sort()
if len(self.files) == 0:
ra... | Python | zaydzuhri_stack_edu_python |
function labels self mapping
begin
string Set labels assigned to this bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets#labels :type mapping: :class:`dict` :param mapping: Name-value pairs (string->string) labelling the bucket.
comment If any labels have been expressly removed, we need to track this... | def labels(self, mapping):
"""Set labels assigned to this bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets#labels
:type mapping: :class:`dict`
:param mapping: Name-value pairs (string->string) labelling the bucket.
"""
# If any labels have b... | Python | jtatman_500k |
comment Author Dayne Fradejas
import sys
append path string ../
from DataAccess.FileHandling import FileHandling
import numpy as np
class LoginBL
begin
function __init__ self
begin
set userName = string
set password = string
set lfh = call FileHandling
end function
comment return if account is valid tpye Bool
functio... | #Author Dayne Fradejas
import sys
sys.path.append('../')
from DataAccess.FileHandling import FileHandling
import numpy as np
class LoginBL:
def __init__(self):
self.userName = ''
self.password = ''
self.lfh = FileHandling()
#return if account is valid tpye Bool
def checkAccount... | Python | zaydzuhri_stack_edu_python |
function __eq__ self other
begin
if not is instance other ScanRecurrenceSchedule
begin
return false
end
return __dict__ == __dict__
end function | def __eq__(self, other):
if not isinstance(other, ScanRecurrenceSchedule):
return False
return self.__dict__ == other.__dict__ | Python | nomic_cornstack_python_v1 |
comment divide and conquer (binary search)
comment Time: O(NlogN) (master theorem)
comment Space: O(logN)
comment Runtime: 156 ms, faster than 5.17% of Python3 online submissions for Maximum Subarray.
comment Memory Usage: 13.7 MB, less than 52.03% of Python3 online submissions for Maximum Subarray.
class Solution
begi... | # divide and conquer (binary search)
# Time: O(NlogN) (master theorem)
# Space: O(logN)
# Runtime: 156 ms, faster than 5.17% of Python3 online submissions for Maximum Subarray.
# Memory Usage: 13.7 MB, less than 52.03% of Python3 online submissions for Maximum Subarray.
class Solution:
def maxSubArray(self, nums:... | Python | zaydzuhri_stack_edu_python |
function search request
begin
comment en, copier sur celinelever formulaire django et ecrire le mien
set query = get GET string query
comment Query Html escape
set user_product = call escape query
if not query
begin
set context = dict string attention string Vous devez renseigner un produit!!
return call render request... | def search(request):
# en, copier sur celinelever formulaire django et ecrire le mien
query = request.GET.get("query")
# Query Html escape
user_product = escape(query)
if not query:
context = {"attention": "Vous devez renseigner un produit!!"}
return render(request, "products/index.h... | Python | nomic_cornstack_python_v1 |
function _on_keypress self event
begin
if key is not none and string escape in key
begin
close self
end
end function | def _on_keypress(self, event):
if event.key is not None and 'escape' in event.key:
self.close() | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Fri Nov 15 18:55:47 2019 @author: CEC
function badFun n
begin
try
begin
return n / 0
end
except ArithmeticError
begin
print string I did it again!
raise
end
end function
try
begin
call badFun 0
end
except ArithmeticError
begin
print string I see!!!!
end
print string THE E... | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 18:55:47 2019
@author: CEC
"""
def badFun(n):
try:
return n/0
except ArithmeticError:
print("I did it again!")
raise
try:
badFun(0)
except ArithmeticError:
print("I see!!!!")
print("THE END") | Python | zaydzuhri_stack_edu_python |
string Mayank Vanjani mv1506 Homework 3 2/16/17
import ctypes
class aList
begin
function __init__ self I=none
begin
comment Number of elements
set _n = 0
comment Capacity
set _cap = 1
set _A = call _make_array _cap
if I
begin
extend self I
end
end function
function _make_array self c
begin
return call
end function
func... | '''
Mayank Vanjani mv1506
Homework 3
2/16/17
'''
import ctypes
class aList():
def __init__(self, I=None):
self._n = 0 #Number of elements
self._cap = 1 #Capacity
self._A = self._make_array(self._... | Python | zaydzuhri_stack_edu_python |
function row_echelon mat
begin
set m = copy mat
set steps = min *m.shape - 1
set r = 0
while r < steps
begin
set pivot_row = call find_pivot_row m r
if pivot_row == r
begin
set pivot_value = m at tuple pivot_row pivot_row
set nothing_done = true
for i in range r + 1 shape at 0
begin
set factor = - 1 * m at tuple i r / ... | def row_echelon(mat: Matrix) -> Matrix:
m = mat.copy()
steps = min(*m.shape)-1
r = 0
while r < steps:
pivot_row = find_pivot_row(m, r)
if (pivot_row == r):
pivot_value = m[pivot_row, pivot_row]
nothing_done = True
for i in range(r+1, m.shape[0]):
... | Python | nomic_cornstack_python_v1 |
for _ in range N
begin
append arr list map int split input
end
set K = integer input
for _ in range K
begin
set tuple i j x y = map int split input
set i = i - 1
set j = j - 1
set x = x - 1
set y = y - 1
set sumVal = 0
for r in range N
begin
for c in range M
begin
if j <= c <= y and i <= r <= x
begin
set sumVal = sumVa... | for _ in range(N):
arr.append(list(map(int, input().split())))
K = int(input())
for _ in range(K):
i, j, x, y = map(int, input().split())
i -= 1
j -= 1
x -= 1
y -= 1
sumVal = 0
for r in range(N):
for c in range(M):
if j <= c <= y and i <= r <= x:
sumV... | Python | zaydzuhri_stack_edu_python |
function remove c
begin
try
begin
call kill
end
except Exception
begin
pass
end
try
begin
remove c
end
except Exception
begin
pass
end
end function | def remove(c):
try:
c.kill()
except Exception:
pass
try:
c.remove()
except Exception:
pass | Python | nomic_cornstack_python_v1 |
import numpy as np
import tensorflow.contrib.keras as K
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn import svm
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
class SVM
begin
function __init__ self **kwargs
begin
set model = call LinearSVC... | import numpy as np
import tensorflow.contrib.keras as K
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn import svm
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
class SVM:
def __init__(self, **kwargs):
self.model = svm.LinearSV... | Python | zaydzuhri_stack_edu_python |
import time
import threading
import datetime
import smtplib
import socket
import json
import requests
import pytemperature
import pyzmail
set jsonDataasPythonValue = get requests string http://api.openweathermap.org/data/2.5/weather?q=colorado+springs&appid=9737923cb9003cf43725c14250599994
set stringsOfJsonData = loads... | import time
import threading
import datetime
import smtplib
import socket
import json
import requests
import pytemperature
import pyzmail
jsonDataasPythonValue = requests.get('http://api.openweathermap.org/data/2.5/weather?q=colorado+springs&appid=9737923cb9003cf43725c14250599994')
stringsOfJsonData = json.loads(json... | Python | zaydzuhri_stack_edu_python |
string 关键字驱动:将selenium中常用的操作行为,封装成自定义的函数,以便于直接调用 selenium本身是一个大型的超市,这里面什么都有,我们将需要的东西先买回来,放在家里面 当买回来的东西不够用了,再去超市买点回来 selenium中常用的所有关键字,结合自身需要,将其提取并二次封装,保存至自定义类中 往后在调用selenium执行自动化时,直接调用自定义类即可
from time import sleep
from selenium import webdriver
comment 自己家。关键字驱动类,
comment 判断用什么浏览器
function open_browser type_
begin
try
... | '''
关键字驱动:将selenium中常用的操作行为,封装成自定义的函数,以便于直接调用
selenium本身是一个大型的超市,这里面什么都有,我们将需要的东西先买回来,放在家里面
当买回来的东西不够用了,再去超市买点回来
selenium中常用的所有关键字,结合自身需要,将其提取并二次封装,保存至自定义类中
往后在调用selenium执行自动化时,直接调用自定义类即可
'''
from time import sleep
from selenium import webdriver
# 自己家。关键字驱动类,
# 判断用什么浏览器
def open_browser(type_):
try:
... | Python | zaydzuhri_stack_edu_python |
function checkRightTime frame
begin
comment not schedule loaded
if schedule is none
begin
return
end
comment no more streams to stream
if length schedule == 0
begin
return
end
if not streamActive
begin
comment check the next stream to start
set nextRow = next call iterrows at 1
set time = nextRow at string Date/Time
se... | def checkRightTime(frame):
if frame.schedule is None: # not schedule loaded
return
if len(frame.schedule) == 0: # no more streams to stream
return
if not frame.streamActive:
# check the next stream to start
nextRow = next(frame.schedule.iterrows())[1]
time = nextRow... | Python | nomic_cornstack_python_v1 |
function edit_profile request
begin
set profile = profile
set form = call ProfileForm instance=profile
if method == string POST
begin
if SYSTEM_MAINTENANCE_NO_UPLOAD
begin
comment Allow submitting the form, but do not allow the photo to
comment be modified.
if string delete_photo in POST or FILES
begin
raise call Servi... | def edit_profile(request):
profile = request.user.profile
form = forms.ProfileForm(instance=profile)
if request.method == 'POST':
if settings.SYSTEM_MAINTENANCE_NO_UPLOAD:
# Allow submitting the form, but do not allow the photo to
# be modified.
if 'delete_photo'... | Python | nomic_cornstack_python_v1 |
function generate_maintainer_script self filename python_executable function **arguments
begin
comment Read the py2deb/hooks.py script.
set py2deb_directory = directory name path absolute path path __file__
set hooks_script = join path py2deb_directory string hooks.py
with open hooks_script as handle
begin
set contents... | def generate_maintainer_script(self, filename, python_executable, function, **arguments):
# Read the py2deb/hooks.py script.
py2deb_directory = os.path.dirname(os.path.abspath(__file__))
hooks_script = os.path.join(py2deb_directory, 'hooks.py')
with open(hooks_script) as handle:
... | Python | nomic_cornstack_python_v1 |
while val <= 2017
begin
set ind = ind + n
set ind = ind % val
set ind = ind + 1
insert s ind val
set val = val + 1
end | while (val<=2017):
ind += n
ind = ind%val
ind +=1
s.insert(ind,val)
val+=1 | Python | zaydzuhri_stack_edu_python |
function right_partial_construct self n
begin
if n == num_dims - 1
begin
return tensor list 1
end
set right_factors = list values factors at slice n + 1 : :
comment Derived from tensorly mps_to_tensor implementation
comment full_shape is the shape of the tensor to return
set full_shape = list comprehension shape at 1... | def right_partial_construct(self, n):
if n == self.num_dims - 1:
return tl.tensor([1])
right_factors = list(self.factors.values())[n + 1:]
# Derived from tensorly mps_to_tensor implementation
# full_shape is the shape of the tensor to return
full_shape = [f.shape[1] for f in right_factors]... | Python | nomic_cornstack_python_v1 |
search string 10 string This string contains the number 10 in it | re.search("10", "This string contains the number 10 in it") | Python | jtatman_500k |
function end_match self **kwargs
begin
call end_match
for target in targets
begin
call end_match
end
end function | def end_match(self, **kwargs):
self.actor.end_match()
for target in self.targets:
target.end_match() | Python | nomic_cornstack_python_v1 |
import json
import tweepy
import pygame
import random
import instaloader
import urllib.request
from settings import *
function makeRectText x y message size
begin
set FONT = call Font VIEW_FONT size
set text_Title = call render format string {:,} integer message true WHITE
set text_Rect = call get_rect
set centerx = ro... | import json
import tweepy
import pygame
import random
import instaloader
import urllib.request
from settings import *
def makeRectText(x, y, message, size):
FONT = pygame.font.Font(VIEW_FONT, size)
text_Title = FONT.render('{:,}'.format(int(message)), True, WHITE)
text_Rect = text_Title.get_rect()
tex... | Python | zaydzuhri_stack_edu_python |
function test_http_get_instance_role self mock_http_get_metadata
begin
set return_value = string {"InstanceProfileArn": "arn:aws:iam::1234:role/alpha-server"}
set role = call http_get_instance_role
call assertEquals role string server
end function | def test_http_get_instance_role(self, mock_http_get_metadata):
mock_http_get_metadata.return_value = "{\"InstanceProfileArn\": \"arn:aws:iam::1234:role/alpha-server\"}"
role = ef_utils.http_get_instance_role()
self.assertEquals(role, "server") | Python | nomic_cornstack_python_v1 |
function IGetTrimCurve self
begin
return call InvokeTypes 65 LCID 1 tuple 5 0 tuple
end function | def IGetTrimCurve(self):
return self._oleobj_.InvokeTypes(65, LCID, 1, (5, 0), (),) | Python | nomic_cornstack_python_v1 |
comment 1. Kilometer Converter
string Write a program that asks the user to enter a distance in kilometers, then converts that distance to miles. The conversion formula is as follows: Miles = Kilometers X 0.6214
string def kilom_to_miles(miles): return miles * 0.6214 user_data_in_kilometers= int(input("Enter distance i... | # 1. Kilometer Converter
"""
Write a program that asks the user to enter a distance in kilometers, then converts that
distance to miles. The conversion formula is as follows:
Miles = Kilometers X 0.6214
"""
"""
def kilom_to_miles(miles):
return miles * 0.6214
user_data_in_kilometers= int(input("Enter distance in... | Python | zaydzuhri_stack_edu_python |
comment -*-coding:utf-8 -*-
string ...
set __author__ = string 张强
from PyQt5.Qt import *
comment print(QObject.__subclasses__())
comment print(QWidget.__subclasses__())
comment 查找子类
function getSubClasses cls
begin
for subcls in call __subclasses__
begin
print subcls
if length call __subclasses__ > 0
begin
call getSubC... | #-*-coding:utf-8 -*-
"""..."""
__author__ = '张强'
from PyQt5.Qt import *
#print(QObject.__subclasses__())
#print(QWidget.__subclasses__())
#查找子类
def getSubClasses(cls):
for subcls in cls.__subclasses__():
print(subcls)
if len(cls.__subclasses__()) > 0:
getSubClasses(subcl... | Python | zaydzuhri_stack_edu_python |
comment para imprimir como string se hace de la siguiente manera
print string el numero es: + string numero | #para imprimir como string se hace de la siguiente manera
print("el numero es: " + str(numero)) | Python | zaydzuhri_stack_edu_python |
function tensor2d_to_global crd tens
begin
set tuple sxx sxy syx syy = call to_xy
set tuple qxx qxy qyx qyy = tuple x y x y
set exx = qxx ^ 2 * sxx + qxx * qyx * sxy + qxx * qyx * syx + qyx ^ 2 * syy
set eyy = qxy ^ 2 * sxx + qxy * qyy * sxy + qxy * qyy * syx + qyy ^ 2 * syy
set exy = qxx * qxy * sxx + qxx * qyy * sxy ... | def tensor2d_to_global(crd: 'Coordinate2D', tens: 'MatrixTensor2D') -> 'MatrixTensor2D':
sxx, sxy, syx, syy = tens.to_xy()
qxx, qxy, qyx, qyy = crd.dirx.x, crd.dirx.y, crd.diry.x, crd.diry.y
exx = qxx**2*sxx + qxx*qyx*sxy + qxx*qyx*syx + qyx**2*syy
eyy = qxy**2*sxx + qxy*qyy*sxy + qxy*qyy*syx + qyy**2*s... | Python | nomic_cornstack_python_v1 |
from google.appengine.ext import db
from lib.http_utils import asset_size
import math
import logging
comment ------------------------------------------------------------------------------
comment Configuration
comment ------------------------------------------------------------------------------
set DEFAULT_MAP_BYTES =... | from google.appengine.ext import db
from lib.http_utils import asset_size
import math
import logging
# ------------------------------------------------------------------------------
# Configuration
# ------------------------------------------------------------------------------
DEFAULT_MAP_BYTES = 1000
DEFAULT_NU... | Python | zaydzuhri_stack_edu_python |
import logging , os , sys , json , subprocess
function tokenize_label_words imagenet_words_string
begin
string Each ImageNet label has one or more words that are associated with it. Each one should be used and say-d. This function tokenizes a string representing all words that refer to an ImageNet label.
return split i... | import logging, os, sys, json, subprocess
def tokenize_label_words(imagenet_words_string):
'''Each ImageNet label has one or more words that are associated with it. Each
one should be used and say-d. This function tokenizes a string representing
all words that refer to an ImageNet label.'''
retur... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
set x = array range 0 2 0.01
set y = sin 2 * pi * x
set N = 7
for i in range N 0 - 1
begin
set offset = call ScaledTranslation 1 - i call IdentityTransform
set shadow_trans = transData + offset
plot x y linewidth=4 color=strin... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
x = np.arange(0, 2, 0.01)
y = np.sin(2*np.pi*x)
N = 7
for i in range(N, 0, -1):
offset = transforms.ScaledTranslation(
1, -i, transforms.IdentityTransform())
shadow_trans = plt.gca().transData+of... | Python | zaydzuhri_stack_edu_python |
comment Uses metadata to help assess degrees
import os , sys
import SonicScrewdriver as utils
set tuple rowindices columns metadata = call readtsv string /Users/tunder/Dropbox/PythonScripts/hathimeta/ExtractedMetadata.tsv
set tuple modelindices modelcolumns modeldata = call readtsv string /Users/tunder/Dropbox/PythonSc... | # Uses metadata to help assess degrees
import os, sys
import SonicScrewdriver as utils
rowindices, columns, metadata = utils.readtsv("/Users/tunder/Dropbox/PythonScripts/hathimeta/ExtractedMetadata.tsv")
modelindices, modelcolumns, modeldata = utils.readtsv("/Users/tunder/Dropbox/PythonScripts/hathimeta/newgenretabl... | Python | zaydzuhri_stack_edu_python |
function get_method_name self
begin
return method_name
end function | def get_method_name(self):
return self.method_name | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment 评价标准
import numpy as np | # -*- coding: utf-8 -*-
## 评价标准
import numpy as np
| Python | zaydzuhri_stack_edu_python |
function configuration self
begin
comment type: () -> Dict[str, str]
return dict string source source ; string location location ; string uri uri ; string options options ; string cache_dir cache_dir
end function | def configuration(self):
# type: () -> Dict[str, str]
return {
'source': self.source,
'location': self.location,
'uri': self.uri,
'options': self.options,
'cache_dir': self.cache_dir
} | Python | nomic_cornstack_python_v1 |
function _get_weights bn_layer_node
begin
return ordered dictionary list items weights + list items weights
end function | def _get_weights(bn_layer_node):
return collections.OrderedDict(
list(bn_layer_node.input_layers[0].weights.items()) +
list(bn_layer_node.weights.items())) | Python | nomic_cornstack_python_v1 |
import numpy as np
import argparse
import cv2
from keras.models import Sequential
from keras.layers.core import Dense , Dropout , Flatten
from keras.layers.convolutional import Conv2D
from keras.optimizers import Adam
from keras.layers.pooling import MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator... | import numpy as np
import argparse
import cv2
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Flatten
from keras.layers.convolutional import Conv2D
from keras.optimizers import Adam
from keras.layers.pooling import MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
f... | Python | zaydzuhri_stack_edu_python |
function amcheck lst_p pattern subset=true
begin
set result = false
if subset
begin
for pat in lst_p
begin
set result1 = call issubset set call get_pattern
set result2 = call issubset set call get_pattern
if result1 or result2
begin
set result = true
break
end
end
end
else
begin
for pat in lst_p
begin
set result1 = cal... | def amcheck(lst_p, pattern, subset=True):
result = False
if subset:
for pat in lst_p:
result1 = set(pattern.get_pattern()).issubset(set(pat.get_pattern()))
result2 = set(pattern.inv_pattern()).issubset(set(pat.get_pattern()))
if result1 or result2:
res... | Python | nomic_cornstack_python_v1 |
comment !C:\Users\hafiz666\AppData\Local\Programs\Python\Python37-32\python.exe
comment this is the home page in which i imported headers.py which have the template html and css (which is same on every page containing css and navigations) and it opens a div called content and in every page
comment i print all of the dy... | #!C:\Users\hafiz666\AppData\Local\Programs\Python\Python37-32\python.exe
#this is the home page in which i imported headers.py which have the template html and css (which is same on every page containing css and navigations) and it opens a div called content and in every page
#i print all of the dynamic data in it an... | Python | zaydzuhri_stack_edu_python |
function read_tiff_with_pil filename
begin
comment import mpop.imageo.formats.ninjotiff as ninjotiff
comment for inf in ninjotiff.info(filename):
comment print inf, '\n'
from PIL import Image
set im = open filename
comment @UndefinedVariable
set arr = array im
set channels = list
if length shape == 2
begin
comment @Un... | def read_tiff_with_pil(filename):
# import mpop.imageo.formats.ninjotiff as ninjotiff
# for inf in ninjotiff.info(filename):
# print inf, '\n'
from PIL import Image
im = Image.open(filename)
arr = np.array(im) # @UndefinedVariable
channels = []
if len(arr.shape) == 2:
channe... | Python | nomic_cornstack_python_v1 |
from text import Text
from voice import Voice | from text import Text
from voice import Voice
| Python | zaydzuhri_stack_edu_python |
import argparse
import os
import subprocess
function execute_cmd cmd
begin
set process = popen cmd stdout=PIPE
wait process
return decode communicate process at 0
end function
function get_cpu_info
begin
set cpu_info = split read popen string cat /proc/cpuinfo string
set cpu_info_dict = dict
for line in cpu_info
begin... | import argparse
import os
import subprocess
def execute_cmd(cmd):
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
process.wait()
return process.communicate()[0].decode()
def get_cpu_info():
cpu_info = os.popen("cat /proc/cpuinfo").read().split('\n')
cpu_info_dict = {}
for line in cpu... | Python | zaydzuhri_stack_edu_python |
function copy self
begin
return call __class__ *self.parameters
end function | def copy( self ):
return self.__class__( *self.parameters ) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Thu Apr 2 16:23:00 2020 @author: Jeet
from wordcloud import WordCloud
import pandas as pd
import matplotlib.pyplot as plt
import ast
from nltk import ngrams
import collections
function tokens_to_setence df column_name
begin
comment Convert to... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 2 16:23:00 2020
@author: Jeet
"""
from wordcloud import WordCloud
import pandas as pd
import matplotlib.pyplot as plt
import ast
from nltk import ngrams
import collections
def tokens_to_setence(df, column_name):
#Convert tokens into sentence... | Python | zaydzuhri_stack_edu_python |
string Parse all project JIRA issues of the given type and pass them to parse_jira
import urllib2
import json
import datetime
import parse_jira as pj
set prot = string https://
set query_url = string issues.apache.org/jira/rest/api/latest/search?maxResults=100&jql=
set query_url = string issues.connectopensource.org/re... | """ Parse all project JIRA issues of the given type
and pass them to parse_jira"""
import urllib2
import json
import datetime
import parse_jira as pj
prot = 'https://'
query_url = 'issues.apache.org/jira/rest/api/latest/search?maxResults=100&jql='
query_url = 'issues.connectopensource.org/rest/api/latest/search?m... | Python | zaydzuhri_stack_edu_python |
from domain.student import Student
from repository.studentRepo import studentRepo
from service.UndoService import FunctionCall , OperationCall , CascadedOperation
class studentServiceException extends Exception
begin
string custom exception handler for student service
function __init__ self msg
begin
set _msg = msg
end... | from domain.student import Student
from repository.studentRepo import studentRepo
from service.UndoService import FunctionCall, OperationCall, CascadedOperation
class studentServiceException(Exception):
""" custom exception handler for student service """
def __init__(self,msg):
self._msg = msg
class... | Python | zaydzuhri_stack_edu_python |
function ray_distributed_data_generation imgenf size nimg seedg=123 test_flag=false
begin
if not have_ray
begin
raise call RuntimeError string Package ray is required for use of this function.
end
if test_flag
begin
call init ignore_reinit_error=true
end
else
begin
call init
end
decorator remote
function data_gen seed ... | def ray_distributed_data_generation(
imgenf: Callable, size: int, nimg: int, seedg: float = 123, test_flag: bool = False
) -> Array:
if not have_ray:
raise RuntimeError("Package ray is required for use of this function.")
if test_flag:
ray.init(ignore_reinit_error=True)
else:
ra... | Python | nomic_cornstack_python_v1 |
function get_attribute_value self typ attr_name
begin
for base_typ in call _get_mro typ
begin
set serialized_base = call serialize_type base_typ
if serialized_base is none
begin
continue
end
set value = get attribute_values at serialized_base attr_name
if value is not none
begin
return value
end
end
for else
begin
retu... | def get_attribute_value(self, typ, attr_name):
for base_typ in self._get_mro(typ):
serialized_base = self.serialize_type(base_typ)
if serialized_base is None:
continue
value = self.attribute_values[serialized_base].get(attr_name)
if value is not No... | Python | nomic_cornstack_python_v1 |
function rotate arr amt
begin
set copy = arr at slice : :
for tuple i val in enumerate arr
begin
set arr at i = copy at i + amt % length arr
end
end function
set mylist = list 1 2 3 4 5 6 7
print mylist
call rotate mylist 2
print mylist | def rotate(arr, amt):
copy = arr[:]
for i, val in enumerate(arr):
arr[i] = copy[(i+amt) % len(arr)]
mylist = [1, 2, 3, 4, 5, 6, 7]
print(mylist)
rotate(mylist, 2)
print(mylist)
| Python | zaydzuhri_stack_edu_python |
function __error bot update error
begin
set logger = call getLogger __name__
warning string Update "%s" caused error "%s" update error
end function | def __error(bot, update, error):
logger = logging.getLogger(__name__)
logger.warning('Update "%s" caused error "%s"', update, error) | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
import pickle
function process_data_for_labels ticker
begin
set hm_days : int = 7
set df = read csv string sp500_joined_closes.csv index_col=0
set tickers = call tolist
comment print(tickers)
fill missing df 0 inplace=true
for i in range 1 hm_days + 1
begin
comment price of 2days
... | import numpy as np
import pandas as pd
import pickle
def process_data_for_labels(ticker : str):
hm_days : int = 7
df = pd.read_csv('sp500_joined_closes.csv', index_col=0)
tickers = df.columns.values.tolist()
# print(tickers)
df.fillna(0, inplace=True)
for i in range(1, hm_days +1):
# p... | Python | zaydzuhri_stack_edu_python |
import pygame
import math
from jam.common.Vec3d import Vec3d , AXIS_VECTORS
class Basket
begin
function __init__ self net
begin
from Court import Court
set net = net
set netPos = call getNetPos net + call Vec3d 0.5 0 0 * net
set netBaseBot = call Vec3d net * LENGTH / 2 + 2 * BASKET_OFFSET 0 0
set netBaseTop = netPos
se... | import pygame
import math
from jam.common.Vec3d import Vec3d, AXIS_VECTORS
class Basket:
def __init__(self, net):
from Court import Court
self.net = net
netPos = Court.getNetPos(net) + Vec3d(0.5, 0, 0) * net
self.netBaseBot = Vec3d(net * (Court.LENGTH / 2 + 2 * Court.BASKET_OFFSET... | Python | zaydzuhri_stack_edu_python |
function AccessSelections self TopDoc=defaultNamedNotOptArg Component=defaultNamedNotOptArg
begin
return call InvokeTypes 2 LCID 1 tuple 11 0 tuple tuple 9 1 tuple 9 1 TopDoc Component
end function | def AccessSelections(self, TopDoc=defaultNamedNotOptArg, Component=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(2, LCID, 1, (11, 0), ((9, 1), (9, 1)),TopDoc
, Component) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import os
import signal
import shlex
import subprocess
import wiringpi2
from time import time , sleep
set abspath = absolute path path __file__
set dname = directory name path abspath
change directory dname
comment Some of these constants are from
comment https://github.com/WiringPi/WiringP... | #!/usr/bin/env python
import os
import signal
import shlex
import subprocess
import wiringpi2
from time import time, sleep
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
# Some of these constants are from
# https://github.com/WiringPi/WiringPi/blob/master/wiringPi/wiringPi.h
INPUT... | Python | zaydzuhri_stack_edu_python |
import csv
import numpy as np
import matplotlib.pyplot as plt
import math
from scipy import signal
from scipy.signal import find_peaks
set filename_Source = string ./data2/b-12.5-1.csv
set filename = string ./data1_arrange/c-12.5-1.csv
set AccX = list
set AccY = list
set AccZ = list
set GyroX = list
set GyroY = lis... | import csv
import numpy as np
import matplotlib.pyplot as plt
import math
from scipy import signal
from scipy.signal import find_peaks
filename_Source = './data2/b-12.5-1.csv'
filename = './data1_arrange/c-12.5-1.csv'
AccX = []
AccY = []
AccZ = []
GyroX = []
GyroY = []
GyroZ = []
with open(filename) as f:
reade... | Python | zaydzuhri_stack_edu_python |
try
begin
set tuple a b = tuple decimal a decimal b
end
except ValueError
begin
pass
end
print string Сумма значений: a + b | try:
a, b = float(a), float(b)
except ValueError:
pass
print("Сумма значений:\n", a + b)
| Python | zaydzuhri_stack_edu_python |
function at self *args
begin
return call qvector_lvar_t_at self *args
end function | def at(self, *args):
return _ida_hexrays.qvector_lvar_t_at(self, *args) | Python | nomic_cornstack_python_v1 |
function num_words_in word
begin
for i in word
begin
Ellipsis
end
return Ellipsis
end function | def num_words_in(word):
for i in word:
...
return ... | Python | nomic_cornstack_python_v1 |
async function get_ip
begin
comment Grabs external IP address from ipify.org.
async_with call ClientSession trust_env=true as session
begin
async_with get session string https://api.ipify.org?format=json ssl=false as response
begin
set resp = await read response
end
return dict string ip resp
end
end function | async def get_ip():
# Grabs external IP address from ipify.org.
async with aiohttp.ClientSession(trust_env=True) as session:
async with session.get(
"https://api.ipify.org?format=json", ssl=False
) as response:
resp = await response.read()
return {"ip": resp} | Python | nomic_cornstack_python_v1 |
function balloon_text self arg
begin
call balloon_text self arg
if call currentThread == thread
begin
return
end
try
begin
set value = eval arg f_globals call get_locals curframe
end
except any
begin
set tuple t v = call exc_info at slice : 2 :
if is instance t str
begin
set exc_name = t
end
else
begin
set exc_name =... | def balloon_text(self, arg):
debugger.Debugger.balloon_text(self, arg)
if threading.currentThread() == self.thread:
return
try:
value = eval(arg, self.curframe.f_globals,
self.get_locals(self.curframe))
except:
t, v = sys.e... | Python | nomic_cornstack_python_v1 |
string Copyright Jelen forráskód a Budapesti Műszaki és Gazdaságtudományi Egyetemen tartott "Deep Learning a gyakorlatban Python és LUA alapon" tantárgy segédanyagaként készült. A tantárgy honlapja: http://smartlab.tmit.bme.hu/oktatas-deep-learning Deep Learning kutatás: http://smartlab.tmit.bme.hu/deep-learning A forr... | '''
Copyright
Jelen forráskód a Budapesti Műszaki és Gazdaságtudományi Egyetemen tartott
"Deep Learning a gyakorlatban Python és LUA alapon" tantárgy segédanyagaként készült.
A tantárgy honlapja: http://smartlab.tmit.bme.hu/oktatas-deep-learning
Deep Learning kutatás: http://smartlab.tmit.bme.hu/deep-learning
A forr... | Python | zaydzuhri_stack_edu_python |
async function send_heartbeat self
begin
set frame = call AmqpRequest TYPE_HEARTBEAT 0
set request = call AmqpEncoder
await call _write_frame frame request
end function | async def send_heartbeat(self):
frame = amqp_frame.AmqpRequest(amqp_constants.TYPE_HEARTBEAT, 0)
request = amqp_frame.AmqpEncoder()
await self._write_frame(frame, request) | Python | nomic_cornstack_python_v1 |
function highscores
begin
if method == string GET
begin
return call redirect call url_for string index
end
if method == string POST
begin
set data = dict
set score = get form string topscore
execute db string SELECT * FROM records ORDER BY score DESC LIMIT 10
set data = call fetchall
return call render_template string... | def highscores():
if request.method == "GET":
return redirect(url_for("index"))
if request.method == "POST":
data = {}
score = request.form.get("topscore")
db.execute("SELECT * FROM records ORDER BY score DESC LIMIT 10")
data = db.fetchall()
return... | Python | nomic_cornstack_python_v1 |
function ann_mean ds season=none time_bnds_varname=string time_bnds time_centered=true n_req=none
begin
comment deep=True)
set ds = copy ds
if n_req is none
begin
if season is not none
begin
set n_req = 2
end
else
begin
set n_req = 8
end
end
if time_bnds_varname is none and not time_centered
begin
raise call NotImpleme... | def ann_mean(ds, season=None, time_bnds_varname='time_bnds', time_centered=True, n_req=None):
ds = ds.copy() #deep=True)
if n_req is None:
if season is not None:
n_req = 2
else:
n_req = 8
if time_bnds_varname is None and not time_centered:
raise Not... | Python | nomic_cornstack_python_v1 |
function _line_example_2_chart price_by_date_and_country
begin
set ch = call Chart blank_labels=true x_axis_type=string datetime
call set_title string Line charts - Grouped by color
call line data_frame=sort values price_by_date_and_country string date x_column=string date y_column=string total_price color_column=strin... | def _line_example_2_chart(price_by_date_and_country):
ch = chartify.Chart(blank_labels=True, x_axis_type="datetime")
ch.set_title("Line charts - Grouped by color")
ch.plot.line(
# Data must be sorted by x column
data_frame=price_by_date_and_country.sort_values("date"),
x_column="date... | Python | nomic_cornstack_python_v1 |
if absolute m > absolute M
begin
set b = index a m
for i in range n
begin
append data string b + 1 + string + string i + 1
end
for i in range n - 1
begin
append data string n - i + string + string n - i - 1
end
end
else
begin
set b = index a M
for i in range n
begin
append data string b + 1 + string + string i + 1
e... | if abs(m)>abs(M):
b=a.index(m)
for i in range(n):
data.append(str(b+1)+" "+str(i+1))
for i in range(n-1):
data.append(str(n-i)+" "+str(n-i-1))
else:
b=a.index(M)
for i in range(n):
data.append(str(b+1)+" "+str(i+1))
for i in range(1,n):
data.append(str(i)+" "+str(... | Python | zaydzuhri_stack_edu_python |
function database self
begin
return get pulumi self string database
end function | def database(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "database") | Python | nomic_cornstack_python_v1 |
import random
function game gamer
begin
set line_1 = list field at 1 field at 2 field at 3
set line_2 = list field at 4 field at 5 field at 6
set line_3 = list field at 7 field at 8 field at 9
set column_1 = list field at 1 field at 4 field at 7
set column_2 = list field at 2 field at 5 field at 8
set column_3 = list f... | import random
def game(gamer):
line_1 = [field[1], field[2], field[3]]
line_2 = [field[4], field[5], field[6]]
line_3 = [field[7], field[8], field[9]]
column_1 = [field[1], field[4], field[7]]
column_2 = [field[2], field[5], field[8]]
column_3 = [field[3], field[6], field[9]]
diag_1 = [fiel... | Python | zaydzuhri_stack_edu_python |
function plot_predict self h=5 past_values=20 intervals=true **kwargs
begin
string Plots forecasts with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) How many past observations to show on the forecast graph? intervals : ... | def plot_predict(self, h=5, past_values=20, intervals=True, **kwargs):
""" Plots forecasts with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
How many pas... | Python | jtatman_500k |
function __check_values self row
begin
comment iterate through each element in the row
for tuple i value_str in enumerate row
begin
comment check the element has data, and that it can be cast into a float
assert length strip value_str > 0 msg format string Check values: no data in column {} i
assert call isFloat value_... | def __check_values(self, row):
# iterate through each element in the row
for i, value_str in enumerate(row):
# check the element has data, and that it can be cast into a float
assert len(value_str.strip()) > 0,\
"Check values: no data in column {}".format(i)... | Python | nomic_cornstack_python_v1 |
import sys
from pathlib import Path
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5.QtGui import *
from FruitDetection01 import predictFruitClass , getTrainedModel
set classes = dict 0 string Apple Braeburn ; 1 string Avocado ; 2 string Banana ; 3 string Corn ; 4 string Eggplant ; 5 string Fig ; 6 str... | import sys
from pathlib import Path
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5.QtGui import *
from FruitDetection01 import predictFruitClass, getTrainedModel
classes = {0: 'Apple Braeburn', 1: 'Avocado', 2: 'Banana', 3: 'Corn', 4: 'Eggplant', 5: 'Fig', 6: 'Grapefruit White', 7: 'Ki... | Python | zaydzuhri_stack_edu_python |
function predict_proba self X
begin
comment Make sure the data is DTYPE for the tree and is 2D
if get attribute X string dtype none != DTYPE or ndim != 2
begin
set X = call array2d X dtype=DTYPE
end
comment Get the dimentions of X
set tuple n_samples n_features = shape
comment Predict class from tree database
set proba... | def predict_proba(self, X):
# Make sure the data is DTYPE for the tree and is 2D
if getattr(X, "dtype", None) != DTYPE or X.ndim != 2:
X = array2d(X, dtype=DTYPE)
# Get the dimentions of X
n_samples, n_features = X.shape
# Predict class from tree database
prob... | Python | nomic_cornstack_python_v1 |
function create_notifications self n_type notification_period hosts services t_wished=none author_data=none
begin
string Create a "master" notification here, which will later (immediately before the reactionner gets it) be split up in many "child" notifications, one for each contact. :param n_type: notification type ("... | def create_notifications(self, n_type, notification_period, hosts, services,
t_wished=None, author_data=None):
"""Create a "master" notification here, which will later
(immediately before the reactionner gets it) be split up
in many "child" notifications, one for eac... | Python | jtatman_500k |
comment lerM23.ContarImpares.
set m = list comprehension list comprehension 0 for i in range 3 for i in range 2
set imp = 0
for l in range 2
begin
for c in range 3
begin
set m at l at c = integer input string Digite Valores de M { l } { c } :
end
end
for l in range 2
begin
for c in range 3
begin
if m at l at c % 2 == 1... | #lerM23.ContarImpares.
m=[[0 for i in range(3)]for i in range(2)]
imp=0
for l in range(2):
for c in range(3):
m[l][c]=int(input(f'Digite Valores de M{l}{c}: '))
for l in range(2):
for c in range(3):
if(m[l][c]%2==1):
imp+=1
if(imp!=0):
print(f'Foram Digitados {imp} Numeros Impare... | Python | zaydzuhri_stack_edu_python |
from urllib.request import urlopen
import string
from bs4 import BeautifulSoup
function fixFile file
begin
print string Fixing: + file
set wordCount = 0
set lines = list
with open file string r as text_file
begin
for line in text_file
begin
print line
set wordCount = wordCount + count line string + 1
append lines line... | from urllib.request import urlopen
import string
from bs4 import BeautifulSoup
def fixFile(file):
print("Fixing: " + file)
wordCount = 0
lines = []
with open(file, "r") as text_file:
for line in text_file:
print(line)
wordCount += line.count(' ') + 1
lines.a... | Python | zaydzuhri_stack_edu_python |
function ls
begin
return call ls OrganizationModel
end function | def ls():
return dynamodb.ls(OrganizationModel) | Python | nomic_cornstack_python_v1 |
import math
set n1 = integer input string enter a num
while n1 != 1
begin
print ceil n1 // 2
set n1 = n1 // 2
end | import math
n1=int(input("enter a num "))
while (n1!=1):
print(math.ceil(n1//2))
n1=n1//2
| Python | zaydzuhri_stack_edu_python |
async function async_set_media_image_url self url
begin
set _media_image_url = url
end function | async def async_set_media_image_url(self, url):
self._media_image_url = url | Python | nomic_cornstack_python_v1 |
while x <= 9
begin
set y = 1
while y <= x
begin
print string %d*%d=%d % tuple y x x * y end=string
set y = y + 1
end
set x = x + 1
print string
end | while x <= 9:
y=1
while y <= x:
print("%d*%d=%d"%(y,x,x*y),end="\t")
y=y+1
x=x+1
print("\n")
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment -*- coding: utf-8 -*-
from threading import Thread
from queue import Queue
class Twork extends Thread
begin
function __init__ self name task_list
begin
comment daemon
call __init__ name=name daemon=true
set task_list = task_list
end function
function get_task self
begin
set task = get ... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from threading import Thread
from queue import Queue
class Twork(Thread):
def __init__(self, name, task_list):
super().__init__(name=name, daemon=True) # daemon
self.task_list = task_list
def get_task(self):
task = self.task_list.get()
... | Python | zaydzuhri_stack_edu_python |
while a in s and i < 1000
begin
set i = i + 1
set s = replace s a b
if i == 1000
begin
print string Impossible
end
end
if i < 1000
begin
print i
end | while a in s and i<1000:
i += 1
s = s.replace(a,b)
if i == 1000:
print('Impossible')
if i<1000:
print(i) | Python | zaydzuhri_stack_edu_python |
import requests
import json
set data_url = string http://www.compjour.org/files/code/json-examples/nyt-books-bestsellers-hardcover-fiction.json
set data = loads text
set books = data at string results at string books
set s_sum = 0
for b in books
begin
if b at string publisher == string Scribner
begin
set s_sum = s_sum ... | import requests
import json
data_url = 'http://www.compjour.org/files/code/json-examples/nyt-books-bestsellers-hardcover-fiction.json'
data = json.loads(requests.get(data_url).text)
books = data['results']['books']
s_sum = 0
for b in books:
if b['publisher'] == 'Scribner':
s_sum += 1
print("A.", s_sum)
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import re
import csv
set items = dictionary
function main
begin
for i in range ordinal string J ordinal string J + 1
begin
set items at character i = list
end
with open string 座位編號_20171031_2.csv string rb as csvfile
begin
set reader = dict reader csvfile
for r... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import csv
items = dict()
def main():
for i in range(ord('J'), ord('J') + 1):
items[chr(i)] = list()
with open('座位編號_20171031_2.csv', 'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
area = row[... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import argparse
import math
import sys
import cv2
from collections import OrderedDict
import pandas as pd
import scipy.io as sio
comment global variables
set MIN_DISTANCE = 5
set GROUP_DISTANCE = 10
set COLOR_POOL = list list 1 50 200 list 150 200 9 list 255 0 0 list 10 79 0 list 200 100 0 list 25 38... | import numpy as np
import argparse
import math
import sys
import cv2
from collections import OrderedDict
import pandas as pd
import scipy.io as sio
# global variables
MIN_DISTANCE = 5
GROUP_DISTANCE = 10
COLOR_POOL = [[1,50,200],[150,200,9],[255,0,0],[10,79,0],\
[200,100,0],[25,38,0],[78,250,250],[15... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import sys
import numpy as np
from PIL import Image
set image = open argv at 1
set image_array = call asarray image
call setflags write=true
comment glitch data
set image_array = image_array - 100
set tuple h w channels = shape
set image_array2 = image_array at tuple slice : : slice : ... | #!/usr/bin/env python
import sys
import numpy as np
from PIL import Image
image = Image.open(sys.argv[1])
image_array = np.asarray(image)
image_array.setflags(write=True)
# glitch data
image_array -= 100
h,w,channels = image_array.shape
image_array2 = image_array[:,:,:]
# image_array2 = image_array[h:0:-1, w:0:-1... | Python | zaydzuhri_stack_edu_python |
function inverseTransform cfs npts
begin
set ncfs = length cfs
set h = npts // 2
set pts = list
comment Compute all the points
for it in range npts
begin
comment t is not a time but the variable of a parametric equation of the final graph
set t = it / npts
comment Compute each point
set zpt = 0
comment Addition is com... | def inverseTransform(cfs,npts):
ncfs=len(cfs)
h=npts//2
pts=[]
#Compute all the points
for it in range(npts):
t=it/npts #t is not a time but the variable of a parametric equation of the final graph
#Compute each point
zpt=0
for (n,cn) in cfs.items(): #Addition is comm... | Python | nomic_cornstack_python_v1 |
import random
import re
from geventirc import message
from commands import Kick
class WebhookMessageHandler extends object
begin
function __init__ self allowed_ips
begin
set allowed_ips = allowed_ips
end function
function webhook self request
begin
pass
end function
end class
class OperatorHandler extends object
begin
... | import random
import re
from geventirc import message
from .commands import Kick
class WebhookMessageHandler(object):
def __init__(self, allowed_ips):
self.allowed_ips = allowed_ips
def webhook(self, request):
pass
class OperatorHandler(object):
"""Authenticates a bot as an operator
... | Python | zaydzuhri_stack_edu_python |
function load_named_settings self settings_name
begin
call CC_LoadNamedSettings serial encode settings_name
end function | def load_named_settings(self, settings_name):
self.KCube.CC_LoadNamedSettings(self.serial, settings_name.encode()) | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
comment @Time : 2019/8/2 19:48
comment @Author : naihai
string 就是一个Dense层
from keras.layers import Dense , Input
import keras
function LogisticRegressionModel input_dim units weight_reg bias_reg lr
begin
set inputs = input shape=tuple input_dim
set outputs = dense units=units use_bias=true ... | # -*- coding:utf-8 -*-
# @Time : 2019/8/2 19:48
# @Author : naihai
"""
就是一个Dense层
"""
from keras.layers import Dense, Input
import keras
def LogisticRegressionModel(input_dim, units, weight_reg, bias_reg, lr):
inputs = Input(shape=(input_dim,))
outputs = Dense(units=units, use_bias=True,
... | Python | zaydzuhri_stack_edu_python |
function delete_artifact artifact_id
begin
from qiita_db.artifact import Artifact
set status = string success
set msg = string
try
begin
delete artifact_id
end
except Exception as e
begin
set status = string danger
set msg = string e
end
return dict string status status ; string message msg
end function | def delete_artifact(artifact_id):
from qiita_db.artifact import Artifact
status = 'success'
msg = ''
try:
Artifact.delete(artifact_id)
except Exception as e:
status = 'danger'
msg = str(e)
return {'status': status, 'message': msg} | Python | nomic_cornstack_python_v1 |
function db_assert request
begin
if string obj in params and string test in params
begin
set query = none
if params at string obj == string participant
begin
set query = query dbsession Participant
end
if query
begin
if params at string test == string count and string value in params
begin
if integer params at string v... | def db_assert(request):
if 'obj' in request.params and 'test' in request.params:
query = None
if request.params['obj'] == 'participant':
query = request.dbsession.query(Participant)
if query:
if request.params['test'] == 'count' and 'value' in request.params:
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment db_06 파일을 참고하여 아래의 문제를 풀어보세요
comment - 사용자에게 삭제할 유저의 ID를 입력받아
comment user_info 테이블에서 해당되는 유저의 정보를
comment 삭제하는 프로그램을 작성하세요
comment - 삭제의 성공여부를 확인하여 출력하세요
set user_id = input string 삭제할 유저의 아이디 입력 :
import pymysql
set conn = call Connect host=string localhost port=3306 user=string ... | # -*- coding: utf-8 -*-
# db_06 파일을 참고하여 아래의 문제를 풀어보세요
# - 사용자에게 삭제할 유저의 ID를 입력받아
# user_info 테이블에서 해당되는 유저의 정보를
# 삭제하는 프로그램을 작성하세요
# - 삭제의 성공여부를 확인하여 출력하세요
user_id = input('삭제할 유저의 아이디 입력 : ')
import pymysql
conn=pymysql.Connect(
host='localhost',
port=3306,
user='root',
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.