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
22813435642
import numpy as np import cv2 import os from cv2 import dnn def ColorizeImage(sourceImg, save): if(os.path.exists(sourceImg) == False): return proto_file = 'Model\colorization_deploy_v2.prototxt' model_file = 'Model\colorization_release_v2.caffemodel' hull_pts = 'Model\pts_in_hull.npy' # R...
OguzkanK/Image-Colorizer
ColorizeImage.py
ColorizeImage.py
py
2,370
python
en
code
0
github-code
1
5563353172
import zmq from time import sleep context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind('tcp://127.0.0.1:2000') messages = [100,200,300] i = 0 while True: sleep(1) socket.send_pyobj({i:messages[i]}) i = 0 if i == 2 else i + 1
williamlun/SomeCommunicationSocket
ZeroMQ/zmq_pub.py
zmq_pub.py
py
257
python
en
code
2
github-code
1
16569111742
""" The version of the package can be returned as a single string or a dict. When a string, it comes from the package __version__. When a dict, it also has __version__, as well as versions of other depdency packages. """ from typing import Optional import dls_mainiac_lib.version import dls_servbase_lib.ve...
DiamondLightSource/soakdb3
src/soakdb3_lib/version.py
version.py
py
1,208
python
en
code
0
github-code
1
18101203760
import sys input = sys.stdin.readline N = int(input()) # num_arr = list(map(int,input().split())) num_arr = input().split() def reverse(x): new_num = [] for i in range(len(x),0,-1): new_num.append(x[i-1]) new_num = ''.join(new_num) return int(new_num) def isPrime(x): count = 0 if x == ...
codnjs3575/TIL
Inflearn/section_2/8_뒤집은_소수.py
8_뒤집은_소수.py
py
525
python
en
code
0
github-code
1
25896635456
from datetime import datetime import Player class Result: def __init__(self, date: datetime, place: int, player: Player, id: int = None): self.id = id self.date = date self.place = place self.player = player
JChoptiany/Poker-Pro-League
Result.py
Result.py
py
246
python
en
code
1
github-code
1
13853365576
import requests import json import re url = "http://www.juzimi.com/article/%E6%83%85%E4%B9%A6" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36", "Referer": "http://www.juzimi.com/search/node/%E5%82%B2%E6%85%A2%E4%B8%8E%E5...
youguanxinqing/Extract_Data
regex.py
regex.py
py
1,513
python
en
code
0
github-code
1
32793763181
"""create table vulnerabilities Revision ID: 7c34e9a89bc0 Revises: b21ffaeed8e4 Create Date: 2016-06-29 10:11:36.057723 """ # revision identifiers, used by Alembic. revision = '7c34e9a89bc0' down_revision = 'b21ffaeed8e4' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa import d...
asrozar/perception_ui
migrations/versions/7c34e9a89bc0_create_table_vulnerabilities.py
7c34e9a89bc0_create_table_vulnerabilities.py
py
1,357
python
en
code
0
github-code
1
1421958380
#!/usr/bin/env python # # # # Autor: Milena Crnogorcevic # # Date created: 7/22/2019 ...
mcrnogor/LLE-ALPs
sensitivity/scripts/ALP_fit.py
ALP_fit.py
py
2,626
python
en
code
0
github-code
1
41012606432
filename = "Inputs/" + __file__.strip("py") + "txt" with open(filename, "r") as file: data = file.readlines() import operator scanners = [] scannerIndex = 0 for line in data: if line.startswith("---"): scanners.append([]) continue if line.isspace(): scannerIndex += 1 cont...
ThomasCulotta/Advent2021
Day19.py
Day19.py
py
3,625
python
en
code
0
github-code
1
1666799492
'''Created on 2021-11-03 @author: Gabriel Bailey This code will solve Burger's equation for a given equation using the leapfrog method. It will produce 4 graphs of the equation at different times, and also an animated graph over time if desired. ''' # Started from laplace.py from numpy import pi,zeros, sin,linspace ...
TheRajeshB/Labwork1
Lab08/Lab08_Q3.py
Lab08_Q3.py
py
2,622
python
en
code
0
github-code
1
62125632
import numpy as np import matplotlib.pyplot as plt def pie_charts(sizes,title): #adjust the size of figure plt.figure(figsize=(6,9)) #define label labels = ['0-17 years','18-64 years','65+ years'] colors = ['yellow','lightskyblue','yellowgreen'] #The larger the value is, the larger the ga...
ShikaZzz/disease-outbreak
scripts/h1n1_piecharts.py
h1n1_piecharts.py
py
1,303
python
en
code
0
github-code
1
43199603252
from itertools import compress import numpy as np from .object_intersect import partition, get_ob_2dbboxes, get_vert_co_2d, get_ob_loc_co_2d, do_selection from .polygon_tests import point_inside_rectangles, points_inside_rectangle, segments_intersect_rectangle def get_obs_mask_in_selbox(obs, obs_mask_check, depsgra...
AtixCG/Universal-3D-Shortcuts
Blender/With Addons/scripts/addons/space_view3d_xray_selection_tools/functions/object_intersect_box.py
object_intersect_box.py
py
3,688
python
en
code
38
github-code
1
27528723023
#!/usr/bin/python3 import argparse import json import time import cv2 import numpy as np # dictionary with ranges ranges_pcss = {"b": {"min": 100, "max": 256}, "g": {"min": 100, "max": 256}, "r": {"min": 100, "max": 256}, } def main(): """ INITIALIZE -----------...
JorgeFernandes-Git/PSR_AULAS_2021
openCV/video_capture/ar_paint_v1/ar_paint.py
ar_paint.py
py
9,828
python
en
code
0
github-code
1
31534568892
__author__ = 'christine' GTEx = ['Pancreas', 'Esophagus', 'Heart', 'Colon', 'Bone Marrow', 'Liver', 'Skin', 'Kidney', 'Brain', 'Pituitary', 'Blood', 'Thyroid', 'Uterus', 'Adipose Tissue', 'Adrenal Gland', 'Breast', 'Stomach', 'Spleen', 'Fallopian Tube', 'Lung', 'Blood Vessel', 'Ovary', 'Testis', '<not provided>', 'Mus...
christinecho/Analysis-of-Gene-Expressions
GTExAndTCGA.py
GTExAndTCGA.py
py
1,281
python
en
code
0
github-code
1
12171273789
import rclpy from rclpy.node import Node from sensor_msgs.msg import Image import cv2 from cv_bridge import CvBridge class CameraSubscriber(Node): def __init__(self): super().__init__("camera_subscriber") self.create_subscription(Image, "/wamv/sensors/cameras/front_left_camera_sensor/optical/image_...
Wavefire5201/boat_ctrl
boat_ctrl/camera.py
camera.py
py
754
python
en
code
1
github-code
1
1633435425
#!/usr/bin/env python3 ''' Perform classification of a corpus using CountVectorizer. Displays the metrics from the classification. ''' import codecs as cs from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn import cross_validation from sklearn import m...
dumoulma/fic-prototype
MeasureTF.py
MeasureTF.py
py
2,326
python
en
code
10
github-code
1
3978233106
# -*- coding: utf-8 -*- """ Class to store Units and perform conversion This script requires that `logging` be installed within the Python environment you are running this script in. """ import logging import json from os import path import logging.config class Unit: """It represents the physical un...
Praveenstein/Intern_Assignment
Q1/Q1_unit_2_dicConfig.py
Q1_unit_2_dicConfig.py
py
3,305
python
en
code
0
github-code
1
20330162062
import scipy.stats import numpy as np class UniformDist: def __init__(self, xmax=1., xmin=None): self.xmax = xmax self.xmin = - xmax if xmin is None else xmin self.prob = 1 / (self.xmax - self.xmin) def __call__(self, *args, **kwargs): return self.prob def __str__(self): ...
uidilr/bayesian_irl
src/utils/prob_dists.py
prob_dists.py
py
2,191
python
en
code
14
github-code
1
8882625049
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('webapp', '0009_auto_20141216_0118'), ] operations = [ migrations.AlterField( model_name='openinghours', ...
IvanCaceres/drunken-octo-spice
appointments/webapp/migrations/0010_auto_20141216_0119.py
0010_auto_20141216_0119.py
py
702
python
en
code
0
github-code
1
9557083189
# 15_function_ex1.py # 다음의 함수를 포함하는 프로그램 작성 # 함수 이름 : sum() # 숫자 2개를 입력 받아서 두수의 합을 구하여 출력 # 숫자1 입력 : 3 # 숫자2 입력 : 4 # 합 : 7 def sum() : num1 = int(input('숫자1 입력 : ')) num2 = int(input('숫자2 입력 : ')) sum = num1+ num2 return sum print('합 : ', sum())
DavidMCKim/TIL
210628-210702 Python 강의/10_function/15_function_ex1.py
15_function_ex1.py
py
380
python
ko
code
0
github-code
1
13043906918
import pytest from iotile.core.exceptions import ArgumentError from iotile.sg.model import DeviceModel from iotile.sg.sensor_log import SensorLog from iotile.sg.exceptions import StorageFullError, UnresolvedIdentifierError from iotile.sg.engine import InMemoryStorageEngine from iotile.sg import DataStreamSelector, Dat...
iotile/coretools
iotilesensorgraph/test/test_sensorlog.py
test_sensorlog.py
py
12,526
python
en
code
14
github-code
1
5410486029
from copy import deepcopy import requests from c2corg_api.legacy.converter import convert_from_legacy_doc, convert_to_legacy_doc from c2corg_api.schemas import schema_validator def test_converter(document_id, document_type): legacy_doc = requests.get(f"https://api.camptocamp.org/{document_type}s/{document_id}", ...
c2corg/c2c_api-poc
migrations/test_converter.py
test_converter.py
py
1,457
python
en
code
0
github-code
1
25159626748
import os from unidecode import unidecode from pathlib import Path import argparse import re parser = argparse.ArgumentParser() parser.add_argument("--path", type=str, required=True) parser.add_argument("--remove_accent", type=bool, required=False, default=True) parser.add_argument("--lower", type=bool, required=False...
eugeniothiago/file-name-padronizer
file_padronizer.py
file_padronizer.py
py
3,190
python
en
code
0
github-code
1
36626195418
import requests def get_and_filter_data(api_url, filter_params): response = requests.get(api_url) if response.status_code == 200: data = response.json() filtered_data = [item for item in data if all(item.get(key) == value for key, value in filter_params.items())] return filtered_data...
Prosik2205/Python
main.PY
main.PY
py
645
python
en
code
0
github-code
1
72696732193
# Python practise 21 (From hackerrank) - List """ List : Consider a list (list = []). You can perform the following commands: - insert i e: Insert integer e at position i. - print: Print the list. - remove e: Delete the first occurrence of integer e. - append e: Insert integer e at the end of the list. - sort: Sort...
Brodevil/Competative-Programming
Python/Solved Questions/practise_set_21.py
practise_set_21.py
py
2,525
python
en
code
3
github-code
1
73001660513
import sys sys.path.insert(1, 'C:\\Users\\upcnet\\Repositoris\\neuroimatge\\nonlinear2') sys.path.insert(1, '/Users/acasamitjana/Repositories/neuroimatge/nonlinear2') from Fitters.GAM import GAM, SmootherSet, SplinesSmoother import numpy as np import numpy.random as R # import matplotlib # matplotlib.use('GTKAgg') imp...
imatge-upc/VNeAT
scripts/legacy/GAM/testGAM_splinesSmoother.py
testGAM_splinesSmoother.py
py
2,588
python
en
code
3
github-code
1
18022324894
import os import numpy as np from PIL import Image import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import time import kornia import copy from torch.utils.data import Dataset import glob import cv2 os.environ["OPENCV_IO_ENABLE_OPENEXR...
PKU-EPIC/DREDS
DepthSensorSimulator/stereo_matching.py
stereo_matching.py
py
25,023
python
en
code
89
github-code
1
291709158
#!/usr/bin/python3 import argparse import string import random from pwn import * import subprocess import requests import netifaces import sys import json import hashlib from urllib.parse import urlencode webserver_port = 9001 proxies = {"http": "http://127.0.0.1:8080"} class dompdf_rce: def __init__(self, dompd...
dugisan3rd/exploit
dompdf v1.2.1 RCE (CVE-2022-28368)/dompdf-rce.py
dompdf-rce.py
py
4,780
python
en
code
0
github-code
1
12889344897
import numpy as np import random from scipy.stats import norm from scipy.special import expit as sigmoid class BBVI(object): def __init__(self,trainSource,testSource,featureDim, maxIteration,batchSize,sampleSize,stepScale,startPara, dataAccessing='RA',interval=100,testSampleNum=200): self._maxitera...
allenzhangzju/Black_Box_Variational_Inference
bayesian_logistic_regression_for_a9a/class_BBVI.py
class_BBVI.py
py
7,041
python
en
code
1
github-code
1
70324000673
import argparse import multiprocessing import shlex import fim import pandas as pd import export import outlier import preprocess ############################################################################## # DATA LOADING AND PRE-PROCESSING def load_metrics(file_in, min_var, min_corr, scaling): # load data ...
bittremieux/qc_analysis
qc_analysis.py
qc_analysis.py
py
6,497
python
en
code
2
github-code
1
21918886906
''' Define the Layers ''' import torch.nn as nn import torch.nn.functional as F from Attention import MultiHeadAttention class PositionwiseFeedForward(nn.Module): ''' A two-feed-forward-layer module ''' def __init__(self, d_in, d_hid, dropout=0.1): super().__init__() self.w_1 = nn.Conv1d(d_in,...
dodohow1011/waveglow_2
SubLayer.py
SubLayer.py
py
2,034
python
en
code
0
github-code
1
28081058204
from django.shortcuts import render from django.shortcuts import get_object_or_404 # Create your views here. from django.http import HttpResponse from .models import Site, Value def index(request): listSites = Site.objects.all() context = {'listaSites' : listSites} return render(request, 'index.html', cont...
bunnis/MWSite1
MW/views.py
views.py
py
2,106
python
en
code
0
github-code
1
30706837147
from functools import lru_cache from ScienceDynamics.config.log_config import logger class PapersFetcher(object): def __init__(self, db_client, db_name="journals", papers_collection="papers_features", papers_join_collection="aminer_mag_papers"): self._db = db_client[db_name] self....
data4goodlab/ScienceDynamics
ScienceDynamics/fetchers/papers_fetcher.py
papers_fetcher.py
py
1,514
python
en
code
0
github-code
1
34872369398
from flask import Flask, request import json app = Flask(__name__) @app.route('/motion-data', methods=['POST']) def motion_data(): data = json.loads(request.data) # Do something with the motion data (e.g., store it in a database) return 'Motion data received' if __name__ == '__main__': app.run(host='...
strikerPro818/strikerBot
Xavier_NX/mobileSelectTrack/appMotion.py
appMotion.py
py
348
python
en
code
0
github-code
1
29991270161
# ************************************************************************** # * # * Authors: Grigory Sharov (gsharov@mrc-lmb.cam.ac.uk) # * # * MRC Laboratory of Molecular Biology (MRC-LMB) # * # * This program is free software; you can redistribute it and/or modify # * it under the terms of the GNU General Public...
scipion-em/scipion-em-relion
relion/protocols/protocol_create_mask3d.py
protocol_create_mask3d.py
py
9,433
python
en
code
3
github-code
1
12238117511
from dataclasses import dataclass import datetime from typing import List, NamedTuple, Tuple import json from copy import deepcopy from event import Event, Location, Timeframe from mapsy import timeDistance @dataclass class Task: id: int begin: datetime.datetime end: datetime.datetime dur: datetime.t...
swiftplan-winhacks/swiftplan
planner.py
planner.py
py
7,527
python
en
code
0
github-code
1
1892667939
''' Created on 09/11/2009 @author: Nahuel ''' from matrix.NDimMatrix import NDimMatrix from matrix.MatrixException import MatrixException class Matrix(NDimMatrix): '''Two dimension Matrix.''' def __init__(self, size): ''' Constructor of Matrix. @note: checks if size has a dimension = ...
ngarbezza/tpi-so1-tp
src/matrix/Matrix.py
Matrix.py
py
5,632
python
en
code
0
github-code
1
29008570208
import FWCore.ParameterSet.Config as cms from Configuration.StandardSequences.Eras import eras from cp3_llbb.Framework import Framework from cp3_llbb.Framework.CmdLine import CmdLine options = CmdLine(defaults=dict(runOnData=1, era="25ns", globalTag='80X_dataRun2_2016SeptRepro_v7', process='RECO')) framework = Fram...
cp3-llbb/Framework
test/TestConfigurationData.py
TestConfigurationData.py
py
1,534
python
en
code
0
github-code
1
26183187886
# Imports import random import time # LINEAR SEARCH # Linear Search method that will search list one element at a time to see if it matches "a" def linear_search(numeric_list, a): for j in range(len(numeric_list)): if numeric_list[j] == a: return j # If match can't be found, return -1 ...
skyquis/ds_m8
SearchingSortingTimingMarquis.py
SearchingSortingTimingMarquis.py
py
8,661
python
en
code
0
github-code
1
6232972354
import uuid from datetime import datetime from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from core.models import Reading, Customer, Device class TestReadingView(APITestCase): def setUp(self): self.url = reverse('reading') def test_send_...
FadyAlfred/envio-challenge
core/tests.py
tests.py
py
2,020
python
en
code
0
github-code
1
2309219912
import numpy as np from PIL import Image, ImageDraw, ImageFilter import streamlit as st # 何個作るか聞く num_trials = st.slider('何個試作しますか?',0,10,0) button = st.button('上記の設定で試作') # 画像を後で入れる空のリスト imgs = [] # URLを下になる画像から順に入れる urls = ['base.png', 'field.jpg', 'yattazeyossya.png', 'Splatoon2logo.png', 'decorators-12...
auto-autumn/streamlit-thumbnails
AutoThumbnailStreamlit.py
AutoThumbnailStreamlit.py
py
2,311
python
en
code
0
github-code
1
12394194085
from aiohttp import web from asyncpg.exceptions import UniqueViolationError from . import permissions from .dataaccess import environmentda from . import auditing async def get_envs(request): env_list = await environmentda.get_envs() envs = {'envs': [{'name': e} for e in env_list]} return web.json_respo...
dvnrsn/toggle-meister
tmeister/environments.py
environments.py
py
1,443
python
en
code
0
github-code
1
6148137744
""" Module to train the decision tree model. """ import logging import typing import pickle import pandas as pd from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier logger = logging.getLogger(__name__) def train_test_split_data(data:pd.DataFrame, target_col:str, test...
jiahaolo/Hotel_Booking_Prediction_Web_App
src/train.py
train.py
py
6,610
python
en
code
0
github-code
1
2797548973
#!/usr/bin/env python3 CLOUD = False try: from polyinterface import Controller,LOGGER except ImportError: from pgc_interface import Controller,LOGGER try: import polyinterface except ImportError: import pgc_interface as polyinterface CLOUD = True import sys import json import time import http.cli...
Einstein42/udi-ecobee-poly
nodes/Controller.py
Controller.py
py
49,710
python
en
code
5
github-code
1
22932495045
#!/usr/bin/env python3 from decimal import Decimal import argparse import json from robinhood.RobinhoodCachedClient import RobinhoodCachedClient, FORCE_LIVE from robinhood.util import ORDER_TYPES, ORDER_SIDES # Set up the client client = RobinhoodCachedClient() client.login() def place_order(order_type, order_side...
mstrum/robinhood-python
order_crypto.py
order_crypto.py
py
2,376
python
en
code
102
github-code
1
2736709243
''' https://www.codewars.com/kata/51c8e37cee245da6b40000bd/python ''' def solution(string:str,markers): s_lst=string.split('\n') content = [] for line in s_lst: find = False for mark in markers: if mark in line: find = True line = line.split(mark)[...
SzybkiRabarbar/CodeWars
2022-03/2022-03-29Strip Comments.py
2022-03-29Strip Comments.py
py
622
python
en
code
0
github-code
1
21049266316
# Miguel Delapaz - CS594 - IRC Server Project import socket import select import sys from enum import Enum try: import queue except ImportError: import Queue as queue class Command(Enum): LOGIN = 1 LOGOUT = 2 ADD_CHANNEL = 3 JOIN_CHANNEL = 4 LEAVE_CHANNEL = 5 LIST_ROOMS = 6 LIST_USE...
mdelapaz/CS594-Project
irc_server.py
irc_server.py
py
10,438
python
en
code
0
github-code
1
8249415108
from twisted.web import server from .base import BaseResource class DataResource(BaseResource): def __init__(self, dataserver): self.dataserver = dataserver BaseResource.__init__(self) def render(self, request): request.setHeader('Content-type', 'text/javascript; charset=UTF-...
wehriam/awspider
awspider/resources/data.py
data.py
py
1,226
python
en
code
19
github-code
1
21012757630
import os import lxml import shutil import requests as re import astropy.units as u from astroquery.vizier import Vizier from astropy.io import fits from astropy.coordinates import SkyCoord from bs4 import BeautifulSoup # Create the download file directory. data_dir = os.path.expanduser('~/astro_data/') ...
Astrohackers-TW/IANCUPyData
iancupy_data/download_file.py
download_file.py
py
3,869
python
en
code
1
github-code
1
15247307437
from AutoSequencerV2.composer import Composer from AutoSequencerV2.runnable import Runnable class SequentialCommandGroup(Runnable, Composer): def __init__(self, cmdList=None): self.cmdList = cmdList if cmdList else [] self._curCmdIdx = 0 def execute(self): if(self._curCm...
RobotCasserole1736/firstRoboPy
AutoSequencerV2/sequentialCommandGroup.py
sequentialCommandGroup.py
py
2,179
python
en
code
1
github-code
1
38149838319
#----------------------------------------------------------------------------- # Name: actors with images example # Purpose: And Example file demoing actors # # Author: Mr. Brooks # Created: 01-Oct-2020 # Updated: 01-Oct-2020 #---------------------------------------------------------------------...
huynhkGW/ICS-Python-Notes
examples/pgzero/games/music example.py
music example.py
py
1,564
python
en
code
0
github-code
1
17517646010
""" # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ from collections import defaultdict class Solution: def getImportance(self, employees: List...
Eben-Success/A2SVOnboarding
A2SV_Education/Graph/690. Employee Importance.py
690. Employee Importance.py
py
714
python
en
code
0
github-code
1
2170063604
import turtle from turtle import * turtle.speed(100) #def draw_circle(x,y,size): # turtle.penup() # turtle.goto(x,y) #def fun(x,y): #turtle.pendown() #t>>> turtle.fillcolor("violet") #turtle.fillcolor() #'violet' #col = turtle.pencolor() #col(50.0, 193.0, 143.0) #turtle.fillcolor(col) #turtle.fillcolor...
bassel16-meet/MEET-YL1
meetconf/meetconf.py
meetconf.py
py
2,287
python
en
code
0
github-code
1
71460302755
import os import json def get_fields_names(fdf_file): with open(fdf_file, "r") as f: content = f.read() field_names = [] start = 0 offset = len("/T (") while not content.find("/T", start) == -1: field_start = content.find("/T", start) field_end = content.find(")", fie...
kai-pinckard/pdf-tools
field_value_mapping.py
field_value_mapping.py
py
6,863
python
en
code
0
github-code
1
9898261445
# Django imports. from django.db import models __author__ = 'Jason Parent' class Task(models.Model): PENDING = 'PENDING' SUCCESS = 'SUCCESS' FAILURE = 'FAILURE' STATUS_CHOICES = ( (PENDING, PENDING), (SUCCESS, SUCCESS), (FAILURE, FAILURE), ) objects = models.Manager...
JasonParentEAB/channeler
channeler/tasks/models.py
models.py
py
557
python
en
code
1
github-code
1
25290301564
import requests import cv2 import cmath import numpy as np import time from globals import * from cam import tracker import tlm def set_resolution(url: str, index: int=1, verbose: bool=False): try: if verbose: resolutions = "10: UXGA(1600x1200)\n9: SXGA(1280x1024)\n8: XGA(1024x768)\n7: SVGA(80...
ksklorz/ITproj
src/cam/video_lib.py
video_lib.py
py
4,811
python
en
code
0
github-code
1
412533190
import os import pytest from pandas.api.types import is_string_dtype # type: ignore from dae.variants.attributes import Role from dae.pedigrees.families_data import FamiliesData from dae.pedigrees.loader import FamiliesLoader @pytest.mark.parametrize( "pedigree", [ ("pedigree_A.ped"), ("ped...
iossifovlab/gpf
dae/dae/pedigrees/tests/test_families_loader.py
test_families_loader.py
py
4,050
python
en
code
1
github-code
1
25562508046
""" File: testnode.py Project 4.10 Add a remove function. Tests the Node class. """ from node import Node def length(head): """Returns the number of items in the linked structure referred to by head.""" probe = head count = 0 while probe != None: count += 1 probe = probe.next ...
hieugomeister/ASU
CST100/Chapter_4/Chapter_4/Ch_4_Solutions/Ch_4_Projects/4.10/testnode.py
testnode.py
py
2,651
python
en
code
0
github-code
1
43903665021
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 16 13:29:10 2019 @author: phoebeharmon """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 9 14:10:19 2019 @author: phoebeharmon """ import speech_recognition as sr print(sr.__version__) #Recognizer instance recongizes spe...
phoebeharmon/chat_server
speechRecPractice.py
speechRecPractice.py
py
1,529
python
en
code
0
github-code
1
39426399340
# Python Program to Calculate the Number of Upper Case Letters and Lower Case Letters in a String name=input("Please input your string: ") lower_n=0 lower="abcdefghijklmnopqrstuvwxyz" upper_n=0 upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i in name: if i in lower: lower_n+=1 if i in upper: upper_n+=1...
YahyaNaq/INTENSIVE-PROGRAMMING-UNIT
Strings/letters.py
letters.py
py
415
python
en
code
1
github-code
1
74473013793
import tkinter as tk from tkinter import ttk from tkinter import filedialog from ttkthemes import ThemedStyle from tkinter import font from win32 import win32api from win32 import win32print import os import sys import matplotlib.font_manager as fm root = tk.Tk() root.withdraw() style = ThemedStyle(root) ...
jeerprank/Tisknu
MTisknu.py
MTisknu.py
py
3,141
python
en
code
0
github-code
1
23789316450
###### Dictionary comprehension ######### """name_age = { "ijhar": 30, "hasan": 40, "majhar": 30 }""" ################################## """num_dict ={} for num in range(1, 30): num_dict[num] = num **3 print(num_dict)""" ############## short ############### """num_dict_comp = { number: numbe...
asharislam/python__dictionary_comprehension
dictionary_comprehension.py
dictionary_comprehension.py
py
779
python
en
code
0
github-code
1
22525799323
from sklearn.metrics import f1_score, matthews_corrcoef import numpy as np from rouge import Rouge from src.utils import qa_utils from datasets import load_metric import re class App: def __init__(self): self.functions = {} def add(self, key): def adder(func): self.functions[key] =...
microsoft/LMOps
uprise/src/utils/metric.py
metric.py
py
5,807
python
en
code
2,623
github-code
1
23065566578
import os import datetime import ConfigParser from tempfile import NamedTemporaryFile from InvoiceGenerator.api import Invoice, Item, Client, Provider, Creator, Address from InvoiceGenerator.pdf import SimpleInvoice # choose english as language os.environ["INVOICE_LANG"] = "en" config = ConfigParser.ConfigParser() co...
WillTuff/InvoiceGenerator
generateinvoices.py
generateinvoices.py
py
1,480
python
en
code
0
github-code
1
27995731321
import pandas as pd import numpy as np import nltk nltk.download('punkt') from nltk.tokenize import word_tokenize df=pd.read_csv("cauhoi.csv",delimiter=";") tt=df.Question Answer={} t,c=np.unique(df.Answer,return_counts=True) for i in range(0,len(t)): Answer[i]=t[i] d=['(',')',',','.','!',' ','-','?','!','...
phamtri1812/website_quan_ly_mam_non
chatbot/model.py
model.py
py
3,045
python
vi
code
0
github-code
1
27848566804
import streamlit as st import pandas as pd from PIL import Image import shap import matplotlib.pyplot as plt from sklearn import datasets import pickle def main(): st.write(""" # Boston House Price Prediction App This app predicts the **Boston House Price**! """) image = Image.open('boston.jpg...
BingQuanChua/DataScienceApps
08_boston_housing_regression/myapp.py
myapp.py
py
5,010
python
en
code
2
github-code
1
42199060348
#! /usr/bin/env python """ Finite State Methods and Statistical NLP """ import nltk import pickle import random from os import path from nltk.corpus import masc_tagged from nltk.tag import hmm from ass3utils import train_unsupervised nltk.download('masc_tagged') short_sent = [ "Once we have finished , we will go...
dmuiruri/nlp
fsm_snlp/fsm_snlp.py
fsm_snlp.py
py
7,250
python
en
code
0
github-code
1
7161385428
import unittest from itertools import chain import torch from pytorch_metric_learning.distances import CosineSimilarity from pytorch_metric_learning.losses import CentroidTripletLoss from pytorch_metric_learning.reducers import MeanReducer from .. import TEST_DEVICE, TEST_DTYPES from ..zzz_testing_utils.testing_util...
jwlee3746/metric_learning_pytorch
pytorch-metric-learning/tests/losses/test_centroid_triplet_loss.py
test_centroid_triplet_loss.py
py
9,166
python
en
code
1
github-code
1
8617676101
import torch from transformers import BertTokenizer, BertModel import pandas as pd import logging dataset = pd.read_csv('tokenized_data_without_punctuation_stopwords_lemma.csv') dataset = dataset[:1000] dataset = dataset['text'].astype(str).tolist() # Set log level to ERROR to suppress warning messages logging.getLog...
nazlicaneroglu/NLP-Project
bertembedding.py
bertembedding.py
py
1,073
python
en
code
0
github-code
1
74537810272
import os import shlex import shutil import sys from pathlib import Path from subprocess import check_call from typing import Callable, Dict, List, Union from pytest import fixture, skip FILES_PATH = Path(__file__).parent / "files" def call(cmd: Union[str, List[str]], cwd: Union[str, Path, None] = None) -> int: ...
jupyterlab/jupyterlab-git
jupyterlab_git/tests/conftest.py
conftest.py
py
2,898
python
en
code
1,327
github-code
1
32185261146
from copy import copy from ldap3 import SUBTREE from plugins.AD import PluginADScanBase from utils.consts import AllPluginTypes class PluginADDuplicateAccount(PluginADScanBase): """存在重复的账户""" # 出现原因是不同用户登录不同域控同时添加同一账户,域控之间同步导致的,添加后有的账户只有"CNF"字段,有的账户有"CNF"的同时 # 在SAMAccountName里也有"$DUPLICATE-"字段 disp...
Amulab/CAudit
plugins/AD/Plugin_AD_Scan_1031.py
Plugin_AD_Scan_1031.py
py
2,067
python
en
code
250
github-code
1
74702200993
import pandas as pd def merge_groups_dummies(data_set_path): dummies_path = data_set_path.replace('.csv', '_dummies_groupscore.csv') dummies_df =pd.read_csv(dummies_path,index_col=[0,1]) dummies_df.drop(['is_churn'],axis=1,inplace=True) groups_path = data_set_path.replace('.csv', '_nocat_groupscore....
carl24k/fight-churn
fightchurn/listings/chap10/listing_10_5_merge_groups_dummies.py
listing_10_5_merge_groups_dummies.py
py
989
python
en
code
227
github-code
1
19460218663
from typing import Any, Dict, List from unittest.mock import call import pandas import pytest from callee.strings import Glob, String from tests.service_test_fixtures import ServiceTestFixture from tests.utils import DataFrameColumnMatcher, shuffled_cases from the_census._variables.models import Group, GroupCode, Gro...
drawjk705/the_census
tests/unit/the_census/variables/repository/variables_repo_test.py
variables_repo_test.py
py
5,924
python
en
code
0
github-code
1
34337715752
from django.conf.urls import url from schedulizer import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^addclasses/$', views.addClasses, name='addClasses'), url(r'^finalschedule/$', views.finalSchedule, name='finalSchedule'), url(r'^getdars/$', views.getDars, name='getDars'), u...
leeonlee/fsched
schedulizer/urls.py
urls.py
py
378
python
en
code
0
github-code
1
10924450539
# -*- coding:utf-8 -*- import logging.config import re from bs4 import BeautifulSoup from utils import spider_utils logging.config.fileConfig('log.ini') file_logger = logging.getLogger(name="fileLogger") def get_dianping_url(url): """ 获取大众点评数据 url :return: """ # url = "http://www.dianping.com/se...
logonmy/spider-mz
spider_producer/dianping_spider.py
dianping_spider.py
py
12,103
python
en
code
0
github-code
1
41244503180
import pandas as pd # 엑셀 데이터를 DataFrame으로 읽어옵니다. df = pd.read_excel("c:/b.xlsx") # 모듈과 슬롯을 저장할 변수 초기화 module_slot_ids = {} # 데이터를 순회하며 모듈과 슬롯 정보 추출 for index, row in df.iterrows(): module = row['id'] item = row['Module'] slot = row['slot'] # 모듈과 슬롯을 조합하여 식별자 생성 identifier = f"{module} {slot}" ...
itvtt/pub
정리/mars/mars.py
mars.py
py
1,147
python
ko
code
0
github-code
1
21457847632
import unittest import case class TitleCase(unittest.TestCase): def test_single_word(self): text = "python" result = case.title_case(text) self.assertEqual(result, "Python") def test_multiple_words(self): text = "python programming" result = case.title_case(text) ...
Know-Thyself/python-exercises
unit_testing/simple_test.py
simple_test.py
py
419
python
en
code
0
github-code
1
2593816440
from typing import List, Optional, Tuple from collections import defaultdict import pickle import json import argparse import os from typing import Union, Dict import math from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity SAVE_DIR = 'retriever_caches' ...
NoviScl/GPT3QA
tfidf_retriever.py
tfidf_retriever.py
py
4,470
python
en
code
4
github-code
1
40043593113
# -*- coding: utf-8 -*- """ Created on Mon Aug 15 15:28:18 2016 @author: hp """ def get_result(alpha): target_df=pd.DataFrame(np.zeros((len(return_df.index),len(return_df.columns))),index=return_df.index,columns=return_df.columns) target_df[target_df==0]=np.nan col=list(return_df.columns) for ...
luilui163/zht
py27/zht/quantitative/internship/cq/tool/get_result.py
get_result.py
py
2,031
python
en
code
0
github-code
1
12853374215
# Clear method Emipro = {'Employee':'Ajay','Age':'21','City':'Thangadh','Employee':'Ajay'} print(Emipro) Emipro.clear() print(Emipro) # fromkey method S = ['Student1','Student2','Student3','Student4'] Datas = dict.fromkeys(S) print(Datas) # get method Student = {'Student1':'Ajay','Student2':'Jigar','Student3':'Sanj...
ajayr-ept/python_exercise1
Ajay Rathod_Python Basic Exercise/firstDemo/Dictionaries/All types.py
All types.py
py
1,270
python
en
code
0
github-code
1
18320858574
import numpy as np from sklearn.linear_model import LogisticRegression class Camargo(): def __init__(self): self.clssfier = LogisticRegression(class_weight='balanced') def transform(self, source,target): col_name = source.columns for col in col_name: s_median = np.log(sou...
cadet6465/eCPDP
baselines/Camargo.py
Camargo.py
py
803
python
en
code
0
github-code
1
40427854063
import numpy as np import pandas as pd #import time import GA_aux_func as hp_opt def main(): # Loading the data, shuffling and preprocessing it # Feature Selection data = pd.read_csv("../Dataset/breast-cancer-wisconsin.csv") data = data.sample(frac=1) n_samples = data.shape[0] n_fe...
OttoMP/ga-feature-selection
Genetic_Algorithm.py
Genetic_Algorithm.py
py
6,028
python
en
code
0
github-code
1
32260441088
from curses.ascii import NUL from templates import * set_selected = None # DISPLAY MAIN MENU AND HANDLE SELECTION INPUT def choose_set(): hide_open_frames() main_frame.pack(fill='both', expand=True) title = tk.Label(main_frame, text="Choose a set to study", bg=BG_COLOR, fg=FONT_COLOR, ...
AlessiaRuggiero/geography-flashcards
main.py
main.py
py
6,606
python
en
code
0
github-code
1
41798632502
#!/usr/bin/python3 from argparse import ArgumentParser import logging import mympd import myhttp import socket import sys import threading import time from tkinter import * import datetime import random import parser from math import cos from math import sin from math import tan import os import vlc import platform ...
LumiH/Adaptive-Informative-Real-Time-Streaming
stream.py
stream.py
py
17,754
python
en
code
2
github-code
1
3196161243
# Given a non-empty string s and a dictionary wordDict containing a list of non- # empty words, add spaces in s to construct a sentence where each word is a valid # dictionary word. Return all such possible sentences. # # Note: # # # The same word in the dictionary may be reused multiple times in the segmentat...
niufenjujuexianhua/Leetcode
[140]Word Break II.py
[140]Word Break II.py
py
2,428
python
en
code
0
github-code
1
29248023161
import os,shutil from jds_utils.yes_or_no import yes_or_no def mkdir_ask(path,make_path=False): if os.path.exists(path): consent = yes_or_no("%s already exists. Delete it?"%path) if consent: shutil.rmtree(path) else: raise IOError if make_path: os.makedirs(path) ...
joschu/python
jds_utils/dir_tools.py
dir_tools.py
py
535
python
en
code
8
github-code
1
3097247249
import argparse def read_user_cli_args(): """Handle the CLI arguments and options.""" parser = argparse.ArgumentParser( prog="sitechecker", description="Teste a disponibilidade de uma URL" ) parser.add_argument( "-u", "--urls", metavar="URLs", nargs="+...
hugosousa111/sitechecker
sitechecker/cli.py
cli.py
py
1,065
python
pt
code
0
github-code
1
13461378784
import sys import os import re import json import xmltodict import time import subprocess import calendar from ..job_tracker import move_to_next_step, get_job_json from ..util import get_md5 import shutil name = 'downloading' next_step = 'uploading' bucket_url = 's3://oicr.icgc/data/' def get_name(): global nam...
ICGC-TCGA-PanCancer/s3-data-qc
s3objectqc/ceph_qc/downloading.py
downloading.py
py
8,261
python
en
code
0
github-code
1
25953580166
############### Blackjack Project ##################### ############### Blackjack House Rules ##################### ## The deck is unlimited in size. ## There are no jokers. ## The Jack/Queen/King all count as 10. ## The the Ace can count as 11 or 1. ## Use the following list as the deck of cards: ## The cards in ...
navil-noor/Python
Days-of-Python/11-blackjack/main.py
main.py
py
3,428
python
en
code
0
github-code
1
26185358631
def start(): print("Enter a Brand") item = str(input()) if item in 'Adidas': adidas() elif item == 'Nike': nike() else: error() def adidas(): print("Enter shoe") item = str(input()) if item == 'Original': noProfit() elif item == 'Yeezy'...
mmellone99/sneaker-resale
SneakerResale.py
SneakerResale.py
py
3,173
python
en
code
0
github-code
1
42613974193
import matplotlib.pyplot as plt # Create the figure and axes fig, ax = plt.subplots() # Sample data x = [1, 2, 3, 4, 5] y = [10, 15, 7, 12, 8] # Plot the data ax.plot(x, y) # Set x-tick positions and labels xtick_positions = range(min(x), max(x)+1) xtick_labels = [str(xtick) for xtick in xtick_positions] ax.set_xti...
wendycahya/Yaskawa-Communication
IntegratedSystem/Basic Function Test/xticks-function.py
xticks-function.py
py
472
python
en
code
3
github-code
1
10994818252
class TSP: def __init__(self,matrix,S): self.m=matrix self.S=S self.N=len(matrix) def tsp(self): N=self.N m=self.m S=self.S memo=[[float('inf') for i in range(2**N)]for j in range(N)] self.setup(m,memo,S,N) self.solve(m,memo,S,N) mi...
Shubham2912/Graph
Basic TSP with path.py
Basic TSP with path.py
py
3,629
python
en
code
0
github-code
1
11002315457
class Solution: def findMin(self, nums: List[int]) -> int: min_val = float('inf') left = 0 right = len(nums) - 1 while left <= right: mid = (left + right) // 2 min_val = min(min_val, nums[mid]) if nums[mid] > nums[right]: left = m...
peaqi/mock
Python/153. Find Minimum in Rotated Sorted Array/better.py
better.py
py
424
python
en
code
0
github-code
1
21035746373
# 请实现两个函数,分别用来序列化和反序列化二叉树 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: flag = -1 def Serialize(self, root): """ 对于序列化:使用前序遍历,递归的将二叉树的值转化为字符,并且在每次二叉树的结点 不为空时,在转化val所得的字符之后添加一个' , '作为分割。对于空节点则以 '#' 代...
EarthChen/LeetCode_Record
newcoder_offer/serialize_deserialize.py
serialize_deserialize.py
py
1,218
python
zh
code
0
github-code
1
12083730428
import pygame, random pygame.init() SIZE = WIDTH, HEIGHT = 1200, 700 SCREEN = pygame.display.set_mode(SIZE) WHITE = 255,255,255 BLACK = 0,0,0 class Ball: def __init__(self): self.x = 100 self.y = 100 self.radius = 50 self.move_x = random.random() self.move_y...
brainmentorspvtltd/RKGIT_IOT
OOPS/BallGame.py
BallGame.py
py
1,556
python
en
code
5
github-code
1
36682257881
# -*- coding: utf-8 -*- """ Created on Sun May 30 11:19:57 2021 @author: Gaurav """ import cv2 import mediapipe as mp import time from google.protobuf.json_format import MessageToDict cap = cv2.VideoCapture(0) mphands = mp.solutions.hands hands = mphands.Hands() mpDraw = mp.solutions.drawing_utils ptime = 0 ctime...
kanojia-gaurav/Advance_opencv
Hand_using_mediaPipe/Hand_detection.py
Hand_detection.py
py
1,251
python
en
code
0
github-code
1
30550400117
def isTrue(obj, attr) : return hasattr(obj, attr) and getattr(obj, attr) import numpy as np import torch def get_sorting_index_with_noise_from_lengths(lengths, noise_frac) : if noise_frac > 0 : noisy_lengths = [x + np.random.randint(np.floor(-x*noise_frac), np.ceil(x*noise_frac)) for x in lengths] ...
lijiehu95/SEAT
attention/model/modelUtils.py
modelUtils.py
py
6,648
python
en
code
0
github-code
1
7954284443
from commom.BrowserStartUp import * import requests import json class RunMain(): # 设置GET请求的带参数的cookie信息 def sent_get_by_cookies(self, url, cookies, paramdata=None): headers = {"Content-Type": "application/json"} response = requests.get(BaseUrl()+url,cookies=getCookies(cookies),data=json.dumps(pa...
King-BAT/RanZhi
RanZhiPython/commom/SendHttp.py
SendHttp.py
py
1,279
python
en
code
0
github-code
1
22093481270
import random def run(): numero_aleatorio=random.randint(1,100) numero_elejido=int(input('Elije un numero del 1 al 100 : ')) while numero_aleatorio != numero_elejido : print(numero_aleatorio) if numero_elejido < numero_aleatorio: print('Busca un numero mayor') else: ...
jjestrada2/jjestrada2.github.io
Juego.py
Juego.py
py
497
python
es
code
1
github-code
1
4404407019
import snap import numpy as np import numpy.linalg as la import matplotlib.pyplot as plt # The function to calculate the distance between two Network of the virtual tree def distance(NId1, NId2, b, H): # NId1 and NId2 are the IDs of two nodes # b is the number of each parent's children # H is the height of...
myishh/adb
hw1/search.py
search.py
py
2,931
python
en
code
0
github-code
1