code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function _read_ignored_tokens self allow_end_of_string begin set is_in_comment = false while _offset < length _document_str begin set char = _document_str at _offset if char in string  , begin pass end else if char == string # begin set is_in_comment = true end else if char in string begin set is_in_comment = false e...
def _read_ignored_tokens(self, allow_end_of_string): is_in_comment = False while self._offset < len(self._document_str): char = self._document_str[self._offset] if char in u"\ufeff \t,": pass elif char == '#': is_in_comment = True ...
Python
nomic_cornstack_python_v1
function test_fftw_rfft2 Nx=64 Ny=none n=7200 begin comment settings if Ny is none begin set Ny = Nx end comment set random stream function set A = randn Nx Ny set Ai = copy A set tstart = time for i in range n begin set Ah = call rfft2 Ai threads=1 set Ai = call irfft2 Ah threads=1 end set tend = time comment error af...
def test_fftw_rfft2(Nx = 64, Ny = None, n = 7200): # settings if Ny is None: Ny = Nx # set random stream function A = np.random.randn(Nx,Ny) Ai = A.copy() tstart = time.time() for i in range(n): Ah = pyfftw.interfaces.numpy_fft.rfft2(Ai, threads=1) Ai = pyfftw.interfaces.n...
Python
nomic_cornstack_python_v1
function run_accessibility_tests self result_file begin comment get webdriver instance set seleniumlib = call get_library_instance string SeleniumLibrary set webdriver = driver comment create axe instance set axe_instance = call Axe webdriver comment inject axe-core javascript into current page call inject comment run ...
def run_accessibility_tests(self, result_file): # get webdriver instance seleniumlib = BuiltIn().get_library_instance('SeleniumLibrary') webdriver = seleniumlib.driver # create axe instance self.axe_instance = Axe(webdriver) # inject axe-core javascript into current page ...
Python
nomic_cornstack_python_v1
function merge_wmi new_wmis begin import inspect import re from dicts import wmi set wmi_src = search string WMI = {([^}]+)} get source wmi MULTILINE assert wmi_src msg string Unable to parse WMI dict body set wmi_src_dict = dict for line in call splitlines begin set line = strip line string , if not line begin contin...
def merge_wmi(new_wmis: dict) -> Tuple[set, str]: import inspect import re from .dicts import wmi wmi_src = re.search('WMI = {([^}]+)}', inspect.getsource(wmi), re.MULTILINE) assert wmi_src, 'Unable to parse WMI dict body' wmi_src_dict = {} for line in wmi_src.group(1).splitlines(): ...
Python
nomic_cornstack_python_v1
function test_pv_2D_potential_no_trigger self begin set trigger = call pv_2D_potential 1.5 0.6 at 2 assert false trigger end function
def test_pv_2D_potential_no_trigger(self): trigger = pv_2D_potential(1.50, 0.60)[2] self.assertFalse(trigger)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment filename :using_sys.py import sys
#!/usr/bin/python #filename :using_sys.py import sys
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import os.path comment STAGE 0: Load configurations comment In the config.py file, you can change important variables such as tokenizer to use import config set my_config = call Configuration comment for easier testing, you could supply a list of PMIDs in the c...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path # STAGE 0: Load configurations # In the config.py file, you can change important variables such as tokenizer to use import config my_config = config.Configuration() # for easier testing, you could supply a list of PMIDs in the constructor here # my_config ...
Python
zaydzuhri_stack_edu_python
function replace self string begin replace buffer index string end function
def replace(self, string: str) -> None: self.buffer.replace(self.index, string)
Python
nomic_cornstack_python_v1
function point_info cube_path x y point_type allow_outside=false begin set point_type = lower point_type if point_type not in set literal string image string ground begin raise exception string { point_type } is not a valid point type, valid types are ["image", "ground"] end if is instance x Number and is instance y Nu...
def point_info(cube_path, x, y, point_type, allow_outside=False): point_type = point_type.lower() if point_type not in {"image", "ground"}: raise Exception(f'{point_type} is not a valid point type, valid types are ["image", "ground"]') if isinstance(x, Number) and isinstance(y, Number): x...
Python
nomic_cornstack_python_v1
function test_periodic self time expect_call fakedevice fakeproduct begin with call patch_sender as fake_client begin with call freeze_time time begin call trigger_scheduled_events end end assert called == expect_call end function
def test_periodic(self, time, expect_call, fakedevice, fakeproduct): with patch_sender() as fake_client: with freeze_time(time): trigger_scheduled_events() assert fake_client.as_device.called == expect_call
Python
nomic_cornstack_python_v1
function __init__ self **kw begin set payload = pop kw string payload set package = pop kw string package set settings = call get_settings app if not package begin raise call PackageRegistrationError string Missing required package definition for package process. end if not is instance package dict begin raise call Pac...
def __init__(self, **kw): self.payload = kw.pop("payload") self.package = kw.pop("package") self.settings = get_settings(app) if not self.package: raise PackageRegistrationError("Missing required package definition for package process.") if not isinstance(self.package...
Python
nomic_cornstack_python_v1
function speed n begin if n <= 70 begin print string Ok end else if n > 70 begin set i = 70 set c = 0 while i < n begin set c = c + 1 set i = i + 5 end print c string points if c > 12 begin print string licensed suspended end end end function set n = integer input string enter a num: call speed n
def speed(n): if n<=70: print("Ok") elif n>70: i=70 c=0 while i<n: c=c+1 i=i+5 print(c,"points") if c>12: print("licensed suspended") n=int(input("enter a num:")) speed(n)
Python
zaydzuhri_stack_edu_python
function to_bytes self frame state begin string Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. This object may be used to track information across cal...
def to_bytes(self, frame, state): """ Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. ...
Python
jtatman_500k
function winning_round_player players begin assert players msg string Must have players to determine winner comment a winner player is defined as the player comment with the highest top card set top = none for player in players begin comment only compare if the player has something to compare if not cards_in_play begin...
def winning_round_player(players): assert players, "Must have players to determine winner" # a winner player is defined as the player # with the highest top card top = None for player in players: # only compare if the player has something to compare if not player.cards_in_play: co...
Python
nomic_cornstack_python_v1
function test_error_no_why_but_message self begin set e = dict string isError true ; string a string b ; string message tuple string delete-server assert equal call get_validated_event e list dict string message tuple string Deleting {server_id} server ; string isError true ; string why string Deleting {server_id} serv...
def test_error_no_why_but_message(self): e = {'isError': True, 'a': 'b', "message": ('delete-server',)} self.assertEqual( get_validated_event(e), [{'message': ('Deleting {server_id} server',), 'isError': True, 'why': 'Deleting {server_id} server', 'a':...
Python
nomic_cornstack_python_v1
import turtle call speed 1 call shape string turtle for i in range 3 begin call forward 100 call left 120 end call exitonclick
import turtle turtle.speed(1) turtle.shape("turtle") for i in range(3): turtle.forward(100) turtle.left(120) turtle.exitonclick()
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Oct 6 11:48:21 2020 @author: Nima comment import pycxsimulator import numpy as np from scipy.integrate import odeint from abc import ABC , abstractmethod from pylab import * import time from tkinter import * from tkinter import messagebox from tkinter import ttk impor...
# -*- coding: utf-8 -*- """ Created on Tue Oct 6 11:48:21 2020 @author: Nima """ # import pycxsimulator import numpy as np from scipy.integrate import odeint from abc import ABC, abstractmethod from pylab import * import time from tkinter import * from tkinter import messagebox from tkinter import ttk import tkinter...
Python
zaydzuhri_stack_edu_python
import pyttsx3 import datetime import speech_recognition as sr import wikipedia import smtplib import webbrowser as wb import os import pyautogui import psutil import pyjokes import random import operator import json import time from urllib.request import urlopen import requests import wolframalpha set engine = call in...
import pyttsx3 import datetime import speech_recognition as sr import wikipedia import smtplib import webbrowser as wb import os import pyautogui import psutil import pyjokes import random import operator import json import time from urllib.request import urlopen import requests import wolframalpha engine = py...
Python
zaydzuhri_stack_edu_python
comment Melhore o jogo do desafio 028 onde o computador vai pensar em um comment numero entre 0 e 10. Só que agora o jagador vai tentar advinhar ate acertar comment Mostrando no final quantos palpites foram necessarios para vencer import random set num = random integer 0 10 set cont = 1 set n1 = integer input string Di...
#Melhore o jogo do desafio 028 onde o computador vai pensar em um #numero entre 0 e 10. Só que agora o jagador vai tentar advinhar ate acertar #Mostrando no final quantos palpites foram necessarios para vencer import random num = random.randint(0,10) cont = 1 n1 = int(input('Digite um numero: ')) while(n1 != n...
Python
zaydzuhri_stack_edu_python
function get_projects_for_admin admin_id preferred_locale search_dto begin return call get_projects_for_admin admin_id preferred_locale search_dto end function
def get_projects_for_admin( admin_id: int, preferred_locale: str, search_dto: ProjectSearchDTO ): return Project.get_projects_for_admin(admin_id, preferred_locale, search_dto)
Python
nomic_cornstack_python_v1
function rand_bipartite utype etype vtype num_src_nodes num_dst_nodes num_edges idtype=int64 device=cpu F begin comment TODO(minjie): support RNG as one of the arguments. set eids = random choice num_src_nodes * num_dst_nodes num_edges replace=false set eids = call zerocopy_to_numpy eids set rows = call zerocopy_from_n...
def rand_bipartite( utype, etype, vtype, num_src_nodes, num_dst_nodes, num_edges, idtype=F.int64, device=F.cpu(), ): # TODO(minjie): support RNG as one of the arguments. eids = random.choice( num_src_nodes * num_dst_nodes, num_edges, replace=False ) eids = F.zeroc...
Python
nomic_cornstack_python_v1
function prepare self p_args begin string Prepares list of operations to execute based on p_args, list of todo items contained in _todo_ids attribute and _subcommand attribute. if _todo_ids begin set id_position = index p_args string {} comment Not using MultiCommand abilities would make EditCommand awkward if _multi b...
def prepare(self, p_args): """ Prepares list of operations to execute based on p_args, list of todo items contained in _todo_ids attribute and _subcommand attribute. """ if self._todo_ids: id_position = p_args.index('{}') # Not using MultiCommand ...
Python
jtatman_500k
function f n begin for i in range 1 11 begin print format string {} * {} = {} n i n * i end end function
def f(n): for i in range(1, 11): print("{} * {} = {}".format(n, i, n*i))
Python
jtatman_500k
function determine_middle_in_triangle segments snap_threshold snap_threshold_error_multiplier begin set candidates = list for tuple idx linestring in enumerate segments begin set others = copy segments pop others idx if sum generator expression distance other < snap_threshold * snap_threshold_error_multiplier for othe...
def determine_middle_in_triangle( segments: List[LineString], snap_threshold: float, snap_threshold_error_multiplier: float, ) -> List[LineString]: candidates = [] for idx, linestring in enumerate(segments): others = segments.copy() others.pop(idx) if ( sum( ...
Python
nomic_cornstack_python_v1
function get_element_at self x y begin for gobj in reversed _contents begin if call contains x y begin return gobj end end return none end function
def get_element_at(self, x, y): for gobj in reversed(self._contents): if gobj.contains(x, y): return gobj return None
Python
nomic_cornstack_python_v1
function trainModel trainFileName testFileName modelFile begin set tuple tokenizer encoder = call __loadTokenizerAndEncoder trainFileName set tuple train_labels train_utterances = call __prepareDataSet trainFileName set tuple test_labels test_utterances = call __prepareDataSet testFileName comment one-hot encoding set ...
def trainModel(trainFileName, testFileName, modelFile): tokenizer, encoder = __loadTokenizerAndEncoder(trainFileName) train_labels, train_utterances = __prepareDataSet(trainFileName) test_labels, test_utterances = __prepareDataSet(testFileName) # one-hot encoding x_train = tokenizer.texts_to_matr...
Python
nomic_cornstack_python_v1
comment Enter your code here. Read input from STDIN. Print output to STDOUT set N = integer strip input set X = list comprehension decimal i for i in split strip input string set Y = list comprehension decimal i for i in split strip input string set rankx = list comprehension index sorted X X at i + 1 for i in range N ...
# Enter your code here. Read input from STDIN. Print output to STDOUT N = int(input().strip()) X = [float(i) for i in input().strip().split(' ')] Y = [float(i) for i in input().strip().split(' ')] rankx = [sorted(X).index(X[i])+1 for i in range(N)] ranky = [sorted(Y).index(Y[i])+1 for i in range(N)] d_i_sq = [(rankx[...
Python
zaydzuhri_stack_edu_python
function default_context begin set ctxt = _default_context_ if ctxt is none begin from enaml import default_operator_context set ctxt = call default_operator_context set _default_context_ = ctxt end return ctxt end function
def default_context(): ctxt = OperatorContext._default_context_ if ctxt is None: from enaml import default_operator_context ctxt = default_operator_context() OperatorContext._default_context_ = ctxt return ctxt
Python
nomic_cornstack_python_v1
function viewfactory self begin raise call NotImplementedError end function
def viewfactory(self): raise NotImplementedError()
Python
nomic_cornstack_python_v1
function writerows self row begin if not resolved begin call _resolve_writer end if is instance resolved ReaderType begin raise call AttributeError string Object CSV has no attribute writerows end call _resolve_writer write rows resolved row end function
def writerows(self, row): if not self.resolved: self._resolve_writer() if isinstance(self.resolved, ReaderType): raise AttributeError('Object CSV has no attribute writerows') self._resolve_writer() self.resolved.writerows(row)
Python
nomic_cornstack_python_v1
function __getitem__ self processor_index begin return list map lambda t -> tasks_durations at t processors at processor_index end function
def __getitem__(self, processor_index: int): return list(map( lambda t: self.instance.tasks_durations[t], self.processors[processor_index] ))
Python
nomic_cornstack_python_v1
function _iterate self from_time to_time begin return call NotImplementedError end function
def _iterate(self, from_time, to_time): return NotImplementedError()
Python
nomic_cornstack_python_v1
from typing import List class Solution begin function minIncrementForUnique_MK1 self A begin sort A set ret = 0 for i in range 1 length A begin if A at i <= A at i - 1 begin set ret = ret + A at i - 1 + 1 - A at i set A at i = A at i - 1 + 1 end end return ret end function function minIncrementForUnique_MK2 self A begi...
from typing import List class Solution: def minIncrementForUnique_MK1(self, A: List[int]) -> int: A.sort() ret = 0 for i in range(1, len(A)): if A[i] <= A[i - 1]: ret += A[i - 1] + 1 - A[i] A[i] = A[i - 1] + 1 return ret def minIncre...
Python
zaydzuhri_stack_edu_python
import requests import time function downloader url file_name begin print format string Start of download {} :- {} file_name call ctime time set r = get requests url allow_redirects=true write open file_name string wb content print format string End of download {} :- {} file_name call ctime time end function call downl...
import requests import time def downloader(url,file_name): print("Start of download {} :- {}".format(file_name,time.ctime(time.time()))) r = requests.get(url, allow_redirects=True) open(file_name, 'wb').write(r.content) print("End of download {} :- {}".format(file_name,time.ctime(time.time()))) downlo...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun May 2 12:46:47 2021 @author: kalan comment 401. Binary Watch comment Easy comment A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least signif...
# -*- coding: utf-8 -*- """ Created on Sun May 2 12:46:47 2021 @author: kalan """ # 401. Binary Watch # Easy # A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the ri...
Python
zaydzuhri_stack_edu_python
comment To change this license header, choose License Headers in Project Properties. comment To change this template file, choose Tools | Templates comment and open the template in the editor. set __author__ = string eshan set __date__ = string $Jan 25, 2016 11:52:47 PM$ import Queue import collections import itertools...
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. __author__ = "eshan" __date__ = "$Jan 25, 2016 11:52:47 PM$" import Queue import collections import itertools def consume(iterator, n): co...
Python
zaydzuhri_stack_edu_python
for i in l begin print i end
for i in l: print(i)
Python
zaydzuhri_stack_edu_python
import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from Queue import Queue import time import subprocess class EmittingStream extends QObject begin set textWritten = call pyqtSignal str function write self text begin call emit string text end function end class class MyThread extends QThread begin function...
import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from Queue import Queue import time import subprocess class EmittingStream(QObject): textWritten = pyqtSignal(str) def write(self, text): self.textWritten.emit(str(text)) class MyThread(QThread): def __init__(self): super...
Python
zaydzuhri_stack_edu_python
string https://codingcompetitions.withgoogle.com/codejam/round/000000000019fef4/00000000003179a1 function run begin set cases = integer input for i in range 1 cases + 1 begin set _ = integer input set leading = dict set available_digits = set for _ in range 10 ^ 4 begin set tuple _ s = split input string set leading a...
""" https://codingcompetitions.withgoogle.com/codejam/round/000000000019fef4/00000000003179a1 """ def run(): cases = int(input()) for i in range(1, cases + 1): _ = int(input()) leading = {} available_digits = set() for _ in range(10**4): _, s = input().split(' ') ...
Python
zaydzuhri_stack_edu_python
string Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output - Fizz instead of the number and for the multiples of five output - Buzz. For numbers which are multiples of both three and five output - FizzBuzz. function fizzbuzz n begin return list comp...
""" Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output - Fizz instead of the number and for the multiples of five output - Buzz. For numbers which are multiples of both three and five output - FizzBuzz. """ def fizzbuzz(n): return ['Fizz'...
Python
zaydzuhri_stack_edu_python
function queryObjectFieldId self doId fieldId context=0 begin assert call debugStateCall self comment Create a message set datagram = call PyDatagram call addServerHeader doId ourChannel STATESERVER_OBJECT_QUERY_FIELD call addUint32 doId call addUint16 fieldId comment A context that can be used to index the response if...
def queryObjectFieldId(self, doId, fieldId, context=0): assert self.notify.debugStateCall(self) # Create a message datagram = PyDatagram() datagram.addServerHeader( doId, self.ourChannel, STATESERVER_OBJECT_QUERY_FIELD) datagram.addUint32(doId) data...
Python
nomic_cornstack_python_v1
function OnSave self event begin save end function
def OnSave(self, event): self.viewer.Save()
Python
nomic_cornstack_python_v1
function set_unspents self unspents begin string Set the unspent inputs for a transaction. :param unspents: a list of :class:`TxOut` (or the subclass :class:`Spendable`) objects corresponding to the :class:`TxIn` objects for this transaction (same number of items in each list) if length unspents != length txs_in begin ...
def set_unspents(self, unspents): """ Set the unspent inputs for a transaction. :param unspents: a list of :class:`TxOut` (or the subclass :class:`Spendable`) objects corresponding to the :class:`TxIn` objects for this transaction (same number of items in each list) ...
Python
jtatman_500k
import argparse function gen_split_dataset file keywords mode validation testing thread begin string Generate and split dataset according to the given criteria Arguments: file(str): keywords(str): mode(str): validation(float): testing(float): thread(str): pass end function if __name__ == string __main__ begin set parse...
import argparse def gen_split_dataset(file, keywords, mode, validation, testing, thread): """ Generate and split dataset according to the given criteria Arguments: file(str): keywords(str): mode(str): validation(float): testing(float): thread(s...
Python
zaydzuhri_stack_edu_python
function any_of_validator self verbose=1 begin assert children set result = false for child in children begin if call validate begin set result = true end end if not result and verbose > 1 begin for child in children begin call validate verbose end end return result end function
def any_of_validator(self, verbose=1): assert self.children result = False for child in self.children: if child.validate(): result = True if not result and verbose > 1: for child in self.children: child.validate(verbose) re...
Python
nomic_cornstack_python_v1
function dict_max_merge dict1 dict2 begin set dict3 = dict for tuple key value in items dict1 begin if key in dict1 and key in dict2 begin set dict3 at key = max value dict2 at key end else begin set dict3 at key = value end end for tuple key value in items dict2 begin if key not in dict3 begin set dict3 at key = valu...
def dict_max_merge(dict1, dict2): dict3 = {} for key, value in dict1.items(): if (key in dict1) and (key in dict2): dict3[key]=max(value, dict2[key]) else: dict3[key]=value for key, value in dict2.items(): if key not in dict3: dict3[key]=value ...
Python
nomic_cornstack_python_v1
comment import re comment from mrjob.job import MRJob comment class WordCount(MRJob): comment def mapper(self, _, line): comment words = re.split("[ *$&#/\t\n\f\"\'\\,.:;?!\[\](){}<>~\-_]", line.lower()) comment for word in words: comment if len(word): comment yield word, 1 comment def combiner(self, key, values): comm...
# import re # from mrjob.job import MRJob # class WordCount(MRJob): # def mapper(self, _, line): # words = re.split("[ *$&#/\t\n\f\"\'\\,.:;?!\[\](){}<>~\-_]", line.lower()) # for word in words: # if len(word): # yield word, 1 # def combiner(self, key, values):...
Python
zaydzuhri_stack_edu_python
function verify_ME7_test_results self results_file begin set full_path = call pjoin tmp_process_dir results_file for line in split read open full_path string r string begin set tuple process limit outcome ratio = split line string | at slice : 4 : assert true strip outcome == string PASSED line end end function
def verify_ME7_test_results(self, results_file): full_path = pjoin(self.tmp_process_dir, results_file) for line in open(full_path,'r').read().split('\n'): process, limit, outcome, ratio = line.split('|')[:4] self.assertTrue(outcome.strip()=='PASSED', line)
Python
nomic_cornstack_python_v1
function test_api_file_depository_fetch_from_other_file_depository self begin set file_depository = call FileDepositoryFactory set other_file_depository = call FileDepositoryFactory set jwt_token = call StudentLtiTokenFactory playlist=playlist set response = get client string /api/filedepositories/ { id } / HTTP_AUTHOR...
def test_api_file_depository_fetch_from_other_file_depository(self): file_depository = FileDepositoryFactory() other_file_depository = FileDepositoryFactory() jwt_token = StudentLtiTokenFactory(playlist=other_file_depository.playlist) response = self.client.get( f"/api/filed...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment Author: Uldis Bojars comment captsolo.net comment PRINT_CASES = True set PRINT_CASES = false import os function read_paths inp out begin set paths = dict for item in inp begin set tmp = item while tmp != string / begin set paths at tmp = true set tuple head tail = split path tmp se...
#!/usr/bin/env python # Author: Uldis Bojars # captsolo.net # PRINT_CASES = True PRINT_CASES = False import os def read_paths(inp, out): paths = {} for item in inp: tmp = item while tmp != "/": paths[tmp] = True head, tail = os.path.split(tmp) tm...
Python
zaydzuhri_stack_edu_python
string @Author: Su Ming Yi @Date: 02/13/2019 @main.py @Goal: Preprocess the images, adding diversity of the training data (1) Blur (2) Noise (3) Morphological Transformations import Blur import Noise import MorTransform from random import randint function main begin print string Start to preprocess training data. set t...
''' @Author: Su Ming Yi @Date: 02/13/2019 @main.py @Goal: Preprocess the images, adding diversity of the training data (1) Blur (2) Noise (3) Morphological Transformations ''' import Blur import Noise import MorTransform from random import randint def main(): print("Start to preprocess train...
Python
zaydzuhri_stack_edu_python
from PIL import ImageGrab from PIL import Image import os from pyzbar import pyzbar import webbrowser set results : any function grab begin string 截屏并解析二维码, 注意截屏时二维码不被遮挡。 global results comment 截屏 set img = call grab print string 正在解码... comment 解码 set results = decode pyzbar image=img symbols=list QRCODE comment 打印解析结...
from PIL import ImageGrab from PIL import Image import os from pyzbar import pyzbar import webbrowser results: any def grab(): """ 截屏并解析二维码, 注意截屏时二维码不被遮挡。 """ global results img = ImageGrab.grab() # 截屏 print('正在解码...') results = pyzbar.decode(image=img, symbols=[pyzbar...
Python
zaydzuhri_stack_edu_python
comment Task1 comment [ ] increase the number of arguments used in print() to 8 or more set student_age = 17 set student_name = string Hiroto Yamaguchi set next_year = string But next year, set graduate = string He will be official graduate. set professional = string Then he will start his professional carreer. print s...
#Task1 #[ ] increase the number of arguments used in print() to 8 or more student_age = 17 student_name = "Hiroto Yamaguchi" next_year = "But next year," graduate = "He will be official graduate." professional = "Then he will start his professional carreer." print(student_name,'will be in the class for',student_age, 'y...
Python
zaydzuhri_stack_edu_python
string 爬取一页知乎粉丝数据 import requests import csv import json function crawl begin set url = string https://www.zhihu.com/api/v4/columns/NewsFlash/followers comment 查询参数 set params = dict string limit 20 ; string offset 0 ; string include string data[*].follower_count,gender,is_followed,is_following comment 必须指定UA,否则知乎服务器会判...
""" 爬取一页知乎粉丝数据 """ import requests import csv import json def crawl(): url = "https://www.zhihu.com/api/v4/columns/NewsFlash/followers" # 查询参数 params = { "limit": 20, "offset": 0, "include": "data[*].follower_count,gender,is_followed,is_following" } # 必须指定UA,否则知乎服务器会判断请求不合法...
Python
zaydzuhri_stack_edu_python
function pdf self X Y begin raise NotImplementedError end function
def pdf(self, X, Y): raise NotImplementedError
Python
nomic_cornstack_python_v1
function distribute_equally daily_data divide=false begin string Obtains hourly values by equally distributing the daily values. Args: daily_data: daily values divide: if True, divide resulting values by the number of hours in order to preserve the daily sum (required e.g. for precipitation). Returns: Equally distribut...
def distribute_equally(daily_data, divide=False): """Obtains hourly values by equally distributing the daily values. Args: daily_data: daily values divide: if True, divide resulting values by the number of hours in order to preserve the daily sum (required e.g. for precipitation). ...
Python
jtatman_500k
for i in range idx begin set arr = list map int split input set count = 0 set s_avg = sum arr at slice 1 : : / arr at 0 for j in arr at slice 1 : : begin if s_avg < j begin set count = count + 1 end end print string %0.3f%% % count / arr at 0 * 100 end
for i in range(idx): arr = list(map(int, input().split())) count = 0 s_avg = (sum(arr[1:]))/arr[0] for j in arr[1:]: if (s_avg < j): count +=1 print('%0.3f%%'%((count/arr[0])*100))
Python
zaydzuhri_stack_edu_python
function sum_of_divisors n begin set sum_divisors = 0 for i in range 1 n + 1 begin set divisor = n % i if divisor == 0 begin set sum_divisors = sum_divisors + i end end return sum_divisors end function
def sum_of_divisors(n): sum_divisors = 0 for i in range(1, n + 1): divisor = n % i if divisor == 0: sum_divisors += i return sum_divisors
Python
zaydzuhri_stack_edu_python
function getAltHierarchyBestFit asimov_data template_maker params minimizer_settings hypo_normal check_octant begin set llh_data = call find_alt_hierarchy_fit asimov_data template_maker params hypo_normal minimizer_settings only_atm_params=true check_octant=check_octant set alt_params = call get_values call select_hier...
def getAltHierarchyBestFit(asimov_data, template_maker, params, minimizer_settings, hypo_normal, check_octant): llh_data = find_alt_hierarchy_fit( asimov_data, template_maker, params, hypo_normal, minimizer_settings, only_atm_params=True, check_octant=check_octant) a...
Python
nomic_cornstack_python_v1
function get self endpoint_uri **kwargs begin debug format string Calling base get with kwargs: {} kwargs if config at string use_https begin set url = string https:// end else begin set url = string http:// end set url = url + config at string hostname + endpoint_uri set headers = dict string Authorization string Toke...
def get(self, endpoint_uri, **kwargs): self.logger.debug("Calling base get with kwargs: {}".format(kwargs)) if self.config['use_https']: url = 'https://' else: url = 'http://' url = url + self.config['hostname'] + endpoint_uri headers = { '...
Python
nomic_cornstack_python_v1
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None class Solution begin function pathSum self root sum begin function find_path current_root expected_sum current_path current_sum begin set current_sum ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: def find_path(current_root, expected_sum, current_path, current_...
Python
zaydzuhri_stack_edu_python
comment 思路一:插入 comment class Solution: comment def rotate(self, nums, k): comment n = len(nums) comment k %= n comment for _ in range(k): comment nums.insert(0, nums.pop()) comment return nums comment 思路二:拼接 comment class Solution: comment def rotate(self, nums, k): comment n = len(nums) comment # k %= n comment nums[:...
# 思路一:插入 # class Solution: # def rotate(self, nums, k): # n = len(nums) # k %= n # for _ in range(k): # nums.insert(0, nums.pop()) # return nums # 思路二:拼接 # class Solution: # def rotate(self, nums, k): # n = len(nums) # # k %= n # nums[:] = num...
Python
zaydzuhri_stack_edu_python
from collections import deque function findSubsets nums result index begin if index < 0 begin print list result return end append result nums at index call findSubsets nums result index - 1 pop result while index > 0 and nums at index == nums at index - 1 begin set index = index - 1 end call findSubsets nums result ind...
from collections import deque def findSubsets(nums, result, index): if index < 0: print(list(result)) return result.append(nums[index]) findSubsets(nums, result, index - 1) result.pop() while index > 0 and nums[index] == nums[index - 1]: index -= 1 findSubsets(nums, res...
Python
zaydzuhri_stack_edu_python
function get_page_and_store url cache_path=none begin set page = read url open url if cache_path is not none begin write open cache_path string w page end return page end function
def get_page_and_store(url, cache_path=None): page = urllib2.urlopen(url).read() if cache_path is not None: open(cache_path, 'w').write(page) return page
Python
nomic_cornstack_python_v1
function var_names_float self begin return list flat end function
def var_names_float(self): return list(np.array([self._X, self._Y]).T.flat)
Python
nomic_cornstack_python_v1
comment 배열 arr가 주어집니다. 배열 arr의 각 원소는 숫자 0부터 9까지로 이루어져 있습니다. comment 이때, 배열 arr에서 연속적으로 나타나는 숫자는 하나만 남기고 전부 제거하려고 합니다. comment 단, 제거된 후 남은 수들을 반환할 때는 배열 arr의 원소들의 순서를 유지해야 합니다. function samenum arr begin set answer = list append answer arr at 0 for i in range 1 length arr begin if arr at i != arr at i - 1 begin append ...
#배열 arr가 주어집니다. 배열 arr의 각 원소는 숫자 0부터 9까지로 이루어져 있습니다. #이때, 배열 arr에서 연속적으로 나타나는 숫자는 하나만 남기고 전부 제거하려고 합니다. # 단, 제거된 후 남은 수들을 반환할 때는 배열 arr의 원소들의 순서를 유지해야 합니다. def samenum(arr): answer = [] answer.append(arr[0]) for i in range(1,len(arr)): if arr[i] != arr[i-1]: answer.append(arr[i]) r...
Python
zaydzuhri_stack_edu_python
import requests import re set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 set r = get requests string http://www.dyyy120.com headers=headers comment print(r.cookies) for tuple key value in items cookies begin ...
import requests import re headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36' } r = requests.get('http://www.dyyy120.com',headers=headers) # print(r.cookies) for key, value in r.cookies.items(): print(key + "=" + value)
Python
zaydzuhri_stack_edu_python
while x < 4000000 begin if x % 2 != 0 begin set soma = soma + x end set aux = x set x = x + y set y = aux end
while x < 4000000: if (x%2 != 0): soma += x aux = x x += y y = aux
Python
zaydzuhri_stack_edu_python
import random from flask import render_template , request from app import app from app.models.player import Player from app.models.game import Game decorator call route string /<choice1>/<choice2> comment Take routes as Rock, Paper, Scissors choices and returns game result function play_route choice1 choice2 begin set ...
import random from flask import render_template, request from app import app from app.models.player import Player from app.models.game import Game # Take routes as Rock, Paper, Scissors choices and returns game result @app.route("/<choice1>/<choice2>") def play_route(choice1, choice2): player_1 = Player("Player...
Python
zaydzuhri_stack_edu_python
import select from collections import namedtuple , deque from fd_pool import FDPool class Event extends named tuple string Event list string fd string func begin function callback self ioloop begin raise NotImplementedError end function end class class TimerEvent extends Event begin function callback self ioloop begin ...
import select from collections import namedtuple, deque from .fd_pool import FDPool class Event(namedtuple('Event', ['fd', 'func'])): def callback(self, ioloop): raise NotImplementedError class TimerEvent(Event): def callback(self, ioloop): self.fd.read() ioloop.del_reader(self.fd) self.func() class Si...
Python
zaydzuhri_stack_edu_python
function is_valid_login self username password begin return call _send_command_to_entity_server SERVER_COMMAND_IS_LOGIN_INFORMATION_VALID username + string | + password end function
def is_valid_login(self, username, password): return self._send_command_to_entity_server(us.SERVER_COMMAND_IS_LOGIN_INFORMATION_VALID, username + '|' + password)
Python
nomic_cornstack_python_v1
function list_clients_request self query=none limit=none skip=none begin set body = call remove_empty_elements dict string query query ; string limit limit ; string skip skip return call _http_request method=string POST url_suffix=string clients params=body end function
def list_clients_request(self, query: Optional[str] = None, limit: Optional[int] = None, skip: Optional[int] = None) -> Dict[str, Any]: body = remove_empty_elements({'query': query, 'limit': limit, 'skip': skip}) ret...
Python
nomic_cornstack_python_v1
comment a set n = 20 for i in range n begin print string * end=string end comment newline print comment b set n = integer input string Enter a number: for i in range n begin print string * end=string end comment newline print comment c set n = 9 set x = n // 2 for i in range x begin print string x * end=string end prin...
#a n = 20 for i in range(n): print("*", end = " ") #newline print() #b n = int(input("Enter a number: ")) for i in range(n): print("*", end = " ") #newline print() #c n = 9 x = n//2 for i in range(x): print("x *", end = " ") print("x", end = " ") #newline print() #d n = int(input("Enter a number: ")) ...
Python
zaydzuhri_stack_edu_python
function test_insertion_string small_queue begin with raises Exception begin call enqueue string a end end function
def test_insertion_string(small_queue): with pytest.raises(Exception): small_queue.enqueue('a')
Python
nomic_cornstack_python_v1
function is_valid_square self row column begin set row_exists = row in range BOARD_SIZE at 0 set column_exists = column in range BOARD_SIZE at 1 return row_exists and column_exists end function
def is_valid_square(self, row, column): row_exists = row in range(self.BOARD_SIZE[0]) column_exists = column in range(self.BOARD_SIZE[1]) return row_exists and column_exists
Python
nomic_cornstack_python_v1
from __future__ import annotations import random from typing import Iterator , List , Tuple , TYPE_CHECKING import entities import tcod from maps import MainMap import tile_type if TYPE_CHECKING begin from engine import Engine end class RectRoom begin function __init__ self x y width height begin set x1 = x set y1 = y ...
from __future__ import annotations import random from typing import Iterator, List, Tuple, TYPE_CHECKING import entities import tcod from maps import MainMap import tile_type if TYPE_CHECKING: from engine import Engine class RectRoom: def __init__(self, x: int, y: int, width: int, height: int): se...
Python
zaydzuhri_stack_edu_python
import urllib.error import re from bs4 import BeautifulSoup set f = open string 13-14.txt string a for i in range 1483716 1483726 begin set f = open string 13-14.txt string a print string Getting data for + string integer i - 1483408 set url = string http://ru.soccerway.com/matches/2011/05/22/england/premier-league/ast...
import urllib.error import re from bs4 import BeautifulSoup f = open("13-14.txt", "a") for i in range(1483716,1483726): f = open("13-14.txt", "a") print("Getting data for " + str(int(i-1483408))) url = "http://ru.soccerway.com/matches/2011/05/22/england/premier-league/aston-villa-football-club/liverpoo...
Python
zaydzuhri_stack_edu_python
class Sintaxis begin comment atributo de clase set instancia = 0 set frase = string Llamando comment __init__Metodoconstructor que se ejecuta cuando se instancia la clase cuyo objetivo es crear comment e inicializar los atributos de la clase. Self es un obejto que se representa la clase creadas function __init__ self d...
class Sintaxis: instancia=0 # atributo de clase frase="Llamando" #__init__Metodoconstructor que se ejecuta cuando se instancia la clase cuyo objetivo es crear # e inicializar los atributos de la clase. Self es un obejto que se representa la clase creadas def __init__(self,dato="Llamando al constru...
Python
zaydzuhri_stack_edu_python
function resend_email_validation user_id begin set user = call get_user_by_id user_id if email_address is none begin raise call ValueError string EmailNotSet- User does not have an email address end call send_verification_email email_address username end function
def resend_email_validation(user_id: int): user = UserService.get_user_by_id(user_id) if user.email_address is None: raise ValueError("EmailNotSet- User does not have an email address") SMTPService.send_verification_email(user.email_address, user.username)
Python
nomic_cornstack_python_v1
function data self begin return __data end function
def data(self): return (self.__data)
Python
nomic_cornstack_python_v1
for x in arr begin if arrMin > x begin set arrMin = x end end print arrMin
for x in arr: if arrMin > x: arrMin = x print(arrMin)
Python
zaydzuhri_stack_edu_python
function test_pnc_cifti_t2wonly data_dir output_dir working_dir begin set test_name = string test_pnc_cifti_t2wonly set dataset_dir = call download_test_data string pnc data_dir set out_dir = join path output_dir test_name set work_dir = join path working_dir test_name comment Simulate a T2w image set anat_dir = join p...
def test_pnc_cifti_t2wonly(data_dir, output_dir, working_dir): test_name = "test_pnc_cifti_t2wonly" dataset_dir = download_test_data("pnc", data_dir) out_dir = os.path.join(output_dir, test_name) work_dir = os.path.join(working_dir, test_name) # Simulate a T2w image anat_dir = os.path.join(dat...
Python
nomic_cornstack_python_v1
import requests import random , re , smtplib , os , ssl from email.mime.text import MIMEText from email.header import Header set fund1 = string https://www.etmoney.com/mutual-funds/axis-focused-25-direct-plan-growth/15251 function getnavs url begin set r = get requests url set fund1_debug = split string content string ...
import requests import random, re, smtplib, os, ssl from email.mime.text import MIMEText from email.header import Header fund1 = "https://www.etmoney.com/mutual-funds/axis-focused-25-direct-plan-growth/15251" def getnavs(url): r = requests.get(url) fund1_debug = str(r.content).split(",") #fund1_debug_1 = ...
Python
zaydzuhri_stack_edu_python
function request_foo self msg begin comment send one inform call send_message call inform string foo string fine comment return reply return call reply string foo string ok string 1 end function
def request_foo(self, msg): # send one inform self.send_message(Message.inform('foo', 'fine')) # return reply return Message.reply('foo', 'ok', '1')
Python
nomic_cornstack_python_v1
function test_create_introduced_individuals_without_age self begin set use_ages = false set host_progression_lists at string prob_exposed_to_asympt = list 1.0 * 17 call create_introduced_individuals time=1 number_individuals_introduced=2 assert equal length persons 2 for person in persons begin assert equal age none as...
def test_create_introduced_individuals_without_age(self): Parameters.instance().use_ages = False Parameters.instance().host_progression_lists[ "prob_exposed_to_asympt"] = [1.0]*17 self.travelsweep.create_introduced_individuals( time=1, number_individuals_introduced=2) ...
Python
nomic_cornstack_python_v1
from http.server import BaseHTTPRequestHandler , HTTPServer import time set HOST_NMAE = string 10.58.8.217 set PORT_NUMBER = 889 class MyServer extends BaseHTTPRequestHandler begin comment print('''处理请求页面''') comment 页面模板 comment page = '''\<html><body><p>hello,world</p></body></html>''' comment 处理一个Get请求 function do_G...
from http.server import BaseHTTPRequestHandler, HTTPServer import time HOST_NMAE = '10.58.8.217' PORT_NUMBER = 889 class MyServer(BaseHTTPRequestHandler): # print('''处理请求页面''') #页面模板 # page = '''\<html><body><p>hello,world</p></body></html>''' #处理一个Get请求 def do_GET(self): self.send_resp...
Python
zaydzuhri_stack_edu_python
function bigram self docs begin set new_docs = list embedding_bigram at docs return call Series new_docs end function
def bigram(self, docs): new_docs = list(embedding_bigram[docs]) return pd.Series(new_docs)
Python
nomic_cornstack_python_v1
function handler method begin decorator wraps method function wrapped self *args **kwargs begin if not call check_headers begin return call client_error 400 string Wrong format request end else begin return call method self *args keyword kwargs end end function return wrapped end function
def handler(method): @wraps(method) def wrapped(self, *args, **kwargs): if not self.check_headers(): return responses.client_error(400, 'Wrong format request') else: return method(self, *args, **kwargs) return wrapped
Python
nomic_cornstack_python_v1
function eliminar_fase request id_fase id_proyecto begin set fase = get objects id=id_fase proyecto_id=id_proyecto set proyecto = get objects id=id_proyecto if estado != string Inactivo begin set mensaje = string Imposible eliminar la fase, ya se esta trabajando en el proyecto. set ctx = dict string mensaje mensaje ; s...
def eliminar_fase (request, id_fase, id_proyecto): fase = Fases.objects.get(id=id_fase, proyecto_id=id_proyecto) proyecto = Proyectos.objects.get(id=id_proyecto) if (proyecto.estado != 'Inactivo'): mensaje = 'Imposible eliminar la fase, ya se esta trabajando en el proyecto.' ctx = {'men...
Python
nomic_cornstack_python_v1
function celine self e c begin set nick = call nm_to_n call source set line = call arguments at 0 if random choice range 100 < 50 begin call privmsg call target string %s: %s % tuple nick random choice celine_messages end end function
def celine(self, e, c): nick = nm_to_n(e.source()) line = e.arguments()[0] if random.choice(range(100)) < 50: c.privmsg(e.target(), "%s: %s"%(nick,random.choice(celine_messages)))
Python
nomic_cornstack_python_v1
function setRadius self radius begin set radius = decimal radius if radius != __radius begin set __radius = radius call _updateGeometry end end function
def setRadius(self, radius): radius = float(radius) if radius != self.__radius: self.__radius = radius self._updateGeometry()
Python
nomic_cornstack_python_v1
function get_chunk_boxes self selection=none begin if selection is none begin set selection = _selection end else begin if is instance selection SelectionBox begin set selection = call SelectionGroup list selection end comment TODO: handle the fact the the selection is not at the origin set selection = intersection sel...
def get_chunk_boxes( self, selection: Optional[Union[SelectionGroup, SelectionBox]] = None ) -> Generator[Tuple[Chunk, SelectionBox], None, None]: if selection is None: selection = self._selection else: if isinstance(selection, SelectionBox): selection...
Python
nomic_cornstack_python_v1
function create_node_faces_array face_nodes num_nodes begin set vertex_faces = zeros tuple num_nodes 4 dtype=int32 - 1 set big = vertex_faces at tuple 0 0 for f_index in range shape at 0 begin set face = face_nodes at f_index for vertex in face begin comment Put the face's vertex in the appropriate index of the comment...
def create_node_faces_array(face_nodes, num_nodes): vertex_faces = np.zeros((num_nodes, 4), dtype=np.int32) - 1 big = vertex_faces[0, 0] for f_index in range(face_nodes.shape[0]): face = face_nodes[f_index] for vertex in face: # Put the face's vertex in the appropriate index of t...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import xlrd import json from datetime import datetime function clean_econsult_activity input_file begin string Cleans weekly eConsult activity data. File to be uploaded weekly. comment Open and load json metadata file with open string metadata.json as json_file begin set data = lo...
import pandas as pd import numpy as np import xlrd import json from datetime import datetime def clean_econsult_activity(input_file): """Cleans weekly eConsult activity data. File to be uploaded weekly.""" # Open and load json metadata file with open("metadata.json") as json_file: data = json.load...
Python
zaydzuhri_stack_edu_python
comment !python from set import Set import unittest class SetTest extends TestCase begin function test_init self begin set q = set assert call length == 0 end function function test_length self begin set q = set assert call length == 0 add q string one assert call length == 1 add q string fish assert call length == 2 a...
#!python from set import Set import unittest class SetTest(unittest.TestCase): def test_init(self): q = Set() assert q.length() == 0 def test_length(self): q = Set() assert q.length() == 0 q.add('one') assert q.length() == 1 q.add('fish') asse...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sat May 18 20:31:48 2019 @author: Shashank Classification Modeling using spaCy - nlp import spacy import random from spacy import displacy class ModelConfiguration begin function __init__ self modelConfigName begin set modelName = modelConfig...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 18 20:31:48 2019 @author: Shashank Classification Modeling using spaCy - nlp """ import spacy import random from spacy import displacy class ModelConfiguration: def __init__(self,modelConfigName): self.modelName=modelConfigName ...
Python
zaydzuhri_stack_edu_python
function _dict_to_samples self dictionary all_dicts=none begin comment Turns NQ dictionaries into a SQuAD style dictionaries if call _is_nq_dict dictionary begin set dictionary = call _prepare_dict dictionary=dictionary end set dictionary_tokenized = call _apply_tokenization dictionary tokenizer answer_type_list at 0 s...
def _dict_to_samples(self, dictionary: dict, all_dicts=None) -> [Sample]: # Turns NQ dictionaries into a SQuAD style dictionaries if self._is_nq_dict(dictionary): dictionary = self._prepare_dict(dictionary=dictionary) dictionary_tokenized = self._apply_tokenization(dictionary, self....
Python
nomic_cornstack_python_v1
function gen_return ret mapping cmd_stack begin set function_name = call get_curr_func set function_epilogue = string { function_name } _epilogue set cmd = tuple BEQ ZERO ZERO function_epilogue append cmd_stack cmd return end function
def gen_return(ret, mapping, cmd_stack): function_name = mapping.get_curr_func() function_epilogue = f"{function_name}_epilogue" cmd = (BEQ, ZERO, ZERO, function_epilogue) cmd_stack.append(cmd) return
Python
nomic_cornstack_python_v1
string Pre processes all of the localization inputs and saves as tfrecords Also handles loading tfrecords The standard we're using is saving the top left corner and bottom right corner in numpy format which is rows x columns or y,x: [ymin, xmin, ymax, xmax] import numpy as np import tensorflow as tf import SODLoader as...
""" Pre processes all of the localization inputs and saves as tfrecords Also handles loading tfrecords The standard we're using is saving the top left corner and bottom right corner in numpy format which is rows x columns or y,x: [ymin, xmin, ymax, xmax] """ import numpy as np import tensorflow as tf import SODLoader...
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 comment 输入location_EachArea_x[i](第i+1个区域的全部端点的x坐标) comment 输入location_EachArea_y[i](第i+1个区域的全部端点的y坐标) comment 判断用户所点的坐标的所属区域并给出评价结果 comment 输出所属区域及评价结果 comment 判断用户所点坐标的所属区域 comment 用户点在区域的边上时判断为在区域外部 function judge_area polyCorners location_EachArea_x location_EachArea_y location_user_x location_u...
#coding:utf-8 #输入location_EachArea_x[i](第i+1个区域的全部端点的x坐标) #输入location_EachArea_y[i](第i+1个区域的全部端点的y坐标) #判断用户所点的坐标的所属区域并给出评价结果 #输出所属区域及评价结果 #判断用户所点坐标的所属区域 #用户点在区域的边上时判断为在区域外部 def judge_area(polyCorners,location_EachArea_x,location_EachArea_y,location_user_x,location_user_y): l = 0 m = polyCorners-1 ...
Python
zaydzuhri_stack_edu_python