Ejemplo n.º 1
0
        
    The graphqlclient module from python-graphql-client also needs to be in the path.
        
    To run against the tutorial1-server, start the server and run this file. 
    To run on swapi.graph.cool, uncomment the server_url and run. 
    
    To run the last two queries, uncomment them in the code. 
'''

from graphqlclient import GraphQLClient
from pprint import PrettyPrinter
import json

server_url = 'http://127.0.0.1:8051/'
#server_url = 'http://swapi.graph.cool/'
client = GraphQLClient(server_url)

# raw query dump from playground
query_meta_raw1 = '''{"operationName":"IntrospectionQuery","variables":{},"query":"query IntrospectionQuery {\n  __schema {\n    queryType {\n      name\n    }\n    mutationType {\n      name\n    }\n    subscriptionType {\n      name\n    }\n    types {\n      ...FullType\n    }\n    directives {\n      name\n      description\n      locations\n      args {\n        ...InputValue\n      }\n    }\n  }\n}\n\nfragment FullType on __Type {\n  kind\n  name\n  description\n  fields(includeDeprecated: true) {\n    name\n    description\n    args {\n      ...InputValue\n    }\n    type {\n      ...TypeRef\n    }\n    isDeprecated\n    deprecationReason\n  }\n  inputFields {\n    ...InputValue\n  }\n  interfaces {\n    ...TypeRef\n  }\n  enumValues(includeDeprecated: true) {\n    name\n    description\n    isDeprecated\n    deprecationReason\n  }\n  possibleTypes {\n    ...TypeRef\n  }\n}\n\nfragment InputValue on __InputValue {\n  name\n  description\n  type {\n    ...TypeRef\n  }\n  defaultValue\n}\n\nfragment TypeRef on __Type {\n  kind\n  name\n  ofType {\n    kind\n    name\n    ofType {\n      kind\n      name\n      ofType {\n        kind\n        name\n        ofType {\n          kind\n          name\n          ofType {\n            kind\n            name\n            ofType {\n              kind\n              name\n              ofType {\n                kind\n                name\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n"}'''
query_meta_raw1m = query_meta_raw1.replace(
    '\n', '\\n')  # modified so that can be sent to a server.

# a first query
# got: Query, String, __Schema, __Type, __TypeKind, Boolean,
#      __Field, __InputValue, __EnumValue, __Directive, __DirectiveLocation
query_meta_raw_ok1 = '''
{
    __schema {
        types {
            name
        }
import ssl
import json
from graphqlclient import GraphQLClient

# HACK: dirty to overcome certificate problems. DON'T USE IN PRODUCITON
ssl._create_default_https_context = ssl._create_unverified_context

URL = 'https://web-backend-dev.zeitgold.com/graphql'

client = GraphQLClient(URL)


def get_data():
    result = client.execute('''{
        business(id: "QnVzaW5lc3NOb2RlOjE0Mjc2Y2FhLTA4NmEtNGVmNi04NzMxLTNmYWUzMjE3ZjVlZQ==") {
            businessTransactions {
              edges {
                node {
                  payables {
                    edges {
                      node {
                        id
                        amount
                        referenceId
                        dateOccurred
                      }
                    }
                  }
                }
              }
            }
Ejemplo n.º 3
0
    def prepare_client(self):
        """If not defined, it prepares the GraphQL client."""

        if self.client == None:
            self.client = GraphQLClient(self.url)
            self.info("Connected to %s", self.url)
Ejemplo n.º 4
0
# coding: utf-8

# In[1]:

from graphqlclient import GraphQLClient
import os
import ujson
import sys
import time

# In[2]:

client = GraphQLClient('https://api.github.com/graphql')

# In[3]:

with open(os.path.expanduser("~/github_token"), 'r') as tokenfile:
    token = tokenfile.readlines()[0].strip()
    client.inject_token(token)

# In[4]:


def github_repos(query):
    SEARCH_RESULTS_LIMIT = 1000
    search_results = 0

    def gql(query_additions, start):
        print("querying...")
        sys.stdout.flush()
        response = ujson.loads(
Ejemplo n.º 5
0
    authToken = input(
        'Paste your api key or add your smash.gg API key in the .py file if you don\'t want to bother with it everytime.\n'
    )


class HorsIntervalle(Exception):
    pass


page = 1
perPage = 100
apiVersion = 'alpha'
liste = []
placements = []

client = GraphQLClient('https://api.smash.gg/gql/' + apiVersion)
client.inject_token('Bearer ' + authToken)

tournament = input(
    "Tournament? (part between smash.gg/tournament/ and the following /)\n")
query = '''
    query tournaments($slug: String) {
        tournament(slug:$slug) {
            events{
                id
                name
                videogame {
                    id
                    name
                }
                phases{
Ejemplo n.º 6
0
 def __init__(self, api_key):
     self.api_key = api_key
     self.client = GraphQLClient('https://api.monday.com/v2')
     self.client.inject_token(api_key)
Ejemplo n.º 7
0
from graphqlclient import GraphQLClient

client = GraphQLClient('https://ocap.arcblock.io/api/btc')

result = client.execute('''
{
  accountByAddress(address: "1F1tAaz5x1HUXrCNLbtMDqcw6o5GNn4xqX") {
    address
    balance
    pubKey
    scriptType
    subKeys
  }
}
''')

print(result)
Ejemplo n.º 8
0
from graphqlclient import GraphQLClient
import json

client = GraphQLClient('https://banku-synfour.herokuapp.com/v1alpha1/graphql')

def getLeaveStats(email):
	result = client.execute('''
	{
  		leavetrack(
    		where: {email: {_eq:"'''+email+'''"}}
  		){
    		hss01
    		min106
    		ecn203
    		csn221
    		csn291
    		csn261
  		}
	}

	''')
	# print(result)
	r = json.loads(result)
	return r['data']['leavetrack']

def getDaysInfo():
	result = client.execute('''
	{
  		daysinfo{
    		startsession
    		endsession
Ejemplo n.º 9
0
 def __init__(self, config):
     self.building_id = config["building_id"]
     self.client = GraphQLClient(config["API"]["host"])
     self._cache = None
def get_gh_issues(gh_api_token, repo_owner, repo_name, gh_cursor=None):
    client = GraphQLClient('https://api.github.com/graphql')
    client.inject_token(f'token {gh_api_token}')

    query = get_gh_query(repo_owner, repo_name, gh_cursor)    
    response = client.execute(query)
    json_response = json.loads(response)

    if json_response is None:
        logging.error(f'[ERROR] while getting issues for {repo_owner}/{repo_name}. Error: Not Found')
        return []
    if 'errors' in json_response:
        logging.error(f'[ERROR] while getting issues for {repo_owner}/{repo_name}. Error: {json_response}')
        return []
    
    issues = json_response['data']['repository']['issues']
    repository_owner_data = json_response['data']['repository']['owner']
    return_issues = []

    if issues['nodes']:
        for issue in issues['nodes']:
            return_issues.append({
                'repo_name': repo_name,
                'repo_owner_name': repository_owner_data['name'],
                'repo_owner_email': repository_owner_data['email'],
                'repo_owner_user_name': repository_owner_data['login'],
                'repo_owner_profile_url': repository_owner_data['url'],
                'title': issue['title'],
                'bodyHTML': issue['bodyHTML'],
                'url': issue['url'],
                'state': issue['state'],
                'createdAt': issue['createdAt'],
                'lastEditedAt': issue['lastEditedAt'],
                'publishedAt': issue['publishedAt'],
                'updatedAt': issue['updatedAt'],
                'labels': [node['name'] for node in issue['labels']['nodes']],
                'is_locked': issue['locked'],
                'total_participants': issue['participants']['totalCount'],
            })

        hasNext = issues['pageInfo']['hasNextPage']

        if hasNext:
            cursor = issues['pageInfo']['endCursor']
            remaining = json_response['data']['rateLimit']['remaining']
            limit = json_response['data']['rateLimit']['limit']
            reset_at = json_response['data']['rateLimit']['resetAt']

            percent_remaining = remaining / limit
            if percent_remaining < 0.15:
                reset_at = datetime.strptime(reset_at, '%Y-%m-%dT%H:%M:%SZ')
                current_time = datetime.now()
                time_diff = current_time - reset_at
                seconds = time_diff.total_seconds()
                time.sleep(seconds)
            else:
                time.sleep(2)
            
            return return_issues.extend(get_gh_issues(gh_api_token, repo_owner, repo_name, cursor))
        else:
            return return_issues
    else:
        logging.debug(f'No issues found for {repo_owner}/{repo_name}')
        return []
def upload(path):
    # Vlt kann man das hier noch etwas schoener laden!
    with open("/home/thahnen/GitHub/labelbox-scripts-etc/.api.key") as fd:
        key = fd.readline()

    # Connect to the Labelbox-Endpoint
    client = GraphQLClient("https://api.labelbox.com/graphql")
    client.inject_token(key)

    # Die JSON-Datei vorfinden und einlesen, sollte folgende Form haben:
    #
    # [
    #   {
    #       "frame_nr" : <Nr des Frames>
    #       "image_url" : "https://127.0.0.1:8000/<Name der Bilddatei>",
    #       "external_id" : "<Name der Bilddatei>"
    #       "prediction_label" : {
    #           object : [
    #               {
    #                   "label_id" : <Id vom NN vergeben>
    #                   "geometry" : [
    #                       {
    #                           "x" : "<X-Koord.>", "y" : "<Y-Koord.>"
    #                       }, ... (4 mal aber nur weil Rechteck, aber im Uhrzeigersinn!)
    #                   ]
    #               }, ...
    #           ]
    #       }
    #   }, ...
    # ]
    #
    json_path = os.path.join(path, "darkflow_parsed.json")
    if not os.path.exists(json_path):
        return 1

    data = []
    try:
        data = json.load(open(json_path))
    except Exception as e:
        return 2

    # TODO: For testing purposes, just use the first 150 images!
    data = data[:150]

    # User Information for the Organization Id!
    user_info = json.loads(
        client.execute("""
        query GetUserInformation {
            user {
                id
                organization {
                    id
                }
            }
        }
    """))["data"]["user"]
    org_id = user_info["organization"]["id"]

    # Get the folder name, usefull for the name of the dataset as well as the project
    #project_folder_name = path.split("/")[-2:][0].split("/")[0]
    #folder_name = path.split("/")[-1:].split("/")[0]

    # Based on this names build the project and its datasets name
    #project_dataset_name = f"DVS_F102 {project_folder_name} {folder_name}"
    project_dataset_name = "DVS_F102 TEST"

    # Every Project gets its own Dataset!
    # they use the data from the Darkflow-NNs!
    project_id = json.loads(
        client.execute(
            """
        mutation CreateProjectFromAPI($name: String!) {
            createProject(data: {
                name: $name
            }){
                id
            }
        }
    """, {'name': project_dataset_name}))['data']['createProject']['id']
    print(f"Created Project '{project_dataset_name}'")

    dataset_id = json.loads(
        client.execute(
            """
        mutation CreateDatasetFromAPI($name: String!) {
            createDataset(data: {
                name: $name
            }){
                id
            }
        }
    """, {'name': project_dataset_name}))['data']['createDataset']['id']
    print(f"Created Dataset '{project_dataset_name}'")

    # Set Interface for this specific project!
    # based on our own build Labeling-Interface-JSON!
    interface_id = json.loads(
        client.execute("""
        query GetImageLabelingInterfaceId {
            labelingFrontends(where: {
                iframeUrlPath: "https://image-segmentation-v4.labelbox.com"
            }){
                id
            }
        }
    """))['data']['labelingFrontends'][0]['id']

    labeling_interface = {
        "classifications": [],
        "tools": [{
            "tool":
            "rectangle",
            "name":
            "object",
            "color":
            "#F09300",
            "classifications": [{
                "name":
                "label-klasse",
                "instructions":
                "Label-Klasse",
                "type":
                "radio",
                "options": [{
                    "value": "person",
                    "label": "Person"
                }, {
                    "value": "personengruppe",
                    "label": "Personengruppe"
                }, {
                    "value": "fahrradfahrer",
                    "label": "Fahrradfahrer"
                }, {
                    "value": "anderes",
                    "label": "Anderes"
                }],
                "required":
                True
            }, {
                "name": "label_id",
                "instructions": "Label (id, id+id, id|id)",
                "type": "text",
                "options": [{
                    "value": "",
                    "label": ""
                }],
                "required": True
            }]
        }]
    }

    configure_interface_for_project(client, labeling_interface, project_id,
                                    interface_id, org_id)
    print("Interface added to project!")

    # Complete Setup of this specific project!
    completeSetupOfProject(client, project_id, dataset_id, interface_id)

    # Create Prediction
    prediction_model_id = create_prediction_model(client, "Darkflow", 1)
    attach_prediction_model_to_project(client, prediction_model_id, project_id)
    print(f"Created prediction {prediction_model_id}")

    # Because requests have been made!
    time.sleep(1)

    # Create and upload datarow!
    # But beware not to send more than 300 requests per minute!
    # So every request has an allowed timeframe of 60/300 = 0.2 sec
    # => every loop equals two requests -> 0.4 sec max duration for a loop.
    amount_uploads = 0
    time_allowed = 0.4
    for elem in data:
        try:
            begin = time.time()

            data_row_id = create_datarow(client, elem["image_url"],
                                         elem["external_id"], dataset_id)
            print(f"Created DataRow : {data_row_id}")

            prediction_id = create_prediction(
                client, json.dumps(elem["prediction_label"]),
                prediction_model_id, project_id, data_row_id)
            print(f"Created Prediction: {prediction_id}")

            duration = time.time() - begin
            if (duration < time_allowed):
                time.sleep(
                    (time_allowed - duration) * 1.05
                )  # waits to not get over the allowed amount of request
        except Exception as e:
            print(e)
            print(
                "Handle it by yourself, maybe delete the whole project/ dataset!"
            )
            return 3

    print(
        f"Everything went fine: https://app.labelbox.com/projects/{project_id}/overview !"
    )
Ejemplo n.º 12
0
n_runs = 100

endpoints = [
    'http://localhost:4201/graphql', 'http://localhost:4202/graphql',
    'http://localhost:4204/graphql', 'http://localhost:4208/graphql',
    'http://localhost:4216/graphql'
]

#endpoints = ['http://localhost:4201/graphql', 'http://localhost:4202/graphql']

information = {}

for endpoint in endpoints:

    client = GraphQLClient(endpoint)

    information[endpoint] = {}

    for q in querys:

        start = time.time()

        for i in range(n_runs):

            client.execute(q["query"])

        delta = time.time() - start

        print(q["name"])
        print(delta)
Ejemplo n.º 13
0
    # ヘッダやパスを指定する
    mqtt_client.ws_set_options(path=f'{urlparts.path}?{urlparts.query}',
                               headers=headers)

    # TLSを有効にする
    mqtt_client.tls_set()

    # wssで接続するため、443ポートに投げる
    mqtt_client.connect(urlparts.netloc, port=443)

    # 受信するのを待つ
    mqtt_client.loop_forever()


if __name__ == '__main__':
    c = GraphQLClient(API_URL)
    c.inject_token(API_KEY, 'X-Api-Key')

    # 登録する
    execute_mutation_api(c, 'ham', 'spam')

    # 登録した情報を取得する
    execute_query_api(c)

    # DynamoDBが更新された時の通知を1回だけ受け取る
    # Subscription API用のGraphQL (onCreate系)
    create_subscription = """
        subscription {
            onCreateAppSyncToDo {
                title
                content
Ejemplo n.º 14
0
#print(querys)

information = {}

results = []

csv = ""

csv2 = ""

n_runs = 5

for endpoint in endpoints:

    client = GraphQLClient(endpoint["url"])

    information[endpoint["name"]] = []

    for q in querys:

        print("Running " + str(q["name"]) + " on " + str(endpoint["url"]) +
              ": [",
              end="")

        start = time.time()

        for v_id in q["values"][endpoint["name"]]:

            v_q = q["query"].replace("$$id$$", str(v_id))
Ejemplo n.º 15
0
def download_query(url, query):
    client = GraphQLClient(url)
    return decoder.decode(client.execute(query))
Ejemplo n.º 16
0
def get_user_winrate(user_id):
    authToken = ""
    apiVersion = "alpha"

    client = GraphQLClient('https://api.smash.gg/gql/' + apiVersion)
    client.inject_token('Bearer ' + authToken)

    result = client.execute(
        """query MatchQuery ($user_id: ID){
    user(id: $user_id){
        player{
            gamerTag
            sets(page: 1, perPage: 100){
            nodes{
                displayScore
            }
            }
        }
    }
    },
    """, {"user_id": user_id})

    resData = json.loads(result)
    if 'errors' in resData:
        print('Error:')
        print(resData['errors'])

    tag = resData['data']['user']['player']['gamerTag']
    last_tag_word = tag.split()[-1]
    matches = resData['data']['user']['player']['sets']['nodes']
    win = 0
    loss = 0
    if (not matches):
        return -1
    for curr_set in matches:
        curr_match = curr_set['displayScore']
        if curr_match != "DQ" and curr_match:
            data = curr_match.split()
            if check_valid_display_score(curr_match):
                your_score = -1
                opp_score = 0
                scores = []
                scores.append(int(curr_match[curr_match.index(' - ') - 1]))
                scores.append(int(curr_match[-1]))
                if (data[-2] == last_tag_word):
                    your_score = scores[1]
                    opp_score = scores[0]
                else:
                    your_score = scores[0]
                    opp_score = scores[1]

                if (your_score > opp_score):
                    win += 1
                else:
                    loss += 1
    if win + loss == 0:
        winrate = -1
    else:
        winrate = win / (win + loss)
    print("Winrate of " + tag + ": " + str(winrate))
    print("(", win, "/", (win + loss), ")")
    return winrate
Ejemplo n.º 17
0
from graphqlclient import GraphQLClient
import json
import time
from .pulse import Pulse
from .board import Board
from .exceptions import *

client = GraphQLClient('https://api.monday.com/v2')


class Monday(object):
    api_key = ""
    prod_board_id = 0
    boards = {}
    pulses = {}
    client = None

    def __init__(self, api_key):
        self.api_key = api_key
        self.client = GraphQLClient('https://api.monday.com/v2')
        self.client.inject_token(api_key)

    def query(self, ql, no=0):
        result = self.client.execute(ql)
        x = lambda: None
        x.__dict__ = json.loads(result)
        try:
            return x.data
        except AttributeError:
            # this could happen if we have either too complex query, or exceeded timeframe, try again with second delay
            if "exceeds max complexity" in x.errors[0]['message']:
Ejemplo n.º 18
0
from flask import Flask, request, jsonify
import json
from waitress import serve
from graphqlclient import GraphQLClient
import os

app = Flask(__name__)

PORT = 8080

graphqlClient = GraphQLClient(os.environ['HASURA_GRAPHQL_URL'])
graphqlClient.inject_token(os.environ['HASURA_GRAPHQL_ADMIN_SECRET'],
                           'x-hasura-admin-secret')

notifications_insert_mutation = '''
mutation insert_notifications($objects: [notifications_insert_input!]! ) {
    insert_notifications(
        objects:$objects
    ) {
        returning {
            id
            user_id
        }
    }
}
'''


def get_problem_query(problem_id):
    problems_query = '''
                        {
Ejemplo n.º 19
0
from flask import Flask, render_template, Response, request
from graphqlclient import GraphQLClient
from bs4 import BeautifulSoup
import json, datetime, os, requests, re, difflib

app = Flask(__name__)
app.static_folder = 'static'

COUNTER = 318782

client = GraphQLClient(
    'https://api-eu-central-1.graphcms.com/v2/ckgi1a7duu2pu01xp02w993pr/master'
)
client.inject_token('Bearer ' + os.environ.get("GRAPHCMS_AUTH"))

basic_routes = {
    "/kancelaria": ["office", "kancelaria"],
    "/cmentarz": ["cementary", "cmentarz"],
    "/msze-swiete": ["mass", "msze"],
    "/sakramenty": ["sacraments", "sakramenty"],
    "/kaplani": ["priests", "kaplani"],
    "/informacje": ["info", "informacje"],
    "/ministranci": ["acolyte", "ministranci"],
    "/najswietsze-serce-jezusa": ["nsj", "nsj"],
    "/polecane-strony": ["pages", "strony"],
    "/galeria": ["galery", "galeria"],
    "/wspolnoty-parafialne": ["groups", "wspolnoty"]
}

invalid_search_res = {
    "title": "Nie znaleziono danej frazy.",
Ejemplo n.º 20
0
def upload_server(filename, timestr, gps_info, serialNo):
    global lastLatLon
    global failed
    with open('/home/pi/scripts/photos/' + filename, 'rb') as f:
        data = f.read()
        base64 = data.encode('base64')

        client = GraphQLClient(GRAPHQL_URL)
        result = None

        if lastLatLon is None:
            lastLatLon = (35.657995, 139.727666)

        if gps_info != {}:
            if gps_info.viewkeys() >= {'lon', 'lat', 'alt', 'track'}:
                try:
                    query = 'mutation{CamCreatePhoto(input: {imageFile: \"\"\"' + \
                        base64 + '\"\"\", longitude: ' + \
                        str(gps_info['lon']) + ', latitude: ' + \
                        str(gps_info['lat']) + ', deviceSerial: \"' + serialNo + '\", altitude: ' + \
                        str(gps_info['alt']) + ', bearing: ' + \
                        str(gps_info['track']) + '})}'
                    result = client.execute(query)
                except urllib2.URLError as err:
                    print err.reason
                    logger.error(err.reason)
                    if err.reason.strerror == 'nodename nor servname provided, or not known':
                        failed.append(query)
                        pass
                    elif err.reason.message == 'timed out':
                        failed.append(query)
                        pass
                    elif err.reason.errno == 51:
                        failed.append(query)
                        pass
                    else:
                        failed.append(query)
                        pass
                if result is not None:
                    print result
                    logger.info(result)
        else:
            try:
                query = "mutation{CamCreatePhoto(input: {imageFile: \"\"\"" + \
                    base64 + "\"\"\",  latitude: " + \
                    str(lastLatLon[0]) + ", longitude: " + \
                    str(lastLatLon[1]) + \
                    ", deviceSerial: \'" + serialNo + "\'})}"
                result = client.execute(query)
            except urllib2.URLError as err:
                print err.reason
                logger.error(err.reason)
                if err.reason.strerror == 'nodename nor servername provided, or not known':
                    failed.append(query)
                    pass
                elif err.reason.message == 'timed out':
                    failed.append(query)
                    pass
                elif err.reason.errno == 51:
                    failed.append(query)
                    pass
                else:
                    failed.append(query)
                    pass
            if result is not None:
                print result
                logger.debug(result)
        r.set("lastLat", lastLatLon[0])
        r.set("lastLon", lastLatLon[1])
Ejemplo n.º 21
0
from graphqlclient import GraphQLClient
from flask import Flask, abort, request, render_template
from uuid import uuid4
import requests
import requests.auth
import urllib
import string
import random
import sys
import os
import json

client = GraphQLClient(
    'https://api.graph.cool/simple/v1/cj5u5gfmajiig0123trm8ibro')
app = Flask(__name__)


def get_all_posts():
    gql_file = open('src/__generated__/appQuery.graphql')
    query = gql_file.read()
    gql_file.close()

    result = client.execute(query)
    parsed_result = json.loads(result)
    posts = parsed_result['data']['allPosts']
    return posts


def create_post(title, content, tag):
    result = client.execute('''
    mutation {
Ejemplo n.º 22
0
import requests
import re
import json
from graphqlclient import GraphQLClient

client = GraphQLClient('https://riley-hasura-test.herokuapp.com/v1/graphql')

response = requests.get(
    'https://www.mountainproject.com/data/get-routes-for-lat-lon?lat=44.366803&lon=%20-121.140765&maxDistance=10&minDiff=5.10&maxDiff=5.12&key=111896882-73c802f3b0ee5993f90fbf10bb77d49f'
)


def get_areas():
    result = client.execute('''
    query Areas {
      area {
        id
        name
      }
    }
    ''')
    return json.loads(result)['data']['area']


def insert_route(name, lat, lng, grade, type, area_id):
    if area_id:
        result = client.execute('''
        mutation InsertRoute {
          insert_route(objects: {name: "%s", location: "(%s, %s)", grade: "%s", type: %s, area_id: "%s"}) {
            returning {
              id
Ejemplo n.º 23
0
import asyncio

from graphqlclient import GraphQLClient

gc = GraphQLClient("ws://domain:<port>/graphql")
query = """
{
  students{
    id
    name
    age

  }
}
"""
# resp = gc.execute(query)
# print(resp)

sub = """
subscription {
  teacher{
    mutation
    updatedFields
    node{
      id
      name
      age
    }
  }
}
"""
Ejemplo n.º 24
0
import os

from graphqlclient import GraphQLClient
from dotenv import load_dotenv

if __name__ == '__main__':
    load_dotenv()

    client = GraphQLClient(os.getenv('GRAPHQL_ENDPOINT'))
    client.inject_token('Bearer {}'.format(os.getenv('GRAPHQ_AUTH_TOKEN')))

    result = client.execute("""
    {
        user {
            environmentId
        }
    }
    """)

    print(result)
Ejemplo n.º 25
0
 def __init__(self):
     self._graphQLEndpoint = ''
     self._client = GraphQLClient(self._graphQLEndpoint)
     self._client.inject_token('')
Ejemplo n.º 26
0
# time
last_time_checked_4chan = 0
last_time_checked_twitter = 0

# log_file
charts_path = BASE_PATH + 'log_files/chart_bot/'

locale.setlocale(locale.LC_ALL, 'en_US')

# web3
infura_url = os.environ.get('INFURA_URL')
pprint.pprint(infura_url)
w3 = Web3(Web3.HTTPProvider(infura_url))
uni_wrapper = Uniswap(web3=w3)

graphql_client_uni = GraphQLClient(
    'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2')
graphql_client_eth = GraphQLClient(
    'https://api.thegraph.com/subgraphs/name/blocklytics/ethereum-blocks')

re_4chan = re.compile(r'\$BOOB|BOOB')
TELEGRAM_KEY = os.environ.get('BOO_TELEGRAM_KEY')
MEME_GIT_REPO = os.environ.get('BOO_MEME_GIT_REPO')
MEME_PWD = os.environ.get('BOO_MEME_GIT_REPO_DELETE_PWD')
TMP_FOLDER = BASE_PATH + 'tmp/'
boob_contract = "0xa9c44135b3a87e0688c41cf8c27939a22dd437c9"
name = "Boo Bank"
ticker = 'BOOB'
ecto_contract = "0x921c87490ccbef90a3b0fc1951bd9064f7220af6"
ecto_name = "Ectoplasma"
ecto_ticker = 'ECTO'
pair_contract = "0x6e31ef0b62a8abe30d80d35476ca78897dffa769"
Ejemplo n.º 27
0
import json
from participant import Participant
from graphqlclient import GraphQLClient

client = GraphQLClient('https://api.smash.gg/gql/alpha')

# SmashGG token taken from ggtoken.dat file
with open('ggtoken.dat') as TokenFile:
    TOKEN = TokenFile.read()

client.inject_token('Bearer ' + TOKEN)


def tournamentPlacements(topcutIn, slugIn):
    '''
  Returns a list of topcut player objects of the participant class
  '''

    # Variables to figure out what is actually being found
    topcut = topcutIn
    slug = slugIn

    # Find top (x) players names, profile pictures, and placements based on event slug
    result = client.execute(
        '''
  query EventStandings($slug: String!, $page: Int!, $perPage: Int!) {
    event(slug: $slug) {
      name
      standings(query: {
        perPage: $perPage,
        page: $page
Ejemplo n.º 28
0
     symbol
    }
    token1 {
     symbol
    }
    reserve0
    reserve1
  }
}
'''
    res_eth_query = graphql_client_uni.execute(query)
    json_resp_eth = json.loads(res_eth_query)
    pprint(json_resp_eth)


if __name__ == '__main__':
    pair = "0x6e31ef0b62a8abe30d80d35476ca78897dffa769"
    graphql_client = GraphQLClient('https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2')
    test(graphql_client)
    # res = get_latest_actions(pair, graphql_client)
    # parsed_swaps = parse_swaps(res)
    # parsed_swaps_sorted = sorted(parsed_swaps, key=lambda x: x.timestamp, reverse=True)
    # parsed_mints = parse_mint(res)
    # parsed_burns = parse_burns(res)
    # all_actions = parsed_burns + parsed_mints + parsed_swaps
    # all_actions_sorted = sorted(all_actions, key=lambda x: x.timestamp, reverse=True)
    # all_actions_light = all_actions_sorted[0:10]
    # strings = list(map(lambda x: x.to_string(), all_actions_light))
    # string = '\n'.join(strings)
    # print(string)
Ejemplo n.º 29
0
def gql_client() -> GraphQLClient:
    client = GraphQLClient('https://api.graph.cool/simple/v1/swapi')
    # Add api token if needed
    # client.inject_token()
    return client
Ejemplo n.º 30
0
import torch.nn as nn
from pascal_voc_writer import Writer
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import numpy as np
import cv2
if torch.cuda.is_available():
    torch.set_default_tensor_type('torch.cuda.FloatTensor')

from ssd import build_ssd

# In[193]:

import json
from graphqlclient import GraphQLClient
client = GraphQLClient('https://api.labelbox.com/graphql')
client.inject_token(
    'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJjanVvMG9kOHUzMmV4MDgxNzRxMW8za2ZtIiwib3JnYW5pemF0aW9uSWQiOiJjanVvMG9kOGM0MmVpMDg3MXc1bWJvcjUxIiwiYXBpS2V5SWQiOiJjanVwZGkyOWt3N2hzMDg3MTZ3dTh6ZW1kIiwiaWF0IjoxNTU1NzU2OTIwLCJleHAiOjIxODY5MDg5MjB9._m24Q4hVQKIJZVi61-y7bqw5iX1he37zSca1VmW027g'
)


def me():
    res_str = client.execute("""
    query GetUserInformation {
      user {
        id
        organization{
          id
        }
      }
    }