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
34564583000
import logging import os from datetime import date from pathlib import Path from ._version import get_versions from .watchdog import Watchdog # Environment variables and if they are required ENVIRONMENT_VARS = { "TZ": False, "INFLUXDB_HOST": False, "INFLUXDB_PORT": False, "INFLUXDB_DATABASE": False, ...
afonsoc12/intrusion-monitor
intrusion_monitor/__init__.py
__init__.py
py
5,669
python
en
code
2
github-code
36
10351048342
class Vertex: #reprezentuje vrchol v grafu def __init__(self, id, name): self.id = id #numerický identifikátor vrcholu (int) self.name = name #jméno vrcholu (String) self.minDistance = float('inf') #deafaultne infinity self.previousVertex = None ...
Hajneken/Python-excercises-
HW9_Dijkstra.py
HW9_Dijkstra.py
py
3,440
python
en
code
0
github-code
36
7086566402
from django.shortcuts import render,redirect from adm.models import * def ViewInicio(request): listJogos = Jogo.objects.select_related('Vencedora','Perdedora').all() context = { "listJogos":listJogos, } return render(request,"inicio.html",context) def ViewCadastro(request): if request.me...
michel110299/Administrador_tranca
adm/views.py
views.py
py
7,068
python
pt
code
0
github-code
36
74752046504
from lxml import etree import unittest from unittest.mock import MagicMock, patch from lib.parsers.parseOCLC import readFromClassify, loadEditions, extractAndAppendEditions from lib.dataModel import WorkRecord from lib.outputManager import OutputManager class TestOCLCParse(unittest.TestCase): @patch.object(Outpu...
NYPL/sfr-ingest-pipeline
lambda/sfr-oclc-classify/tests/test_parseOCLC.py
test_parseOCLC.py
py
1,821
python
en
code
1
github-code
36
34124762528
""" this program is a simulation of the inner planets of our solar system (namely the sun, Mercury, Venus, Earth and Mars). The planets are objects of the class Planet which enables this class (solarSystemAnimation) to animate them. The information of the planets can be found in the file PropertiesPlanets. """ i...
Platiniom64/OrbitalMotionSimulation
OrbitalMotion.py
OrbitalMotion.py
py
11,622
python
en
code
0
github-code
36
40983404414
"""new fileds are added user Revision ID: 7758fd2f291e Revises: 5444eea98e3f Create Date: 2019-05-03 01:12:53.120773 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '7758fd2f291e' down_revision = '5444eea98e3f' branch_labels = None depends_on = None def upgra...
ShashwatMishra/Mini-Facebook
Mini Facebook/migrations/versions/7758fd2f291e_new_fileds_are_added_user.py
7758fd2f291e_new_fileds_are_added_user.py
py
911
python
en
code
1
github-code
36
40057143195
#!/usr/bin/env python3 import scapy.all as scapy import argparse from datetime import datetime import sys def ip(): parse = argparse.ArgumentParser() parse.add_argument("-ip", dest="ip", help="Needs IP range /24") parse.add_argument("-i", dest="interface", help='Needs interface') parse.add_...
WMDA/ctf
tools/python_scripts/network_scanner.py
network_scanner.py
py
1,853
python
en
code
1
github-code
36
24678905467
class Poker: from Trump import Trump as trump def is_int(n): try: int(n) return True except ValueError: return False def error_check(s): if len(s) > 5: message = "ハンドは5枚です。" elif len(s) != len(set(s)): ...
193-M/Trump-game
Poker.py
Poker.py
py
9,206
python
en
code
0
github-code
36
29291642217
import numpy as np import statsmodels.api as sm import pandas as pd alpha = 0.05 df = pd.read_excel("4_6.xlsx", header=None) y = df.values # 提取数据矩阵 y = y.flatten() a = np.array(range(1, 8)) x = np.tile(a, (1, 10)).flatten() d = {'x': x, 'y': y} # 构造字典 model = sm.formula.ols("y~C(x)", d).fit() # 构建模型 anovat = sm.sta...
BattleforAzeroth/MMHomework
4.6.py
4.6.py
py
565
python
en
code
0
github-code
36
38055178106
import numpy as np from tensorflow import keras from src.util.load_review import return_tensored_review #cutoff value for the sentiment cutoff = 0.5 #loading movie review movie_review = return_tensored_review("pale_blue_eyes.txt") #loading the saved model model = keras.models.load_model("src/saved_model") predicti...
Weierstrash/review_sentiment_analysis
main.py
main.py
py
467
python
en
code
0
github-code
36
41662398078
import pandas as pd import numpy as np import os PATH = 'data/movielens/' TRAINFILE = PATH + 'train.csv' TESTFILE = PATH + 'test.csv' VALIDFILE = PATH + 'val.csv' MAPFILE=PATH+'item2id.map' def get_item(): train = pd.read_csv(TRAINFILE, sep='\t') valid = pd.read_csv(VALIDFILE, sep='\t') test ...
TraceIvan/RCNN_for_Recommendation
utils.py
utils.py
py
2,245
python
en
code
5
github-code
36
12803394908
import urllib2 import json headers = {'Content-Type': 'application/json; charset=utf-8'} XXX_HOST = "http://xxx.xxx.com/xxx-app/" # post请求,json格式数据 def post_json(url, header, request_data): req = urllib2.Request(url, request_data, header) page = urllib2.urlopen(req) res = page.read() page.close() ...
AldrichYang/HelloPython2
src/http/http_helper.py
http_helper.py
py
690
python
en
code
0
github-code
36
39479105306
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.management.base import BaseCommand, CommandError from cards.search import searchservice from cards.models import Card, BaseCard from cards.models import PhysicalCard import json from django.utils import dateparse import codecs import s...
jcrickmer/mtgdbpy
cards/management/commands/reindex_es.py
reindex_es.py
py
5,648
python
en
code
0
github-code
36
42883327134
class Solution: def findWinners(self, matches): ans = [[],[]] games = {} for game in matches: if not (game[0] in games): games[game[0]] = 0 if game[1] in games: games[game[1]] += 1 continue else: games[game[1]] = 1 f...
pablorenato1/leetcode-problems
Medium/Find-Players-With-Zero-or-One-Losses.py
Find-Players-With-Zero-or-One-Losses.py
py
684
python
en
code
0
github-code
36
40587003321
from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.decorators import login_required from django.http import (HttpRequest, HttpResponse, HttpResponseNotFound, HttpResponseRedirect) from django.shortcuts import redirect, render from django.urls import reverse_lazy...
Xewus/Examiner
src/questions/views.py
views.py
py
4,430
python
ru
code
0
github-code
36
31635729829
import os import torch import torchvision import random import pandas as pd import numpy as np import torch.nn as nn import matplotlib.pyplot as plt from PIL import Image import cv2 import torch.nn.functional as F import torchvision.transforms as transforms import torchvision.models as models from torc...
a20815579/cat_face_detection
cat_CNN.py
cat_CNN.py
py
13,278
python
en
code
1
github-code
36
31298538173
def solution(relation): column = len(relation[0]) row = len(relation) candidateKey = [] for case in range(1, 2**column): minimality = True uniqueness = True hashmap = {} for key in candidateKey: if key & case == key: minimality = False ...
shwjdgh34/algorithms-python
codingTest/2019kakao/후보키.py
후보키.py
py
1,122
python
en
code
2
github-code
36
39472235141
import json from flask import request, jsonify from flask_restful import Resource from werkzeug.exceptions import BadRequest from managers.brand import BrandManager from models import RoleType from models.products import * from schemas.request.brand import CreateBrandRequestSchema, EditBrandRequestSchema from schemas...
a-angeliev/Shoecommerce
server/resources/brand.py
brand.py
py
2,486
python
en
code
0
github-code
36
11371604753
import logging from sklearn.metrics import accuracy_score from pytorch_tabular import TabularModel from pytorch_tabular.config import DataConfig, OptimizerConfig, TrainerConfig from ml.solvers.base_solver import Solver class PytorchTabularSolver(Solver): def init_model(self): super(PytorchTabularSolver,...
gregiberri/coupon
ml/solvers/pytorch_tabular_solver.py
pytorch_tabular_solver.py
py
2,165
python
en
code
0
github-code
36
36211707503
#file a transaction #any changes to the users balanace should be reflected in the account file import datetime def transaction_options(accounts_path, line_number): stay_logged_in = True while stay_logged_in == True: ask = input('Would you like to make a transaction, return to the homepage, or logout ...
2105-may24-devops/fletcher-project0
transaction_module.py
transaction_module.py
py
3,661
python
en
code
0
github-code
36
8755383285
# -*- coding: utf-8 -*- import json import logging from datetime import datetime, date, timedelta from odoo import api, fields, models from odoo.addons.muk_dms.models import dms_base logger = logging.getLogger('FOLLOW-UP') AVAILABLE_PRIORITIES = [ ('0', u'Normale'), ('1', u'Basse'), ('2', u'Haute'), ...
odof/openfire
of_followup/models/of_followup.py
of_followup.py
py
70,070
python
en
code
3
github-code
36
38672578742
import shodan import requests from shodan import Shodan ''' api = Shodan('Insert_your_Shodan_Api_Key') print(api.search(query='product:nginx', facets='country,org')) ''' SHODAN_API_KEY = "Insert_your_Shodan_Api_Key" api = shodan.Shodan(SHODAN_API_KEY) target = 'www.packtpub.com' dnsResolve = 'https://api.shodan.io/...
MuhammadAli947/shodanCode
ShodanScans.py
ShodanScans.py
py
1,526
python
en
code
0
github-code
36
38650316304
#%% import pyautogui, pyperclip Y = 550 # 507 X = 800 # 740 pyperclip.copy("직") pyautogui.moveTo(x=X, y=Y, duration=0.001) pyautogui.click(clicks=1) pyautogui.hotkey("ctrl", "v") pyperclip.copy("업") pyautogui.moveTo(x=X, y=Y, duration=1) pyautogui.click(clicks=1) pyautogui.hotkey("ctrl", "v") pypercli...
shetshield/src
stitching_img/pymacro.py
pymacro.py
py
1,353
python
en
code
0
github-code
36
38313990919
from flask import flash from flask_app.config.mysqlconnection import connectToMySQL from flask_app.models import user from flask_app.models import message class Event: db = "plannendar_schema" def __init__(self, data): self.id = data['id'] self.event = data['event'] self.description =...
rchuu/plannendar
flask_app/models/event.py
event.py
py
5,351
python
en
code
0
github-code
36
39524154736
def zero_matrix(row, colons): out = [([0] * row) for i in range(colons)] return out # test matrix a = [[1, 2], [3, 4]] b = [[5, 6], [7, 8]] def add_matrix(vec_a, vec_b): out = zero_matrix(len(a[0]), len(a)) for i in range(len(a)): for j in range(len(a[0])): out[i][j] = a[i][j] + b...
Viachkov/Tutor_ML
test2.py
test2.py
py
1,051
python
en
code
0
github-code
36
26419037040
import datetime from functools import wraps from django.http import HttpResponseRedirect from django.urls import reverse from django.utils import timezone def authentication_required(function=None): def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): ...
qiuosier/Pisces
decorators.py
decorators.py
py
1,068
python
en
code
0
github-code
36
3270527178
""" Model implementation. """ from helper import cache_func, INIT_METHODS import tensorflow as tf class CNNModel: """ CNN model implementation. Covers the implementations for both the large and the compact network. """ def __init__(self, data, target, model_params, data_params): self.data ...
Oguzhanka/face_attractiveness
models/cnn_model.py
cnn_model.py
py
13,191
python
en
code
0
github-code
36
7416408824
import pywt import numpy as np from scipy import stats import matplotlib.pyplot as plt plt.style.use("resources/figstyle.mplstyle") FIG_WIDTH = 2.3 * 7.16 # Gaussian fitting utils from scipy import optimize def fit_generalized_gaussian(x): μ0 = x.mean() σ0 = x.std() β0 = 2 res = optimize.minimiz...
mattbit/wavelet-wqn-acha
acha_scripts/02_figure_2__coeff_distributions.py
02_figure_2__coeff_distributions.py
py
4,260
python
en
code
2
github-code
36
35217860162
from itertools import product import sys from bs4 import BeautifulSoup from selenium import webdriver import time import json import random sys.path.append('../..') from lib import excelUtils from lib import httpUtils from lib import textUtil from lib.htmlEleUtils import getNodeText from lib.htmlEleUtils import getInn...
Just-Doing/python-caiji
src/work/20230205/parchem.py
parchem.py
py
2,568
python
en
code
1
github-code
36
12410410025
""" Update existing "embargo_approved_no_user" logs to link to registered project instead of the registration. """ from copy import deepcopy import logging import sys from modularodm import Q from framework.transactions.context import TokuTransaction from website.models import Node, NodeLog from website.app import i...
karenhanson/osf.io_rmap_integration_old
scripts/fix_embargo_approved_logs.py
fix_embargo_approved_logs.py
py
1,458
python
en
code
0
github-code
36
10246834959
import os import argparse import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt if __name__ == '__main__': parser = argparse.ArgumentParser(description='Some hyperparameters') parser.add_argument('--epochs', type=int, default=200) parser.add_argument('--frac', type=float, default=0.1) ...
jinwoolim8180/fl-sparse-masking
accuracy.py
accuracy.py
py
3,163
python
en
code
0
github-code
36
69997777065
from re import split from typing import Dict, Mapping from elasticsearch import Elasticsearch import cbor import json from trec_car.read_data import * class IndexManagement: def __init__(self): self.es_cli = Elasticsearch( timeout=200, max_retries=15, retry_on_timeout=True) self.es_cli...
Hanifff/ConversationalAssistance
index_data.py
index_data.py
py
3,917
python
en
code
0
github-code
36
216572710
import time def measure(f): t0 = time.time() result = f() duration = time.time() - t0 return duration, result def show_duration(duration): if duration < 1: return '%.2fms' % (duration * 1e3) if duration < 60: return '%.2fs' % duration sec = int(duration) mm, ss = sec ...
kungfu-team/kungfu-mindspore
debug/mindspore_debug/__init__.py
__init__.py
py
614
python
en
code
0
github-code
36
30793302432
import cv2 import numpy as np cap = cv2.VideoCapture(0) # size = (600, 200, 3) # Указываем желаемый размер окна (высоту, ширину, число каналов) while True: ret, frame = cap.read() # ret - успешность захвата кадра. Если кадр был успешно захвачен, ret будет равен True. В противном случае, если что-то пошло не так и...
SeVaSe/Open_CV_test_vision
cameras&videocapture.py
cameras&videocapture.py
py
1,671
python
ru
code
0
github-code
36
42307266488
# s = "applepenapple", wordDict = ["apple", "pen"] # 输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] # 输出: false s = "applepenapple" wordDict = ["apple", "pen"] s2 = "catsandog" wordDict2 = ["cats", "dog", "sand", "and", "cat"] def isComposed(s,wordDict): wordDict = set(wordDict) maxLen...
jing-ge/Jing-leetcode
offer/2.py
2.py
py
758
python
en
code
0
github-code
36
37393448771
# Dependencies import json # Get influencer criteria from config.json file config_file = open('config.json') config = json.load(config_file) influencer = config['influencer'] def is_influencer(tweet): """ Determines if an user who tweeted a tweet is an influencer """ rts = tweet['retweet_count'] fav = tweet['...
janielMartell/twitter-influencer-scraper
utils.py
utils.py
py
860
python
en
code
0
github-code
36
31566863140
import sys import csv # preprocessing import gensim from gensim.utils import simple_preprocess import re import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize # lemmitization from nltk.stem import WordNetLemmatizer def pre_processor(): user_input = input('Please enter a dream...
connormeaton/dream_cluster
src/app/SampleTextPreprocessor.py
SampleTextPreprocessor.py
py
1,906
python
en
code
1
github-code
36
12185526029
"""Inference for 2D US Echocardiography EchoNet dataset.""" import os import numpy as np import torch import torchvision.transforms as transforms import torch.nn.functional as F from PIL import Image from torch.autograd import Variable import matplotlib.pyplot as plt from models.unet import UNet from models.cenet impo...
SanoScience/TTTS_CV
src/inference.py
inference.py
py
2,235
python
en
code
0
github-code
36
74506400423
from rest_framework import serializers from onbici.bike.serializers import BikeSerializer from onbici.bike.models import Bike from onbici.station.models import Station from .models import Slot class SlotSerializer(serializers.ModelSerializer): bike = BikeSerializer(required=False) class Meta: model =...
jubelltols/React_DRF_MySql
DRF/src/onbici/slot/serializers.py
serializers.py
py
2,029
python
en
code
0
github-code
36
26859540681
# -*- coding: utf-8 -*- ''' Created on 9 janv. 2019 @author: Nicolas MEO ''' from Plateforme.Adafruit_PWM_Servo_Driver import PWM import time # Definition des constantes de positions des servo-controller CONST_TRUE_PL1 = 355 CONST_TRUE_PL2 = 120 CONST_TRUE_PL3 = 140 CONST_TRUE_PL4 = 225 CONST_TRUE_PL5 = 125 CONST_TR...
Lancey139/GamificationDevOps
Plateforme/Servo_Controller.py
Servo_Controller.py
py
5,382
python
en
code
0
github-code
36
33532112483
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ A script to test if the associations.csv are good. Typically you would run this file from a command line like this: ipython3.exe -i -- /deploy/cbmcfs3_runner/scripts/check_associations.py """ # Built-in modules # # Third party modules # import pandas from tqd...
xapple/cbmcfs3_runner
scripts/associations/check_associations.py
check_associations.py
py
4,628
python
en
code
2
github-code
36
20240238686
class Solution: def numDecodings(self, s: str) -> int: # list: s[i] # メモするべきもの: その単語の長さまでの組み合わせの数 # 考慮するべきもの: 0は単体で使用できない(10, 20として使用するしかない) # arr = list(s) # if arr[0] == "0": # return 0 # # そこまでに格納できる組み合わせのtotal # dp = [0] * (len(arr)) # ...
sugitata/leetCode
dp/decode_ways.py
decode_ways.py
py
1,605
python
ja
code
0
github-code
36
39804183733
import os from celery import Celery # Set the default Django settings module for the 'celery' program. # similar to the setup in asgi.py # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prolube76site.settings') app = Celery('prolube76site') # Using a string here means the worker doesn't have to serialize # the co...
zjgcainiao/new_place_at_76
prolube76site/celery.py
celery.py
py
952
python
en
code
0
github-code
36
74876500585
t=int(input()) while(t): t-=1 n,m=list(map(int,input().split())) a=input().split() for i in a: i=list(i) #print(a) count=0 for i in range(1,n): if(len(set(a[i])&(set(a[i-1])))==0): count+=1 if(count<=m): print("Welcome to a world without r...
anirudhkannanvp/CODECHEF
Shaastra Online Programming Contest 2018/Let us put a smile on that face-- OPC1701.py
Let us put a smile on that face-- OPC1701.py
py
382
python
en
code
0
github-code
36
23670018346
guess = input('Digite numeros naturais separados por virgula: ') formated = guess.split(",") add = 0 for number in formated: if not number.isdigit(): print(f"Erro ao somar valores, {number} é um valor inválido”") else: add += int(number) print(f"A soma dos valores válidos é: {add}")
Andreyrvs/trybe-exercicios
T20A-Ciencia-da-Computacao/sessao-01-Introducao-a-Python/dia-02-Entrada-e-Saida-de-Dados/para-fixar/exercicio-02.py
exercicio-02.py
py
318
python
pt
code
0
github-code
36
71788582503
# TAGS: input(), end=' ' # () <-- parenthesis age = input("How old are you? ") # you can put what you wanna ask inside () height = input("How tall are you? ") weight = input("How much do you weigh? ") print(f"So you're {age} old, {height} tall and {weight} heavy.") #print("How old are you? ", input(...
jakszewa/Python-Notes
lpthw/ex12.py
ex12.py
py
424
python
en
code
1
github-code
36
19348729652
from app import app from flask import request, jsonify, make_response from api_exception import ApiException from data.internal_configurations.internal_configurations import InternalConfigurations @app.errorhandler(ApiException) def handle_invalid_service(error): response = jsonify(error.to_dict()) response.s...
mbast100/st-joseph-backend-services
routes/internal_configurations.py
internal_configurations.py
py
1,885
python
en
code
1
github-code
36
26531156238
#!/usr/bin/env python import rclpy from rclpy.node import Node from std_msgs.msg import String class DebugNode(Node): def __init__(self): super().__init__("debug_node") self.robot_mode_subs = self.create_subscription(String, "/robot_mode", self.callback_robot_mode_subs, 1) self.go_to...
gautamr0312/Obstacle-Avoidance-and-Waypoint-Navigation
Obstacle Avoidance and Waypoint Navigation/hr13_navigate_to_goal/hr13_navigate_to_goal/debug_node.py
debug_node.py
py
1,205
python
en
code
0
github-code
36
16721355609
import torch import torch.nn.functional as F from torch.distributions import Normal from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler from torch.nn.utils import clip_grad_norm_ from PPO_Continuous.version2.Network import Actor, Critic class PPO(object): def __init__(self, st...
zhihangmuzi/deep-reinforcement-learning-with-pytorch
PPO_Continuous/version2/Agent.py
Agent.py
py
3,981
python
en
code
0
github-code
36
70597091303
from mpio import LED import time from mpio import GPIO import mpio #Press the user push button for LED's to trigger def main(): red = LED("red") green = LED("green") blue = LED("blue") pin_out=GPIO(84,GPIO.OUT) pin_out.set(False) while(True): print("Please Press The User ...
epsilon1234/SAMA-5D-I-O-Triggering
output_trigger.py
output_trigger.py
py
1,375
python
en
code
0
github-code
36
37248697117
# Importing libraries and modules from tkinter import * from PIL import ImageTk, Image import time from tkinter import messagebox from tkinter.filedialog import askopenfilename # Start of GUI root = Tk() root.title("A-Star Grid World") # Grid Initialization # Ask the user if he wants to load a pre-deined world map ...
abhianshi/DynamicPathPlanning
src/AStarGUI.py
AStarGUI.py
py
8,336
python
en
code
1
github-code
36
8491596435
class Student: def __init__(self, name, major, gpa, is_on_probation): self.name = name self.major = major self.gpa = gpa self.is_on_probation = is_on_probation ''' We created this student class here in this file. If we are in another file/program, we an import this class, a...
ncterry/Python
CLASSES MAIN/class_Student.py
class_Student.py
py
397
python
en
code
0
github-code
36
72640625383
""" Project: SSITH CyberPhysical Demonstrator health.py Author: Ethan Lew <elew@galois.com> Date: 08/23/2021 Python 3.8.3 O/S: Windows 10 Component Health Monitoring Objects and Components """ import threading import abc import collections import re import requests import typing import struct import socket import time...
GaloisInc/BESSPIN-Tool-Suite
besspin/cyberPhys/cyberphyslib/cyberphyslib/demonstrator/healthmonitor.py
healthmonitor.py
py
11,624
python
en
code
5
github-code
36
25969594435
""" Given an array A of integers, return true if and only if it is a valid mountain array. Recall that A is a mountain array if and only if: A.length >= 3 There exists some i with 0 < i < A.length - 1 such that: A[0] < A[1] < ... A[i-1] < A[i] A[i] > A[i+1] > ... > A[B.length - 1] Example 1: Input: [2,1] Output: f...
wqh872081365/leetcode
Python/941_Valid_Mountain_Array.py
941_Valid_Mountain_Array.py
py
939
python
en
code
0
github-code
36
12259799552
from PySide2 import QtWidgets import ui.devicesDialog_ui import input.audio class form(QtWidgets.QDialog, ui.devicesDialog_ui.Ui_Dialog): def __init__(self): super(form, self).__init__() self.setupUi(self) #setup user interface self.currentDevice = 0 #set default device self.butto...
HamerKits/RoscoeQRSSViewer
devicesDialog.py
devicesDialog.py
py
948
python
en
code
0
github-code
36
71578985703
#!/usr/bin/env python import vtk def main(): pd_fn, scene_fn = get_program_parameters() colors = vtk.vtkNamedColors() polyData = ReadPolyData(pd_fn) mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(polyData) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().Set...
lorensen/VTKExamples
src/Python/Utilities/SaveSceneToFile.py
SaveSceneToFile.py
py
5,409
python
en
code
319
github-code
36
24347527125
# :參閱5-17頁 import os from os import path import platform def pyTube_folder(): sys = platform.system() home = path.expanduser('~') if sys == 'Windows': folder = path.join(home, 'Videos', 'PyTube') elif sys == 'Darwin': folder = path.join(home, 'Movies', 'PyTube') ...
theoyu13/python3
python程式設計入門/F9796/ch05/ch5_2.py
ch5_2.py
py
473
python
en
code
0
github-code
36
21848108182
import numpy as np from sklearn.externals.joblib import Parallel, delayed from multiprocessing import cpu_count def apply_parallel_joblib(func, data, *args, chunk=None, overlap=10, n_jobs=None, **kwargs): """ Apply a function in parallel to overlapping chunks of an array Parameters ---------- ...
emmanuelle/skimage-sprint
chunk_joblib.py
chunk_joblib.py
py
1,921
python
en
code
0
github-code
36
30523769752
#设立一个哨兵 #为负数的哨兵 #虽然可行,但是不是最好的,因为不能累加负数了... #改进的版本看Average4 def main(): sum = 0.0 count=0 x = eval(input("Enter a number (negative to quit)>> ")) while x>=0: sum+=x count += 1 x=eval(input("Enter a number (negative to quit)>> ")) print("\n The average of the numbers is",sum/...
ZTYZZ/learnPython
Average3.py
Average3.py
py
411
python
en
code
0
github-code
36
33377706423
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np eps = 1e-7 class SCELoss(nn.Module): def __init__(self, num_classes=10, a=1, b=1): super(SCELoss, self).__init__() self.num_classes = num_classes self.a = a self.b = b self.cross_entropy ...
hitcszx/lnl_sr
losses.py
losses.py
py
10,369
python
en
code
42
github-code
36
30003125789
memo = set() def get_first_lowercase(a): for i, c in enumerate(a): if c == c.lower(): return i return -1 def solve(a, b): global memo if f"{a}{b}" in memo: return False memo.add(f"{a}{b}") i = get_first_lowercase(a) if (i == -1 and a != b) or len(a) < len(b) o...
dimgatz98/coding_challenges
hackerrank/abbreviation/abbreviation.py
abbreviation.py
py
752
python
en
code
0
github-code
36
24396409804
import logging logger = logging.getLogger(__name__) def do_something(): logger.debug( 'Detailed information, typically of interest only when diagnosing problems.') logger.info('Confirmation that things are working as expected.') logger.warning( 'An indication that something unexpected hap...
jmhart/python-template
src/stuff/thing.py
thing.py
py
656
python
en
code
0
github-code
36
13425691279
### Unzip the Dataset # importing the zipfile module from zipfile import ZipFile import pandas as pd import random # loading the temp.zip and creating a zip object with ZipFile("./resources/Sentences_from_Stormfront_dataset.zip", 'r') as zip_oject: # Extracting all the members of the zip # into a specific loc...
Speymanhs/SemEval_2023_Task_11_Lonea
reading_dataset_stormfront.py
reading_dataset_stormfront.py
py
1,887
python
en
code
0
github-code
36
17093960893
#!/usr/bin/env python from __future__ import print_function import sys data = '' for line in open(sys.argv[1], 'r'): if len(line.strip()) == 0: # skip the label lines = data.splitlines() print('\n'.join(lines[1:])) data = '' else: data += line
Oneplus/learn2compose
scripts/yelp/remove_document_splitter_and_label.py
remove_document_splitter_and_label.py
py
293
python
en
code
7
github-code
36
3479784873
# This is the model definition of retrieval model. from typing import List, Dict, Tuple, Text import os import tensorflow as tf import tensorflow_recommenders as tfrs import numpy as np from . import dataset as ds, params # Get unique query and candidate and timestamp. unique_user_ids, unique_therapist_ids = ds.get_u...
thomiaditya/theia
theia/config/recommender/retrieval_definition.py
retrieval_definition.py
py
6,028
python
en
code
0
github-code
36
8024464551
""" Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For example: A = [2,3,1,1,4], return true. A = [3,2,1,0,4], return false. """ ...
cyandterry/Python-Study
Ninja/Leetcode/55_Jump_Game.py
55_Jump_Game.py
py
1,784
python
en
code
62
github-code
36
74430413223
class PushingList(list): """ При переполнении выталкивает первый элемент. Стандартная максимальная длинна 10 элементов. """ max_len = 10 def append(self, *args): for arg in args: super(PushingList, self).append(arg) if self.__len__() > self.max_len: self.pop(...
Apolliner/Field-Mini-Game
libraryNPC/classes.py
classes.py
py
401
python
ru
code
0
github-code
36
33532139383
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ A script to convert the column names from CamelCase to snake_case. Typically you would run this file from a command line like this: ipython3.exe -i -- /deploy/cbmcfs3_runner/scripts/orig/convert_column_case.py """ # Built-in modules # import os # Third party ...
xapple/cbmcfs3_runner
scripts/orig/convert_column_case.py
convert_column_case.py
py
7,647
python
en
code
2
github-code
36
4828779456
import torch from torch import nn import pickle from model import WideResNet from autoattack import AutoAttack from torch.utils.data import Dataset from torch.utils.data import DataLoader from torchvision import datasets, transforms, models class ImageDataset(Dataset): def __init__(self, file): super().__i...
AmadeusloveIris/AutoAdversarialTraining
test.py
test.py
py
2,316
python
en
code
0
github-code
36
12234497572
import datetime from typing import List from sqlalchemy.orm import make_transient from data_access.entities.person import Person from data_access.entities.policy import Policy from data_access.entities.policy_offer_template import PolicyOfferTemplate from data_access.entities.policy_risk import PolicyRisk from data_a...
bastyje/policyapp
python/src/services/policy_service.py
policy_service.py
py
8,189
python
en
code
0
github-code
36
12487564602
import filecmp import subprocess import pytest from typer.testing import CliRunner import erdantic as erd from erdantic.cli import app, import_object_from_name import erdantic.examples.dataclasses as examples_dataclasses import erdantic.examples.pydantic as examples_pydantic from erdantic.examples.pydantic import Par...
drivendataorg/erdantic
tests/test_cli.py
test_cli.py
py
6,182
python
en
code
205
github-code
36
10208120572
import socket import threading from collections import deque from concurrent.futures import ThreadPoolExecutor from jsock.protocol import Protocol from jsock.message import MessageHeader, Message from jsock.errors import Errors from jsock.client import Client from jsock.config import Config PORT = 1337 LISTEN_NUM = 50...
jacobggman/python_black_jack_server
jsock/server.py
server.py
py
7,368
python
en
code
0
github-code
36
35183490035
import asyncio import os import oneai from oneai import Input, Output oneai.api_key = os.getenv("ONEAI_KEY") async def split(filepath): pipeline = oneai.Pipeline( steps=[ oneai.skills.SplitByTopic(), ] ) with open(filepath, 'r') as file_input: output = await pipeline....
clande/demo
oneai_splitbytopic_repro.py
oneai_splitbytopic_repro.py
py
808
python
en
code
0
github-code
36
20604733756
from sklearn import preprocessing from pandas import read_csv from sklearn.model_selection import train_test_split from keras.layers import Dense from keras.models import Sequential from keras.optimizers import Adam from sklearn.metrics import r2_score from matplotlib import pyplot as plt df = read_csv("C:\Code\RNASeq...
taytay191/RNAseqAnalysis
RNAseqFinal/model.py
model.py
py
1,905
python
en
code
0
github-code
36
2063569811
from functools import cache from . import get_track_data, get_countries_charts import pandas as pd @cache def get_basic_track_features(): tracks = get_track_data() isrc_cols = tracks.columns[tracks.columns.str.contains("isrc")].tolist() album_cols = tracks.columns[tracks.columns.str.contains("album")].tol...
Sejmou/exploring-spotify-charts
data-collection-and-exploration/helpers/model.py
model.py
py
3,256
python
en
code
2
github-code
36
34448705706
"""Test model file for users.""" from app.api.v1.models.user_models import UserModel, database from .import BaseClass class TestUserModel(BaseClass): """docstring for TestUserModel.""" def test_can_save_user(self): """Test if we can save a user.""" user = self.user1.save() self.asser...
Bakley/SendIT-Api-V1
test/test_user_model.py
test_user_model.py
py
1,054
python
en
code
0
github-code
36
16589607570
import random import requests import codecs import json import re import queue import time from threading import Thread requests.packages.urllib3.disable_warnings() proxy = '127.0.0.1:8888' def sec(): while True: headers = { 'Referer': 'https://www.achievemint.com/signup?referral=1&utm_campaign=YOaBLXQNLBg%3D%0...
breitingerchris/public_code
Python/Achievemint/anker.py
anker.py
py
1,509
python
en
code
0
github-code
36
40988144291
from pathlib import Path from typing import Any, Dict import json MockData = Dict[str, Any] class Mock: """ A class that holds the `mock.json` file contents """ mock: MockData = {} @staticmethod def populate(mock_path: Path) -> None: if not mock_path.exists(): raise Exce...
viscript/Ox4Shell
lib/mock.py
mock.py
py
490
python
en
code
null
github-code
36
19915052730
""" Write a function that takes directory path, a file extension and an optional tokenizer. It will count lines in all files with that extension if there are no tokenizer. If a the tokenizer is not none, it will count tokens. For dir with two files from hw1.py: #>>> universal_file_counter(test_dir, "txt") 6 #>>> univer...
Abbath90/python_epam
homework9/task3/file_counter.py
file_counter.py
py
1,333
python
en
code
0
github-code
36
938934612
import os import json class Settings: def __init__(self, settings_directory, settings_default): self.settings_directory = settings_directory self.settings_default = settings_default self.settings_file = os.path.join(self.settings_directory, "settings.json") # Make sure a settings ...
ChimeraOS/chimera
chimera_app/settings.py
settings.py
py
2,180
python
en
code
189
github-code
36
37989832631
""" Steps to run: python python policy_list_report_scraper.py Program written in Python 3 Program Output: 1 file: Exported_data.csv - csv file that contains the policy list report data Program Description: Progam first fetches the ASP login page paramters - __VIEWSTATE, __VIEWSTATEGENERATOR, etc and then inputs the...
tebbythomas/Freelance_Projects
Web_Data_Extraction_Projects/J11_Finance_Pro_Policy_List_Report_Generator/Policy_List_Report/policy_list_report_scraper.py
policy_list_report_scraper.py
py
7,187
python
en
code
1
github-code
36
74436898025
t = int(input()) for _ in range(t): n,m = [int(x) for x in input().split()] a = [] for i in range(n): a.append(input()) s = input() l = len(s) flag = 0 for i in range(l): if(s[i] in a[i%n]): f = a[i%n].index(s[i]) a[i%n] = a[i%n][:f]+a[i%n][f+1:] ...
hamdan-codes/codechef-unrated-contests
HackCon_String Generation.py
HackCon_String Generation.py
py
449
python
en
code
2
github-code
36
21138228098
import os, sys path = "outages/" dirs = os.listdir(path) total_count = 0 total_count2 = 0 for filename in dirs: count = 0 count2 = 0 with open(path+filename, "r") as f: lines = f.readlines() for line in lines: word = line.split(" ") if word and word[0] == "Message-ID:": count+=1 if word and word[0]...
zhasun/CSE534Project
Data_Preprocessing/Tim/extract_and_assign_content/count_post.py
count_post.py
py
617
python
en
code
0
github-code
36
9109984564
from pwn import * import struct import re def recvall(conn): msg = b'' while True: try: new_block = conn.recv(timeout=1) if new_block == b'': break msg += new_block except EOFError as e: break return msg def ret_to_main(pie_base_addr, conn): payload = b'a'*0x2c payload += struct.pack("<I", ...
Altelus1/Hacking_Adventures
TUCTF2019/pwn/leakalicious_prob/leakalicious_exploit.py
leakalicious_exploit.py
py
2,287
python
en
code
0
github-code
36
477236470
import io, os from .comment_parser import CommentParser from .create_parser import CreateParser from .insert_parser import InsertParser class Reader: def __init__(self): self._tables = {} self._rows = {} self._global_errors = [] self._global_warnings = [] self._parsing_error...
cmancone/mygrations
mygrations/formats/mysql/file_reader/reader.py
reader.py
py
5,702
python
en
code
10
github-code
36
523657887
#REGINALD HUEY TAN IAN JAY (S10239913) - IT01 (P01) #============================== IMPORTING RESOURCES =============================== import random, math, time import os, asyncio os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" #hide pygame initialisation message from pygame import mixer from S10239913E_Assignment_...
klystrn/Tower-Defence-Game
towerDefence.py
towerDefence.py
py
42,879
python
en
code
0
github-code
36
26290834166
"""Tests for common_utils.py.""" import common_utils import pytest class TestCommonUtils: def testGetFilePathShouldRaiseError(self): common_utils.input = lambda _: 'foo' with pytest.raises(FileNotFoundError): common_utils.get_file_path() common_utils.input = input def testGetFilePathShouldNotR...
thompsond/PyAVMisc
com/AVMisc/common_utils_test.py
common_utils_test.py
py
687
python
en
code
0
github-code
36
6296104681
import requests import urllib.parse from models import PlayByPlay from constants import headers from db_utils import insert_many class PlayByPlayRequester: url = 'https://stats.nba.com/stats/playbyplayv2' def __init__(self, settings): self.settings = settings self.settings.db.bind([PlayByPl...
Promise-Igbo/nba-sql
stats/play_by_play.py
play_by_play.py
py
3,273
python
en
code
null
github-code
36
36057963305
lst = [10, 5, 2, 7, 4, 9, 12, 1, 15] l = list() r = list() #print(len(lst)) #print(len(list)//2) for i in range(0, (len(lst)//2)): l.append(lst[i]) print(l.__len__()) print(len(l)) for i in range((len(lst)//2), len(lst)): r.append(lst[i]) print(r)
srikloud/PyProjects
Sorts/mergesort.py
mergesort.py
py
261
python
en
code
0
github-code
36
23219260357
import random def get_random_word(): words = ["pizza", "cheese", "apples"] word = words[random.randint(0, len(words)-1)] return word def show_word(word): for character in word: print(character, end="") def play_word_game(): strikes = 0 max_strikes = 3 playing = True word ...
sizif/python-path-one
main.py
main.py
py
723
python
en
code
0
github-code
36
71666166824
# The following code was adapted from Week 3 Programming Assignment 2 in the Convolutional Neural Networks course by DeepLearning.AI offered on Coursera # https://www.coursera.org/learn/convolutional-neural-networks/home/week/3 import tensorflow as tf import numpy as np from tensorflow.keras.layers import Input fro...
AndrewZhang126/Neural-Networks
U-Net.py
U-Net.py
py
6,154
python
en
code
1
github-code
36
40083862973
#!/usr/bin/env python3 import argparse import random import json import re import importlib.util import os.path import sys import types import inspect import pandas as pd import numpy as np MAX_SLOT=8 SMART_COMMENT="\\s*#+\\s*(fastscore|odg)\\.(\\S*)\\s*:\\s*(\\S*)\\s*$" def is_input_slot(s): return s % 2 == 0 ##...
modelop/modelop.github.io
Product Manuals/Model Launchers/Python Launcher/lh.py
lh.py
py
9,190
python
en
code
1
github-code
36
19568803995
from random import randint y = randint(1,5) hscore = 0 cscore = 0 print("Winners and Losers - Human is Even, Computer is Odd") for i in range (1, 6) : print("Round: {}".format(i)) x = int(input("Enter Your Guess: ")) print ("Human Guess: {} - Computer Guess: {}".format(x , y)) sum = x + y if sum % 2...
wgrevis/ifsc1202
Exam One.py
Exam One.py
py
609
python
en
code
0
github-code
36
10567641757
import time from datetime import datetime, timedelta from pydantic import BaseModel from fastapi import FastAPI, Depends, File, UploadFile, HTTPException, Request, status from fastapi.responses import HTMLResponse, JSONResponse, FileResponse import uvicorn import os from pytube import YouTube from pytube import Playlis...
uponex/YoutubeAPI
main.py
main.py
py
7,761
python
en
code
0
github-code
36
21704376256
# # @lc app=leetcode.cn id=40 lang=python3 # # [40] 组合总和 II # from typing import List # @lc code=start class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: ans = [] current = [] def dfs(i, target): if target == 0: ans.append(current[:]) ...
LinkTsang/.leetcode
solutions/40.组合总和-ii.py
40.组合总和-ii.py
py
780
python
en
code
0
github-code
36
69812436265
import numpy as np import cv2 from PIL import Image #В этом скрипте делаем маску #С помощью манипуляций с opencv создаем два файла #первый - с контрастными крышами, второй - с выделенными дорогами #затем - используя второй файл, убираем дороги с первого image = "ZRYNEEUSVQ213QTY.png" input = cv2.imread(image) _, th =...
kekartem/BuildingDefine
RunFirst.py
RunFirst.py
py
1,512
python
ru
code
0
github-code
36
70537874663
import unittest import player_factory from inning_creator import Inning from positional_data import StandardPosition def collect_benched_players(inning): bench_assignments = [ assignment for assignment in inning.assignments if assignment.position.title == "Bench" ] return bench_assignments...
jasonmrimer/roster
test_inning.py
test_inning.py
py
2,193
python
en
code
0
github-code
36
34141195826
import numpy as np import torch from snownlp import SnowNLP from common_utils import * from preprocessing.clean_data import batchify def get_overlap(list1, list2): """ Returns a list of words that occur in both list1 and list2. Also returns total number of words in list1 and in list2 (can be used to ...
JasmineZhangxyz/ewb-ml-censorship
similarity/metrics/list_metrics.py
list_metrics.py
py
4,969
python
en
code
0
github-code
36
11571428709
from django.utils.module_loading import import_string from django.urls import (RegexURLResolver, RegexURLPattern) from CRM import settings from collections import OrderedDict def recursion_urls(pre_namespace, pre_url, urlpatterns, url_ordered_dict): # None, '/', urlpatterns, url_ordered_dict ''' 第一次递归: ...
heyhito/CRM
rbac/server/routes.py
routes.py
py
2,278
python
en
code
0
github-code
36
18913603323
from collections import defaultdict class Solution: def valid_tree(self, n: int, edges: list[list[int]]) -> bool: seen: set[int] = set() children: dict[int, list[int]] = defaultdict(list) for x, y in edges: children[x].append(y) children[y].append(x) def d...
lancelote/leetcode
src/graph_valid_tree.py
graph_valid_tree.py
py
689
python
en
code
3
github-code
36