seq_id
stringlengths
4
11
text
stringlengths
113
2.92M
repo_name
stringlengths
4
125
sub_path
stringlengths
3
214
file_name
stringlengths
3
160
file_ext
stringclasses
18 values
file_size_in_byte
int64
113
2.92M
program_lang
stringclasses
1 value
lang
stringclasses
93 values
doc_type
stringclasses
1 value
stars
int64
0
179k
dataset
stringclasses
3 values
pt
stringclasses
78 values
37750672638
# coding=utf-8 from global_test_case import GlobalTestCase as TestCase from ..models import Message, WriteItInstance, \ Moderation, Confirmation, OutboundMessage from popit.models import Person from django.core import mail from subdomains.utils import reverse import datetime from mock import patch from django.core....
ciudadanointeligente/write-it
nuntium/tests/moderation_messages_test.py
moderation_messages_test.py
py
19,167
python
en
code
38
github-code
36
42578063251
''' This module contains TextForWeights class which is a text widget used for displaying and editing weight restrictions. Attributes: TEXT_WIDTH_VAL (int): width of Text widget. TEXT_HEIGHT_VAL (int): heigth of Text widget. ''' from tkinter import Text, NONE, N, W, E, S, HORIZONTAL, END, TclE...
araith/pyDEA
pyDEA/core/gui_modules/text_for_weights_gui.py
text_for_weights_gui.py
py
7,933
python
en
code
38
github-code
36
37862194723
from scipy.spatial.distance import cosine from sentence_transformers import SentenceTransformer model = SentenceTransformer("AI-Growth-Lab/PatentSBERTa") def get_sim(anchor: str, target: str) -> float: anchor_embed = model.encode([anchor]) target_embed = model.encode([target]) return float(1 - cosine(an...
vquilon/kaggle-competitions
patent-phrase-to-phrase-matching/models/patent_sbert_a.py
patent_sbert_a.py
py
681
python
en
code
0
github-code
36
569522296
from qtsalome import QSqlQuery from Base.tableDeBase import TableDeBase class TableGroupes (TableDeBase): def __init__(self): TableDeBase.__init__(self,"Groupes") self.setField(('Groupe','Maillage','Version','Entite','NbEntite')) self.setTypeField(('str','int','int','str','int'),('n...
luzpaz/occ-smesh
src/Tools/Verima/Base/tableGroupes.py
tableGroupes.py
py
1,938
python
en
code
2
github-code
36
74446495144
from typing import Dict, List from aiplayground.api.bots import Bot from aiplayground.api.tournaments.models import Participant, Tournament, Match, PlayerQueueEntry, MatchState from collections import defaultdict import operator from aiplayground.exceptions import AlreadyInTournament from aiplayground.logging import...
jackadamson/AI-Playground
aiplayground/api/tournaments/tournaments.py
tournaments.py
py
2,268
python
en
code
0
github-code
36
43297592584
import sys from rpython.rlib.rarithmetic import r_uint, r_singlefloat, r_longlong, r_ulonglong from rpython.rlib.libffi import IS_32_BIT from pypy.module._rawffi.alt.interp_ffitype import app_types, descr_new_pointer from pypy.module._rawffi.alt.type_converter import FromAppLevelConverter, ToAppLevelConverter class Du...
mozillazg/pypy
pypy/module/_rawffi/alt/test/test_type_converter.py
test_type_converter.py
py
6,464
python
en
code
430
github-code
36
29914164702
#_*_ coding:utf-8 _*_ # import datetime # time1=datetime.date(2019,1,29) # time2=datetime.date(2019,7,12) # days=(time2-time1).days # seconds=(time2-time1).total_seconds() # time3=time1+datetime.timedelta(30) # print(time3) ''' 假设你有无限数量的邮票,面值分别为6角,7角,8角,请问你最大的不可支付邮资是多少元? ''' a=6 b=7 c=8 t=50 s=[] for i in range(t+1): ...
haitest/617_repository
runAll.py
runAll.py
py
1,132
python
en
code
0
github-code
36
1253707592
import time from selenium import webdriver # browser = webdriver.Firefox() # browser.get('https://www.jd.com/') # browser.execute_script('window.scrollTo(0, document.body.scrollHeight)') # browser.execute_script('alert("123")') # browser.close() # # # # print("=================================================") bro = ...
lyk4411/untitled
pythonWebCrawler/JavaScriptFireFox.py
JavaScriptFireFox.py
py
711
python
en
code
0
github-code
36
18068483494
# -*- coding:utf8 -*- import tweepy import os import sys import json import time import urllib2 import requests """ ref. http://kslee7746.tistory.com/entry/python-tweepy-%EC%82%AC%EC%9A%A9%ED%95%9C-%ED%8A%B8%EC%9C%84%ED%84%B0-%ED%81%AC%EB%A1%A4%EB%A7%81crawling ref. https://proinlab.com/archives/1562 ref. http://kye...
songjein/polatics
twitter_client.py
twitter_client.py
py
2,878
python
en
code
7
github-code
36
72908301864
def dijkstra(graph, start): # Инициализация списка расстояний distances = {vertex: float('inf') for vertex in graph} distances[start] = 0 while True: # Находим вершину с минимальным текущим расстоянием min_distance = float('inf') min_vertex = None for vertex, distance in...
TatsianaPoto/yandex
Algorithm_complexity/search/dijkstra_arr.py
dijkstra_arr.py
py
1,751
python
ru
code
0
github-code
36
17363789570
''' Задача 3. Клетки В научной лаборатории выводят и тестируют новые виды клеток. Есть список из N этих клеток, где элемент списка — это показатель эффективности, а индекс списка — это ранг клетки. Учёные отбирают клетки по следующему принципу: если эффективность клетки меньше её ранга, то эта клетка не подходит. Напиш...
Pasha-lt/Skillbox-security
Python_basic/lesson_15/hw_15_03.py
hw_15_03.py
py
2,093
python
ru
code
0
github-code
36
37635311990
# Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. # If target is not found in the array, return [-1, -1]. # You must write an algorithm with O(log n) runtime complexity. # Example 1: # Input: nums = [5,7,7,8,8,10], target = 8 # Output: [3,...
sunnyyeti/Leetcode-solutions
34 Find First and Last Position of Elements in Sorted Array.py
34 Find First and Last Position of Elements in Sorted Array.py
py
1,330
python
en
code
0
github-code
36
29398421861
import setuptools from setuptools import find_namespace_packages with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="JarvisAI", version="3.9", author="Dipesh", author_email="dipeshpal17@gmail.com", description="JarvisAI is python library to build your own AI...
MrVanHendrix/Beth.Ai
BETH_Ai/BETH_Ai/setup.py
setup.py
py
1,722
python
en
code
0
github-code
36
31379873011
__author__ = 'Vincent' from scrapy.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors import LinkExtractor from scrapy.selector import HtmlXPathSelector from mediascrap.items import NewsItem import datetime from pymongo import MongoClient class ChokomagSpider(CrawlSpider): """ A spider cr...
fisheatfish/mediascrap
mediascrap/spiders/chokomag.py
chokomag.py
py
1,620
python
en
code
0
github-code
36
23966959472
""" Data readers for remote sensing devices ======================================= Written by Eliot Quon (eliot.quon@nrel.gov) This is a collection of readers to be used with the NWTC datatools.wfip2 module for processing WFIP2 data downloaded from the A2e Data Archive and Portal (DAP). No effort is made to standardi...
NWTC/datatools
remote_sensing.py
remote_sensing.py
py
15,912
python
en
code
2
github-code
36
19031635136
from Data import Data class Delete: def __init__(self): self.Data=Data() def run(self,arr): print(arr[1][1]) if arr[1][0]=='@': num=Data.find_name_or_id_by_id_or_name(arr[1][1],1) else: num='#'+str(arr[1][1]) z=self.Data.find(arr[1])...
RivkiZolti/DNA
delete.py
delete.py
py
796
python
en
code
3
github-code
36
5618318828
import cv2 import os import argparse def image_folder_to_video(folder_path, output_path): # Get the list of image filenames filenames = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.lower().endswith('.jpg')] filenames.sort() # Sort the filenames # Get the dimensions of the first...
danfinlay/face-lapse
src/picstitch.py
picstitch.py
py
1,418
python
en
code
0
github-code
36
11410582849
#David Crespo, 2017 class Web: def __init__(self, datos): self.frm = self.partir(datos) self.pttn = self.get_peticion() self.mtd = self.pttn[0] self.webfile = self.pttn[1] self.direccion = None self.tiene_extension = False self.cmds = self.get_comandos() self.get_direccion() def partir(self, datos): ...
maskr/pyserver
htmlsrv.py
htmlsrv.py
py
3,190
python
es
code
0
github-code
36
4551962390
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "stdrickforce" # Tengyuan Fan # Email: <stdrickforce@gmail.com> <tfan@xingin.com> # Definition for binary tree with next pointer. # class TreeLinkNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.righ...
terencefan/leetcode
python/116.py
116.py
py
546
python
en
code
1
github-code
36
3337416724
# -*- coding: utf-8 -*- """ Created on Tue Jun 11 14:09:58 2019 @author: Neel Tiruviluamala Description: More efficient way to merge datasets. Note: This code was written by Dr. Tiruviluamala of the USC Math department. """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import time...
rajdua22/tennis_betting
Cleaning_Merging/Merge_Datasets.py
Merge_Datasets.py
py
3,429
python
en
code
3
github-code
36
21252216686
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
extremenetworks/pybind
pybind/slxos/v17s_1_02/capabilities/bgp/__init__.py
__init__.py
py
8,050
python
en
code
0
github-code
36
37706438436
import time from tadek.core import utils from tadek.engine.testresult import TestCaseResult from tadek.engine.channels import register, TestResultChannel from tadek.engine.testexec import * __all__ = ["SummaryChannel", "COUNTER_N_TESTS", "COUNTER_TESTS_RUN", "COUNTER_CORE_DUMPS", "COUNTER_RUN_TIME"] # Cou...
tadek-project/tadek-common
tadek/engine/channels/summarychannel.py
summarychannel.py
py
3,192
python
en
code
2
github-code
36
8194426823
import ast import os, glob _bBeVerbose = False def _InsertLine(sFilename: str, index: int, sContent: str): """Insert string content at line index into source file f Args: sFilename (str): File to be modified index (int): Line number to be inserted at sContent (str): Line to be insert...
boschresearch/image-render-setup
src/catharsys/setup/cmd/code_format_impl.py
code_format_impl.py
py
9,488
python
en
code
4
github-code
36
75096299625
import requests from bs4 import BeautifulSoup import re def loastone_login(): print('http://na.finalfantasyxiv.com/lodestone/account/login/') #Get a page from the Loadstone # returns a BeautifulSoup object def get_loadstone_page(url,session_id): #Time format used for cookies #import time #time.strftim...
EmperorArthur/Loadstone_Parser
parse_loadstone.py
parse_loadstone.py
py
5,272
python
en
code
0
github-code
36
11484721845
from kubecepodvs.sumo.mapmessage.trafficmap import TrafficMap class SumotrInputHandle: def __init__(self, filename, map_: TrafficMap): self._map = map_ # 这里去掉了traffic log相关的属性 with open(str(filename), 'r') as file: time = 0.0 time_step_flag = True # ...
LeyNmania/kubecepodvs
kubecepodvs/sumo/io/sumotrinputhandle.py
sumotrinputhandle.py
py
1,540
python
en
code
0
github-code
36
71673331943
import pandas as pd import datetime as dt from kucoincli.client import Client def test_lending_liquidity(quote='USDT'): """Obtain max point-in-time liquidity for lending markets in USDT terms""" client = Client() l = client.symbols(marginable=True).baseCurrency liq = {} for curr in l: try...
jaythequant/VBToptimizers
research/utils.py
utils.py
py
1,411
python
en
code
2
github-code
36
72076380264
# SPDX-License-Identifier: LGPL-3.0-only """Package for the doorstop.core tests.""" import logging import os from typing import List from unittest.mock import MagicMock, Mock, patch from doorstop.core.base import BaseFileObject from doorstop.core.document import Document from doorstop.core.item import Item from door...
doorstop-dev/doorstop
doorstop/core/tests/__init__.py
__init__.py
py
7,484
python
en
code
424
github-code
36
18317520839
# ----------------------------------------------------------------------------# # Imports # ----------------------------------------------------------------------------# import random from flask import Flask, abort, jsonify, request from flask_cors import CORS from models import setup_db, Category, Question # ------...
RaghavGoel13/trivia-solution
backend/flaskr/app.py
app.py
py
8,877
python
en
code
0
github-code
36
73172240425
import cv2 import numpy as np class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): while True: a="Not Found" lower_green = np.array([45, 140, 50]) upper_green =...
ishivanshgoel/Technocrats-T1
camera.py
camera.py
py
936
python
en
code
0
github-code
36
38833898049
from django.urls import path from rest_framework.routers import DefaultRouter from src.dates_api.views import DateViewSet, PopularMonthListView app_name = "dates_api" router = DefaultRouter() router.register("dates", DateViewSet, basename="dates") urlpatterns = [ path("popular/", PopularMonthListView.as_view(),...
danielkosytorz/dates-DRF-app
backend/src/dates_api/urls.py
urls.py
py
373
python
en
code
0
github-code
36
22317892633
from django.urls import path from django.conf.urls import include from django.contrib import admin from app.accounts.api.v1.views import ( UserCreatView, UserUpdateView, GetAuthToken, AvatarAPIView, ClubAPIView, ) app_name = 'accounts' urlpatterns = [ path('login/', GetAuthToken.as_view(), ...
AndresGomesIglesias/LanTool-Backend
app/accounts/api/v1/urls.py
urls.py
py
664
python
en
code
0
github-code
36
16232453581
from faker import Faker from faker.providers import person, job, company, internet, phone_number class BaseCard: def __init__(self, name, family_name, e_mail, priv_phone): self.name = name self.family_name = family_name self.e_mail = e_mail self.priv_phone = priv_phone self...
szczesnym/Kodilla-Python
Chapter7/AddressBook.py
AddressBook.py
py
2,662
python
en
code
0
github-code
36
25445515185
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2022/5/6 20:48 # @Author : nujaijey # @File : 字符串.py # @Desc : # s1 = "" # s2 = " " # print("s1的长度:", len(s1)) # print("s2的长度:", len(s2)) # s3 = '1234567' # res3 = s3[0:7:3] # print(res3) # s4 = ' python ' # print(s4) # res = s4.strip() # prin...
nujaijey/python_study
basics/字符串.py
字符串.py
py
1,319
python
zh
code
0
github-code
36
20115420162
import logging import concurrent.futures import pandas as pd import random import time import requests import os import sys from datetime import datetime from utils.vars import * from utils.common import * from requests.structures import CaseInsensitiveDict # Output the logs to the stdout logging.basicConfig(stream=s...
jotozhun/azure-pre-scale
azure_auth_scale.py
azure_auth_scale.py
py
17,441
python
en
code
0
github-code
36
6994509380
from lib.cuckoo.common.abstracts import Signature class DropBox(Signature): name = "cloud_dropbox" description = "Looks up the Dropbox cloud service" severity = 2 categories = ["cloud"] authors = ["RedSocks"] minimum = "2.0" domains = [ "dropbox.com", "www.dropbox.com", ...
cuckoosandbox/community
modules/signatures/windows/cloud_dropbox.py
cloud_dropbox.py
py
689
python
en
code
312
github-code
36
74736328744
import pyautogui # Returns two integers, the width and height of the screen. (The primary monitor, in multi-monitor setups.) screenWidth, screenHeight = pyautogui.size() # Returns two integers, the x and y of the mouse cursor's current position. currentMouseX, currentMouseY = pyautogui.position() print(screenWidth, sc...
davidyu37/fruit-ninja-cv
mouse.py
mouse.py
py
1,028
python
en
code
0
github-code
36
417569576
from abc import ABC,abstractmethod class Shape(ABC): def __init__(self,dim1,dim2): self.dim1=dim1 self.dim2=dim2 @abstractmethod def area(self): #print("Shape has no area") pass #this method have no body other method will overwrite this and use this class Triangle...
Rakibuz/Robotics_HCI
OOP_Python/Abstraction.py
Abstraction.py
py
792
python
en
code
0
github-code
36
25947046788
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head or not head.next: return head cur_val = head.val la...
dzaytsev91/leetcode-algorithms
easy/83_remove_duplicates_from_sorted_list.py
83_remove_duplicates_from_sorted_list.py
py
678
python
en
code
2
github-code
36
7595557598
#!/usr/bin/env python3 import argparse import sys import os from pathlib import Path import json import io import re import tempfile import shutil import copy re_has_whitespace = re.compile(r"\s+") re_has_indent = re.compile(r"\s{4}\s+") re_empty_line = re.compile(r"^\s*$") def parse_args(args): parser = argparse...
padresmurfa/yapl
v1/2_modules_from_package/cli.py
cli.py
py
15,896
python
en
code
0
github-code
36
13459025825
import argparse class HackAssembler: def __init__(self): self.__comp_code = { "0": "0101010", "1": "0111111", "-1": "0111010", "D": "0001100", "A": "0110000", "!D": "0001101", "!A": "0110001", "-D": "0001111", ...
zhixiangli/nand2tetris
projects/06/hack_assembler.py
hack_assembler.py
py
5,017
python
en
code
1
github-code
36
16779750056
from kelimeler import sozluk """ eksik yada yanlış yazılan kelimeyi tespit ederek sözlükteki en yakın kelimelerin listesini döner. """ def duzelten(cumle): duzelenCumle=[]#düzeltilen kelimelerin listesini içerir. donenCumle="" cumle=cumle.split() for i in range(len(cumle)): ...
FerhatKartal/text_correction
duzelten.py
duzelten.py
py
2,353
python
tr
code
0
github-code
36
15646853934
import json import os import string import requests from selenium import webdriver from selenium.webdriver.common.by import By import urllib.request options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', Fa...
fatbrother/crawler-test
main.py
main.py
py
9,656
python
en
code
0
github-code
36
9512661257
w, w_unit = input("Weight : ").split() h, h_unit = input("Height : ").split() w, h = float(w), float(h) # w Convert if w_unit == "lbs": # Convert lbs to kg w /= 2.205 # h Convert if h_unit == "ft": # Convert ft to m h /= 3.2808399 elif h_unit == "cm": # Convert cm to m h /= 100 # Calcula...
ratchanonp/comproglab
64-1LAB4/6434480323LAB4P2.py
6434480323LAB4P2.py
py
621
python
th
code
0
github-code
36
6790532061
from django.db import models from django.conf import settings from ..querysets.resource import ResourceQuerySet class ResourceManager(models.Manager): queryset_class = ResourceQuerySet def get_queryset(self): return self.queryset_class(self.model, using=self._db) def filter_by_project(self, pro...
tomasgarzon/exo-services
service-exo-core/files/managers/resource.py
resource.py
py
1,318
python
en
code
0
github-code
36
39916510161
import os import re import xlwt from tkinter import * from tkinter.filedialog import askdirectory from xlwt import Workbook root=Tk() root.withdraw() path=askdirectory() print(path) file_names=os.listdir(str(path)) name_lists=[] output=[] for file in file_names: file_path=path + '/' + file f=open(file_path,'r',...
nigo81/python_spider_learn
TXT处理/readtxt.py
readtxt.py
py
1,005
python
en
code
3
github-code
36
31829455558
# -*- coding: utf-8 -*- def validate(f): names = ['narrow-bold', 'wide-bold', 'narrow-thin', 'wide-thin'] if f is None: return for n in names: g = f[n] print(g.name, len(g.contours)) for c in g.contours: print(g.name, len(c)) if __name__ == "__main__": ...
LettError/responsiveLettering
ResponsiveLettering.roboFontExt/lib/mathShape/cmd_validateMathShape.py
cmd_validateMathShape.py
py
357
python
en
code
152
github-code
36
4255274214
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: ans = 0 start = 0 tracker = {} for end, char in enumerate(s): if char in tracker: start = max(start, tracker[char] + 1) tracker[char] = end ans = max(ans, end - ...
blhwong/algos_py
leet/length_of_longest_substring/main.py
main.py
py
351
python
en
code
0
github-code
36
31524102898
""" Test the lookup_specs_chain NOTE: this just makes sure the chain executes properly but DOES NOT assess the quality of the agent's analysis. That is done in the ipython notebooks in the evals/ folder """ import pytest import json from meche_copilot.get_equipment_results import get_spec_lookup_data, get_spec_page_va...
fuzzy-tribble/meche-copilot
tests/unit_tests/chains/get_lookup_specs_chain_test.py
get_lookup_specs_chain_test.py
py
2,625
python
en
code
1
github-code
36
27193740899
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import glob import logging import argparse from ngsmetavirus.config import * from ngsmetavirus.common import check_path, mkdir, read_tsv from dagflow import DAG, Task, do_dag LOG = logging.getLogger(__name__) __version__ = "1.0.0" __author__ = ("Xingguo Zhang"...
zxgsy520/metavirus
ngsmetavirus/mngs_multi.py
mngs_multi.py
py
6,833
python
en
code
1
github-code
36
11883950060
# lcp Core # iMagineLab - Living Character Program from lcp.core.module_loader import ModuleLoader from lcp.core.lcp_system_configurator import SystemConfigurator import time class LCPCore(object): __version = "0.1" def __init__(self): print("LCP Core - Version", self.__version) print(">> Ini...
huybthomas/LCP-Core-Old
src/lcp/core/lcp_core.py
lcp_core.py
py
1,069
python
en
code
0
github-code
36
74958840742
class Solution: def isPalindrome(self, src: int) -> bool: """ 处理回文,不采用字串转型的方式。 如果小于正整数则返回 Fasle,否则透过取得不断除以 10 取得商数来判断循环是否到底。 而获得的余数的方式放入阵列,待完成后透过阵列来做寻访 [::-1] 判断是否相符 """ slices = [] if src < 0: return False while(src != 0): re...
kokokuo/oh-leetcode
9-PalindromeNumber.py
9-PalindromeNumber.py
py
650
python
zh
code
1
github-code
36
4062581538
def main(): cities = placeRecordsIntoList("Cities.txt") # Sort list by percentage population growth. cities.sort(key=lambda city: (city[3] - city[2])/city[2], reverse=True) createNewFile(cities) # Create file of cities and their % growth. def placeRecordsIntoList(fileName): infile = open(fileName,...
guoweifeng216/python
python_design/pythonprogram_design/Ch5/5-PP-7.py
5-PP-7.py
py
929
python
en
code
0
github-code
36
71300192743
import itertools import tqdm import subprocess def add_to_seq(seq, feature, label): if label[0] == 'B': seq.append(feature) elif label[0] == 'I': if len(seq) > 0: seq[-1] += feature else: seq.append(feature) elif label[0] == 'S': seq.append(feature) ...
YaooXu/Chinese_seg_ner_pos
evaluate.py
evaluate.py
py
9,381
python
en
code
5
github-code
36
43319739352
times = int(input()) a, d =[],[] counta = 100 countd = 100 for i in range(times): ap,dp = input().split(" ") a.append(int(ap)) d.append(int(dp)) if int(a[i]) > int(d[i]): countd -= int(a[i]) counta = counta elif int(a[i]) < int(d[i]): countd = countd ...
Aanjneya/CCC-UWaterloo-Solutions
2014/Junior/2014 - J3.py
2014 - J3.py
py
464
python
en
code
0
github-code
36
14783455392
''' ME 598 CUDA Homework 2 Author: Hien (Ryan) Nguyen Last modified: 01/28/2018 ''' import numpy as np # import scientific computing library import matplotlib.pyplot as plt # import plotting library from numba import cuda import math import time from mpl_toolkits import mplot3d ''' Question 2 func...
ryannguyen94/CUDA
HW2/hw2.py
hw2.py
py
9,498
python
en
code
0
github-code
36
127603653
# encoding=utf8 import requests from lxml import etree class cityAreaCode(): def __init__(self): self.url = "http://www.ip33.com/area/2019.html" def get(self): page = requests.get(self.url) page.encoding = 'utf-8' _element = etree.HTML(page.text) divs = _element.xpath(...
lazyting/climbworm
python/CityAreaCode.py
CityAreaCode.py
py
1,228
python
en
code
1
github-code
36
74678159463
''' Created on 07/02/2018 @author: Carolina ''' import unittest from shapes import Shape, Rectangle class Test(unittest.TestCase): def test_shape(self): shape = Shape ((0,0,0), 'wood') self.assertEqual('Color: (0,0,0) Material: wood Max_Temp: 20') shape2 = Shape ((0,0,0), '...
carolinanconceicao/day_3
day_3/test_shapes.py
test_shapes.py
py
1,157
python
en
code
0
github-code
36
34415438640
from timeit import timeit def runLengthEncoding(string): # Write your code here. res = [] fp = 0 sp = 1 ln = 1 while sp <= len(string): if sp == len(string) or string[sp] != string[fp] or ln == 9: res.append(f'{ln}{string[fp]}') fp = sp sp += 1 ...
serb00/AlgoExpert
Strings/Easy/012_run_lenght_encoding.py
012_run_lenght_encoding.py
py
1,432
python
en
code
0
github-code
36
21788142764
import numpy as np from scipy.constants import G from scipy.interpolate import interp1d from astropy.constants import kpc import general as ge class zhao(object): """ Class for generating a potential for a spherical dark matter halo, using the data generated by the model of Zhao (2009). Attrib...
Evd-V/Bachelor-thesis
zhao.py
zhao.py
py
9,478
python
en
code
0
github-code
36
9710179885
import random from random import randint import pygame from essais.essai_dijkstra_damier import title from lib_dijkstra import DijkstraManager, Point, pyrect_to_point, point_to_pyrect verbose = False class Entity(pygame.sprite.Sprite): def __init__(self, name, x, y, screen=None): super().__init__() ...
bermau/PW_19_pygamon
src/player.py
player.py
py
10,618
python
fr
code
0
github-code
36
73379175144
from functools import wraps from flask import url_for, redirect, session # 登陆限制装饰器 # 用于需要登陆的页面,如果没有登陆则要求登陆(跳转至登陆页面) def login_required(func): @wraps(func) def wapper(*args, **kwargs): if session.get('user_id'): return func(*args, **kwargs) else: return redirect(url_for(...
BobXGY/bobqa
decorators.py
decorators.py
py
419
python
zh
code
0
github-code
36
25626046403
def repeatedStringMatch (A: str, B: str) -> int: # lenA = len(A) # lenB = len(B) # # # # if lenA > lenB: # if B in A: # return 1 # else: # a = A # count = 1 # FLAG = True # while lenA < 1000: # if FLAG: # a = a +...
Akashdeepsingh1/project
LeetcodeRandom/substring.py
substring.py
py
824
python
en
code
0
github-code
36
25106892699
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.layers.experimental import preprocessing import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import tensorflowjs as tfjs url = 'http://archive.ics.uci.edu/ml/machine-l...
RashmitShrestha/mlModels
nn.py
nn.py
py
1,993
python
en
code
0
github-code
36
74309241063
import time, os, boto3, json, decimal from boto3.dynamodb.conditions import Key from helpers import send_to_datastream from helpers import _get_body from helpers import _get_response from helpers import DecimalEncoder try: dynamodb = boto3.resource('dynamodb') phase_status_table = dynamodb.Table(os.getenv('...
LCOGT/photonranch-status
phase_status.py
phase_status.py
py
2,369
python
en
code
0
github-code
36
15695220227
import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.stats import wbgapi as wb import seaborn as sns def world(ind, code, years): ''' this function returns original data, transposed data and world data for above indicators Parameters ---------- ind : index code ...
sunithasomasundaran/ads1_statistics_and_trends_sunitha
assignment2.py
assignment2.py
py
4,686
python
en
code
0
github-code
36
34212052955
# https://www.acmicpc.net/problem/1260 # solution # 1) 주어진 입력을 인접행렬로 저장한다 # 2) 현재 정점 그때그때 출력하는 dfs를 돌린다 # 3) bfs 하고 path를 출력한다 # TIL # adj_mat = [([0,] * n),]*n -> 이런식으로 초기화 하면안됨. copy라 원소의 id값 다 같아지는 문제 # 파이썬 입력으로 input()은 굉장히 느리다. sys.stdin.readline() 사용 # dfs의 경우 최단거리 찾는 문제(탐색 여러번 반복)와 단순히 탐색하는 문제(한번만 탐색) 구분해서 풀자 ...
chankoo/problem-solving
graph/1260-DFS와BFS.py
1260-DFS와BFS.py
py
2,933
python
ko
code
1
github-code
36
42243182620
import matplotlib.pyplot as plt import numpy as np import dill as pickle sens_to_plot = ['20180314_grav_noshield_cant-0mV_allharm.npy', \ '20180314_grav_shieldin-nofield_cant-0mV_allharm.npy', \ '20180314_grav_shieldin-1V-1300Hz_cant-0mV_allharm.npy', \ '20180314_grav_...
charlesblakemore/opt_lev_analysis
scripts/mod_grav/plot_sensitivity.py
plot_sensitivity.py
py
1,634
python
en
code
1
github-code
36
44480283459
import Collatz import one import twonums import drag import infinite import biology def func88(which): if which == str(1): num1 = int(input('insert the first number: ')) one.grat(num1).use() elif which == str(2): num1 = int(input('insert the first number: ')) num2 = int(input('i...
Tanticion/Importent-Projects
School_Proj/mathsolver.py
mathsolver.py
py
1,528
python
en
code
1
github-code
36
5154312569
from sklearn.datasets import make_circles from sklearn.datasets import make_blobs from sklearn.datasets import make_moons from sklearn.model_selection import train_test_split class Circles(object): def __init__(self): self.X, self.labels = make_circles(n_samples=300, noise=0.1, random_state=5622, factor=0...
peterrrock2/ML_coursework
Homework/Hw4/data/__init__.py
__init__.py
py
4,114
python
en
code
0
github-code
36
74586144105
from collections import defaultdict def solution(id_list, report, k): table = defaultdict(int) # 누가 몇번 신고 받은지 체크하는 테이블 answer = [0] * len(id_list) for repo in set(report): table[repo.split()[1]] += 1 # k번 이상 신고 받은 사람(report.split(' ')[1])인 경우 # 신고한 사람(report.split(' ')[0]) 메일 발송 횟수 1 추가 ...
ycs1m1yk/TWS
Programmers/92334_sjh.py
92334_sjh.py
py
551
python
ko
code
2
github-code
36
30394243625
""" FILES to YAML """ import argparse import json import json.decoder import os from pathlib import Path import yaml import yaml.scanner def walk_thru(startdir: str) -> list: p = Path(startdir) a = [str(el).replace('\\', '/').replace(startdir, '') for el in p.rglob('*')] return a def read_file_content(...
MaksimPashkovsky/python-labs
week5/task1.py
task1.py
py
1,452
python
en
code
0
github-code
36
20081039110
#!/usr/bin/env python # coding: utf-8 # In[1]: # !pip install numpy # !pip install pandas # !pip install matplotlib # !pip install sklearn # !pip install dmba # !pip install statsmodels # !pip install yellowbrick # In[2]: import pandas as pd import numpy as np df = pd.read_csv("data/medical_clean.csv") outcome ...
cjhammons/Multiple-Linear-Regression-on-Medical-Data
submission/multiple-linear-regression.py
multiple-linear-regression.py
py
4,028
python
en
code
0
github-code
36
71960613545
import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix import itertools from PIL import Image as PIL def show_image(image, cmap=None): plt.figure(figsize=(12, 12)) plt.imshow(image, cmap=cmap) plt.show() def show_images(images, labels=None): if labels: ...
fukuta0614/active_learning
shared/PIA/analysis.py
analysis.py
py
3,289
python
en
code
0
github-code
36
30133687535
#!/ust/bin/python3 import fire import sys from functools import reduce import os.path red = '\033[0;31m' green = '\033[0;32m' yellow = '\033[0;33m' blue = '\033[0;34m' purple = '\033[0;35m' cyan = '\033[0;36m' white = '\033[0;37m' end = '\033[0m' host_file = '/etc/hosts' new_file_path = None def log_error(*msg): ...
Kuangcp/Script
python/tool/switch-host-group/app.py
app.py
py
5,437
python
en
code
10
github-code
36
21678791673
# Reverse a linked list from position m to n. Do it in-place and in one-pass. # For example: # Given 1->2->3->4->5->NULL, m = 2 and n = 4, # return 1->4->3->2->5->NULL. # Note: # Given m, n satisfy the following condition: # Definition for singly-linked list. # 1. 逗号输出与赋值 class ListNode(object): def __init__(sel...
WangsirCode/leetcode
Python/reverse-likned-lis-ii.py
reverse-likned-lis-ii.py
py
1,569
python
en
code
0
github-code
36
6792942210
import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data print("Current TF Version Is [%s]" % (tf.__version__)) print("Package Loaded") mnist = input_data.read_data_sets('data/', one_hot = True) n_hidden_1 = 256 n_hidden_2 = 128 n_hidden_3 = 64 n_input = 784 n_...
MiloSi/python_tensorflow_study
multi_layer_perceptron.py
multi_layer_perceptron.py
py
2,867
python
en
code
0
github-code
36
9915851905
class Inventory: def __init__(self, __capacity: int): self.__capacity = __capacity self.items = [] def add_item(self, item: str): if len(self.items) < self.__capacity: self.items.append(item) else: return "not enough room in the inventory" def get_ca...
qceka88/Fundametals-Module
22 Objects and Classes - Exercise/06inventory.py
06inventory.py
py
1,872
python
en
code
8
github-code
36
19826180596
""" --- Day 9: Smoke Basin --- https://adventofcode.com/2021/day/9 """ from aoc import * inputs = puzzle_input(9, 2021, sample=False).split('\n') inputs = [[int(x) for x in i] for i in inputs] def valid_point(x, y): return 0 <= x <= len(inputs) - 1 and 0 <= y <= len(inputs[0]) - 1 def is_lowest(x, y): ret...
BricksAndPieces/AdventOfCode
2021/days/day09.py
day09.py
py
1,160
python
en
code
1
github-code
36
31219990233
import logging import os import sys from logging import Logger from typing import Any, Dict, List import datasets import torch import transformers import wandb from transformers import TrainingArguments from dp_arguments import DataTrainingArguments, ModelArguments LABEL_DICT = {} LABEL_DICT['ner'] = ['CARDINAL', 'D...
yileitu/probing-via-prompting
utils.py
utils.py
py
9,989
python
en
code
null
github-code
36
15602167748
import nukescripts sn = nuke.selectedNode() #make a panel that we use to apply presets class buttonPanel(nukescripts.PythonPanel): def knobChanged(self,knob): #manually set presets because nuke sets other knobs to default and I don't want that for knob_name, setting in nuke.getUserPresetKno...
KieranOwenShepherd/NukeTools
QuickScripts/NODE_quick_presets.py
NODE_quick_presets.py
py
744
python
en
code
1
github-code
36
5411923106
import requests import json from config import currency class APIException(Exception): pass class Converter: @staticmethod def get_price(base, sym, amount): try: base_key = currency[base.lower()] except KeyError: raise APIException(f'Валюта {base} н...
kopitski/SkillFactory
Exchange_bot/extensions.py
extensions.py
py
1,243
python
en
code
0
github-code
36
24754731347
import dash_bootstrap_components as dbc from explainerdashboard.custom import * class FeaturesImportanceTab(ExplainerComponent): """ A class for creating a 'Feature Impact' tab in an explainer dashboard. """ def __init__(self, explainer, title="Feature Impact", name=None, hide_des...
0Kan0/Academic-Failure-Prediction-Tool
src/tabs/FeaturesImportancesTab.py
FeaturesImportancesTab.py
py
1,837
python
en
code
0
github-code
36
18825417053
import random def shuffle(A): """Fisher-Yates shuffle.""" for i in range(len(A)): j = random.randint(i, len(A) - 1) A[i], A[j] = A[j], A[i] def random_sample(m, n): """Returns a random sample of m integers from [1,...,n] as a list.""" if m == 0: return [] el...
tzyl/algorithms-python
algorithms/random/randomize.py
randomize.py
py
701
python
en
code
2
github-code
36
34445125382
#!/usr/bin/env python import os import sys import fileinput import datetime import logging logFile = 'setup.log' logging.basicConfig( filename = logFile,filemode = 'w', level = logging.INFO,format = '%(asctime)s - %(levelname)s: %(message)s', datefmt = '%m/%d/%Y %I:%M:%S %p' ) #import poaMenu def g...
maratP/poa-devops
poa-node-setup.py
poa-node-setup.py
py
7,598
python
en
code
1
github-code
36
5045789896
#!/usr/bin/python # coding:utf8 # # 配置文件 # config = {} config['url'] = 'https://127.0.0.1:15789' # token,验证服务端与客户端传输数据是否匹配 config['token'] = 'hahaha' # 实现加密混淆的字符串,长度应该是16或32或64 config['CryptoKey'] = 'jikjhg457hgdetyh' # 主机名 config['hostname'] = 'mzs-mac'
mzs0207/automationTool
Client/config.py
config.py
py
345
python
en
code
3
github-code
36
17498596227
import time import tkinter as tk import tkinter.ttk as ttk import tkinter.messagebox as tkmsg from ttkthemes import ThemedTk from PIL import ImageTk, Image from geoCosiCorr3D.geoImageCorrelation.geoCorr_utils import splitcall, project_path, clamp import geoCosiCorr3D.geoImageCorrelation.geoCorr_utils as utils def r...
SaifAati/Geospatial-COSICorr3D
geoCosiCorr3D/geoCosiCorr3D_GUI/geoImageCorrelation_GUI/tk_utils.py
tk_utils.py
py
20,960
python
en
code
37
github-code
36
70389328743
import constants as vals import funcs as fun def findingDepth(rpt, rpt2, tipThumb,tipThumb2, kThumb,kThumb2, tipIndex,tipIndex2,kIndex,kIndex2): focal=1380 #pixels, I found this online disparityTipThumb=fun.distanceVec([rpt[tipThumb][0]],[rpt[tipThumb][1]],\ [rpt2[tipThumb2][...
julian-ramos/fingers
doDepth.py
doDepth.py
py
2,671
python
en
code
0
github-code
36
14086949836
import streamlit as st from pages.common.queries import run_query from pages.common.presenter import display_result from pages.common.utils import convert_template from pages.common.plotting import get_figure import logging logging.getLogger("pybatfish").setLevel(logging.WARNING) APP = """This is a Streamlit app th...
martimy/Bat-Q
pages/2_Analysis.py
2_Analysis.py
py
1,801
python
en
code
1
github-code
36
69930126823
import pygame import BulletClass from EnemiesControllerClass import EnemiesController class PlayerShip: ShipSpeed = 7 # Static variable containing all the bullets the ship has fired BULLET_RESOURCE = "../Resources/Images/bullet.png" Bullets = [] def __init__(self, imageLocation, screenSize): ...
ErikTillberg/Space_Invaders_Clone
Game/PlayerShipClass.py
PlayerShipClass.py
py
2,586
python
en
code
0
github-code
36
11620940756
import tkinter as tk # Tipografia FONT_FAMILY0=("Unispace",9) FONT_FAMILY1=("Unispace", 13) FONT_FAMILY2=("Unispace", 15) FONT_FAMILY2=("Unispace", 15) FONT_FAMILY3=("Unispace",17) FONT_FAMILY4=("Unispace",19) COLOR_AMARILLO="#fbf236" # Button BUTTON_LAYOUT=dict(fill="both",expand=True) # print(*BUTTON_LAYOUT) # GUI...
AldoVR03/Prototipo
presentacion/constants.py
constants.py
py
849
python
es
code
0
github-code
36
28522269867
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from opus_core.misc import unique from variable_functions import my_attribute_label from numpy imp...
psrc/urbansim
urbansim_parcel/building/occupied_spaces.py
occupied_spaces.py
py
3,952
python
en
code
4
github-code
36
74429979942
import streamlit as st from fastai.vision.all import * import plotly.express as px import pathlib from streamlit_option_menu import option_menu from apps import home, app, contact temp = pathlib.PosixPath with st.sidebar: navbar = option_menu("Main Menu", ["Home", "Project", "Contact"], i...
farkhod-developer/DL_Image_Classification_Model
manage.py
manage.py
py
1,434
python
en
code
0
github-code
36
37407105905
import pandas as pd from sklearn.tree import DecisionTreeClassifier, plot_tree import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder # read in your data df = pd.read_excel("CreditRisk.xlsx") # define your independent and dependent variables X = df[['Volume', 'Value', 'Age']] y = df[...
HyperionDevBootcamps/C4_DS_lecture_examples
Lecture code/Machine Learning/Decision Trees/Decision_Trees_cat.py
Decision_Trees_cat.py
py
702
python
en
code
37
github-code
36
33589796845
import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class fist_bookSpider(CrawlSpider): name = 'fist_book' allowed_domains = ['books.toscrape.com'] start_urls = ['http://books.toscrape.com/'] rules = ( Rule(LinkExtractor(), callback='pars...
andycortex/blog-scraper
first_book.py
first_book.py
py
598
python
en
code
0
github-code
36
18481411775
def kartotajs(): with open("sakarto.txt", "r", encoding="utf-8") as fails: dati = fails.readlines() vardi = [] skaitļi = [] for i in range(len(dati)): dati[i] = dati[i].rstrip() if dati[i].isdecimal(): skaitļi.append(dati[i]) else: vardi....
aleksspauls/aleksspauls
12_c/12_04.py
12_04.py
py
414
python
en
code
0
github-code
36
18977859509
from dask.distributed import Client, wait import dask.dataframe as dd import os from shapely.geometry import LineString, Polygon, Point, box from shapely import wkb import rtree import xarray as xr import pandas as pd import pyarrow as pa index_url = './../data/roads' df_url = './../data/osm_roads/roads.parquet' clie...
maximyudayev/YY-MANET-Protocol
local/network_graph_build_no_dem.py
network_graph_build_no_dem.py
py
7,549
python
en
code
0
github-code
36
23295546136
import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Flatten, Dense, Dropout, BatchNormalization, Conv2D, MaxPool2D from tensorflow.keras.optimizers import Adam from tensorflow.keras.preprocessing import image print(tf.__version__) import numpy as np import pandas as p...
Ryan-Red/MoviePosters
main.py
main.py
py
2,665
python
en
code
0
github-code
36
20583493606
import numpy as np import cv2 import math cap = cv2.VideoCapture(0) while(True): ret,frame = cap.read() img = cv2.imread('D:/HW/OpenCV Workshop - distro2/OpenCV Workshop/tek1.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): b...
Altair115/OpenCV2-Workshop
Opdrachten/Op2.py
Op2.py
py
363
python
en
code
0
github-code
36
74028994663
# script to parse raw logging from the four sensor/actuators into a single file # # Run after running log_terminal.py # # Some changes might have ro be changed on line 60-70 depending on the logging level used. # settings sps = 128 # samples per second used in the inner loop ts = 1/sps t = 0 files_to_log =...
basboot/WIS-com
parse_serial_log.py
parse_serial_log.py
py
3,030
python
en
code
0
github-code
36
73721495784
#!/usr/bin/env python try: import RPi.GPIO as GPIO except RuntimeError: print("Error importing RPi.GPIO! sudo?") raise from time import sleep LED_COUNT = 32 SIN_PIN = 22 CLOCK_PIN = 27 LATCH_PIN = 17 def setup(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup((SIN_PIN, CLOCK_PIN...
yossizap/UV-Bicycle
src/pi/cat4016_uv_leds_test/cat4016_uv_leds_test.py
cat4016_uv_leds_test.py
py
759
python
en
code
0
github-code
36