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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
72515571067 | from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains import RetrievalQAWithSourcesChain, RetrievalQA
from langchain import OpenAI
from langchain.vectorstores import Chroma
import gradio as gr
from langchain.chains.question_answering i... | uni-3/gradio-apps | qa_retrieval/app.py | app.py | py | 2,753 | python | en | code | 0 | github-code | 6 |
71754427069 | import paramiko
import paramiko.client
client = paramiko.client.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(
paramiko.AutoAddPolicy()
)
client.connect(
"localhost",
username="developer",
password="4linux"
)
(stdin, stdout, stderr) = client.exec_command("ls")
status ... | elderlima/4linux | ssh/main.py | main.py | py | 500 | python | en | code | 0 | github-code | 6 |
4487177002 | """
Lab 7.4 Document Exceptons
"""
class AbstractException(Exception):
""" Basic class for class exceptions"""
def __init__(self, message):
super().__init__(message)
self.message = message
class WrongInput(AbstractException):
""" Invalid input """
class CursorRangeError(AbstractException)... | sviat-l/FP_Labs | 7_Lab_Exceptions_Tests/4_Document/main.py | main.py | py | 4,283 | python | en | code | 0 | github-code | 6 |
20678034139 | from omegaconf import DictConfig
import hydra
from VisualClassificationRunner import VisualClassificationRunner
class CueConflictRunner(VisualClassificationRunner):
def test(self) -> dict:
"""Test the model on the standard dataset and the randomized datasets.
:return: Dictionary wi... | nathansomavarapu/core-ml | src/CueConflictRunner.py | CueConflictRunner.py | py | 1,053 | python | en | code | 0 | github-code | 6 |
24416364915 | import grp
import json
import logging
import os
import pkgutil
import tempfile
from cloudify.decorators import operation
from cloudify.exceptions import NonRecoverableError
from managed_nagios_plugin._compat import text_type
from managed_nagios_plugin.constants import (
BASE_OBJECTS_DIR,
OBJECT_DIR_PERMISSION... | cloudify-cosmo/cloudify-managed-nagios-plugin | managed_nagios_plugin/nagios/tasks.py | tasks.py | py | 26,382 | python | en | code | 0 | github-code | 6 |
11711962924 | import os
import numpy as np
import bpy
import mathutils
import math
from satvis.utils.blender_utils import make_sat, make_sun, \
make_camera, make_torch, setup_depth, rotate_sat, \
rotate_earth, save_render, get_data, CAMERA_VIEW_DIRECTION, \
... | Ben-Guthrie/satvis | utils/vis_utils.py | vis_utils.py | py | 9,405 | python | en | code | 3 | github-code | 6 |
41117547284 | """
Created by hu-jinwen on 2022/4/25
"""
# 打开文件
file_read = open("content")
file_write = open("content[copy]", "w")
# 读写
while True:
#读取一行内容
text = file_read.readline()
# 判断是否读取到内容
if not text:
break
file_write.write(text)
# 关闭
file_write.close()
file_read.close() | wu-qiqin/python_learn | documents/open_write_read_copy.py | open_write_read_copy.py | py | 341 | python | en | code | 0 | github-code | 6 |
8213198289 | import sublime
import sublime_plugin
import os
class JaiToolsBuildCommand(sublime_plugin.WindowCommand):
common_parent_dir = None
abs_file_paths = []
rel_file_paths = []
active_rel_file_path = None
def run(self):
paths_set = get_all_jai_project_file_paths()
# Add open files to the paths set, in case they... | RobinWragg/JaiTools | JaiToolsBuildCommand.py | JaiToolsBuildCommand.py | py | 1,602 | python | en | code | 28 | github-code | 6 |
16557567463 | from zscript import *
#######################################################################################################################
# p_init = """L = 1350
# albedo = 0.3
# epsilon = 1
# sigma = 5.67*10^-8
# waterdepth = 4000
# heatcapground = 4.2*1000^2*waterdepth
# heatcapair = 100^2*30
#
# csurface = 6.... | zavierboyd/ZS-Appengine | testing.py | testing.py | py | 2,943 | python | en | code | 0 | github-code | 6 |
4083668934 | from urllib.parse import urlencode
import httpx
from common.kan_params import crd_params
from common.voe_ipc import KanAgent
#host = 'localhost'
#host = 'kan-agent'
#port = '8088'
class KanAgentClient:
#def __init__(self, host=host, port=port, scope='default', version='v1', ref='v1alpha2.ReferenceK8sCRD'):
... | Azure/KAN | src/edge/EdgeSolution/modules/common/common/kan_agent_client.py | kan_agent_client.py | py | 3,527 | python | en | code | 61 | github-code | 6 |
4520925854 | from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView, TokenVerifyView,
TokenObtainSlidingView, TokenRefreshSlidingView
)
from .views import SingUpView, BlacklistRefreshView
urlpatterns = [
path('signup/', SingUpView.as_view(), name='sign_up'),
... | rustamovjavohir/EcommerceSHOP | auth_user/urls.py | urls.py | py | 638 | python | en | code | 8 | github-code | 6 |
6846678287 | from tkinter import Frame, Label, Menu, ttk
from tkinter.messagebox import showinfo
import tkinter as tk
import requests
class AttackInfo(Frame):
def __init__(self, master=None):
super(AttackInfo, self).__init__(master)
master = master
self.type_label = Label(self, text=" ", font=('Helve... | iamcrysun/eqw | desktop/views/attackinfo.py | attackinfo.py | py | 2,001 | python | en | code | 0 | github-code | 6 |
10167784496 | # (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from django.http.multipartparser import parse_header
from rest_framework.renderers import BaseRenderer
COLNAME_FORMAT = '%Y-%m-%d %H:%M:%S.%f'
class CSVRenderer(BaseRenderer):
"""
Renderer which serializes to c... | ddsc/dikedata-api | dikedata_api/renderers.py | renderers.py | py | 957 | python | en | code | 0 | github-code | 6 |
14959290509 | import json
from json import JSONEncoder
from yoti_python_sdk.crypto import Crypto
from yoti_python_sdk.http import SignedRequestBuilder
import yoti_python_sandbox
from .anchor import SandboxAnchor
from .attribute import SandboxAttribute
from .endpoint import SandboxEndpoint
from .sandbox_exception import SandboxExce... | getyoti/yoti-python-sdk-sandbox | yoti_python_sandbox/client.py | client.py | py | 4,176 | python | en | code | 0 | github-code | 6 |
6105704383 | import requests
import sys
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
proxies = {'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'}
def promote_to_admin(s, url):
# login as the wiener user
login_url = url + "/login"
data_login = {"username": "wiene... | rkhal101/Web-Security-Academy-Series | broken-access-control/lab-06/access-control-lab-06.py | access-control-lab-06.py | py | 1,364 | python | en | code | 396 | github-code | 6 |
20701388833 | import sqlite3
samira = sqlite3.connect('shallownowschool.db')
cursor = samira.cursor()
cursor.execute("""
INSERT INTO td_estudante(nome, endereco, nascimento, matricula)
VALUES ('Maria da Conceição', 'Rua da Paz', '1902-12-12', 20161382596);
""")
samira.commit()
print("Inserido com sucesso.")
samira.close(... | kemelynfigueiredo/TopicosEspeciais | MeuPrimeiroSQLite/temp.py | temp.py | py | 324 | python | pt | code | 0 | github-code | 6 |
13511594492 | """
This module is unit-tested using doctest when run directly. :)
python duration_string.py
"""
import doctest
import re
__version__ = "1.2.3"
TIMING_MAP = {"s": 1, "m": 60, "h": 60 * 60, "d": 24 * 60 * 60}
def is_valid(string):
"""
>>> is_valid('')
False
>>> is_valid(None)
False
>>> is_val... | geonyoro/durationstring | durationstring.py | durationstring.py | py | 2,106 | python | en | code | 2 | github-code | 6 |
17625798812 | import sys
import os
import pandas as pd
from util import load_column_transformers, preprocess_data
from alphagan_class import AlphaGAN
from keras.losses import MeanAbsoluteError
from bigan import BIGAN
import keras.backend as K
import tensorflow as tf
import numpy as np
if __name__ == '__main__':
session = K.ge... | royalsalute/fraud-creditcard-detection | eval.py | eval.py | py | 1,784 | python | en | code | 1 | github-code | 6 |
30789951381 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklear... | nimishakhaitan/Evil-Geniuses-assessment | Assessment_Data_Science.py | Assessment_Data_Science.py | py | 11,117 | python | en | code | 0 | github-code | 6 |
13659068319 | from django.http import HttpResponse
from django.shortcuts import redirect, render
from .forms import ContactForm
from django.core.mail import send_mail, BadHeaderError
from config.settings import RECIPIENTS_EMAIL, DEFAULT_FROM_EMAIL
# Create your views here.
def contact_view(request):
if request.method == "GET... | Dauka03/food_project_back | sendemail/views.py | views.py | py | 1,235 | python | en | code | 1 | github-code | 6 |
24519278933 | import argparse
import os
import cv2
from wand.image import Image
import numpy as np
#ArgumentParser객체:명령행을 파이썬 데이터형으로 파싱하는데 필요한 모든 정보가 들어있음
#ArgumentParser객체 생성
ap=argparse.ArgumentParser()
ap.add_argument("-i","--images",required=True, help="absolute path to the input image")
ap.add_argument("-c","--cascade",default... | Zzang-yeah/catholic | cat_detection/feic_to_jpg.py | feic_to_jpg.py | py | 1,733 | python | en | code | 0 | github-code | 6 |
34607069404 | import os
import json
import pandas as pd
import numpy as np
import networkx as nx
#所有节点和边构成网络图
def form_graph(parent_path):
every_pro_path = os.path.join(parent_path, r'dataset\secondExperiments\COVID_Node2Vec.csv')
simGO_path = os.path.join(parent_path, r'dataset\secondExperiments\train_COVID_AllHuman_GoSim.... | LittleBird120/DiseaseGenePredicition | DiseaseGenePredicition/20210315covering-clustering-algorithm - COVID/algorithm/formComplex.py | formComplex.py | py | 6,315 | python | en | code | 0 | github-code | 6 |
1414123757 | import pytest
import os
import shutil
import tngsdk.project.workspace as workspace
from tngsdk.project.workspace import Workspace
from tngsdk.project.project import Project
class TestProjectUnit:
# create and return a temporary workspace 'test-ws'
@pytest.fixture(scope='module')
def workspace(self):
... | sonata-nfv/tng-sdk-project | tests/test_project_unit.py | test_project_unit.py | py | 1,124 | python | en | code | 5 | github-code | 6 |
41283122101 | # -*- coding: utf-8 -*-
import math
import numpy as np
from scipy.interpolate import interp1d
class SpatialParameters:
def __init__(self, signal, fs, window_size, running_step):
self.time_steps, self.iacc, self.tiacc, self.wiacc = self.__get_xcorr_descriptors(
signal, fs, window_... | kgordillo-hub/SoundMonitor-MetricsCalculator | SpatialParameters.py | SpatialParameters.py | py | 4,821 | python | en | code | 0 | github-code | 6 |
25273398870 | import sys
sys.stdin = open('input.txt', 'r')
def check(L, i):
c = 0
cnt = 0
for j in range(N):
if L[i][j]:
cnt += 1
if not L[i][j] or j == N-1:
if cnt == K:
c += 1
cnt = 0
return c
for t in range(1, int(input())+1):
N, K = map(... | powerticket/algorithm | Practice/실습/D10_문제풀이.py | D10_문제풀이.py | py | 575 | python | en | code | 0 | github-code | 6 |
2416697564 | import pygame
import sys
from random import randint
display = True
class snakeGame:
snake = [(16, 16),(16,15)]
apple = (18, 18)
is_dead = False
is_left = False
is_right = False
def move_left(self):
self.is_left = True
self.move_forward()
self.is_left = False
... | dogancanalgul/Pong | scratch.py | scratch.py | py | 3,004 | python | en | code | 0 | github-code | 6 |
43364784094 | from pathlib import Path
from argparse import ArgumentParser
# The path the project resides in
BASE_PATH = Path(__file__).parent.parent
# Alarm net dimensions
ALARM_HUGE = (5000, 2000, 500, 200)
ALARM_BIG = (1000, 500, 200, 75)
ALARM_SMALL = (100, 50, 25, 10)
# Standard arguments
def add_standard_arguments(parser: ... | Fraunhofer-AISEC/DA3D | libs/constants.py | constants.py | py | 2,063 | python | en | code | 1 | github-code | 6 |
30896806208 | import cv2
# loading the images
img1 = cv2.imread("png//yy.jpg")
img2 = cv2.imread("png//ra.jpg")
# resizing the both images in same resolution
scale_percent = 60 # percent of original size
width = int(img1.shape[1] * scale_percent / 90)
height = int(img2.shape[0] * scale_percent / 90)
dim = (width, height)... | singhsaurabh1998/OpenCv | SimilarImg.py | SimilarImg.py | py | 2,656 | python | en | code | 0 | github-code | 6 |
37693718022 | from enum import Enum, auto
from typing import Any, Tuple
from mesa import Model
from mesa.datacollection import DataCollector
from mesa.space import ContinuousSpace
from mesa.time import SimultaneousActivation
from autonomous_intersection.agents.direction import Direction
from autonomous_intersection.agents.visualce... | GrzegorzNieuzyla/Autonomous-Intersection | autonomous_intersection/model.py | model.py | py | 3,906 | python | en | code | 0 | github-code | 6 |
39363863586 | import networkx as nx
from node import Node
class Graph(nx.Graph):
def __init__(self):
super().__init__()
self.arcs=[]
self.nao_servido = 0
def increment_nao_servido(self):
self.nao_servido += 1
def decrement_nao_serveido(self):
self.nao_servido-=1
def create... | marcoscezar1/Simulador | Simulação I/graph.py | graph.py | py | 1,642 | python | en | code | 0 | github-code | 6 |
12755233630 | """
This file contains the 16-state EKF for INS/GNSS integration in direct configuration
The following states are estimated in three dimensions
position, velocity, orientation, accel bias, gyro bias
References
https://github.com/NorthStarUAS/insgnss_tools/blob/main/insgnss_tools/Kinematics.py
https://github.com/PX4/PX... | Birkehoj/gazebo_ins_analysis | ins_samples/ins_ekf_16_states.py | ins_ekf_16_states.py | py | 13,019 | python | en | code | 0 | github-code | 6 |
42253873273 | from tkinter import IntVar
from tkinter.constants import N, NE, S, TRUE, W
from controllers.edocsController import *
from helpers import helper
import json
class view:
def __init__(self, program):
self.program = program
self.frame_bgc = "#f5f5f5"
self.controller = edocsController()
... | REYJDR/COLOMETRIC_ANALISYS | views/Settings/Edocs.py | Edocs.py | py | 1,958 | python | en | code | 0 | github-code | 6 |
5095318867 | import random
import torchvision
from torchvision import datasets, transforms
from data.RPSLS.types import *
transformations = transforms.Compose([
transforms.ToTensor(),
])
dataset = datasets.ImageFolder(
root='../../../data/RPSLS/rock-paper-scissors-lizard-spock',
transform = transformations
)
def gener... | AytugAltin/ProblogRPSLS | examples/RPSLS/Rock-Paper-Scissors/generate_data.py | generate_data.py | py | 698 | python | en | code | 1 | github-code | 6 |
34511399562 | from django import forms
from .models import Producto
from django.forms import ModelForm
class ProductosForm(forms.ModelForm):
class Meta:
model = Producto
fields = ('nombre','material','cantidad','categoria')
labels = {
'nombre':'Nombre',
'cantidad':'n. can... | SteveManfred/eco_facil_mio | test/electivo_2023/productos/forms.py | forms.py | py | 543 | python | es | code | 0 | github-code | 6 |
28051281167 | """
Tests for the petl.fluent module.
"""
from __future__ import absolute_import, print_function, division
from tempfile import NamedTemporaryFile
import csv
from nose.tools import eq_
import petl
import petl.interactive as etl
from petl.testutils import ieq
def test_basics():
t1 = (('foo', 'bar'),
... | podpearson/petl | src/petl/test/test_interactive.py | test_interactive.py | py | 2,716 | python | en | code | null | github-code | 6 |
33585138405 | __author__ = 'Vivek'
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# @param A : head node of linked list
# @return the head node in the linked list
def mergeTwoLists(self, A, B):
curA, curB = A, B
if A == ... | viveksyngh/InterviewBit | Linked List/SORTLIST.py | SORTLIST.py | py | 1,904 | python | en | code | 3 | github-code | 6 |
37740591228 | from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from app.auth import main as auths
from app.users import main as users
from app.blogs import main as blogs, sub as blogs_sub
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
... | tokusumi/fastapi-nuxt-blog | backend/app/app/main.py | main.py | py | 524 | python | en | code | 6 | github-code | 6 |
17813388652 | from typing import Callable, Any, Type
from lyrid import Address
from lyrid.base import ActorSystemBase
from lyrid.core.node import NodeSpawnProcessMessage
from lyrid.core.process import Process
from lyrid.core.system import Placement
from tests.factory.system import create_actor_system
from tests.mock.messenger impor... | SSripilaipong/lyrid | tests/system/actor_placement/_assertion.py | _assertion.py | py | 3,625 | python | en | code | 12 | github-code | 6 |
36511035270 | def read_file(fileName):
content = []
with open(fileName, 'r', encoding='utf-8-sig') as f:
for line in f:
content.append(line.strip())
return content
def convert(textContent):
output = []
person = None
for line in textContent:
if line == 'Allen':
person = 'Allen'
continue
elif line == 'Tom':
p... | taylorchen78/chat | chat.py | chat.py | py | 634 | python | en | code | 0 | github-code | 6 |
21832705996 | from .piece import Piece
class King(Piece):
"""
Class that represents a king.
"""
def __init__(self, color, row, column, board, rooks):
Piece.__init__(self, color, row, column, board)
self.offsets = [(1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1)]
self.ro... | wuhw234/chess_bot | chess_game/pieces/king.py | king.py | py | 9,001 | python | en | code | 0 | github-code | 6 |
35091600325 | import unittest
from Soda import Soda
class TestSoda(unittest.TestCase):
def test_valid_no_tasty(self):
self.soda = Soda('')
self.assertEqual(self.soda.show_my_drink(), 'Обычная газировка')
def test_valid_add_tasty(self):
self.soda = Soda('клубника')
self.assertEqual(self.sod... | Sensor45/oop | soda_test.py | soda_test.py | py | 453 | python | ru | code | 0 | github-code | 6 |
15484480802 | #!/usr/bin/env python
from __future__ import print_function
import sys
import os
if sys.version_info >= (3, 0):
import tkinter
else:
import Tkinter as tkinter
import interaction
import canvas
import FigureManager
# The size of the button (width, height) for buttons in root gui.
SIZE_BUTTON = (18, 4)
def ... | t-lou/pytena | main.py | main.py | py | 1,537 | python | en | code | 0 | github-code | 6 |
21138659052 | from neo4j import GraphDatabase
# neo4j connection
driver = GraphDatabase.driver("bolt://127.0.0.1:7687", auth=("neo4j", "neo4j"))
# random walk
k = 10 # Number of neighbors
pre_weight = 2 # Weight of return
n = -1 # number of users to use, -1 means using all the users.
batch_size = 1000 # batchsize to save
cores... | RManLuo/MotifGNN | src_sjjy/pipline_config.py | pipline_config.py | py | 3,021 | python | en | code | 7 | github-code | 6 |
36636572184 |
import random
import pyxel
import utils
import stage
TYPE_AGGRESSIVE = 0
TYPE_MILD = 1
TYPE_RANDOM_SLOW = 2
TYPE_RANDOM_FAST = 3
TYPES = [
TYPE_AGGRESSIVE,
TYPE_MILD,
TYPE_RANDOM_SLOW,
TYPE_RANDOM_FAST
]
TICKS_PER_FRAME = 10
MAX_FRAME = 4
MAX_SPEED = 0.4
MAX_RESPAWN_TICKS = 300 # 5 secs
class Sp... | helpcomputer/megaball | megaball/spinner.py | spinner.py | py | 4,317 | python | en | code | 7 | github-code | 6 |
1568812252 | #mark ericson
#9/12/2022
#This program creates a cubic grid
import rhinoscriptsyntax as rs
from random import uniform
def cubic_grid(x_number, y_number, z_number, cell_size):
rs.EnableRedraw(False)
point_list = []
for i in range(0, x_number,cell_size):
x = i
for j in range(0, y_number, ce... | mcericson/arch_441_repo_fall_22 | 03_week/sphere_grid_inclasss.py | sphere_grid_inclasss.py | py | 1,037 | python | en | code | 0 | github-code | 6 |
21998531046 | from collections import Counter
class Solution:
def minWindow(self, s: str, t: str) -> str:
s_len = len(s)
t_len = len(t)
begin = 0
win_freq = {}
t_freq = dict(Counter(t))
min_len = s_len + 1
distance = 0
left = 0
right = 0
while rig... | hangwudy/leetcode | 1-99/76. 最小覆盖子串.py | 76. 最小覆盖子串.py | py | 1,359 | python | en | code | 0 | github-code | 6 |
1004121962 | from flask import Flask, render_template, request
import pypandoc
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/convert', methods=['POST'])
def convert():
input_markup = request.form['input_markup']
output_markup = pypandoc.convert(input_markup, format='... | myw/wiki-converter | converter.py | converter.py | py | 552 | python | en | code | 0 | github-code | 6 |
19203182463 | import os
from dotenv import load_dotenv
from minio import Minio
from io import BytesIO
from data_pipeline.classes.data_loader.DataLoader import DataLoader
class MinIOLoader(DataLoader):
def __init__(self, endpoint, bucket_name):
super().__init__(endpoint)
self._bucket_name = bucket_... | robbailiff/data_pipeline | src/data_pipeline/classes/data_loader/MinIOLoader.py | MinIOLoader.py | py | 1,836 | python | en | code | 0 | github-code | 6 |
72519791227 | import json
from warnings import warn
# def init_from_config(meas_cls, config: dict):
# arg_str = ''
#
# for key, value in config.items():
# arg_str = key+'='+value
def export_measurement_config(obj, attr_keys=None):
if attr_keys is None:
attr_keys = obj.__init__.__code__.co_varnames
... | yyzidea/measurement-automation | utilities/measurement_helper.py | measurement_helper.py | py | 1,278 | python | en | code | 0 | github-code | 6 |
8068261091 | from torchvision.models.detection import maskrcnn_resnet50_fpn
from rigl_torch.models import ModelFactory
@ModelFactory.register_model_loader(model="maskrcnn", dataset="coco")
def get_maskrcnn(*args, **kwargs):
return maskrcnn_resnet50_fpn(
weights=None, weights_backbone=None, trainable_backbone_layers=5... | calgaryml/condensed-sparsity | src/rigl_torch/models/maskrcnn.py | maskrcnn.py | py | 400 | python | en | code | 10 | github-code | 6 |
69868074749 | # 字典 values() 方法返回一个迭代器,可以使用 list() 来转换为列表,列表为字典中的所有值。
# dict.values()
# 返回值 返回迭代器。
Object = {
"name": "Tom",
"age": 18,
"other": "其他"
}
print(Object.values()) # dict_values(['Tom', 18, '其他'])
for value in Object.values():
print('value', value) # value Tom\value 18\value 其他
print... | yangbaoxi/dataProcessing | python/字典(对象)/遍历字典/values.py | values.py | py | 467 | python | zh | code | 1 | github-code | 6 |
38160567413 | #import bpy
from random import seed
from random import uniform
import numpy as np
import cv2
# seed random number generator
seed(1)
"""
def test1():
# make mesh
vertices = [(1, 0, 0),(1,0,5),(0,1,0)]
edges = []
faces = []
faces.append([0,1,2])
faces.append([2,0,3])
#new_mesh = bpy.data.m... | olaals/masteroppgave-old | src/testing/blender/generate-mesh/generate-alu-parts/generate-test.py | generate-test.py | py | 5,601 | python | en | code | 0 | github-code | 6 |
39019535632 | from typing import Union
import numpy as np
from numpy import typing as npt
from .outlier_removal_interface import OutlierRemovalInterface
class AbsoluteOutlierRemoval(OutlierRemovalInterface):
def __init__(self, top: float=None, bottom= None) -> None:
super().__init__(top, bottom)
def fit(self, X... | Diogo364/AirBnB_PriceRegressor | utils/outlier_removal/absolute_outlier_removal.py | absolute_outlier_removal.py | py | 893 | python | en | code | 0 | github-code | 6 |
2521814692 | #!/usr/bin/env python
import random
def merge(left, right):
res = []
while True:
if len(left) == 0:
res += right
break
elif len(right) == 0:
res += left
break
elif left[0] > right[0]:
res += [ right.pop(0) ]
else:
... | pmediaandy/bullpen | hackerrank/merge_sort.py | merge_sort.py | py | 918 | python | en | code | 0 | github-code | 6 |
37304550340 | import pyrealsense2 as rs
import numpy as np
import cv2
WIDTH = 640
HEIGHT = 480
FPS = 30
# file name which you want to open
FILE = './data/stairs.bag'
def main():
# stream(Depth/Color) setting
config = rs.config()
config.enable_stream(rs.stream.color, WIDTH, HEIGHT, rs.format.rgb8, FPS)
config.enabl... | masachika-kamada/realsense-matome | play_bagfile.py | play_bagfile.py | py | 1,686 | python | en | code | 0 | github-code | 6 |
35566573513 | from locale import windows_locale
import turtle
import tkinter as tk
from tkinter import ttk
"""
Koch Snowflake Program
Author: Katherine Butt
This program uses a recursive algorithm to draw a koch snowflake
The user is able to use a slider and button to control the number of times the recursion occurs
Depending on h... | Katherinebutt/COSC-326 | Etude 3/snowflake.py | snowflake.py | py | 2,777 | python | en | code | 0 | github-code | 6 |
46046574096 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
REQUIREMENTS = open(os.path.join(os.path.dirname(__file__), 'requirements.txt')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os... | nitely/django-hooks | setup.py | setup.py | py | 1,303 | python | en | code | 16 | github-code | 6 |
35470658937 | import queue, time
import threading
'''This is a basic reference script that shows how to use Queues & different types of Queues in python
There are basically 3 types of Queues :-
1. FIFO (default)
2. LIFO
3. Priority
'''
# q = queue.Queue()
# q.put(5)
# print(q.get()) # to fetch the items in the Queue
... | AbhishekMaity001/Python-Code-Snippets | Queue-Threading-1.py | Queue-Threading-1.py | py | 1,311 | python | en | code | 1 | github-code | 6 |
36846615388 | from typing import cast
from .kotlin_entities import (
KotlinEntity,
KotlinProperty,
KotlinEntityEnumeration,
PARSING_ERRORS_PROP_NAME,
ENTITY_STATIC_CREATOR
)
from ..base import Generator
from ... import utils
from ...config import GenerationMode, GeneratedLanguage, TEMPLATE_SUFFIX
from ...schema.... | divkit/divkit | api_generator/api_generator/generators/kotlin/generator.py | generator.py | py | 16,470 | python | en | code | 1,940 | github-code | 6 |
38959212336 | obj=open("Demo.txt","w+")
obj.write("Hello World")
obj.seek(3) #Move to 4th Byte
print(obj.tell()) #Gives the byte number(in terms of index
print(obj.read())
obj.seek(2,0)#Move 2 bytes further from beginning(0[First character at 0]+2=2)
print(obj.read())
obj.close()
obj=open("Demo.txt","rb")
obj.seek(1)
obj.s... | 9Mugen/int108 | seeking_another.py | seeking_another.py | py | 646 | python | en | code | 0 | github-code | 6 |
41058690136 | # Nicolas Gomollon, Lab 6
class Poly:
def __init__(self,*terms):
# __str__ uses the name self.terms for the dictionary of terms
# So __init__ should build this dictionary from terms
self.terms = {}
for coeff, power in terms:
assert type(coeff) in (int, floa... | solomc1/python | ics 33/solutions/ile2 solutions/Lab 6/GomollonNicolas/poly.py | poly.py | py | 6,377 | python | en | code | 0 | github-code | 6 |
1282652745 | import datetime
import pandas as pd
from tqdm import tqdm
from emailer import Emailer
from shipping import Shipping
from shipstation import Shipstation
def main():
# Instantiate objects to be used throughout the script
shipstation = Shipstation()
shipping = Shipping()
# Get all shipment information ... | mattgrcia/review-booster | main.py | main.py | py | 4,870 | python | en | code | 0 | github-code | 6 |
21894452141 | from dsa_stack import DSAStack
import sys
from typing import Union
class TowersOfHanoi:
def __init__(self, num_pegs: int, num_disks: int) -> None:
self.num_pegs = num_pegs
self.num_disks = num_disks
self.pegs = [
DSAStack(num_disks),
DSAStack(num_disks),
... | MC-DeltaT/DSA-Practicals | P2/towers_of_hanoi.py | towers_of_hanoi.py | py | 3,845 | python | en | code | 0 | github-code | 6 |
26333498275 | # Face detection is done using classifier
# classifier is an algorithm that decides wherether a face is present or not
# classifier need to be trained images thousands of with and without the faces.
# Opencv have pretrained classifier called haarcascade, localbinary pattern.
import cv2 as cv
img = cv.imread('Ima... | JinalSinroja/OpenCV | Face_Detection.py | Face_Detection.py | py | 1,299 | python | en | code | 0 | github-code | 6 |
26435457278 | # Import all necessary libraries
from distutils.cmd import Command
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import font as tkFont
import math
# Initialize tkinter and set the display
root = tk.Tk()
root.configure(bg = "green")
root.title("Calculator MIN 3000")
root.ge... | IonMurzac/tkinter_calculator | P_13_Calculator.py | P_13_Calculator.py | py | 7,168 | python | en | code | 0 | github-code | 6 |
575142348 | #breakout.py
#A. Colwell (2015)
# graphics2 module returns a TUPLE when using .getOverlap()
# The tuple will have two numbers, indicating which objects
# have overlapped. Only useful if you know the corresponding
# object. In this case, the first brick (brick1) is the first
# object drawn in the window, and the... | MrColwell/PythonProfessionalLearning | PythonForTeachers/StudentCode/Example6_BrickBreaker.py | Example6_BrickBreaker.py | py | 13,772 | python | en | code | 0 | github-code | 6 |
11137230909 | #!/usr/bin/python
''' Advent of code - Day 1: Chronal Calibration - Problem 1.2
https://adventofcode.com/2018/day/1#part2
'''
import os, sys
# Reading file
filename = 'input1.txt'
lines = []
input_file_path = "%s/%s" % (os.path.abspath(os.path.dirname(__file__)), filename)
try:
with open(input_file_path, 'r... | dvdantunes/adventofcode-2018 | day-01/day-01-02.py | day-01-02.py | py | 940 | python | en | code | 0 | github-code | 6 |
906797873 | import os
from gptwntranslator.helpers.config_helper import Config
from gptwntranslator.helpers.file_helper import write_md_as_epub
from gptwntranslator.helpers.text_helper import write_novel_md, parse_chapters
from gptwntranslator.helpers.ui_helper import print_title, wait_for_user_input
from gptwntranslator.storage.j... | combobulativedesigns/gptwntranslator | src/gptwntranslator/ui/page_novel_exporting.py | page_novel_exporting.py | py | 4,092 | python | en | code | 18 | github-code | 6 |
41559253356 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.action_chains import ActionChains as ... | cermen/SecondCompanyScraping | scrap.py | scrap.py | py | 8,973 | python | en | code | 0 | github-code | 6 |
4501146166 | import asyncio
import contextlib
import types
import unittest
import pytest
from lsst.ts import salobj, watcher
from lsst.ts.idl.enums.Watcher import AlarmSeverity
# Timeout for normal operations (seconds)
STD_TIMEOUT = 5
class GetRuleClassTestCase(unittest.TestCase):
"""Test `lsst.ts.watcher.get_rule_class`.""... | lsst-ts/ts_watcher | tests/test_model.py | test_model.py | py | 18,435 | python | en | code | 0 | github-code | 6 |
7323087980 | from __future__ import division
from collections import deque
class BiGramDict(object):
def __init__(self):
self.count = dict()
self.dictionary = dict()
def put(self, key, value):
if key not in self.dictionary:
self.count[key] = 0
self.dictionary[key] = dict()
if value not in self.dictionary[key]:
... | vigneshwerv/HMM | hmm.py | hmm.py | py | 4,436 | python | en | code | 0 | github-code | 6 |
38831039266 | # Module 5
# Programming Assignment 6
# Prob-2.py
# Esther Pisano
from graphics import *
def main():
# creating a label "win" for the graph that we wish to draw in.
# titled it "Squares"
win = GraphWin("Squares", 200, 200)
# created first rectangle
shape = Rectangle(Point(50, 50), Point... | CTEC-121-Spring-2020/mod-4-programming-assignment-EPisano526 | Prob-2/Prob-2.py | Prob-2.py | py | 1,215 | python | en | code | 0 | github-code | 6 |
2544504801 | import cv2
import numpy as np
###Color detection
def empty(a):
pass
def stackImages(scale,imgArray):
rows = len(imgArray)
cols = len(imgArray[0])
rowsAvailable = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvailable:
for x ... | monsterpit/openCVDemo | Resources/chapter7.py | chapter7.py | py | 3,458 | python | en | code | 0 | github-code | 6 |
19399743449 | from typing import List
import collections
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
q = collections.deque()
for i in range(1, n + 1):
q.append([i])
while q:
e = q.popleft()
if len(e) == k:
q.appendleft(e)
... | Yigang0622/LeetCode | combine.py | combine.py | py | 576 | python | en | code | 1 | github-code | 6 |
20521842050 | import time
from telapi import tas_api
from database import db
api_caller = tas_api(db.phone1.accountId, db.phone1.mailboxId)
api_callee = tas_api(db.phone2.accountId, db.phone2.mailboxId)
session_id, caller_party_id = api_caller.callout(db.phone1.deviceId, db.phone2.number)
callee_party_id = api_caller.get... | annoviko/sandbox | applications/telapi/scenario_pickup_outgoing.py | scenario_pickup_outgoing.py | py | 829 | python | en | code | 5 | github-code | 6 |
6017725196 | import re
re.findall(r'(\w+)=(\d+)', 'set width=20 and height=10')
# 查全部 没有为[], [('width', '20'), ('height', '10')]
def dashreplace(matchobj):
"""普通替换"""
if matchobj.group(0) == '-':
return ' '
else:
return ''
re.sub('-{1,4}', dashreplace, 'pro----gram-files')
# program files
def das... | Yuelioi/Program-Learning | Python/Basic/标准库/05.文本处理服务/_re.py | _re.py | py | 1,135 | python | en | code | 0 | github-code | 6 |
69986222269 | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model
class CustomUser(AbstractUser):
phone = models.CharField(max_length=13, blank=True, null=True)
bonus_coin = models.IntegerField(default=0)
class NameIt(models.Model):
name = mo... | Pdnky/MySite | FoodDelivery/core/models.py | models.py | py | 1,427 | python | en | code | 0 | github-code | 6 |
11120994067 | import logging
import typing as tp
from collections import deque
from librarius.domain.messages import (
AbstractMessage,
AbstractEvent,
AbstractCommand,
AbstractQuery,
)
from librarius.service.uow import AbstractUnitOfWork
from librarius.domain.exceptions import SkipMessage
logger = logging.getLogger(... | adriangabura/vega | librarius/service/message_bus.py | message_bus.py | py | 2,802 | python | en | code | 1 | github-code | 6 |
8213590960 | import numpy as np
from ..helpers import unify_tags, flatten_fillins
from .special_tokens import BLANK_TOK
def create_blanked_sents(doc, indexes=None):
if indexes:
if type(indexes[0]) == int:
indexes = [indexes]
indexes_list = indexes #[indexes]
else:
indexes_list = get_ran... | tongshuangwu/polyjuice | polyjuice/generations/create_blanks.py | create_blanks.py | py | 3,984 | python | en | code | 89 | github-code | 6 |
23091348874 | '''
Epidemic modelling
YOUR NAME
Functions for running a simple epidemiological simulation
'''
import random
import sys
import click
# This seed should be used for debugging purposes only! Do not refer
# to this variable in your code.
TEST_SEED = 20170217
def has_an_infected_neighbor(city, location):
'''
... | MaxSaint01/pa1 | sir.py | sir.py | py | 13,436 | python | en | code | 1 | github-code | 6 |
11324258537 | import pygame
from random import randint
from pygame.locals import *
pygame.init()
display_widht = 600
display_height = 360
spaceship_widht = 84
spaceship_height = 50
shots_x = []
shots_y = []
asteroids_x = []
asteroids_y = []
asteroids_type = []
gameDisplay = pygame.display.set_mode((display_widht, display_height... | macelai/star-wars | game.py | game.py | py | 3,439 | python | en | code | 0 | github-code | 6 |
22868194593 | import requests
from googletrans import Translator, LANGUAGES
import pickle
import webScraping
with open('Resources/API key/oxford.pck', 'rb') as file:
api_key = pickle.load(file)
app_id = api_key['app id']
app_key = api_key['app key']
url_base = 'https://od-api.oxforddictionaries.com/api/v2/'
la... | TroySigX/smartbot | dictionary.py | dictionary.py | py | 2,176 | python | en | code | 2 | github-code | 6 |
39263007416 | import datetime as datetime
import json
from django.db.models import Q
from django.test import override_settings
from mock import MagicMock, patch
from rest_framework.status import HTTP_403_FORBIDDEN, HTTP_201_CREATED
from eums.models import MultipleChoiceAnswer, TextAnswer, Flow, Run, \
NumericAnswer, Alert, Run... | unicefuganda/eums | eums/test/api/test_web_answers_end_point.py | test_web_answers_end_point.py | py | 18,674 | python | en | code | 9 | github-code | 6 |
38979909130 | from datetime import datetime, timedelta, timezone
import pytz
tokyo_tz = pytz.timezone('Asia/Tokyo')
# def delete_feed_with_too_many_entries(reader, db, url):
# entries = list(reader.get_entries())
# if len(entries) > 300:
# print("deleting feeds: ", url)
# reader.delete_feed(url)
# ... | kei49/rss-to-slack | src/feed.py | feed.py | py | 637 | python | en | code | 0 | github-code | 6 |
34891232871 | import todo
def main():
run = 1
todo.create_table()
while run:
print("\n")
print("1. Inser Task in todo list \n"
"2. View data from todo list \n"
"3. Delete task from todo list \n"
"4. Exit \n")
x = int(input("Choose any of t... | hrishikesh-godbole/Python_Daily | TODO App/my_todo.py | my_todo.py | py | 808 | python | en | code | 0 | github-code | 6 |
17321484534 | from uiplib.setWallpaper import change_background
import os
from uiplib.constants import CURR_DIR, PICS_FOLDER, WEBSITE, TIMEOUT
import random
import time
from uiplib.scrape import get_images
from threading import Thread
import sys
from select import select
try:
import msvcrt
except ImportError:
#not on windows... | teja-315/UIP | uiplib/scheduler.py | scheduler.py | py | 2,856 | python | en | code | null | github-code | 6 |
14362032569 | import math
infile = open("bank1.cc", "r")
outfile = open("bank2.cc", "w")
i=0
for line in infile:
i=i+1
if i==1:
val = 2
else:
val = int(math.log(i/2, 10) + 2)
line2 = line[val:]
outfile.write (line2)
| Skeletrox/Dump | zz.py | zz.py | py | 213 | python | en | code | 0 | github-code | 6 |
1466500793 | from dataclasses import dataclass, field
from src.shared.general_functions import sum_all_initialized_int_attributes
@dataclass
class ShareholdersEquity:
"""Shareholders' equity is the amount that the owners of a company have invested in their business. This includes
the money they've directly invested and t... | hakunaprojects/stock-investing | src/domain/financial_statements/balance_sheet_statement/shareholders_equity.py | shareholders_equity.py | py | 785 | python | en | code | 0 | github-code | 6 |
18959073144 | import boto3
import time
import json
import configparser
from botocore.exceptions import ClientError
redshift_client = boto3.client('redshift', region_name='ap-southeast-1')
ec2 = boto3.resource('ec2', region_name='ap-southeast-1')
def create_udacity_cluster(config):
"""Create an Amazon Redshift cluster
Args... | hieutdle/bachelor-thesis | airflow/scripts/create_cluster.py | create_cluster.py | py | 2,942 | python | en | code | 1 | github-code | 6 |
6371745337 | #!/usr/bin/python3
"""
this module defines the Pascal's Triangle function
"""
def pascal_triangle(n):
"""
this stands for the size(n) of pascal's Triangle
"""
if n <= 0:
return []
triangle = [[1]]
while len(triangle) != n:
th_triangle = triangle[-1]
new = [1]
f... | Laabk/alx-higher_level_programming | 0x0B-python-input_output/12-pascal_triangle.py | 12-pascal_triangle.py | py | 490 | python | en | code | 0 | github-code | 6 |
22164374876 | from .bayesianPwLinearRegression import BayesianPieceWiseLinearRegression
from .bayesianLinearRegression import BayesianLinearRegression
from .seqCoupledBayesianPwLinReg import SeqCoupledBayesianPieceWiseLinearRegression
from .globCoupBayesianPwLinReg import GlobCoupledBayesianPieceWiseLinearRegression
from .vvglobCoup... | charx7/DynamicBayesianNetworks | src/dyban/network.py | network.py | py | 19,868 | python | en | code | 16 | github-code | 6 |
45385920976 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
##### System wide lib #####
import sys
import os
import operator
from StringIO import StringIO
##### Theory lib #####
from theory.apps.command.baseCommand import SimpleCommand
from theory.gui import field
from theory.apps import apps
from theory.db.migrations import Migr... | grapemix/theory | theory/apps/command/makeMigration.py | makeMigration.py | py | 10,198 | python | en | code | 1 | github-code | 6 |
39680498179 | """ General functions for data_tables and data_table_manager
We are using a class here just to make it easier to pass around
"""
import logging
import pprint
import subprocess
from pathlib import Path
import re
from typing import Union
import matplotlib.pyplot as mpl
import numpy as np
import pandas as pd
from py... | marsiwiec/ephys | ephys/gui/data_table_functions.py | data_table_functions.py | py | 51,215 | python | en | code | null | github-code | 6 |
27001984731 |
import random
def structDataSampling(**kwargs):
"""
:param num:
:param struct:
:return:
"""
result = []
for index in range(0, kwargs['num']):
element = []
for key, value in kwargs['struct'].items():
if value['datatype'] == "int":
... | wanghan79/2023_Python | 2021013675 刘蓝营/work1/work1.py | work1.py | py | 2,428 | python | en | code | 8 | github-code | 6 |
1422010768 | #Dilation and Erosion
import cv2
import matplotlib.pyplot as plt
import numpy as np
#-----------------------------------Dilation------------------------------
# Reads in a binary image
img = cv2.imread('j.png',0)
# Create a 5x5 kernel of ones
Kernel = np.ones((5,5), np.uint8)
'''
To dilate an image in OpenCV, yo... | haderalim/Computer-Vision | Types of features and Image segmentation/Dilation- Erosion- Opeining and Closing/test.py | test.py | py | 2,245 | python | en | code | 1 | github-code | 6 |
7436815802 | from pathlib import Path
from zoneinfo import ZoneInfo
import datetime
import sys
TIME_ZONE = ZoneInfo('US/Eastern')
def main():
station_name = sys.argv[1]
dir_path = Path(sys.argv[2])
file_paths = sorted(dir_path.glob('*.WAV'))
for file_path in file_paths:
move_file(file_path... | HaroldMills/Vesper | scripts/organize_audiomoth_wav_files_by_night.py | organize_audiomoth_wav_files_by_night.py | py | 1,464 | python | en | code | 47 | github-code | 6 |
3929101533 | from sqlalchemy import Column, INTEGER, Identity, String
from src.data_access.database.models.base_entity import InoversityLibraryBase
__all__ = [
"StaffEntity"
]
class StaffEntity(InoversityLibraryBase):
user_id = Column("id", INTEGER, Identity(), primary_key=True, index=True)
role_level = Column("role... | mariusvrstr/PythonMicroservice | src/data_access/database/models/staff_entity.py | staff_entity.py | py | 582 | python | en | code | 0 | github-code | 6 |
16543455789 | from ai_chatbot.scripts import REDataHeader as Header
import dateparser
import datetime
def printData(data):
print('Station from : {0}'.format(data[Header.STATIONFROM]))
print('Station to : {0}'.format(data[Header.STATIONTO]))
print('departure date : {0}'.format(data[Header.DEPARTDATE]))
print('depart... | Grimmii/TrainChatBot | src/ai_chatbot/scripts/RE_function_booking.py | RE_function_booking.py | py | 2,542 | python | en | code | 0 | github-code | 6 |
38217506704 |
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.animation as animation
import matplotlib.patches as mpatches
from matplotlib import ticker
from matplotlib import cm
from matplotlib.ticker import FuncFormatter
import numpy as np
from utils.occ_map_utils import load_map, display_oc... | stomachacheGE/bofmp | tracking/animation.py | animation.py | py | 17,318 | python | en | code | 0 | github-code | 6 |
33359791664 | import sys
import unittest
import psycopg2
sys.path.insert(0, '../src')
from src.utils import daily_reports_return_json, daily_reports_return_csv, time_series_return_csv, check_query_data_active, check_request
from src.config import connect_database
# import copy
class TestUtils(unittest.TestCase):
def __init__... | shin19991207/CSC301-A2 | tests/test_utils.py | test_utils.py | py | 4,518 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.