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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
2808266661 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__version__ = "0.1.0"
__author__ = "Abien Fred Agarap"
import argparse
from normalize_data import list_files
import numpy as np
import os
import pandas as pd
def csv_to_npy(csv_path, npy_path, npy_filename):... | AFAgarap/gru-svm | dataset/csv_to_npy.py | csv_to_npy.py | py | 1,586 | python | en | code | 136 | github-code | 36 |
18631976524 | import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import precision_score, recall_score
from scipy.stats import norm
import plotly.graph_objects as go
from libs.Models.ModelParent import ModelParent
import itertools
class STD(ModelParent):
def __init__(self, trainX: np.arra... | xorbey/CATS_public | libs/Models/Anomaly/STD.py | STD.py | py | 5,909 | python | en | code | 0 | github-code | 36 |
28067552432 | # 배열 합치기
# https://www.acmicpc.net/problem/11728
def solution() :
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
index_a = 0
index_b = 0
answer = []
while index_a < n and index_b < m :
if a[index_a] <= b[index_b] :
... | hwanginbeom/algorithm_study | 1.algorithm_question/19.Two_Pointer/164.TwoPointer_wooseok.py | 164.TwoPointer_wooseok.py | py | 633 | python | en | code | 3 | github-code | 36 |
34957895973 | from os import path
import shutil, glob
from subprocess import Popen, PIPE, STDOUT
from lib import cd, CouldNotLocate, task
class IEError(Exception):
pass
@task
def package_ie(build, root_dir, **kw):
'Run NSIS'
nsis_check = Popen('makensis -VERSION', shell=True, stdout=PIPE, stderr=STDOUT)
stdout, stderr = nsi... | workingBen/forge-demo | .template/generate_dynamic/ie_tasks.py | ie_tasks.py | py | 1,203 | python | en | code | 2 | github-code | 36 |
20491810241 | import re
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
path = context['request'].path
if re.search(pattern, path):
return 'active'
return ''
| sirodoht/avocado-jobs | main/templatetags/app_filters.py | app_filters.py | py | 248 | python | en | code | 1 | github-code | 36 |
6249836683 | from trytond.model import fields
from trytond.pool import PoolMeta
from trytond.i18n import gettext
from trytond.exceptions import UserError
__all__ = ['BOMInput']
class BOMInput(metaclass=PoolMeta):
__name__ = 'production.bom.input'
use_lot = fields.Boolean('Use Lot')
@classmethod
def validate(cls,... | NaN-tic/trytond-production_output_lot | bom.py | bom.py | py | 736 | python | en | code | 0 | github-code | 36 |
16137647125 | # coding: utf-8
import time
import pywss
import threading
from copy import deepcopy
def NewCacheHandler(expire=60, maxCache=30):
cache = dict()
lock = threading.Lock()
def cacheHandler(ctx: pywss.Context):
cache_key = f"{ctx.method}{ctx.url}{ctx.version}{ctx.content_length}"
if cache_key... | czasg/pywss | pywss/handler/cache.py | cache.py | py | 1,336 | python | en | code | 76 | github-code | 36 |
35026404794 | from google.api_core import retry
from loguru import logger
from pkg.utils.mongo_utils import get_db
from pkg.project.validate import validate
from bson.objectid import ObjectId
@logger.catch
def delete_project(request):
db = get_db()
request_data = request.json
logger.debug(request_data["_id"]... | rayjan0114/infra | gcp/main/gcpFunction/functions/pkg/project/delete_project.py | delete_project.py | py | 757 | python | en | code | 1 | github-code | 36 |
10154914902 | """
Author: Anastasia Yazvinskaya, (Faud Torres), Lindsay Gardels, Christian Maciel
Class: CS 241 - 03 (Fall 2021)
Assignment: Team W04
"""
""" CORE REQUIREMENTS """
"""
1. Create a Date class in a file date.py with the above variables and methods.
"""
from date import Date, DateStretch
"""
2. Create an Assignment cla... | AnastasiaYazvinskaya/CS-241-Survey-Obj-Ort-Prog--Data-Struct | team/teamW04/teamW04.py | teamW04.py | py | 1,336 | python | en | code | 0 | github-code | 36 |
12035843668 | # a = \
# 2
# print(a)
# initializing list
test_list = [5, 6, 2, 3, 9]
# printing original list
print ("The original list is : " + str(test_list))
# index to begin slicing
K = 2
# using None
# to perform list slicing from K to end
res = test_list[1 : None]
# printing result
print ("The sliced list is : " + str... | Natedude/PacMan-AI-Course | Asmt_3/reinforcement/notes.py | notes.py | py | 326 | python | en | code | 0 | github-code | 36 |
27235166738 | # -*- coding: utf-8 -*-
__author__ = "Michele Samorani"
import pandas as pd
import cplex
import time
import random
TIME_LIMIT_SECONDS = 60
def build_scenarios(show_probs, max_scenarios,seed):
"""
Builds the scenarios
:param show_probs:
:type show_probs: list[float]
:return: a list of (probability,... | samorani/Social-Justice-Appointment-Scheduling | src/stochastic.py | stochastic.py | py | 6,965 | python | en | code | 0 | github-code | 36 |
44292327781 | from collections import namedtuple
import hashlib
from itertools import product
from typing import TYPE_CHECKING, Optional
import uuid
import pytest
from pynenc import Pynenc
from pynenc.broker.base_broker import BaseBroker
from pynenc.orchestrator.base_orchestrator import BaseOrchestrator
from pynenc.runner.base_run... | pynenc/pynenc | tests/integration/apps/mem_combinations/conftest.py | conftest.py | py | 4,473 | python | en | code | 1 | github-code | 36 |
41748486239 | from flask import Flask, request, jsonify
import producer as p
import time
import metricas as m
app = Flask(__name__)
@app.route('/', methods=['POST'])
def index():
if request.method == 'POST':
data = request.form
tiempo_inicio = time.time() # Registrar el tiempo de inicio
m.tiem... | cesarlmt27/CIT2011 | tarea2/inscripcion/api.py | api.py | py | 1,077 | python | es | code | 0 | github-code | 36 |
42504873893 | import random as rnd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
p_show = lambda x: rnd.uniform(0.907, 0.968)
def show_up(p):
if rnd.random() <= p:
return True
return False
def flight(num_tix, tix_price, comp_cost, capacity):
p = p_show(0)
shows = sum([1 fo... | behtashgolshani/Monte-Carlo-simulation-airline-overbooking | simulation.py | simulation.py | py | 1,991 | python | en | code | 0 | github-code | 36 |
16326329103 | from ranger.colorschemes.solarized import Solarized
from ranger.gui.color import (
cyan, magenta, red, white, default,
normal, bold, reverse,
default_colors,
)
class Scheme(Solarized):
def use(self, context):
fg, bg, attr = Solarized.use(self, context)
if context.in_titlebar:
... | kopfing/i3dotfiles | .config/ranger/colorschemes/mysolarized.py | mysolarized.py | py | 572 | python | en | code | 0 | github-code | 36 |
23363352897 | import torch
import torch.nn as nn
import math
class GlobalReinitNet(nn.Module):
def __init__(self):
super(GlobalReinitNet, self).__init__()
# Spatial transformer localization-network
self.localization = nn.Sequential(
nn.Conv2d(3, 8, kernel_size=5, stride=2, padding=0),
... | shaoxiaohu/Face_Alignment_DPR | networks/ReinitNet.py | ReinitNet.py | py | 3,833 | python | en | code | 11 | github-code | 36 |
20270458219 | import numpy as np
class wave_packet(object):
"""
Class which implements a numerical solution of the time-dependent
Schrodinger equation for an arbitrary potential. Serves as a blue print for
different inputs.
"""
def __init__(self, t_f, dt, dx, x_min, x_max, k_0, sigma_0, x_0, L, V... | nmonrio/wave_packet_sim | src/schrodinger.py | schrodinger.py | py | 8,366 | python | en | code | 1 | github-code | 36 |
32001007621 | class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
s_track = {}
t_track = {}
s_counter, t_counter = 0, 0
for i in range(len(s)):
if s[i] not in s_track:
s_track[s[i]] = s_counter
s_counter += 1
... | plan-bug/LeetCode-Challenge | landwhale2/easy/205. Isomorphic Strings.py | 205. Isomorphic Strings.py | py | 536 | python | en | code | 2 | github-code | 36 |
5820956370 | class LinearSort(object):
@staticmethod
def counting_sort(a):
res = [0] * len(a)
storage = [0] * (max(a)+1)
for val in a:
storage[val] += 1
for i in range(1, len(storage)):
storage[i] += storage[i-1]
for val in a:
... | pro1710/Sandbox | Algorithms_Cormen/linear_sort.py | linear_sort.py | py | 1,747 | python | en | code | 0 | github-code | 36 |
9576788233 | # bank.py
# Prompts users for money values in cents, adds those values, then outputs in human readable format with euro sign a decmial.
# Author: Tom Brophy
amount1 = int(input('Enter amount1 (in cent): '))
amount2 = int(input('Enter amount2 (in cent): '))
total = amount1+amount2
#print(total)
totalString = str(total... | tomdbrophy/pands-problem-sheet | bank.py | bank.py | py | 513 | python | en | code | 0 | github-code | 36 |
13870407522 | # 1부터 n까지의 정수의 합 구하기1(while문)
n = int(input('정수를 입력해주세요.: '))
i = 1 # 카운터용 변수
nsum = 0
while i <= n:
nsum += i
i += 1
print(f'1부터 {n}까지의 합은 {nsum}입니다.')
print(f'i의 값은{i}입니다.')
''' while 문 반복 알아보기
어떤 조건이 성립하는 동안 처리하는것을 반복구조(repetition structure)라고 하고 일반적으로 루프(loop)라고 합니다.
이때 while문은 실행하기 전에 반복을 계속 할 것인지 판단하는데 ... | hye0ngyun/PythonPractice | books/AlgorithmWithPython/chap01/01_2/chap01_2Ex1.py | chap01_2Ex1.py | py | 634 | python | ko | code | 0 | github-code | 36 |
6158000083 | import cipher
import random
def main():
loop = True
while loop == True:
inputtext = input("Please enter a string: (q to Quit) ")
if inputtext == "q":
print("Goodbye!")
loop = False
break
encrypted = cipher.encrypt(inputtext)
decryptinput = input("Would you like to decrypt your message?: (y/n)")
i... | dharper998/CS110-Course-Work | lab8/lab8.py | lab8.py | py | 482 | python | en | code | 0 | github-code | 36 |
19988594566 | import bpy
bl_info = {
"name": "Apply Modifier",
"author": "mate.sus304",
"version": (1, 2),
"blender": (2, 80, 0),
"location": "View3D > Object > Apply",
"description": "Apply All Modifier to Mesh Object",
"warning": "",
"wiki_url": "",
"tracker_url": "",
"website":"https://sit... | Taremin/ApplyModifier | __init__.py | __init__.py | py | 7,817 | python | en | code | 29 | github-code | 36 |
10062739523 | from django.http import HttpResponse, JsonResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser, FormParser,MultiPartParser
from rest_framework.renderers import JSONRenderer, Browsabl... | hongdy-python/03drf | prapp/views.py | views.py | py | 3,368 | python | en | code | 0 | github-code | 36 |
12435303383 | """
202. Happy Number
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops end... | ashishkssingh/Leetcode-Python | Algorithms/Easy/happy_number.py | happy_number.py | py | 1,200 | python | en | code | 0 | github-code | 36 |
71488499305 | import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
from matplotlib.widgets import Slider, Button
def dft(x):
N = x.__len__()
print(f'there will be {N} circles')
X = np.array([])
for k in range(N):
re, im = 0, 0
for n in range(N):
phi = (np.p... | chickysnail/fourier-transform-drawing | Fourier series.py | Fourier series.py | py | 4,080 | python | en | code | 0 | github-code | 36 |
23395076072 | import argparse
import datetime
import hashlib
import logging
import shutil
import os
import tempfile
import time
import requests
from stoq import Stoq, RequestMeta
from malwaretl_stoq_transformer import transformer
from malware_collector import MalwareCollector
logger = logging.getLogger(__name__)
logger.setLevel... | g-clef/malware_collector | URLHausSource.py | URLHausSource.py | py | 5,247 | python | en | code | 1 | github-code | 36 |
24458145308 | import time
import os
import requests
from sense_hat import SenseHat
updateInterval = 300 # update once every 5 minutes
writeAPIkey = 'OY8DUS7XDPAU2KTT' # write API key for the channel
readAPIkey = 'TXI2BWJFGPTIVELP' # read API key for the channel
channelID = '2003669' # channel ID
def sensorData():
"""Funct... | jycal/iot-temps-rpi | temps_monitor.py | temps_monitor.py | py | 2,180 | python | en | code | 0 | github-code | 36 |
844685088 | import unittest
import os
from api.interfaces.admin import version1
espa = version1.API()
class TestAdminConfiguration(unittest.TestCase):
def setUp(self):
os.environ['espa_api_testing'] = 'True'
base = os.path.dirname(os.path.abspath(__file__))
self.bfile = os.path.join(base, 'test-back... | Jwely/espa-api | test/test_admin_api.py | test_admin_api.py | py | 2,321 | python | en | code | 1 | github-code | 36 |
71685394345 | __author__ = 'apple'
from turtle import *
def szary(n):
pendown()
fillcolor("grey")
begin_fill()
k=2*n+1
s=760/k
bk(760/2)
fd(760)
lt(90)
fd(4*s)
lt(90)
fd(s)
lt(90)
fd(s)
rt(90)
fd(s)
rt(90)
fd(s)
lt(90)
fd(s)
lt(90)
fd(s)
rt(90... | chinski99/minilogia | 2012/etap 2/zamek.py | zamek.py | py | 1,260 | python | en | code | 0 | github-code | 36 |
26428963144 | import sys
from flask import Flask, render_template, request, jsonify
from clusterization import clusterize
app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
@app.route("/test-action", methods=["POST", "GET"])
def test_btn_handle():
data = request.get_j... | alt2019/SRW-visualization | flask-proj/app-python-mcs.py | app-python-mcs.py | py | 1,187 | python | en | code | 0 | github-code | 36 |
29984268730 | import cv2
import torch
from .flowers_dataset import FlowersDataset
import warnings
warnings.filterwarnings("ignore")
def prepare_data_for_model(path_to_image, transform=None, use_descriptors_as_features=False, features_type='hog'):
image = cv2.imread(path_to_image)
image = cv2.cvtColor(image, cv2.COLOR_BGR2... | kryvokhyzha/azure-ml-courses | flowers-azure-ml/src/datasets/__init__.py | __init__.py | py | 943 | python | en | code | 0 | github-code | 36 |
28918133028 | #!/usr/bin/env python
import piexif # need to install by pip install piexif
import exifread # need to install by pip install exifread
from fractions import Fraction
import datetime
import time
# Class used to change image EXIF Data
def set_gps_location(file_name, lat, lng, altitude):
"""Adds GPS position as E... | ronakbhag/ids_coordinates_setter | scripts/image_editor.py | image_editor.py | py | 3,027 | python | en | code | 0 | github-code | 36 |
22153487897 | x = int(input())
for i in range(x):
a,b,c = map(int,input().split())
f = c - b
g = (f % a)
ans = c - g
print(ans)
'''
Alternate logic...
z = c % a;
if(z >= b):
print(c - (z - b))
else:
print(c - (z + a - b))
'''
| saurav912/Codeforces-Problemset-Solutions | CDFRequiredRemainder.py | CDFRequiredRemainder.py | py | 285 | python | en | code | 0 | github-code | 36 |
165914696 | import gym
import numpy as np
import random
from time import sleep
import matplotlib.pyplot as plt
from scipy.special import entr
from utils import clear,calculate_entropy,save_training_progress,early_stop
import config
import time
import cv2
class Agent():
def __init__(self):
clear()
"""Setup"""
... | Abdulhady-Feteiha/Information-Digital-Twin | Genesis-Taxi/Agent.py | Agent.py | py | 8,004 | python | en | code | 2 | github-code | 36 |
41628533597 | def ordinal(n: int) -> str:
"""
Convert integer to ordinal.
1 -> 1st
2 -> 2nd
3 -> 3rd
4 -> 4th
-----------
Parameters:
n: int
Returns:
string: ortinal
"""
if 11 <= (n % 100) <= 13:
suffix = "th"
else:
suffix = ["th", "st", "nd", "rd", "th... | tsume-ha/elech_tools | src/elech_tools/utils/ordinal.py | ordinal.py | py | 366 | python | en | code | 0 | github-code | 36 |
28440391809 | import glob
import os
import pickle
import time
from abc import ABC
from pathlib import Path
from typing import Tuple
import numpy as np
from smart_settings.param_classes import recursive_objectify
from mbrl import allogger
from mbrl.base_types import Controller, ForwardModel, Pretrainer
from mbrl.controllers import ... | martius-lab/cee-us | mbrl/initialization.py | initialization.py | py | 18,460 | python | en | code | 11 | github-code | 36 |
6658450371 | from django.contrib import admin
from .models import User, Supplier
class UserAdmin(admin.ModelAdmin):
readonly_fields = ("last_login", "password", "phone_no", "email")
list_display = (
"email",
"first_name",
"last_name",
"is_active",
"created_at",
)
list_filter ... | Corestreamng/adzmart-supplier | adzmart-develop/apps/authentication/admin.py | admin.py | py | 866 | python | en | code | 0 | github-code | 36 |
6791618821 | from rest_framework import serializers
from ...models import ServiceRequest
class ServiceRequestSerializer(serializers.ModelSerializer):
name = serializers.CharField(required=True)
email = serializers.EmailField(required=True)
class Meta:
model = ServiceRequest
fields = [
'na... | tomasgarzon/exo-services | service-exo-core/marketplace/api/serializers/service_request.py | service_request.py | py | 646 | python | en | code | 0 | github-code | 36 |
33621622326 | from models import QP
from tqdm import tqdm
import matplotlib.pyplot as plt
import torch
from torch import optim
from torch.autograd import Variable
import torch.nn.functional as F
from copy import copy
from random import shuffle, sample
import numpy as np
from IPython.core.debugger import set_trace
import config
impo... | jprothero/MetaQP | MetaQP.py | MetaQP.py | py | 20,649 | python | en | code | 0 | github-code | 36 |
21545450902 | #!/usr/bin/env python
import rospy
from std_msgs.msg import Float64, Float64MultiArray
import math
if __name__ == '__main__':
rospy.init_node('klackalica_mm_sine_ref_pub')
pub_mm_ref = rospy.Publisher('movable_mass_all/command', Float64MultiArray, queue_size=1)
cmd_msg = Float64()
T = 0.5
w = 2.0... | larics/mmuav_gazebo | mmuav_arducopter_bridge/src/mm_sine_ref_pub.py | mm_sine_ref_pub.py | py | 658 | python | en | code | 7 | github-code | 36 |
40145189651 | from pyface.qt.QtGui import QLineEdit, QGroupBox, QHBoxLayout, QVBoxLayout
from pyface.qt.QtGui import QWidget
class AtomPropertiesWidget(QWidget):
"""
This widget modifies properties of a specific atom
"""
def __init__(self, parent=None):
super(AtomPropertiesWidget, self).__init__(parent)
... | aloschilov/simple-game-engine | engine_configurator/atom_properties_widget.py | atom_properties_widget.py | py | 1,589 | python | en | code | 0 | github-code | 36 |
74557771942 | from logger import err
def parse(hexdump, from_loc: str, to_loc: str):
"""
Parse a hex dump from a location to another location
:param hexdump: dump contents
:param from_loc: starting location
:param to_loc: end location
:return: lines of hex between
"""
dump_as_arr = str(hexdump).spli... | bfu4/mdis | parser/hex_dump_parser.py | hex_dump_parser.py | py | 2,504 | python | en | code | 12 | github-code | 36 |
39928884000 | __all__ = ["fit_transform_to_paired_points"]
import os
import numpy as np
from tempfile import mktemp
from .apply_transforms import apply_transforms
from ..core import ants_image_io as iio
from ..core import ants_transform_io as txio
def fit_transform_to_paired_points(
moving_points, fixed_points, transform_typ... | acamargofb/ANTsPy | ants/registration/landmark_transforms.py | landmark_transforms.py | py | 2,581 | python | en | code | null | github-code | 36 |
11695999761 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/3/31 22:32
# @Author : TanLHHH
# @Site :
# @File : 前程无忧_测试.py
# @Software: PyCharm
import requests
from lxml import etree
import csv
import time
import random
import re
fp = open('51job.csv', 'wt', newline='', encoding='utf-8', errors='ignore')
... | TanLHHHH/Spiders | 测试文件夹/前程无忧_测试.py | 前程无忧_测试.py | py | 3,832 | python | en | code | 3 | github-code | 36 |
24846541046 | #!/usr/bin/env python3
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Circle
from skimage.io import imread_collection, imshow
from skimage.feature import canny
from skimage.color import rgb2gray
from skimage.transform import hough_circle, hough_circle_peaks
def ... | eugenbobrov/vision-hack | vision.py | vision.py | py | 2,580 | python | en | code | 0 | github-code | 36 |
16413121892 | import subprocess
import requests
from flask import Flask, request, json
from jproperties import Properties
configs = Properties()
with open('server.properties', 'rb') as config_file:
configs.load(config_file)
app = Flask(__name__)
@app.route("/health")
def healthCheck():
return "alive", 200
@app.route("/page",... | zarcha/pirate-pager | node/app.py | app.py | py | 1,926 | python | en | code | 0 | github-code | 36 |
33147614582 | #!/usr/bin/env python3
# Author: Jan Demel (xdemel01@fit.vutbr.cz)
# This script was made as a part of IPK course
# Don't copy this please...
# My API key: 419db25b1d35c32d9f83525f3bc9931c
import socket
import json
import sys
# Error codes
ERROR_ARGS = -1
ERROR_SOCKET_CONNECTION = -2
ERROR_FORMAT_OUTPUT_DATA = -3
... | hondem/FIT | ipk_proj_1/script.py | script.py | py | 2,040 | python | en | code | 0 | github-code | 36 |
7060223293 | import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from tkinter import simpledialog as sd
from tkinter import messagebox as mb
from tkinter import scrolledtext as st
from unittest import mock
from functools import reduce
from os import path
import textwrap as tw
import glob
import io
impo... | ceucomputing/automarker | automarker.py | automarker.py | py | 46,918 | python | en | code | 1 | github-code | 36 |
30372470703 | from django.shortcuts import render,redirect
# from .models import details
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
from .forms import SignUpForm, UserName
from django.contrib.auth import authenticate, login, logout
from .models import FriendDetails
import requests
fr... | harithlaxman/CodeChef-Friends | main/views.py | views.py | py | 4,773 | python | en | code | 0 | github-code | 36 |
6759362866 | import pandas as pd
import numpy as np
import random,math
from scipy.spatial import distance
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from collections import defaultdict
def plot_3d(res_datapoints,m,pdf):
fig = plt.figure()
ax = Axes3D(f... | swadtasnim/My-K-Means-Clustering | synthetic_data.py | synthetic_data.py | py | 2,705 | python | en | code | 0 | github-code | 36 |
2318482284 | import torch
import math
import numpy as np
import os
import cv2
import imutils
import random
import shutil
from slim_net import FaceQualityNet, FaceQualitySlim
from myconfig import config as testconf
from load_data import pytorch_to_dpcoreParams, save_feature_channel, get_patches, get_patches_augment
from detector.c... | xinyunmian/Face_compliance_detection | face_quality/train/test_quality.py | test_quality.py | py | 19,759 | python | en | code | 0 | github-code | 36 |
39688739792 | #!/usr/bin/env python3
"""
Node for control PCA9685 using AckermannDriveStamped msg
referenced from donekycar
url : https://github.com/autorope/donkeycar/blob/dev/donkeycar/parts/actuator.py
"""
#완성
import threading
import sys
import socket
from ackermann_msgs.msg import AckermannDriveStamped
import rospy
import os
... | Bumkie/COSMOS | autodrive_test.py | autodrive_test.py | py | 4,237 | python | en | code | 1 | github-code | 36 |
36091442978 | #lex_auth_012693816331657216161
def encode(message):
i = 0
j = 0
count = 1
res = ''
while i < len(message) :
j = i+1
while j < len(message) :
if message[i] == message[j] :
count += 1
j += 1
i += 1
else :
... | Ghazi-Khan/InfyTraining | PythonProgramming/Assignment/Set3/StringLevel2.py | StringLevel2.py | py | 594 | python | en | code | 0 | github-code | 36 |
27976899334 | import tkinter as tk
import tkinter.ttk as ttk
from time import sleep
from PIL import ImageTk, Image
import sys
import Initialise
import Manual
import Settings
class Controls():
def __init__(self, background, initialise_panel, manual_panel, settings_panel, tileprint_panel, state):
self.background = backg... | InfiniteAnswer/Robot_GUI_V2 | Controls.py | Controls.py | py | 4,308 | python | en | code | 0 | github-code | 36 |
37508516152 | from flask import Blueprint, request
from .connection import client
import datetime
now = datetime.datetime.utcnow()
user_route = Blueprint('user_route', __name__)
# Connect to collection
db = client.swiper
collection = db.users
# Post/get route acceser
@user_route.route('/', methods=['GET', 'POST'])
def userCreate... | acedinstitute/swipingApi | routes/user.py | user.py | py | 939 | python | en | code | 0 | github-code | 36 |
15826823002 | import logging
import scipy.cluster.hierarchy as sch
import sklearn.cluster as sc
# to map the user labels
# - user_input_df: pass in original user input dataframe, return changed user input dataframe
# - sp2en: change Spanish to English
def map_labels_sp2en(user_input_df):
# Spanish words to English
span_eng_... | e-mission/e-mission-server | emission/analysis/modelling/tour_model/label_processing.py | label_processing.py | py | 6,913 | python | en | code | 22 | github-code | 36 |
36840887809 | """Various utilities that are handy."""
import codecs
import re
import os
import os.path
import subprocess
import sys
def get_git_branch():
"""Return the git branch version."""
if not os.path.exists(".git") or not os.path.isdir(".git"):
return None
version = open(".git/HEAD", "r").read().strip()... | mongodb/mongo | buildscripts/utils.py | utils.py | py | 3,156 | python | en | code | 24,670 | github-code | 36 |
26454125237 | import argparse
import gc
import logging
import os
import glob
import pandas as pd
import sys
sys.path.append("../ddn/")
sys.path.append("./")
from collections import defaultdict
import torch
import warnings
warnings.filterwarnings('ignore')
import numpy as np
torch.backends.cudnn.benchmark = True
from matplotlib ... | Vikr-182/ddn-forecasting | scripts/data_prep.py | data_prep.py | py | 9,023 | python | en | code | 0 | github-code | 36 |
31408771837 | #!/usr/bin/env python
import pandas as pd
# Read injuries
# Data from https://www.cpsc.gov/cgibin/NEISSQuery/Home.aspx
injuries = pd.read_csv("data/firework-injuries-2013.tsv", sep="\t")
# Combine narrative columns
injuries["narrative"] = injuries.narr1.fillna("") + " " + injuries.narr2.fillna("")
# Read diagnosis c... | BuzzFeedNews/2014-06-firework-injuries | fireworks.py | fireworks.py | py | 1,790 | python | en | code | 6 | github-code | 36 |
14566329358 | from django.db import models, migrations
import cover.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Image',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=Tr... | fnp/redakcja | src/cover/migrations/0001_initial.py | 0001_initial.py | py | 1,275 | python | en | code | 4 | github-code | 36 |
12483497322 | from os.path import expanduser, join
from types import SimpleNamespace
from common_utils_v4 import toDotDict
cfg = SimpleNamespace(**{})
# cfg.train_seed = None # moved to args
# DATA_DIR = 'data'
cfg.DATA_DIR = expanduser('./data/raw')
# TRAIN_DIR = f'{DATA_DIR}/train_features'
cfg.TRAIN_DIR = join(cfg.DATA_DIR, ... | drivendataorg/mars-spectrometry-gcms | 2nd-place/config_main_v4.py | config_main_v4.py | py | 4,761 | python | en | code | 1 | github-code | 36 |
6482900973 | import requests
url = "https://www.caberj.com.br/wspls/WS005.apw"
querystring = {"WSDL":""}
payload = ""
headers = {
"cookie": "SESSIONID=36c9c80f7d7d823affe2b4d5d3522477",
"Authorization": "Basic cmVzdHVzZXI6UEBzc3cwcmQyMDIz"
}
response = requests.request("GET", url, data=payload, headers=headers, params=q... | msullivancm/ProjetosComAte10LinhasDeCodigoPython | apiRestMosiaBkp/requestWS005.py | requestWS005.py | py | 353 | python | en | code | 0 | github-code | 36 |
35676671945 | """
*Element Shape*
"""
from dataclasses import dataclass
from strism._geoshape import Pixel
__all__ = ["ElementShape"]
@dataclass
class ElementShape:
width: Pixel
height: Pixel
@classmethod
def create(
cls,
width: int,
height: int,
):
return cls(
... | jedhsu/text | text/_shape/_shape.py | _shape.py | py | 375 | python | en | code | 0 | github-code | 36 |
31045215488 | import os
import logging
import boto3
import json
import io
import pandas as pd
logger = logging.getLogger()
logger.setLevel(logging.INFO)
s3 = boto3.client("s3")
iam = boto3.client("iam")
personalizeRt = boto3.client("personalize-runtime")
solution_arn = os.environ["SOLUTION_ARN"]
campaign_arn = os.environ["CAMPAIG... | ryankarlos/AWS-ML-services | lambdas/realtimepersonalize/lambda_function.py | lambda_function.py | py | 2,097 | python | en | code | 1 | github-code | 36 |
2006853859 |
import json
import datetime
from . import db
class View(db.Model):
__tablename__ = 'devicer_views'
view_key = db.Column(db.String(20), primary_key=True)
view_name = db.Column(db.String)
view_saved = db.Column(db.DateTime, default=datetime.datetime.now())
selecter_mode = db.C... | rleschuk/devicer | app/models.py | models.py | py | 1,944 | python | en | code | 0 | github-code | 36 |
21120299087 | from Sentence_Encoder.meta_response_encoder_fast import encode as response_encode
import Utils.functions as utils
import numpy as np
import torch as T
import copy
def random_response(candidates, conversation_history, p=None):
loop = 5
if p is None:
response = random.choice(candidates)
else:
... | JRC1995/Chatbot | ReRanker/rerank.py | rerank.py | py | 3,529 | python | en | code | 79 | github-code | 36 |
6677016753 | class Item:
def __init__(self, profit, weight):
self.profit = profit
self.weight = weight
def FractionalKnapsack(items, weight):
items.sort(key=lambda x: (x.profit/x.weight), reverse=True)
finalProfit = 0
finalWeights = [0 for i in range(len(items))]
for i in range(len(items)):
... | saplynx/daa | ass3.py | ass3.py | py | 850 | python | en | code | 0 | github-code | 36 |
34970482318 | import dbus
import os
import re
import time
import unittest
import six
import sys
import glob
from packaging.version import Version
import udiskstestcase
class UDisksLVMTestBase(udiskstestcase.UdisksTestCase):
@classmethod
def setUpClass(cls):
udiskstestcase.UdisksTestCase.setUpClass()
if n... | storaged-project/udisks | src/tests/dbus-tests/test_20_LVM.py | test_20_LVM.py | py | 42,717 | python | en | code | 302 | github-code | 36 |
13938469838 | from analysers.WarningAnalyser import WarningAnalyser
from auto_editor.StructuredProjectSource_Recommendation import StructuredProjectSource_Recommendation
from enums import RecommendationItem
from typing import List
class WarningRecommendationAnalyser(WarningAnalyser):
"""
Basically, the same as the pre-anal... | UCL-oneAPI/CTA-oneAPI | analysers/WarningRecommendationAnalyser.py | WarningRecommendationAnalyser.py | py | 2,371 | python | en | code | 3 | github-code | 36 |
9628433548 | import numpy as np
import pandas as pd
#Global variable
suit = {'S1', 'S2', 'S3', 'S4', 'S5'}
rank = {'C1', 'C2', 'C3', 'C4', 'C5'}
#A function that is given a list it would count the number of n dupilciates of a rank. Used in one pair, three of a kind and four of a kind
def count_duplicate(l,n):
for i in range (... | ksuhartono97/COMP-3211-poker-induction | oracles.py | oracles.py | py | 4,952 | python | en | code | 0 | github-code | 36 |
72871590183 | import os
import torch
from torch.utils.data import Dataset
import torchvision
import data
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
PGT_LOAD_FILE = "pseudo_gt_thesis.pth"
CLEAN_PGT_LOAD_FILE = "cleaned_pseudo_gt_thesis.pth"
# img size: (200,400)
class TabletopWorkDataset(Dataset):
... | LDenninger/se3_pseudo_ipdf | data/tabletop/pls_dataset.py | pls_dataset.py | py | 4,837 | python | en | code | 0 | github-code | 36 |
12507615961 | # 힙
# 더 맵게
import heapq
def solution(scoville, K):
answer = 0
heap = []
# 스코빌 목록을 힙에 담기
for s in scoville:
heapq.heappush(heap, s)
# K보다 작은 값이 힙에 하나라도 있다면
while any(K > i for i in heap):
# 불가능한 경우
if len(heap) < 2:
return -1
# 문제에서 제시한 연산
... | Hong-Jinseo/Algorithm | programmers/42626.py | 42626.py | py | 609 | python | ko | code | 0 | github-code | 36 |
31033799131 | import numpy as np
import os, pickle
import random
import torch
import torch.nn as nn
from collections import deque
from torch import Tensor
from torch import tensor
from time import time, sleep
import src.model_greedy
if torch.cuda.is_available():
cuda = torch.device('cuda')
else:
cuda = torch.device('cpu... | atakanyasar/hungry-geese | src/model.py | model.py | py | 7,803 | python | en | code | 0 | github-code | 36 |
41145724331 | import numpy as np
var_x = 1
var_y = 1
corr = 0.8
covariance = np.matrix([[var_x, corr * np.sqrt(var_x * var_y)], [corr * np.sqrt(var_x * var_y), var_y]])
# Compute the Decomposition:
A = np.linalg.cholesky(covariance)
mean = np.matrix([[0.], [1.]])
X= np.zeros((2,10))
Z = np.random.normal(size=(2, 1))
x= n... | dansmith5764/A-study-of-fairness-in-transfer-learning | simulations python/test_n.py | test_n.py | py | 496 | python | en | code | 0 | github-code | 36 |
72314053544 | import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-atlassian',
... | fluendo/django-atlassian | setup.py | setup.py | py | 1,409 | python | en | code | 7 | github-code | 36 |
30178594395 | from matplotlib import pyplot as plt
from PIL.Image import frombytes
import cv2
import numpy as np
from traceback import print_exc
'''
Toolkit for image process
with the method from cv2,plt,np
个人工具包,对一些需要调用多次函数的
过程打包,主要用于图像的处理和输出,
使用的库为cv2,matplotlib,PIL,numpy
'''
class count_show(object):
def ... | wmillers/coursewarePhotoProcess | toolkit.py | toolkit.py | py | 12,134 | python | en | code | 0 | github-code | 36 |
16140915477 | import typing
import time
import sys
import logging
import itertools
import numpy as np
from scipy.spatial import distance as sp_dist
import pyautogui as pg
import actionplanner as planner
# pylint: disable=too-few-public-methods
class MouseClicker(planner.MouseClicker):
def __init__(self, bdetector):
"... | kkew3/sat-minesweeper | virtual/actionplanner.py | actionplanner.py | py | 4,350 | python | en | code | 6 | github-code | 36 |
32542351130 | from google.cloud import storage
from configparser import ConfigParser
from google.oauth2 import service_account
from googleapiclient.discovery import build
from utils.demo_io import (
get_initial_slide_df_with_predictions_only,
get_fovs_df,
get_top_level_dirs,
populate_slide_rows,
get_histogram_df,... | alice-gottlieb/nautilus-dashboard | examples/gcs_example.py | gcs_example.py | py | 1,919 | python | en | code | 0 | github-code | 36 |
18794245329 | from typing import Any
import pytest
from click.testing import CliRunner
from happi.prompt import enforce_list, read_user_dict
from happi.utils import EnforceError
def test_user_dict(runner: CliRunner):
default_dict = {'default_key': 'default_value'}
# normal operation
with runner.isolation('key1\nvalu... | pcdshub/happi | happi/tests/test_prompt.py | test_prompt.py | py | 1,324 | python | en | code | 10 | github-code | 36 |
7132570944 | ### Retrieve only the pieces of document chunks that are relevant to the query because context window of LLMs is limited.
### Different ways to split the documents :
#### Characters, tokens, context aware splitting such Markdown header splitter.
### Parameter needed to be tuned : separated, chunk size, chunk overlap,... | kn-neeraj/NotionKnowledgeAssistant | document_chunks.py | document_chunks.py | py | 1,879 | python | en | code | 0 | github-code | 36 |
19792929420 | from sklearn.ensemble import RandomForestClassifier
from scipy import signal
import pandas as pd
import numpy as np
import statsmodels.api as sm
from sklearn.preprocessing import MinMaxScaler
from statsmodels.tsa.stattools import adfuller
import pickle
from io import BytesIO
def classifier(data_set):
with open('mo... | shyamsivasankar/TIME-SERIES-DATA | findClass.py | findClass.py | py | 2,042 | python | en | code | 0 | github-code | 36 |
7689812417 | def method1(ll: list, n: int, k: int) -> int:
x = n // k
freq = {}
for i in range(n):
if ll[i] in freq:
freq[ll[i]] += 1
else:
freq[ll[i]] = 1
for i in freq:
if freq[i] > x:
print(i)
if __name__ == "__main__":
"""
from timeit import t... | thisisshub/DSA | H_hashing/problems/M_more_than_nk_occurences.py | M_more_than_nk_occurences.py | py | 490 | python | en | code | 71 | github-code | 36 |
7089966560 | from bottle import redirect, request, post
import uuid
import jwt
import time
from check_if_logged_in import check_if_logged_in
from global_values import *
@post("/new-tweet")
def new_tweet_post():
if not check_if_logged_in():
return redirect("/login")
# title
new_tweet_title = request.forms.... | sara616b/01_mandatory_web_dev | new_tweet_post.py | new_tweet_post.py | py | 1,355 | python | en | code | 0 | github-code | 36 |
12126429354 | from email import message
from email.mime import text
from typing import Text
from cv2 import data
import pyttsx3
from requests.api import head, request #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowse... | Lavya-Gohil/Jarvis | jarvis.py | jarvis.py | py | 27,563 | python | en | code | 1 | github-code | 36 |
26614333632 | import enum
import jsonpatch
import jam
from jam import O
from jam import Q
from jam import exceptions
from jam.schemas import load_schema
from jam.backends.util import load_backend
class Operation(enum.IntEnum):
CREATE = 0
UPDATE = 1
REPLACE = 2
DELETE = 3
SNAPSHOT = 4
RENAME = 5
class Re... | CenterForOpenScience/jamdb | jam/base.py | base.py | py | 8,174 | python | en | code | 3 | github-code | 36 |
34398233401 | import os
import subprocess
def run_scripts_in_folder():
current_path = os.path.dirname(os.path.abspath(__file__))
scripts_to_run = [
'Instrument-dlya-opressovki-nakonechnikov.py',
'Instrument-dlya-prosekaniya-otverstiy.py',
'Instrument-dlya-rezki-kabelya.py',
'Instrument-dly... | Foxhole96/MetaParser | Instrument-sredstva-individualnoy-zaschity/Mass_Start.py | Mass_Start.py | py | 1,346 | python | en | code | 0 | github-code | 36 |
6073108961 |
from traits.api import \
HasTraits, List, Array, Property, cached_property, \
Instance, Trait, Button, on_trait_change, \
Int, Float, DelegatesTo, provides, WeakRef, Bool
from ibvpy.mesh.sdomain import \
SDomain
# from ibvpy.view.plot3d.mayavi_util.pipelines import \
# MVPolyData, MVPointLabels
im... | bmcs-group/bmcs_ibvpy | ibvpy/mesh/cell_grid/dof_grid.py | dof_grid.py | py | 12,406 | python | en | code | 0 | github-code | 36 |
27734664933 | import os, sys
from http import HTTPStatus
from fastapi import FastAPI
from fastapi import Response
from fastapi_sqlalchemy import DBSessionMiddleware
from dotenv import load_dotenv
from app.main.adapters import fast_api_adapter
from app.domain.usecases import CreateUserParams, CreateUserResponse
from app.main.factori... | victoroliveirabarros/fastapi-sql | app/main/main.py | main.py | py | 1,309 | python | en | code | 1 | github-code | 36 |
36998634880 | from django.shortcuts import render
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status
from api.models import SunExposure
from api.serializers import SunExposureSerializer
from rest_framework.decorators import api_view
# Create your views her... | ejustis/garden-tracker-api | api/views.py | views.py | py | 2,265 | python | en | code | 0 | github-code | 36 |
26116785786 | from genericpath import samefile
import torch
# import mmcv
# from mmseg.apis import init_segmentor#, inference_segmentor, init_cfg
# from mmseg.models import build_segmentor
# from mmcv import ConfigDict
import torchvision
# from SETR.transformer_seg import SETRModel, Vit
import segmentation_models_pytorch as smp
d... | aya49/flowMagic_data | method/models.py | models.py | py | 2,805 | python | en | code | 0 | github-code | 36 |
43508300282 | """
"""
import sys
from pathlib import Path
print(Path(__file__).resolve().parents[1])
sys.path.append(Path(__file__).resolve().parents[1])
if __name__ == '__main__' and __package__ is None:
__package__ = 'kurosc'
#
# from lib.plotformat import setup
import numpy as np
np.set_printoptions(precision=2, suppress=Tr... | chriswilly/kuramoto-osc | Python/kurosc/kurosc/unit_test.py | unit_test.py | py | 6,957 | python | en | code | 2 | github-code | 36 |
74224410343 | import datetime
import logging
import numpy as np
import os
import skimage.io as io
from skimage.exposure import equalize_adapthist
from skimage.filters import gaussian
from skimage.transform import resize
from skimage.color import rgb2lab
from src.data_loader import root_dir, FOLDER_EXPERIMENTS, references_paths, re... | AntoineRouland/ki67 | src/v8_test/optimization.py | optimization.py | py | 7,179 | python | en | code | 1 | github-code | 36 |
27239521850 | # youtube/youtube_api.py
import google.auth
from google.auth.transport.requests import AuthorizedSession
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from config.config import YOUTUBE_API_KEY
class YoutubeAPI:
def __init__(self):
self.credentials = None
... | eddari-me/youtube_shorts_to_instagram | youtube/youtube_api.py | youtube_api.py | py | 1,136 | python | en | code | 0 | github-code | 36 |
73202406184 | from bokeh.models import (
HoverTool,
Range1d,
ColumnDataSource,
BBoxTileSource,
TapTool,
)
from bokeh.plotting import figure
from bokeh.layouts import row, column
import bokeh.models as bokeh_models
from bokeh.models.widgets import Div, RadioGroup, CheckboxGroup
BOKEH_BACKGROUNDS = {
"luchtfo... | d2hydro/hydrodashboards | src/hydrodashboards/bokeh/widgets/map_figure_widget.py | map_figure_widget.py | py | 4,761 | python | en | code | 1 | github-code | 36 |
72900986983 | import time
import numpy as np
import tensorflow as tf
import tensorflow.keras.optimizers as O
import tensorflow.compat.v1.losses as Losses
from log_utils import save_weights, plot_results, print_log
DEFAULT_LR = 1e-3
DEFAULT_BETA_1 = 0.7
class Trainer(object):
def __init__(self, generator, discriminator, g_opti... | Ambrozy/GAN_utils | trainer.py | trainer.py | py | 4,842 | python | en | code | 0 | github-code | 36 |
42873043264 | """Class definition and associated functions for requesting data from
IUCN Red List. Run as a script it downloads the latest Red List.
You need an API token to use it, available from
http://apiv3.iucnredlist.org/api/v3/token.
"""
import requests
import requests_cache
import csv
import datetime
import time
from argpa... | barnabywalker/threatened_species_classification_comparison | scripts/redlist_api.py | redlist_api.py | py | 8,897 | python | en | code | 1 | github-code | 36 |
12483249842 | import cfgrib
import xarray as xr
import matplotlib.pyplot as plt
import os
import glob
from pathlib import Path
from tqdm import tqdm, tnrange
import pandas as pd
import math
import shapely.wkt
def get_csv_from_grib_files(grib_files: list) -> pd.DataFrame:
"""_summary_
Args:
grib_files... | drivendataorg/nasa-airathon | pm25/3rd Place/src/preprocessing/gfs/gfs_prep_group_1.py | gfs_prep_group_1.py | py | 3,731 | python | en | code | 12 | github-code | 36 |
25053087228 | # Std Libs:
import logging
# Django Libs:
from django.contrib.auth.models import User
# Django Rest Framework Libs:
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
# Locals:
from .models import Client
from .permissions import ClientPermissions
from .ser... | Emericdefay/OCR_P12 | CRM/client/views.py | views.py | py | 7,612 | python | en | code | 0 | github-code | 36 |
42307406368 | T = int(input())
res = []
def getres(d):
if len(d)==0:
return 0
if len(d)==1:
return 1
t = min(d)
res = t
for i in range(len(d)):
d[i]-=t
data = []
l = 0
r = 0
while r<len(d):
while l<len(d) and d[l]==0:
l+=1
r = l
whil... | jing-ge/Jing-leetcode | offer/pdd/44.py | 44.py | py | 660 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.