code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function R2 self z zpred
begin
set zmean = call average z
return 1 - sum z - zpred ^ 2 / sum z - zmean ^ 2
end function | def R2(self, z, zpred):
zmean = np.average(z)
return 1 - np.sum((z - zpred)**2)/np.sum((z - zmean)**2) | Python | nomic_cornstack_python_v1 |
comment Imports ##
import re
import numpy as np
import scipy.optimize as optim
import pandas as pd
from IPython.display import display , HTML , Markdown
import ipywidgets as ipw
comment Recipe Inversion Algorithm
function estim_quantities A b tol=none
begin
comment Number of ingredients
set p = shape at 1
comment Objec... | ## Imports ##
import re
import numpy as np
import scipy.optimize as optim
import pandas as pd
from IPython.display import display, HTML, Markdown
import ipywidgets as ipw
## Recipe Inversion Algorithm
def estim_quantities(A, b, tol=None):
# Number of ingredients
p = A.shape[1]
# Objective function
... | Python | zaydzuhri_stack_edu_python |
function testSearchWithNotEqualsBoolComparison self
begin
set objectID = uuid 4
yield update index dict objectID dict string test/bool true ; uuid 4 dict string test/bool false
yield commit index
set query = call parseQuery string test/bool != False
set result = yield search query
assert equal set list objectID result
... | def testSearchWithNotEqualsBoolComparison(self):
objectID = uuid4()
yield self.index.update({objectID: {u'test/bool': True},
uuid4(): {u'test/bool': False}})
yield self.index.commit()
query = parseQuery(u'test/bool != False')
result = yield self.i... | Python | nomic_cornstack_python_v1 |
comment Open Source
comment Decode By Virgo Gans
comment Subscribe Virgo Gans
from time import sleep
from os import system
comment Reset
comment Text Reset
set Color_Off = string [0m
comment Regular Colors
comment Black
set Black = string [0;30m
comment Red
set Red = string [0;31m
comment Green
set Green = string [... | #Open Source
#Decode By Virgo Gans
#Subscribe Virgo Gans
from time import sleep
from os import system
# Reset
Color_Off="\033[0m" # Text Reset
# Regular Colors
Black="\033[0;30m" # Black
Red="\033[0;31m" # Red
Green="\033[0;32m" # Green
Yellow="\033[0;33m" # Yellow
Blue="\033[0;34m... | Python | zaydzuhri_stack_edu_python |
function ks_onchange_price self
begin
for rec in self
begin
if ks_woo_regular_price
begin
if ks_woo_regular_price <= ks_woo_sale_price
begin
raise call ValidationError call _ string Sale price cannot be more than Regular price !
end
end
if ks_woo_sale_price
begin
if ks_woo_regular_price <= ks_woo_sale_price
begin
raise... | def ks_onchange_price(self):
for rec in self:
if rec.ks_woo_regular_price:
if rec.ks_woo_regular_price <= rec.ks_woo_sale_price:
raise ValidationError(_("Sale price cannot be more than Regular price !"))
if rec.ks_woo_sale_price:
if rec... | Python | nomic_cornstack_python_v1 |
function McNuggets n
begin
string n is an int Returns True if some integer combination of 6, 9 and 20 equals n Otherwise returns False.
if n == 0
begin
return false
end
set packages = dict string 20pcs 0 ; string 9pcs 0 ; string 6pcs 0
set totalPcs = 0
set remainder = n
if remainder % 20 == 0
begin
set packages at stri... | def McNuggets(n):
"""
n is an int
Returns True if some integer combination of 6, 9 and 20 equals n
Otherwise returns False.
"""
if n == 0:
return False
packages = { '20pcs': 0, '9pcs': 0, '6pcs': 0 }
totalPcs = 0
remainder = n
if remainder%20 == 0:
... | Python | zaydzuhri_stack_edu_python |
function _get_switched_vlan self
begin
return __switched_vlan
end function | def _get_switched_vlan(self):
return self.__switched_vlan | Python | nomic_cornstack_python_v1 |
function evaluate_portfolio username
begin
set user_obj = first filter username == username
set date = get args string date
if user_obj is none
begin
return call build_json_response string User does not exist
end
if not call is_valid_date_string date
begin
return call build_json_response string Not a valid date of the ... | def evaluate_portfolio(username):
user_obj = User.query.filter(User.username == username).first()
date = request.args.get('date')
if user_obj is None:
return util.build_json_response('User does not exist')
if not util.is_valid_date_string(date):
return util.build_json_response("Not a v... | Python | nomic_cornstack_python_v1 |
function tweet_token_analogy_alg self tweet_tokens spam_tokens
begin
set start = call timer
set tweet_score = 0
comment initialize words list
set words = list
print string Searching for tokens...
for token in tweet_tokens
begin
comment correction of word
set token = call correction token
comment clear word list
clear ... | def tweet_token_analogy_alg(self, tweet_tokens, spam_tokens):
start = timer()
tweet_score = 0
# initialize words list
words = []
print('Searching for tokens...')
for token in tweet_tokens:
# correction of word
token = self.spell.correction(token)... | Python | nomic_cornstack_python_v1 |
class Excercise
begin
set arg2 = 25
function __init__ self arg1
begin
set arg1 = arg1
end function
end class
set obj = call Excercise arg1=string Tom
print arg1 | class Excercise():
arg2 = 25
def __init__(self, arg1):
self.arg1 = arg1
obj = Excercise(arg1 = "Tom")
print(obj.arg1)
| Python | zaydzuhri_stack_edu_python |
from MyLibrary.LinkedLists.SinglyLinkedLists.SinglyLinkedList import SinglyLinkedList
class Solution extends object
begin
function __init__ self givenSinglyLinkedList
begin
set givenSinglyLinkedList = givenSinglyLinkedList
set l = range 20
end function
function partitionLinkedListBasedOnAGivenNumber_createNewList self ... | from MyLibrary.LinkedLists.SinglyLinkedLists.SinglyLinkedList import SinglyLinkedList
class Solution(object):
def __init__(self, givenSinglyLinkedList):
self.givenSinglyLinkedList = givenSinglyLinkedList
self.l = range(20)
def partitionLinkedListBasedOnAGivenNumber_createNewList(self, givenNum... | Python | zaydzuhri_stack_edu_python |
function _validate_ad_compliance self
begin
set action = action
if action == string updateAdsSettings
begin
return
end
comment exempt from accepts_ad check
if action not in list string adReject string adFund string adWithdraw
begin
set accepts_ads = ads_context at string enabled
assert accepts_ads msg string community ... | def _validate_ad_compliance(self):
action = self.action
if action == 'updateAdsSettings': return
if action not in ['adReject', 'adFund', 'adWithdraw']: # exempt from accepts_ad check
accepts_ads = self.ads_context['enabled']
assert accepts_ads, 'community does not acc... | Python | nomic_cornstack_python_v1 |
function __init__ self thumbImage center
begin
set center = center
set thumbImage = thumbImage
set z = call Pt 0
comment if 1, the card should fill the frame
set zoom = 0
end function | def __init__(self, thumbImage, center):
self.center = center
self.thumbImage = thumbImage
self.z = Pt(0)
self.zoom = 0 # if 1, the card should fill the frame | Python | nomic_cornstack_python_v1 |
comment Importing the Class Question from the questions.py file.
from question import Question
comment Array of prompts for the user to respond to
set question_prompts = list string What color are apples? (a) Red/Green (b) Purple (c) Orange string What color are bananas? (a) Teal (b) Magenta (c) Yellow string What colo... | from question import Question #Importing the Class Question from the questions.py file.
question_prompts = [ #Array of prompts for the user to respond to
"What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n",
"What color are bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n",
"What color are str... | Python | zaydzuhri_stack_edu_python |
for tc in range 1 integer input + 1
begin
set N = integer input
set res = list
for _ in range N
begin
append res list
end
for i in range N
begin
if i == 0
begin
set res at i = list 1
end
else
if i == 1
begin
set res at i = list 1 1
end
else
begin
append res at i 1
for j in range length res at i - 1 - 1
begin
append re... | for tc in range(1,int(input())+1):
N = int(input())
res =[]
for _ in range(N):
res.append([])
for i in range(N):
if i == 0:
res[i] = [1]
elif i == 1:
res[i] = [1,1]
else:
res[i].append(1)
for j in range(len(res[i-1])-1):
... | Python | zaydzuhri_stack_edu_python |
import pickle
comment Python Numerical and Plotting Libraries
import numpy as np
import matplotlib.pyplot as plt
call xkcd
comment HMTK Catalogue Import/Export Libraries
from hmtk.parsers.catalogue.csv_catalogue_parser import CsvCatalogueParser , CsvCatalogueWriter
comment HMTK Plotting Tools
from hmtk.plotting.seismic... | import pickle
# Python Numerical and Plotting Libraries
import numpy as np
import matplotlib.pyplot as plt
plt.xkcd()
# HMTK Catalogue Import/Export Libraries
from hmtk.parsers.catalogue.csv_catalogue_parser import CsvCatalogueParser, CsvCatalogueWriter
# HMTK Plotting Tools
from hmtk.plotting.seismicity.catalogue_pl... | Python | zaydzuhri_stack_edu_python |
function get_columns_in_expression exp
begin
return set generator expression e for e in exp if is instance e Column
end function | def get_columns_in_expression(exp: Expression) -> Set[Column]:
return set(e for e in exp if isinstance(e, Column)) | Python | nomic_cornstack_python_v1 |
function __iadd__ self matrix
begin
return call itkMatrixD44___iadd__ self matrix
end function | def __iadd__(self, matrix: 'itkMatrixD44') -> "itkMatrixD44 const &":
return _itkMatrixPython.itkMatrixD44___iadd__(self, matrix) | Python | nomic_cornstack_python_v1 |
from tkinter import *
import tkinter as tk
from tkinter import ttk
from HistoricalAnomaly import HistoricalAnomaly
from RealTime import RealTime
from tkinter import ttk
from ttkthemes import themed_tk as tk1
comment import RealGraph as rg
comment from RealGraph import RealGraph
comment import matplotlib.animation as an... | from tkinter import *
import tkinter as tk
from tkinter import ttk
from HistoricalAnomaly import HistoricalAnomaly
from RealTime import RealTime
from tkinter import ttk
from ttkthemes import themed_tk as tk1
#import RealGraph as rg
#from RealGraph import RealGraph
#import matplotlib.animation as animation
... | Python | zaydzuhri_stack_edu_python |
function test_chart_block self
begin
set browse_page = call BrowsePage title=string Browse Page slug=string browse
comment Adds a Chart Block to a browse page
set content = call StreamValue stream_block list chart_block true
call publish_page child=browse_page
comment Call management command to update values
set filena... | def test_chart_block(self):
browse_page = BrowsePage(
title='Browse Page',
slug='browse',
)
# Adds a Chart Block to a browse page
browse_page.content = StreamValue(
browse_page.content.stream_block,
[atomic.... | Python | nomic_cornstack_python_v1 |
function plot_correlation self x y T fs prn1 prn2
begin
set x = call create_constant_magnitude_signal x
set y = call create_constant_magnitude_signal y
set auto_1 = call circular_correlation x x
set auto_2 = call circular_correlation y y
set cross = call circular_correlation x y
set fig = figure figsize=tuple 12 5
set ... | def plot_correlation(self, x,y, T, fs, prn1, prn2):
x = self.create_constant_magnitude_signal(x)
y = self.create_constant_magnitude_signal(y)
auto_1 = self.circular_correlation(x, x)
auto_2 = self.circular_correlation(y, y)
cross = self.circular_correlation(x, y)
fig = pl... | Python | nomic_cornstack_python_v1 |
set numbers = list map lambda x -> round decimal x split input string
print min numbers
print max numbers
set multiplied = map lambda x -> x * 3 numbers
set uniques = sorted set multiplied
print *uniques | numbers = list(map(lambda x: round(float(x)), input().split(' ')))
print(min(numbers))
print(max(numbers))
multiplied = map(lambda x: x * 3, numbers)
uniques = sorted(set(multiplied))
print(*uniques) | Python | zaydzuhri_stack_edu_python |
string This is a reverse challenge, have fun! Input/Ouput [time limit] 4000ms (py) [input] integer n Constraints: 0 ≤ n ≤ 100. [output] integer Input: n: 1 Expected Output: 123 Input: n: 2 Expected Output: 456 Input: n: 3 Expected Output: 789 # Challenge's link: https://codefights.com/challenge/o6Jz5K69quZeuAckn #
func... | """
This is a reverse challenge, have fun!
Input/Ouput
[time limit] 4000ms (py)
[input] integer n
Constraints:
0 ≤ n ≤ 100.
[output] integer
Input:
n: 1
Expected Output:
123
Input:
n: 2
Expected Output:
456
Input:
n: 3
Expected Output:
789
# Challenge's link: https://codefights.com/challenge/o6Jz5K69quZeuAckn #... | Python | zaydzuhri_stack_edu_python |
function check ch
begin
for entry in d
begin
if entry at string name == ch
begin
return string found
end
end
return string Not Found
end function
while true
begin
set ch = input string Enter Your Name:
if ch == string stop
begin
break
end
print call check ch
end | def check(ch):
for entry in d:
if entry['name']==ch:
return("found")
return("Not Found ")
while True:
ch=input("Enter Your Name:")
if ch=='stop':
break
print(check(ch))
| Python | zaydzuhri_stack_edu_python |
async function list_local_server_async namespace=none x_additional_headers=none **kwargs
begin
if namespace is none
begin
set tuple namespace error = call get_services_namespace
if error
begin
return tuple none error
end
end
set request = call create namespace=namespace
return await call run_request_async request addit... | async def list_local_server_async(
namespace: Optional[str] = None,
x_additional_headers: Optional[Dict[str, str]] = None,
**kwargs
):
if namespace is None:
namespace, error = get_services_namespace()
if error:
return None, error
request = ListLocalServer.create(
... | Python | nomic_cornstack_python_v1 |
from pandas import read_csv
import numpy as np
set file_name = string ~/Desktop/machine learn/ch7/data3.0.csv
set test_name = string ~/Desktop/machine learn/ch7/test.csv
set dataset = read csv file_name
set test_input = read csv test_name
function pn x mu sigma
begin
return 1 / square root 2 * pi * sigma * exp - x - mu... | from pandas import read_csv
import numpy as np
file_name = "~/Desktop/machine learn/ch7/data3.0.csv"
test_name = "~/Desktop/machine learn/ch7/test.csv"
dataset = read_csv(file_name)
test_input = read_csv(test_name)
def pn(x, mu, sigma):
return 1 / (np.sqrt(2 * np.pi) * sigma) * np.exp(-(x-mu) ** 2 / (2 * sigma ... | Python | zaydzuhri_stack_edu_python |
function getProjectStages
begin
set pl = list
for tuple ix g in enumerate sorted PR_STAGES at string PROGRESS
begin
set stage = PR_STAGES at string STAGE at g
set stage at string index = ix + 1
append pl stage
end
return pl
end function | def getProjectStages():
pl = []
for ix, g in enumerate(sorted(PR_STAGES['PROGRESS'])):
stage = PR_STAGES['STAGE'][g]
stage['index'] = ix + 1
pl.append(stage)
return pl | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string Parse data from csv and log files.
import csv
import re
from aoristic import aoristic
from aoristic.units import Unit
comment import aoristic
comment import time
function log_to_dict hotspot t_map
begin
string Reads log file and creates a dict
comment co... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Parse data from csv and log files.
"""
import csv
import re
from aoristic import aoristic
from aoristic.units import Unit
# import aoristic
# import time
def log_to_dict(hotspot, t_map):
"""
Reads log file and creates a dict
"""
# counter = 0
patte... | Python | zaydzuhri_stack_edu_python |
comment _*_ coding:utf-8 _*_
class client
begin
comment Define client object
function __init__ self id first_name last_name email gender city source
begin
set id = id
set first_name = first_name
set last_name = last_name
set email = email
set gender = gender
set city = city
set source = source
end function
function __s... | # _*_ coding:utf-8 _*_
class client:
##Define client object
def __init__(self,id , first_name,last_name,email,gender,city,source):
self.id = id
self.first_name = first_name
self.last_name = last_name
self.email = email
self.gender = gender
self.city = city
... | Python | zaydzuhri_stack_edu_python |
import json
function lambda_handler event context
begin
comment Get the input numbers
set num1 = event at string Input-1
set num2 = event at string Input-2
comment Calculate the sum
set result = num1 + num2
comment Return the output
return dict string Result result
end function | import json
def lambda_handler(event, context):
# Get the input numbers
num1 = event['Input-1']
num2 = event['Input-2']
# Calculate the sum
result = num1 + num2
# Return the output
return {
'Result': result
} | Python | jtatman_500k |
function get_transformation_matrix theta=45
begin
comment in radians
set theta = theta / 360 * 2 * pi
set hx = cos theta
set sy = sin theta
set S = array list list 1 hx 0 list 0 sy 0 list 0 0 1
comment S_inv = np.linalg.inv(S)
comment old_coords = np.array([[2, 2, 1], [6, 6, 1]]).T
comment new_coords = np.matmul(S, old... | def get_transformation_matrix(theta=45):
theta = theta/360 * 2 * np.pi # in radians
hx = np.cos(theta)
sy = np.sin(theta)
S = np.array([[1, hx, 0],
[0, sy, 0],
[0, 0, 1]])
#S_inv = np.linalg.inv(S)
#old_coords = np.array([[2, 2, 1], [6, 6, 1]]).T
#new_co... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Author : 野猪佩奇
comment @contact : 2790279232@qq.com
comment @File : dependent_data.py
comment @Software: PyCharm
comment @Time : 2020/5/9 16:23
from Python3_Requests_Excel.util.operation_excel import OperationExcel
from Python3_Requests_Excel.base.runme... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 野猪佩奇
# @contact : 2790279232@qq.com
# @File : dependent_data.py
# @Software: PyCharm
# @Time : 2020/5/9 16:23
from Python3_Requests_Excel.util.operation_excel import OperationExcel
from Python3_Requests_Excel.base.runmethond import RunMethod
from... | Python | zaydzuhri_stack_edu_python |
function config self
begin
function _convert_fields item
begin
if get item string boolean
begin
return true
end
else
if get item string number
begin
return integer get item string number
end
else
if get item string string
begin
return capitalize get item string string
end
end function
set kwargs = dictionary comprehens... | def config(self) -> config.Config:
def _convert_fields(item):
if item.get("boolean"):
return True
elif item.get("number"):
return int(item.get("number"))
elif item.get("string"):
return item.get("string").capitalize()
... | Python | nomic_cornstack_python_v1 |
function subtract_resources res_a res_b
begin
return dictionary comprehension resource : value - get res_b resource 0 for tuple resource value in call iteritems res_a
end function | def subtract_resources(res_a, res_b):
return {resource: value - res_b.get(resource, 0)
for resource, value in iteritems(res_a)} | Python | nomic_cornstack_python_v1 |
function create self data
begin
set data = dict string attribute data
set content = call create data
set result = get content string attribute_id
if not result
begin
raise call FailedJobError string Result from Magento : %s % content
end
return result
end function | def create(self, data):
data = {
"attribute":data
}
content = super(ProductAttributeAdapter,self).create(data)
result = content.get('attribute_id')
if not result :
raise FailedJobError("Result from Magento : %s"%content)
return resu... | Python | nomic_cornstack_python_v1 |
function fit_easing_mobility self
begin
comment Get start of increase in mobility
set outbreak_m_increase_week = outbreak_obs_weekly at elms_m_lockdown at - 1
set elms_m_easing = outbreak_obs_weekly >= outbreak_m_increase_week
set subset = outbreak_obs_weekly at elms_m_easing
set T = days / 7 + 1
set t_easing_fit = arr... | def fit_easing_mobility(self):
# Get start of increase in mobility
self.outbreak_m_increase_week = self.outbreak_obs_weekly[self.elms_m_lockdown][-1]
self.elms_m_easing = (self.outbreak_obs_weekly>=self.outbreak_m_increase_week)
subset = self.outbreak_obs_weekly[self.elms... | Python | nomic_cornstack_python_v1 |
function array_graph_xy x XYs
begin
if type XYs is ndarray
begin
set Xs = XYs at 0
set Ys = XYs at 1
end
else
begin
set tuple Xs Ys = map list zip *XYs
end
return call _inner_array_graph x Xs Ys
end function | def array_graph_xy(x, XYs):
if type(XYs) is np.ndarray:
Xs = XYs[0]
Ys = XYs[1]
else:
Xs, Ys = map(list, zip(*XYs))
return _inner_array_graph(x, Xs, Ys) | Python | nomic_cornstack_python_v1 |
class CommandLog extends object
begin
function __init__ self
begin
set _entries = list
set _latest_unexecuted = 0
end function
decorator property
function latest_unexecuted self
begin
return _latest_unexecuted
end function
function add_command self cmd
begin
string :type cmd: level.commands.Command.Command
append _entr... | class CommandLog(object):
def __init__(self):
self._entries = list()
self._latest_unexecuted = 0
@property
def latest_unexecuted(self):
return self._latest_unexecuted
def add_command(self, cmd):
""":type cmd: level.commands.Command.Command"""
self._entries.appen... | Python | zaydzuhri_stack_edu_python |
function output_profile runtime all_results
begin
set all_results_list = list
for daf in all_results
begin
for location_daf in all_results at daf
begin
for result in all_results at daf at location_daf
begin
append all_results_list result
end
end
end
set results = sorted all_results_list key=lambda x -> - x at string s... | def output_profile(runtime, all_results):
all_results_list = []
for daf in all_results:
for location_daf in all_results[daf]:
for result in all_results[daf][location_daf]:
all_results_list.append(result)
results = sorted(all_results_list, key=lambda x: -x["score"])
po... | Python | nomic_cornstack_python_v1 |
set lst = list 7 * 7
append lst 1
append lst 888
append lst list 9 8 5
append list string abc
print lst | lst = [7]*7
lst.append(1)
lst.append(888)
lst.append([9,8,5])
list.append('abc')
print(lst)
| Python | zaydzuhri_stack_edu_python |
function puntuacion self *args **kwargs
begin
return numero
end function | def puntuacion(self, *args, **kwargs):
return self.numero | Python | nomic_cornstack_python_v1 |
function __rrshift__ self other
begin
if is instance other Callable
begin
return self @ other
end
else
begin
comment Function application
return call self other
end
end function | def __rrshift__(self, other):
if isinstance(other, Callable):
return self @ other
else:
return self(other) # Function application | Python | nomic_cornstack_python_v1 |
function test_client_wpa_personal_pkt_MTU_2g self get_vif_state lf_test station_names_twog create_lanforge_chamberview_dut get_configuration
begin
set profile_data = setup_params_general at string ssid_modes at string wpa_personal at 0
set ssid_name = profile_data at string ssid_name
set security_key = profile_data at ... | def test_client_wpa_personal_pkt_MTU_2g(self, get_vif_state,
lf_test, station_names_twog, create_lanforge_chamberview_dut,
get_configuration):
profile_data = setup_params_general["ssid_modes"]["wpa_personal"][0]
ssid... | Python | nomic_cornstack_python_v1 |
comment Probabbility that atleast one woman is chosen
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import bernoulli
from scipy.stats import norm
from scipy.stats import binom
import random
from scipy.special import comb
comment let the numbers 1,2,3 denote the women while the others denote men
se... | #Probabbility that atleast one woman is chosen
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import bernoulli
from scipy.stats import norm
from scipy.stats import binom
import random
from scipy.special import comb
list_people =(list)(range(1,9)) #let the numbers 1,2,3 denote the women whil... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string kMeans 알고리즘 - 비계층적(확인적) 군집분석 - 군집수(k) 알고 있는 경우 이용
import pandas as pd
comment array
import numpy as np
comment from sklearn.cluster import kMeans # model
comment model
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
comment 1. txt dataset load as np.array
comment ... | # -*- coding: utf-8 -*-
"""
kMeans 알고리즘
- 비계층적(확인적) 군집분석
- 군집수(k) 알고 있는 경우 이용
"""
import pandas as pd
import numpy as np # array
#from sklearn.cluster import kMeans # model
from sklearn.cluster import KMeans # model
import matplotlib.pyplot as plt
# 1. txt dataset load as np.array
# text file -... | Python | zaydzuhri_stack_edu_python |
function tmdb_movies_genre id page raw=false
begin
call import_tmdb
set result = call movies id=id language=LANG page=page
if raw
begin
return result
end
else
begin
return call list_tmdb_movies result
end
end function | def tmdb_movies_genre(id, page, raw=False):
import_tmdb()
result = tmdb.Genres(id).movies(id=id, language=LANG, page=page)
if raw: return result
else: return list_tmdb_movies(result) | Python | nomic_cornstack_python_v1 |
function test_get_id self
begin
call create_or_update data=create
comment First pick up by name
set res_name = call get_by_name entity=Topic fqdn=fullyQualifiedName
comment Then fetch by ID
set res = call get_by_id entity=Topic entity_id=string __root__
assert equal id id
end function | def test_get_id(self):
self.metadata.create_or_update(data=self.create)
# First pick up by name
res_name = self.metadata.get_by_name(
entity=Topic, fqdn=self.entity.fullyQualifiedName
)
# Then fetch by ID
res = self.metadata.get_by_id(entity=Topic, entity_id... | Python | nomic_cornstack_python_v1 |
function get_action_command self
begin
set action_command = none
end function | def get_action_command(self):
self.action_command = None | Python | nomic_cornstack_python_v1 |
function update_cid cid
begin
set st = time
set count = 0
for tuple i g in enumerate call query_to_tuples string select distinct group_id from hits_mv where crawl_id = %s cid
begin
set g = g at 0
if i == 0
begin
info string processing %s, %s %s i cid g
end
call updatehitgroup g cid
set count = count + 1
end
call execut... | def update_cid(cid):
st = time.time()
count = 0
for i, g in enumerate(query_to_tuples("select distinct group_id from hits_mv where crawl_id = %s", cid)):
g = g[0]
if i == 0:
log.info("processing %s, %s %s", i, cid, g)
updatehitgroup(g, cid)
count += 1
execu... | Python | nomic_cornstack_python_v1 |
function _get_data self file_lines
begin
raise NotImplementedError
end function | def _get_data(self, file_lines):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
import os
import json
import time
set LOG_DIR = string ./log
class Logger
begin
string Get data from the text files and output a JSON file at the end of game containing all the informations easy to read
function __init__ self player_id
begin
comment type: list
set _log = list
set id = player_id
end function
function lo... | import os
import json
import time
LOG_DIR = './log'
class Logger():
"""
Get data from the text files and output a JSON file
at the end of game containing all the informations
easy to read
"""
def __init__(self, player_id: int):
self._log = list() # type: list
self.id = player... | Python | zaydzuhri_stack_edu_python |
string 6.2.MaxProductOfThree Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R).
import unittest
function solution A
begin
comment write your code in Python 2.7
sort A
if A at 1 >= 0
begin
return A at - 1 * A at - 2 * A at - 3
end
else
begin
return max A at 0 * A at 1 * A at - 1 A at - 3 * A at - 2 * A at - 1
end
en... | """
6.2.MaxProductOfThree
Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R).
"""
import unittest
def solution(A):
# write your code in Python 2.7
A.sort()
if A[1] >= 0:
return A[-1] * A[-2] * A[-3]
else:
return max(A[0] * A[1] * A[-1], A[-3] * A[-2] * A[-1])
class TestSolution... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string The command line system for the Choc_an System.
import functions_list as f
import decimal as decimal
function intro
begin
string The introduction text to the Choc_an system.
end function | #!/usr/bin/env python
"""The command line system for the Choc_an System."""
import functions_list as f
import decimal as decimal
def intro():
"""The introduction text to the Choc_an system.""" | Python | zaydzuhri_stack_edu_python |
comment !usr/bin/python3
import re
import sys
function co_occurs
begin
set entidade = argv at 1
set ficheiro = argv at 2
set count = 1
with open ficheiro as file
begin
set texto = read file
end
set frases = split re string [.?!]+ texto
for frase in frases
begin
if find frase string { entidade } != - 1
begin
set temp = ... | #!usr/bin/python3
import re
import sys
def co_occurs():
entidade=sys.argv[1]
ficheiro=sys.argv[2]
count=1
with open (ficheiro) as file:
texto=file.read()
frases=re.split(r'[.?!]+',texto)
for frase in frases:
if(frase.find(f'{entidade}')!=-1):
temp=re.findall(r'{\w+}'... | Python | zaydzuhri_stack_edu_python |
function string_analysis input_string
begin
string This function takes a string as input and returns the length of the string, the number of unique characters (excluding uppercase letters), and a dictionary with the frequency of each unique lowercase character. The function iterates over the string, incrementing a coun... | def string_analysis(input_string):
"""
This function takes a string as input and returns the length of the string, the number of unique characters (excluding uppercase letters),
and a dictionary with the frequency of each unique lowercase character.
The function iterates over the string, incrementing a... | Python | jtatman_500k |
function find_median arr
begin
set n = length arr
set mid = n // 2
comment Find the kth smallest element using the QuickSelect algorithm
set kth_smallest = call quickselect arr 0 n - 1 mid
comment Count the frequency of the kth smallest element
set frequency = count arr kth_smallest
comment Find the medians with the hi... | def find_median(arr):
n = len(arr)
mid = n // 2
# Find the kth smallest element using the QuickSelect algorithm
kth_smallest = quickselect(arr, 0, n - 1, mid)
# Count the frequency of the kth smallest element
frequency = arr.count(kth_smallest)
# Find the medians with the high... | Python | jtatman_500k |
function blackwhite image
begin
set output = image at tuple slice : : slice : : 0 + image at tuple slice : : slice : : 1 + image at tuple slice : : slice : : 2 / 3
return output
end function | def blackwhite(image: np.ndarray):
output = (image[:, :, 0] + image[:, :, 1] + image[:, :, 2]) / 3
return output | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sat Apr 17 15:06:38 2021 @author: Grupo 1
from numpy import arange , nonzero
from copy import copy
class Nodo
begin
set hijos = list
set padre = 0
set f = 0
set g = 0
set h = 0
set meta = false
function __init__ self ciudad_cabecera heuristi... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 17 15:06:38 2021
@author: Grupo 1
"""
from numpy import arange, nonzero
from copy import copy
class Nodo:
hijos = []
padre = 0
f = 0
g = 0
h = 0
meta = False
def __init__(self, ciudad_cabecera, heuristica=0, me... | Python | zaydzuhri_stack_edu_python |
string [summary]
from HSKVocabSite.apps.HSKVocabSiteApp.models import Hsklevels
from HSKVocabSite.apps.HSKVocabSiteApp.models import Vocab
set DATAPATH = string /home/matt/Desktop/Work/CV/Projects/HSKVocabSiteRepo/data/lists/HSK2012_Vocab/
comment For each HSK Vocab Level dataset
for i in range 1 7
begin
with open DATA... | """[summary]
"""
from HSKVocabSite.apps.HSKVocabSiteApp.models import Hsklevels
from HSKVocabSite.apps.HSKVocabSiteApp.models import Vocab
DATAPATH = '/home/matt/Desktop/Work/CV/Projects/HSKVocabSiteRepo/data/lists/HSK2012_Vocab/'
#For each HSK Vocab Level dataset
for i in range(1,7):
with open(DATAPATH+'L'+str... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[ ]:
function not_gir
begin
set name = input string İsmi:
set surname = input string Soyadı:
set not1 = input string Not1:
set not2 = input string Not2:
set not3 = input string Not3:
with open string notes.txt string a encoding=string utf-8 as file
begin
writ... | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
def not_gir():
name = input("İsmi:")
surname = input("Soyadı:")
not1 = input("Not1:")
not2 = input("Not2:")
not3 = input("Not3:")
with open("notes.txt","a",encoding="utf-8") as file:
file.write(name+" "+surname+":"+not1+","+not2+","+not3... | Python | zaydzuhri_stack_edu_python |
function _set_sky_products self sky=true
begin
set sky_spectrum = sky
set prodtype_map = copy default_prodtype_map
set prodnames = copy default_prodnames
set step_map = copy default_step_map
if sky
begin
info string Setting sky product names.
update prodtype_map sky_prodtype_map
update prodnames sky_prodnames
update st... | def _set_sky_products(self, sky=True):
self.sky_spectrum = sky
self.prodtype_map = self.default_prodtype_map.copy()
self.prodnames = self.default_prodnames.copy()
self.step_map = self.default_step_map.copy()
if sky:
log.info('Setting sky product names.')
... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
import time
import sys
function output
begin
set i = 1
while true
begin
comment print "this is %s time output"%i
set msg = string this is %s time output % i
comment FIXME:have to use sys.stdout...
write stdout msg
write stdout string
flush stdout
sleep 3
set i = i + 1
if i >= 3
begin
break
end
end
... | # coding=utf-8
import time
import sys
def output():
i = 1
while True:
#print "this is %s time output"%i
msg = "this is %s time output"%i
# FIXME:have to use sys.stdout...
sys.stdout.write(msg)
sys.stdout.write('\n')
sys.stdout.flush()
time.sleep(3)
i=i+1
if i>= 3:
break
if __name__=="__ma... | Python | zaydzuhri_stack_edu_python |
function fcylinder self base apex radius texture
begin
append _objects call FCylinder base apex radius texture
end function | def fcylinder(self, base, apex, radius, texture):
self._objects.append(FCylinder(base, apex, radius, texture)) | Python | nomic_cornstack_python_v1 |
comment pragma: no cover
function _tile_generator self i is_labels
begin
set i = integer i
set tiles = call _list_tiles i
comment track epoch (must be same for label and non-label)
set epoch = _access_counts at if expression is_labels then 1 else 0 at i
set _access_counts at if expression is_labels then 1 else 0 at i =... | def _tile_generator(self, i, is_labels): # pragma: no cover
i = int(i)
tiles = self._list_tiles(i)
# track epoch (must be same for label and non-label)
epoch = self._access_counts[1 if is_labels else 0][i]
self._access_counts[1 if is_labels else 0][i] += 1
if not tiles:
... | Python | nomic_cornstack_python_v1 |
function get self loop ctrl
begin
set prefix = string
if loop is not none or loop == - 1
begin
set prefix = prefix + format string /sl/{} loop
end
call send_message prefix + string /get list ctrl uri string /get_response
end function | def get(self, loop, ctrl):
prefix = ''
if loop is not None or loop == -1:
prefix += '/sl/{}'.format(loop)
self._osc_client.send_message(prefix + '/get', [ctrl, self._osc_server.uri, '/get_response']) | Python | nomic_cornstack_python_v1 |
function test_migrations_failures use_upload_jobs_table monkeypatch
begin
comment Mock alembic
set attribute migrations string op call MagicMock
comment Mock sqlalchemy
set mock_session_builder = call MagicMock
set mock_session = call MagicMock
set return_value = mock_session
set attribute migrations string Session moc... | def test_migrations_failures(use_upload_jobs_table, monkeypatch):
# Mock alembic
monkeypatch.setattr(migrations, "op", MagicMock())
# Mock sqlalchemy
mock_session_builder = MagicMock()
mock_session = MagicMock()
mock_session_builder.return_value = mock_session
monkeypatch.setattr(migrations... | Python | nomic_cornstack_python_v1 |
function filter_stream self req method filename stream data
begin
if sql_read_only and filename == string admin_users.html
begin
set stream = stream ? call attr string value string Remove session and permissions data for selected accounts
end
return stream
end function | def filter_stream(self, req, method, filename, stream, data):
if self.sql_read_only and filename == 'admin_users.html':
stream |= Transformer(".//input[@name='remove']").attr('value', 'Remove session and permissions data for selected accounts')
return stream | Python | nomic_cornstack_python_v1 |
function _setup_http_session self
begin
set headers = dict string Content-type string application/json
if _id_token
begin
update headers dict string authorization format string Bearer {} _id_token
end
update headers headers
comment TODO is this unsafe????
set verify = false
end function | def _setup_http_session(self):
headers = {"Content-type": "application/json"}
if (self._id_token):
headers.update({"authorization": "Bearer {}".format(
self._id_token)})
self._session.headers.update(headers)
# TODO is this unsafe????
self._session.veri... | Python | nomic_cornstack_python_v1 |
function updatea t0=none t1=none x0=none P0=none Q=none f=none z=none R=none h=none **kwargs
begin
comment Weighting of center sigma point, Time Update step 1
set W0 = 1.0 / 3.0
comment Number of elements in state vector
set n = size
comment Number of elements in measurement vector
set m = size
comment Number of elemen... | def updatea(t0=None, t1=None, x0=None, P0=None, Q=None, f=None, z=None, R=None, h=None,**kwargs):
W0=1.0/3.0 #Weighting of center sigma point, Time Update step 1
n=x0.size #Number of elements in state vector
m=z.size #Number of elements in measurement vector
q=Q.sh... | Python | nomic_cornstack_python_v1 |
function sum arg1 arg2
begin
set total = arg1 + arg2
end function
sum 10 20 | def sum( arg1, arg2 ):
total = arg1 + arg2
sum( 10, 20 ) | Python | zaydzuhri_stack_edu_python |
function split_path path minsegs=1 maxsegs=none rest_with_last=false
begin
if not maxsegs
begin
set maxsegs = minsegs
end
if minsegs > maxsegs
begin
raise call ValueError string minsegs > maxsegs: %d > %d % tuple minsegs maxsegs
end
if rest_with_last
begin
set segs = split path string / maxsegs
set minsegs = minsegs + ... | def split_path(path, minsegs=1, maxsegs=None, rest_with_last=False):
if not maxsegs:
maxsegs = minsegs
if minsegs > maxsegs:
raise ValueError('minsegs > maxsegs: %d > %d' % (minsegs, maxsegs))
if rest_with_last:
segs = path.split('/', maxsegs)
minsegs += 1
max... | Python | nomic_cornstack_python_v1 |
string Doomsday Fuel ============= Making fuel for the LAMBCHOP's reactor core is a tricky process because of the exotic matter involved. It starts as raw ore, then during processing, begins randomly changing between forms, eventually reaching a stable form. There may be multiple stable forms that a sample could ultima... | """
Doomsday Fuel
=============
Making fuel for the LAMBCHOP's reactor core is a tricky process because of the exotic matter involved. It starts as raw ore, then during processing, begins randomly changing between forms, eventually reaching a stable form. There may be multiple stable forms that a sample could ultimate... | Python | zaydzuhri_stack_edu_python |
comment 정확성: 53.8 합계: 53.8 / 100.0 FAIL
function solution str1 str2
begin
set _str1 = call make_multiset str1
set _str2 = call make_multiset str2
return call make_jaccard _str1 _str2
end function
comment 다중집합 만들기
function make_multiset str0
begin
set _str = list
set str0 = lower str0
for i in range length str0 - 1
beg... | # 정확성: 53.8 합계: 53.8 / 100.0 FAIL
def solution(str1, str2):
_str1 = make_multiset(str1)
_str2 = make_multiset(str2)
return make_jaccard(_str1, _str2)
# 다중집합 만들기
def make_multiset(str0):
_str = []
str0 = str0.lower()
for i in range(len(str0)-1):
if 'a' <= str0... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
from sklearn.metrics import mean_squared_error
from pandas import read_csv
import matplotlib.pyplot as plt
from statsmodels.tsa.vector_ar.var_model import VAR
from matplotlib import pyplot
import csv
set dataset = read csv string input.csv header=0 infer_datetime_format=true parse_dates=list string ... | import pandas as pd
from sklearn.metrics import mean_squared_error
from pandas import read_csv
import matplotlib.pyplot as plt
from statsmodels.tsa.vector_ar.var_model import VAR
from matplotlib import pyplot
import csv
dataset = read_csv('input.csv', header=0, infer_datetime_format=True, parse_dates=['date'], index_co... | Python | zaydzuhri_stack_edu_python |
function send_command self command
begin
if is_iina_start
begin
print format string put command to queue: {} command
put command
end
end function | def send_command(self, command):
if self.is_iina_start:
print("put command to queue: {}".format(command))
self.commond_queue.put(command) | Python | nomic_cornstack_python_v1 |
function delete_layer self group_id
begin
set layer = layers at group_id
del layers at group_id
set is_attached = false
end function | def delete_layer(self, group_id):
layer = self.layers[group_id]
del self.layers[group_id]
layer.is_attached = False | Python | nomic_cornstack_python_v1 |
function on_finish self
begin
pass
end function | def on_finish(self):
pass | Python | nomic_cornstack_python_v1 |
for i in range 2 11 2
begin
print string Vai + string i
end | for i in range (2, 11, 2):
print('Vai ' + str(i)) | Python | zaydzuhri_stack_edu_python |
function getugly index
begin
set uglyarr = list 0 * index
set ugly2index = 0
set ugly3index = 0
set ugly5index = 0
set uglyindex = 0
set uglyarr at 0 = 1
set uglyindex = uglyindex + 1
while uglyindex < index
begin
set uglyarr at uglyindex = min uglyarr at ugly2index * 2 uglyarr at ugly3index * 3 uglyarr at ugly5index *... | def getugly(index):
uglyarr = [0] * index
ugly2index = 0
ugly3index = 0
ugly5index = 0
uglyindex = 0
uglyarr[0] = 1
uglyindex += 1
while uglyindex < index:
uglyarr[uglyindex] = min(uglyarr[ugly2index] * 2,
uglyarr[ugly3index] * 3,
... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function largestSumOfAverages self A K
begin
set cumulative = list 0
for a in A
begin
append cumulative cumulative at - 1 + a
end
function average i j
begin
return cumulative at j - cumulative at i / j - i
end function
set N = length A
comment Default values account for K = 0
set dp ... | class Solution(object):
def largestSumOfAverages(self, A, K):
cumulative = [0]
for a in A: cumulative.append(cumulative[-1] + a)
def average(i, j):
return (cumulative[j] - cumulative[i]) / (j - i)
N = len(A)
# Default values account for K = 0
dp = [avera... | Python | zaydzuhri_stack_edu_python |
function run_node_task self caller_data logger inception
begin
call set_caller_node inception
call write_status string running_node format string Running: {} name
log name string Running task
set acc_data = dict name dict string acc-params dict ; string acc-data dict ; string acc-json dict
if string acc-params in ke... | def run_node_task(self, caller_data, logger, inception):
self.set_caller_node(inception)
self.write_status('running_node', 'Running: {}'.format(self.name))
logger.log(self.name, 'Running task')
acc_data = {self.name: {'acc-params': {},
'acc-data': {},
... | Python | nomic_cornstack_python_v1 |
function test_create_user_with_email_successful self
begin
set email = string test@test.test
set password = string secret123
set user = call create_user email=email password=password
assert equal email email
assert true call check_password password
end function | def test_create_user_with_email_successful(self):
email = 'test@test.test'
password = 'secret123'
user = get_user_model().objects.create_user(
email=email,
password=password
)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import cmath
import math
import matplotlib.gridspec as gridspec
class Calculator
begin
function __init__ self
begin
set n = 8
set start = 0.0
set end = pi
set step = end - start / n
set x_array = array range start end step
set y_array = cal... | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import cmath
import math
import matplotlib.gridspec as gridspec
class Calculator:
def __init__(self):
self.n = 8
self.start = 0.0
self.end = math.pi
self.step = (self.end - self.start) / self.n
self.... | Python | zaydzuhri_stack_edu_python |
function test_youtube_parse_good_result
begin
set parsed = call youtube_parse GOOD_YOUTUBE_RESPONSE
assert parsed == list tuple string oyEuk8j8imI string JustinBieberVEVO string dummy title
end function | def test_youtube_parse_good_result():
parsed = youtube_api.youtube_parse(API_DATA.GOOD_YOUTUBE_RESPONSE)
assert parsed == [('oyEuk8j8imI', 'JustinBieberVEVO', 'dummy title')] | Python | nomic_cornstack_python_v1 |
function gen_letters_list letters
begin
string Generates the ragnoli rows.
reverse letters
set row = string
for i in letters
begin
set row = row + string i + string -
end
reverse letters
pop letters 0
for i in letters
begin
set row = row + string i + string -
end
set row_letters_list = split row string -
pop row_lette... | def gen_letters_list(letters):
"""Generates the ragnoli rows."""
letters.reverse()
row = ""
for i in letters:
row = row+str(i)+"-"
letters.reverse()
letters.pop(0)
for i in letters:
row = row+str(i)+"-"
row_letters_list = row.split("-")
row_letters_list.pop()
retu... | Python | zaydzuhri_stack_edu_python |
set usd = input string Nhap so tien usd:
set tygia = input string Nhap ty gia:
set vnd = decimal usd * decimal tygia
print string Ket qua: vnd
print string Ket qua: VND { vnd } | usd = input("Nhap so tien usd: ")
tygia = input("Nhap ty gia: ")
vnd = float(usd)*float(tygia)
print("Ket qua: ", vnd)
print(f"Ket qua: VND{vnd:,.2f}") | Python | zaydzuhri_stack_edu_python |
from clase_cuadrado import Cuadrado
set obj_cuadrado = call Cuadrado 5 5 string rojo
print color
print ancho
print alto
print call calcular_area
comment mro: sivre para ver que clases se ejecutan (y su orden)
print call mro | from clase_cuadrado import Cuadrado
obj_cuadrado = Cuadrado(5, 5, 'rojo')
print(obj_cuadrado.color)
print(obj_cuadrado.ancho)
print(obj_cuadrado.alto)
print(obj_cuadrado.calcular_area())
# mro: sivre para ver que clases se ejecutan (y su orden)
print(Cuadrado.mro())
| Python | zaydzuhri_stack_edu_python |
function encodeLZ fileIn fileOut dictionarySize=1114112
begin
try
begin
set fileContent = call getFileContent fileIn
set dictionary = dict
for i in range 0 dictionarySize
begin
set dictionary at character i = i
end
set currentCode = dictionarySize
set encodedFileContent = string
set buffer = fileContent at 0
for pos ... | def encodeLZ(fileIn, fileOut, dictionarySize = 1114112):
try:
fileContent = FileWork.getFileContent(fileIn)
dictionary = {}
for i in range(0, dictionarySize):
dictionary[chr(i)] = i
currentCode = dictionarySize
encodedFileContent = "... | Python | nomic_cornstack_python_v1 |
import threading
set SPEED = 15
set MIN_HEIGHT = 200
set MAX_HEIGHT = 984
import math
comment sys нужен для передачи argv в QApplication
import sys
from PyQt5 import QtWidgets , QtCore , QtGui , QtNetwork
comment Это наш конвертированный файл дизайна
import design
from tcp import start_socket
class ClientApp extends QM... | import threading
SPEED = 15
MIN_HEIGHT = 200
MAX_HEIGHT = 984
import math
import sys # sys нужен для передачи argv в QApplication
from PyQt5 import QtWidgets, QtCore, QtGui, QtNetwork
import design # Это наш конвертированный файл дизайна
from tcp import start_socket
class ClientApp(QtWidgets.QMainWindow, design.Ui... | Python | zaydzuhri_stack_edu_python |
comment encoding: utf-8
string Created on 2018年9月17日 @author: Administrator
comment from __future__ import (absolute_import, division, print_function, unicode_literals)
import json , math
from itertools import groupby
from btc_close_2017 import line_chart
from idlelib.iomenu import encoding
set filename = string files/... | # encoding: utf-8
'''
Created on 2018年9月17日
@author: Administrator
'''
# from __future__ import (absolute_import, division, print_function, unicode_literals)
import json, math
from itertools import groupby
from btc_close_2017 import line_chart
from idlelib.iomenu import encoding
filename = "files/btc_close_2017.json... | Python | zaydzuhri_stack_edu_python |
comment Examples and Exercises From 'Computer Graphics using Open GL" by Hill 2nd Ed
comment all code by George A. Merrill (except where otherwise noted)
comment Example 3_2_2 Plotting the sinc function, revisited
import sys
import OpenGL
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import... | # Examples and Exercises From 'Computer Graphics using Open GL" by Hill 2nd Ed
# all code by George A. Merrill (except where otherwise noted)
#################################################################################################
# Example 3_2_2 Plotting the sinc function, revisited
import sys
import OpenGL
f... | Python | zaydzuhri_stack_edu_python |
comment tahminimiz birden fazla parametreye bağlı olduğunda
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
set datas = read csv string values.csv
comment print(datas)
set age = values
comment print(age)
comment encoding
set country = values
print country
from sklearn import preprocessing
set le ... | #tahminimiz birden fazla parametreye bağlı olduğunda
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
datas = pd.read_csv('values.csv')
#print(datas)
age = datas.iloc[:,1:4].values
#print(age)
#encoding
country = datas.iloc[:,0:1].values
print(country)
from sklearn import preproce... | Python | zaydzuhri_stack_edu_python |
comment n = 4
set n = integer input
set direction = list
set finalDestinationX = 0
set finalDestinationY = 0
for i in range n
begin
set currentData = input
append direction split currentData string
end
for i in direction
begin
if i at 0 == string север
begin
set finalDestinationY = finalDestinationY + integer i at 1
e... | # n = 4
n= int(input())
direction = []
finalDestinationX = 0
finalDestinationY = 0
for i in range(n):
currentData = input()
direction.append(currentData.split(' '))
for i in direction:
if i[0] == 'север':
finalDestinationY += int(i[1])
elif i[0] == 'юг':
finalDestinationY -= int(i[1])
... | Python | zaydzuhri_stack_edu_python |
from repeating_vowels import multi_vowel_words
import unittest
class TestRepeatingVowels extends TestCase
begin
function test_basic self
begin
set testcase = string Life is beautiful
set expected = list string beautiful
assert equal call multi_vowel_words testcase expected
end function
function test_empty self
begin
se... | from repeating_vowels import multi_vowel_words
import unittest
class TestRepeatingVowels(unittest.TestCase):
def test_basic(self):
testcase = "Life is beautiful"
expected = ['beautiful']
self.assertEqual(multi_vowel_words(testcase),expected)
def test_empty(self):
testcase =... | Python | zaydzuhri_stack_edu_python |
function get_D x
begin
return sin x * 0.5 + 1
end function | def get_D(x):
return np.sin(x)*0.5+1 | Python | nomic_cornstack_python_v1 |
function on_comboBox_currentIndexChanged self p0
begin
comment TODO: not implemented yet
set selectedItem = decode string call toUtf8 string utf-8
end function
comment raise NotImplementedError | def on_comboBox_currentIndexChanged(self, p0):
# TODO: not implemented yet
self.selectedItem = str(p0.toUtf8()).decode('utf-8')
#raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function exists self
begin
comment TODO: What about broken sym-links?
return exists path path
end function | def exists(self):
# TODO: What about broken sym-links?
return os.path.exists(self.path) | Python | nomic_cornstack_python_v1 |
function traffic_statuscodes_requestresponsetype self **kwargs
begin
set url_path = string traffic/statuscodes/requestresponsetype
debug string Get list of request-response types
set body = call _make_body kwargs
return call _common_get request_path=url_path parameters=body
end function | def traffic_statuscodes_requestresponsetype(self, **kwargs):
url_path = 'traffic/statuscodes/requestresponsetype'
self.logger.debug(f"Get list of request-response types")
body = self._make_body(kwargs)
return self._common_get(request_path=url_path, parameters=body) | Python | nomic_cornstack_python_v1 |
from pathlib import Path
import sys
import os
string python生成文件目录树:方法一使用pathlib库 原地址:https://blog.csdn.net/yaoyefengchen/article/details/80195231 Python有一个标准文件路径处理库 os.path ,从 Python3.4 开始,Python 又加入了一个标准库 pathlib ,该库是跨平台的、面向对象的路径操作库。
comment 第一步:查看基本操作
comment p = Path('/Volumes/B/8手机壁纸') #创建路径对象
comment print(p.name)... | from pathlib import Path
import sys
import os
"""python生成文件目录树:方法一使用pathlib库
原地址:https://blog.csdn.net/yaoyefengchen/article/details/80195231
Python有一个标准文件路径处理库 os.path ,从 Python3.4 开始,Python 又加入了一个标准库 pathlib ,该库是跨平台的、面向对象的路径操作库。
"""
# 第一步:查看基本操作
# p = Path('/Volumes/B/8手机壁纸') #创建路径对象
# print(p.name) # 获取路径地址中的文件名
#... | Python | zaydzuhri_stack_edu_python |
function __str__ self
begin
return format string {} name
end function | def __str__(self):
return "{}".format(self.name) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.