Exemplo n.º 1
0
def listen():
    k_adi = getpass.getuser()
    if os.name == "nt":
        path = "C:\\Users\\%s\\Desktop\\" % (str(k_adi))
    else:
        if k_adi != "root":
            try:
                os.chdir("/home/" + k_adi + "/Masaüstü/")
                path = "/home/" + k_adi + "/Masaüstü/"
            except OSError:
                os.chdir("/home/" + k_adi + "/Desktop/")
                path = "/home/" + k_adi + "/Desktop/"

        else:
            try:
                os.chdir("/root/Masaüstü/")
                path = "/root/Masaüstü/"
            except OSError:
                os.chdir("/root/Desktop/")
                path = "/root/Desktop/"

    file = open(path + "musics.txt", "a")
    print "[+] Dosya, '%s' dizinine açıldı.\n" % (path + "musics.txt")
    while True:
        try:
            if "youtube" in xerox.paste() and "watch" in xerox.paste():
                url = xerox.paste()
                file.write(url + "\n")
                xerox.copy("Tamamdir")
                print "[>] Dosyaya yazılan: %s" % (url)
            else:
                pass
        except KeyboardInterrupt:
            print "\n[!] CTRL+C algılandı, çıkılıyor..."
            sys.exit(0)
Exemplo n.º 2
0
def main(cmd, *args):
    keeper = Keeper('safe.db')
    master_password = getpass('Master password: '******'password incorrect')
        return
    if cmd == 'new':
        account = input('Account: ')
        password = crypt.random_password()
        set_password(keeper, key, account, password)
        xerox.copy(password)
        print('\ncopied to clipboard')
    elif cmd == 'get':
        account = input('Account: ')
        if account not in keeper['accounts']:
            print('no account found')
            return
        password = get_password(keeper, key, account)
        xerox.copy(password)
        print('\ncopied to clipboard')
    elif cmd == 'set':
        account = input('Account: ')
        password = getpass('Password: '******'list':
        print('')
        for account in keeper['accounts']:
            print(account)
    elif cmd == 'help':
        help()
Exemplo n.º 3
0
def set_clipboard(text, datatype=None):
    """
    Arg datatype currently not used. Will generally assumed to be unicode text.
    From http://stackoverflow.com/questions/579687/how-do-i-copy-a-string-to-the-clipboard-on-windows-using-python
    """
    if 'xerox' in list(sys.modules.keys()):
        xerox.copy(text)
    elif 'pyperclip' in list(sys.modules.keys()):
        pyperclip.copy(text)
    elif 'gtk' in list(sys.modules.keys()):
        clipboard = gtk.clipboard_get()
        text = clipboard.set_text(text)
    elif 'win32clipboard' in list(sys.modules.keys()):
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        # SetClipboardData Usage:
        # >>> SetClipboardData(<type>, <data>)
        win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT,
                                        str(text))
        win32clipboard.CloseClipboard(
        )  # User cannot use clipboard until it is closed.
    else:
        # If code is run from within e.g. an ipython qt console, invoking Tk root's mainloop() may hang the console.
        r = Tk()
        # r.withdraw()
        r.clipboard_clear()
        r.clipboard_append(text)
        r.mainloop()  # the Tk root's mainloop() must be invoked.
        r.destroy()
Exemplo n.º 4
0
 def test_copy_xsel(self):
     if not sys.platform.startswith('linux'):
         return
     xerox.copy(self.text, xsel=True)
     # Check that we can copy from the clipboard and the X selection
     self.assertEqual(xerox.paste(), self.text)
     self.assertEqual(xerox.paste(xsel=True), self.text)
Exemplo n.º 5
0
Arquivo: get.py Projeto: snark/pink
def action(args):
    # TODO Handle STDOUT on get
    keyword = args.keyword
    namespace = args.namespace
    conn = util.connect_database()
    if not conn:
        exit('Unable to access %s; exiting' % util.DB_LOCATION)

    clippings = util.get_clippings(
        conn,
        key=keyword,
        namespace=namespace
    )

    msg = value = None
    if len(clippings) == 0:  # Key not found
        if namespace:
            msg = "Unknown namespace/key: %s/%s" % (namespace, keyword)
        else:
            msg = "Unknown key: %s" % keyword
    elif len(clippings) == 1:
        value = clippings[0][1]
        msg = "Set clipboard to %s" % value
        xerox.copy(value)
    else:
        msg = 'Multiple choices:\n' + '\n'.join(
            ["\t%s/%s: %s" % (c[0], keyword, c[1]) for c in clippings]
        )

    return msg
Exemplo n.º 6
0
def emoji_search(args):

    words = args['query']
    to_print = u''

    for search in words:
        exact_search = ':' + search + ':'
        exact = False
        for key in emojiCodeDict.keys():
            if exact_search == key:
                if to_print:
                    to_print = to_print + ' ' + emojiCodeDict[key]
                else:
                    to_print = emojiCodeDict[key]
                exact = True
                break
        if exact:
            continue
        for key in emojiCodeDict.keys():
            if search in key:
                if to_print:
                    to_print = to_print + ' ' + emojiCodeDict[key]
                else:
                    to_print = emojiCodeDict[key]
                break

    print(to_print)
    if args['copy']:
        xerox.copy(to_print)
Exemplo n.º 7
0
def main():
    parser = optparse.OptionParser()
    using_help = '''
    the service that you want to use. For example: gist for Github's Gist,
    pastebin for PasteBin.com
    '''
    parser.add_option('-u', '--using', dest='using',
                      help=using_help)

    (options, args) = parser.parse_args()

    using = options.using
    if not using:
        using = 'pastebin'

    obj = SharePastesFactory.create(using)
    try:
        url = obj.api_call(xerox.paste())
        xerox.copy(url)
    except xerox.base.XclipNotFound:
        print 'xclip not found. Install xclip for SharePastes to work.'
        sys.exit(1)

    try:
        from pync import Notifier
        Notifier.notify('URL added to your clipboard %s.' % url,
                        title='SharePastes')
    except:
        pass
Exemplo n.º 8
0
def set_clipboard(text, datatype=None):
    """
    Arg datatype currently not used. (This can be used to get e.g. an image from clipboard instead of text.)
    For now, this is generally assumed to be unicode text.
    From http://stackoverflow.com/questions/579687/how-do-i-copy-a-string-to-the-clipboard-on-windows-using-python
    """
    if 'xerox' in sys.modules.keys():
        xerox.copy(text)
    elif 'pyperclip' in sys.modules.keys():
        pyperclip.copy(text)
    elif 'gtk' in sys.modules.keys():
        clipboard = gtk.clipboard_get()
        text = clipboard.set_text(text)
    elif 'win32clipboard' in sys.modules.keys():
        wcb = win32clipboard
        wcb.OpenClipboard()
        wcb.EmptyClipboard()
        # wcb.SetClipboardText(text)  # doesn't work
        # SetClipboardData Usage:
        # >>> wcb.SetClipboardData(<type>, <data>)
        # wcb.SetClipboardData(wcb.CF_TEXT, text.encode('utf-8')) # doesn't work
        wcb.SetClipboardData(wcb.CF_UNICODETEXT, unicode(text)) # works
        wcb.CloseClipboard() # User cannot use clipboard until it is closed.
    else:
        # If code is run from within e.g. an ipython qt console, invoking Tk root's mainloop() may hang the console.
        tkroot = Tk()
        # r.withdraw()
        tkroot.clipboard_clear()
        tkroot.clipboard_append(text)
        tkroot.mainloop() # the Tk root's mainloop() must be invoked.
        tkroot.destroy()
Exemplo n.º 9
0
def create(checklist, output_format, output, clipboard, overwrite):
    # load checklist
    cl_path = Path(checklist) if checklist else DEFAULT_CHECKLIST
    cl = Checklist.read(cl_path)

    output = Path(output) if output else None

    # output extension is given priority if differing format is included
    if output:
        # get format by file extension
        ext = output.suffix.lower()
        if ext in EXTENSIONS.keys():
            output_format = EXTENSIONS[ext]
        else:
            raise ExtensionException(ext)
    elif output_format:
        if output_format not in FORMATS:
            raise FormatException(output_format)
    else:
        output_format = 'markdown'

    template = FORMATS[output_format](cl)

    # write output or print to stdout
    if output:
        template.write(output, overwrite=overwrite)
    elif clipboard:
        xerox.copy(str(template.render()))
    else:
        return template.render()
Exemplo n.º 10
0
def set_clipboard(text, datatype=None):
    """
    Arg datatype currently not used. Will generally assumed to be unicode text.
    From http://stackoverflow.com/questions/579687/how-do-i-copy-a-string-to-the-clipboard-on-windows-using-python
    """
    if 'xerox' in sys.modules.keys():
        xerox.copy(text)
    elif 'pyperclip' in sys.modules.keys():
        pyperclip.copy(text)
    elif 'gtk' in sys.modules.keys():
        clipboard = gtk.clipboard_get()
        text = clipboard.set_text(text)
    elif 'win32clipboard' in sys.modules.keys():
        wcb = win32clipboard
        wcb.OpenClipboard()
        wcb.EmptyClipboard()
        # wcb.SetClipboardText(text)  # doesn't work
        # SetClipboardData Usage:
        # >>> wcb.SetClipboardData(<type>, <data>)
        # wcb.SetClipboardData(wcb.CF_TEXT, text.encode('utf-8')) # doesn't work
        wcb.SetClipboardData(wcb.CF_UNICODETEXT, unicode(text)) # works
        wcb.CloseClipboard() # User cannot use clipboard until it is closed.
    else:
        # If code is run from within e.g. an ipython qt console, invoking Tk root's mainloop() may hang the console.
        r = Tk()
        # r.withdraw()
        r.clipboard_clear()
        r.clipboard_append(text)
        r.mainloop() # the Tk root's mainloop() must be invoked.
        r.destroy()
Exemplo n.º 11
0
def echo_support():

    data = {}
    data['cli'] = {}
    data['compiler'] = {}
    data['python'] = {}
    data['app'] = {}
    data['context'] = {}

    data['cli']['version'] = version
    data['cli']['path'] = os.path.dirname(__file__)
    data['compiler']['version'] = compiler_version
    data['compiler']['path'] = os.path.dirname(storyscript.__file__)
    data['python']['path'] = sys.executable
    data['python']['version'] = sys.version.split()[0]
    data['app']['name'] = get_app_name_from_yml()
    data['app']['story.yml'] = get_asyncy_yaml(must_exist=False)
    data['app']['story.yml_path'] = find_story_yml()
    data['context']['cwd'] = os.getcwd()
    data['context']['environ_keys'] = [k for k in os.environ.keys()]
    data['context']['argv'] = sys.argv

    report = json.dumps(data, indent=4)
    click.echo(report)

    # Copy the report to the clipboard!
    try:
        xerox.copy(report)
        click.echo(click.style('Copied to clipboard!', fg='red', bold=True))
    except Exception:
        pass
Exemplo n.º 12
0
def parse(return_output=True, file_path=None):
    if not file_path:
        try:
            file_path = sys.argv[1]
        except IndexError:
            # assume `email.html`
            file_path = 'email.html'

    # check file exists
    if not exists(file_path):
        raise IOError('File does not exist')

    # check extension and mimetype
    filename, ext = splitext(file_path)
    mime_type = MimeTypes().guess_type(file_path)[0]
    if ext.lower() not in ['.htm', '.html'] or mime_type != 'text/html':
        raise Exception('File does not appear to be an HTML file.')

    # process file
    with open(file_path, 'r') as html_file:
        data = html_file.read()

        # extract body
        soup = BeautifulSoup(data, 'html.parser')
        body = soup.body.contents[1]

        # strip comments
        [
            comment.extract() for comment in body.findAll(
                text=lambda text: isinstance(text, Comment))
        ]

        # replace image tags with the name of the image
        body_soup = BeautifulSoup(str(body), 'html.parser')
        for img in body_soup.findAll('img'):
            img.replace_with(img['name'])

        # add trouble link row
        trouble_row = body_soup.new_tag('tr')
        trouble_column = body_soup.new_tag('td')
        trouble_column.string = 'trouble'
        trouble_row.append(trouble_column)
        body_soup.tr.insert_before(trouble_row)

        # add inline css to each td
        for td in body_soup.find_all('td'):
            td['style'] = 'text-align: left; vertical-align: top;'

        # right align trouble link text
        body_soup.tr.td['style'] = 'text-align: right; vertical-align: top;'

        output = unicode(body_soup)

        # copy HTML to clipboard FTW
        xerox.copy(output)
        sys.stdout.write('HTML copied to clipboard' + '\n')

        if return_output:
            return output
Exemplo n.º 13
0
def main():
    curl_input = xerox.paste()
    print("Input: -----")
    print(curl_input)
    print("-----\n\n")
    context = uncurl.parse_context(curl_input)
    request_data = json.loads(context.data)
    url = urlparse(context.url)
    query_params = get_query_dict(url.query)
    cookie_string = ";".join(f"{key}={value}"
                             for key, value in context.cookies.items())
    postman_collection = {
        "info": {
            "name":
            request_data["operationName"],
            "schema":
            "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
        },
        "item": [{
            "name": request_data["operationName"],
            "request": {
                "method": "POST",
                "header": [],
                "body": {
                    "mode": "graphql",
                    "graphql": {
                        "query": request_data["query"],
                        "variables": json.dumps(request_data["variables"]),
                    },
                },
                "url": {
                    "raw":
                    context.url,
                    "protocol":
                    url.scheme,
                    "host": [url.hostname],
                    "port":
                    url.port,
                    "path":
                    url.path.split("/"),
                    "query": [{
                        "key": key,
                        "value": value
                    } for key, value in query_params.items()],
                },
            },
            "response": [],
        }],
        "protocolProfileBehavior": {},
    }
    result = json.dumps(postman_collection)
    print("----- Postman Collection ----")
    print(result)
    print("---- Headers -----")
    for key, value in context.headers.items():
        print(f"{key}:{value}")
    print(f"Cookie:{cookie_string}")
    print("-----")
    xerox.copy(result)
Exemplo n.º 14
0
    def set_clipboard(self, text=None):
        if text == None:
            text = ''

        if DROID:
            droid.setClipboard(text)
        else:
            xerox.copy(text)
Exemplo n.º 15
0
def main():
  args = parse_args()

  tab = not args.spaces
  code = add_indentation(get_code(args), tab)
  
  if args.stdout: print code
  else: xerox.copy(code)
Exemplo n.º 16
0
def convert_zalgo(text, intensity=50, copy=False):
    input_text = u' '.join(text)
    zalgotext = zalgo.zalgo(input_text, intensity)

    if copy:
       xerox.copy(u'' + zalgotext)

    return zalgotext
Exemplo n.º 17
0
def convert_zalgo(text, intensity=50, copy=False):
    input_text = u' '.join(text)
    zalgotext = zalgo.zalgo(input_text, intensity)

    if copy:
        xerox.copy(u'' + zalgotext)

    return zalgotext
Exemplo n.º 18
0
def callback(event):
    # moved to a name with Screen Shot in it
    if event.mask is 128 and file_str in str(event.name):
        # split the extension
        fileExtension = os.path.splitext(event.name)[1]
        newName = str(hash_for_file(event.name))[0:6] + fileExtension
        upload_file(event.name, scp_path + newName)
        xerox.copy(protocol + hostname + web_path + newName)
Exemplo n.º 19
0
    def test_copy_and_paste(self):
        # copy
        self.assertIsInstance(self.text, str)
        xerox.copy(self.text)

        # paste
        got = xerox.paste()
        self.assertIsInstance(got, str)
        self.assertEqual(got, self.text)
Exemplo n.º 20
0
 def paste_formatted_text(self, font_type):
     """
     Paste the currently selected text in the clipboard with the input font type
     :param font_type: name of font
     """
     font = self.fonts_dict.get(font_type, 'Serif-Normal')
     text = xerox.paste(xsel=True)
     ftext = ''.join(list(map(lambda ch: font.get(ch, ch), text)))
     xerox.copy(ftext)
Exemplo n.º 21
0
def parse(return_output=True, file_path=None):
    if not file_path:
        try:
            file_path = sys.argv[1]
        except IndexError:
            # assume `email.html`
            file_path = 'email.html'

    # check file exists
    if not exists(file_path):
        raise IOError('File does not exist')

    # check extension and mimetype
    filename, ext = splitext(file_path)
    mime_type = MimeTypes().guess_type(file_path)[0]
    if ext.lower() not in ['.htm', '.html'] or mime_type != 'text/html':
        raise Exception('File does not appear to be an HTML file.')

    # process file
    with open(file_path, 'r') as html_file:
        data = html_file.read()

        # extract body
        soup = BeautifulSoup(data, 'html.parser')
        body = soup.body.contents[1]

        # strip comments
        [comment.extract() for comment in body.findAll(
            text=lambda text: isinstance(text, Comment))]

        # replace image tags with the name of the image
        body_soup = BeautifulSoup(str(body), 'html.parser')
        for img in body_soup.findAll('img'):
            img.replace_with(img['name'])

        # add trouble link row
        trouble_row = body_soup.new_tag('tr')
        trouble_column = body_soup.new_tag('td')
        trouble_column.string = 'trouble'
        trouble_row.append(trouble_column)
        body_soup.tr.insert_before(trouble_row)

        # add inline css to each td
        for td in body_soup.find_all('td'):
            td['style'] = 'text-align: left; vertical-align: top;'

        # right align trouble link text
        body_soup.tr.td['style'] = 'text-align: right; vertical-align: top;'

        output = unicode(body_soup)

        # copy HTML to clipboard FTW
        xerox.copy(output)
        sys.stdout.write('HTML copied to clipboard' + '\n')

        if return_output:
            return output
Exemplo n.º 22
0
def greeting(message, protocol, host, port, copy):
    client_id = message['client_id']
    client_protocol = 'https' if protocol == 'wss' else 'http'  # FIXME
    client_endpoint = make_endpoint(client_protocol, host, port, client_id)

    click.echo(" * Tunnel has been created at {}".format(client_endpoint))
    if copy:
        xerox.copy(client_endpoint)
        click.echo(" * (Tunnel endpoint copied to clipboard)")
Exemplo n.º 23
0
    def __short__(self, link):
        if link.short_url is None:
            settings = Settings.default()
            link.short(settings.api_provider)

        copy(link.short_url)
        flash(
            u'Link has been shortened and copied to clipboard. {}'.format(
                link.short_url), 'success')
Exemplo n.º 24
0
    def on_key_press( self, symbol, modifiers ):
        # whether we handle the text here 
        self.texthandled = 0
        
        # kill the alert if you push anything
        self.alerttime = 0
        # some global key strokes
        if symbol == key.F11:
            if self.fullscreenwait == 0:
                self.set_fullscreen( not self.fullscreen )
                self.fullscreenwait = 1 # wait a second before allowing switching back
                self.activate()
                self.set_focus(None)
            self.texthandled = 1
        elif (symbol == key.Q or symbol == key.W) and modifiers & key.MOD_CTRL:
            pyglet.app.exit()
        # check for command mode...
        elif self.commandmode:
            if symbol == key.RETURN:
                # if we pressed enter after entering a command...
                self.setcommand( False )
                self.texthandled = 1
        # check for inputting things in some other focus box...
        elif self.focus:
            # if we are focused on some input device, don't let
            # any other commands be available except to possibly escape from it,
            # also basic copy and paste.
            if symbol == key.ESCAPE:
                self.set_focus( None )
                self.texthandled = 1
            elif symbol == key.C and modifiers & key.MOD_CTRL:
                xerox.copy(  self.focus.getselectedtext()  )
                self.texthandled = 1
            elif symbol == key.V and modifiers & key.MOD_CTRL:
                self.focus.dealwithtext( xerox.paste() )
                self.texthandled = 1
        # otherwise look at what it could mean for the global guy
        else:
            if ( symbol == key.Q or symbol == key.ESCAPE ):
                self.texthandled = 1
                self.alert( "ctrl+Q or ctrl+W to quit" )
            elif symbol == key.SLASH:
                self.texthandled = 1
                self.setcommand() # get command mode ready

            elif symbol == key.W:
                self.alert(self.lastalert,10)

            elif symbol == key.S:
                self.savefile()

            elif symbol == key.E:
                self.loadfile( "scratch" )

        print "key press ", symbol, " are we handled? ", self.texthandled
        return pyglet.event.EVENT_HANDLED
Exemplo n.º 25
0
    def on_key_press(self, symbol, modifiers):
        # whether we handle the text here
        self.texthandled = 0

        # kill the alert if you push anything
        self.alerttime = 0
        # some global key strokes
        if symbol == key.F11:
            if self.fullscreenwait == 0:
                self.set_fullscreen(not self.fullscreen)
                self.fullscreenwait = 1  # wait a second before allowing switching back
                self.activate()
                self.set_focus(None)
            self.texthandled = 1
        elif (symbol == key.Q or symbol == key.W) and modifiers & key.MOD_CTRL:
            pyglet.app.exit()
        # check for command mode...
        elif self.commandmode:
            if symbol == key.RETURN:
                # if we pressed enter after entering a command...
                self.setcommand(False)
                self.texthandled = 1
        # check for inputting things in some other focus box...
        elif self.focus:
            # if we are focused on some input device, don't let
            # any other commands be available except to possibly escape from it,
            # also basic copy and paste.
            if symbol == key.ESCAPE:
                self.set_focus(None)
                self.texthandled = 1
            elif symbol == key.C and modifiers & key.MOD_CTRL:
                xerox.copy(self.focus.getselectedtext())
                self.texthandled = 1
            elif symbol == key.V and modifiers & key.MOD_CTRL:
                self.focus.dealwithtext(xerox.paste())
                self.texthandled = 1
        # otherwise look at what it could mean for the global guy
        else:
            if (symbol == key.Q or symbol == key.ESCAPE):
                self.texthandled = 1
                self.alert("ctrl+Q or ctrl+W to quit")
            elif symbol == key.SLASH:
                self.texthandled = 1
                self.setcommand()  # get command mode ready

            elif symbol == key.W:
                self.alert(self.lastalert, 10)

            elif symbol == key.S:
                self.savefile()

            elif symbol == key.E:
                self.loadfile("scratch")

        print "key press ", symbol, " are we handled? ", self.texthandled
        return pyglet.event.EVENT_HANDLED
Exemplo n.º 26
0
    def transpose_csv():
        """ Transposes csv data

        Takes copied csv data from the copy buffer, rotates it, and
        replaces it
        """
        data = xerox.paste().split("\n")
        transposed = zip(*[x.strip().split(",") for x in data])
        new_text = "\n".join([",".join(y) for y in transposed])
        xerox.copy(new_text)
Exemplo n.º 27
0
def cli():
    # CLI argument parsing.
    arguments = docopt(__doc__)
    names = tuple(map(clean_name, arguments['<name>']))
    no_copy = arguments['--no-copy']

    # Marker for if the given emoji isn't found.
    missing = False

    # Grab the lookup dictionary.
    lookup = parse_emojis()

    if os.path.isfile(CUSTOM_EMOJI_PATH):
        lookup.update(parse_emojis(CUSTOM_EMOJI_PATH))

    # Search mode.
    if arguments['-s']:

        # Lookup the search term.
        found = do_find(lookup, names[0])

        # print them to the screen.
        for (n, v) in found:
            # Some registered emoji have no value.
            try:
                print(u'{}  {}'.format(' '.join(v), n))
            # Sometimes, an emoji will have no value.
            except TypeError:
                pass

        return sys.exit(0)

    # Process the results.
    results = (translate(lookup, name) for name in names)
    results = list(itertools.chain.from_iterable(results))

    if None in results:
        no_copy = True
        missing = True
        results = (r for r in results if r)

    # Prepare the result strings.
    print_results = ' '.join(results)
    results = ''.join(results)

    # Copy the results (and say so!) to the clipboard.
    if not no_copy and not missing:
        xerox.copy(results)
        print(u'Copied! {}'.format(print_results))

    # Script-kiddies.
    else:
        print(print_results)

    sys.exit(int(missing))
Exemplo n.º 28
0
def list_all_emoji(copy=False):

    all_keys = emojiCodeDict
    keys = sorted(all_keys, key=lambda key: all_keys[key])

    to_copy = ''
    for word in keys:
        print(word + ' ' + emojiCodeDict[word])
        to_copy = to_copy + word + ' ' + emojiCodeDict[word] + '\n'
    if copy:
        xerox.copy(to_copy)
Exemplo n.º 29
0
def main(poster, file):
    payload = {}
    payload["poster"] = poster
    content, syntax = get_data_from_file(file)
    payload["content"] = content
    payload["syntax"] = syntax
    res = requests.post('http://paste.ubuntu.com', data=payload)
    link = res.url
    print('link is {}'.format(link))
    xerox.copy(link)
    print('It\'s copied to the clipboard !')
Exemplo n.º 30
0
def main(poster, file):
    payload = {}
    payload["poster"] = poster
    content, syntax = get_data_from_file(file)
    payload["content"] = content
    payload["syntax"] = syntax
    res = requests.post('http://paste.ubuntu.com', data=payload)
    link = res.url
    print ('link is {}'.format(link))
    xerox.copy(link)
    print ('It\'s copied to the clipboard !')
Exemplo n.º 31
0
 def run(self):
     youdao = Youdao()
     #youdao.get_translation(msg)
     print "start youdao_copy"
     xerox.copy("你好")
     word = None
     word_new = None
     err_old = None
     try:
         word = xerox.paste()
     except BaseException, err:
         print err
Exemplo n.º 32
0
 def run(self):
     youdao = Youdao()
     #youdao.get_translation(msg)
     print "start youdao_copy"
     xerox.copy("你好")
     word = None
     word_new =None
     err_old = None
     try :
         word = xerox.paste()
     except BaseException,err:
         print err
Exemplo n.º 33
0
def emote(name):
    """
    Return named emoticon on the clipboard.
    """
    if name == 'list':
        list_emoticons()
        return
    string = emoticons.get(name)
    if not string:
        print(f"Sorry, {name!r} unknown. Try 'emote list'.")
        return
    xerox.copy(string)
Exemplo n.º 34
0
def dump_all_emoji(copy=False):

    all_keys = emojiCodeDict
    keys = sorted(all_keys, key=lambda key: all_keys[key])

    to_print = ''
    for word in keys:
        to_print = to_print + ' ' + emojiCodeDict[word]
    print(to_print)

    if copy:
        xerox.copy(to_print)
Exemplo n.º 35
0
def kirimTextMedia(pesan, path):
    hits.sekarangbuat()
    driver.find_element_by_css_selector('span[data-icon="clip"]').click()
    driver.find_element_by_css_selector('input[type="file"]').send_keys(path)
    time.sleep(3)
    driver.find_element_by_xpath('//span[@data-testid="emoji-input"]').click()
    form_pesan = driver.find_element_by_xpath(
        '//div[@class="_2FVVk _3WjMU _1C-hz"]')
    form_pesan.click()
    xerox.copy(pesan)
    form_pesan.send_keys(Keys.CONTROL + 'v')
    driver.find_element_by_xpath('//span[@data-testid="send"]').click()
Exemplo n.º 36
0
    def find_password(self):
        with open('brute_param.json') as json_file:
            param = json.load(json_file)

        current = browser.get('safari')
        current.open(self.web_address)

        time.sleep(1)
        flag = 0

        for i in range(0, 10):
            if flag == 1:
                break
            for j in range(0, 10):
                if flag == 1:
                    break
                for k in range(0, 10):
                    if flag == 1:
                        break

                    password = str(i) + str(j) + str(k)

                    auto.press('tab')
                    keyboard.write(param['username'])

                    auto.press('tab')
                    keyboard.write(password)

                    auto.press('tab')
                    auto.press('enter')

                    auto.press('tab')
                    auto.hotkey(
                        'command', 'q'
                    )  #===> NOTE: on "qwerty" keyboards, replace "q" by "a"
                    auto.hotkey('command', 'c')

                    webpage_reply = xerox.paste()

                    print(password)
                    print(webpage_reply)
                    print()

                    if "Incorrect" in webpage_reply:
                        for n in range(
                                0, 8
                        ):  #===> NOTE: the number of necessary 'tab' can change
                            auto.press('tab')
                        auto.press('enter')
                        xerox.copy("stop")
                    else:
                        flag = 1
Exemplo n.º 37
0
def copy():

    with open('data', 'rb') as file:

        load_data = pickle.Unpickler(file)
        name_ctf = load_data.load()

    flag = str(name_ctf) + "{" + (sys.argv[1]) + "}"
    flag_color = colored(flag, "green")
    xerox.copy(flag, xsel=True)

    print("\n[*]The Flag: " + str(flag_color) +
          " has been copied in your clipboard.\n")
Exemplo n.º 38
0
def main():
    if (len(sys.argv) != 2):
        exit("Which file?")
    if APP_KEY == '' or APP_SECRET == '':
        exit("You need to set your APP_KEY and APP_SECRET!")
    lnd = LinkAndDelete(APP_KEY, APP_SECRET)
    path = lnd.upload(sys.argv[1])
    if (path):
        path = path.replace(PUBLIC_DIR,"/")
        url = "http://dl.dropbox.com/u/" + repr(lnd.getUID()) + path
        Notifier.notify("LinkAndDelete","Loaded successfuly\n" + url,"GetLinkAndDelete")
        xerox.copy(url)
        os.remove(sys.argv[1])
Exemplo n.º 39
0
    def test_run(self):
        """ Test if ClipboardMonitor will report changes to callback
        function. """
        def reporter(str):
            assert TEST_STRING == str

        cb_monitor = ClipboardMonitor(reporter, TEST_INTERVAL)
        cb_monitor.start()

        xerox.copy(TEST_STRING)
        sleep(TEST_INTERVAL)

        cb_monitor.stop()
Exemplo n.º 40
0
Arquivo: cli.py Projeto: hexxter/pw
def pw(query, database_path, copy, echo, open, strict):
  """Search for USER and KEY in GPG-encrypted password database."""
  # install silent Ctrl-C handler
  def handle_sigint(*_):
    click.echo()
    sys.exit(1)
  signal.signal(signal.SIGINT, handle_sigint)

  # load database
  db = Database.load(database_path)

  # parse query (split at right-most "@"" sign, since user names are typically email addresses)
  user_pattern, _, key_pattern = query.rpartition('@')

  # search database
  results = db.search(key_pattern, user_pattern)
  results = list(results)
  if strict and len(results) != 1:
    click.echo('error: multiple or no records found (but using --strict mode)', file=sys.stderr)
    sys.exit(1)

  # sort results according to key (stability of sorted() ensures that the order of accounts for any given key remains untouched)
  results = sorted(results, key=lambda e: e.key)

  # print results
  output = ''
  for idx, entry in enumerate(results):
    # key and user
    key = style_match(key_pattern).join(entry.key.split(key_pattern)) if key_pattern else entry.key
    user = style_match(user_pattern).join(entry.user.split(user_pattern)) if user_pattern else entry.user
    output += key
    if user:
      output += ': ' + user

    # password
    if echo:
      output += ' | ' + style_password(entry.password)
    if copy and idx == 0:
      xerox.copy(entry.password)
      output += ' | ' + style_success('*** PASSWORD COPIED TO CLIPBOARD ***')

    # other info
    if entry.link:
      if open and idx == 0:
        import webbrowser
        webbrowser.open(entry.link)
      output += ' | ' + entry.link
    if entry.notes:
      output += ' | ' + entry.notes
    output += '\n'
  click.echo(output.rstrip('\n'))   # echo_via_pager has some unicode problems & can remove the colors
Exemplo n.º 41
0
def main():
    if (len(sys.argv) != 2):
        exit("Which file?")
    if APP_KEY == '' or APP_SECRET == '':
        exit("You need to set your APP_KEY and APP_SECRET!")
    lnd = LinkAndDelete(APP_KEY, APP_SECRET)
    path = lnd.upload(sys.argv[1])
    if (path):
        path = path.replace(PUBLIC_DIR, "/")
        url = "http://dl.dropbox.com/u/" + repr(lnd.getUID()) + path
        Notifier.notify("LinkAndDelete", "Loaded successfuly\n" + url,
                        "GetLinkAndDelete")
        xerox.copy(url)
        os.remove(sys.argv[1])
Exemplo n.º 42
0
def trapify(args):

    words = ' '.join(args['query']).upper()
    to_print = u''

    for letter in words:
        if letter in trap_letters:
            to_print = to_print + trap_letters[letter]
        else:
            to_print = to_print + letter

    print(to_print)
    if args['copy']:
        xerox.copy(to_print)
Exemplo n.º 43
0
def test_echo_vs_copy():
    # no copy nor echo
    expected = "phones.myphone"
    xerox.copy("")
    result = invoke_cli("--no-copy", "--no-echo", "myphone")
    assert not result.exception and result.exit_code == 0
    assert result.output.strip() == expected.strip()
    assert xerox.paste() == ""

    # only echo
    expected = "phones.myphone | 0000"
    xerox.copy("")
    result = invoke_cli("--no-copy", "--echo", "myphone")
    assert not result.exception and result.exit_code == 0
    assert result.output.strip() == expected.strip()
    assert xerox.paste() == ""

    # only echo
    expected = "phones.myphone | *** PASSWORD COPIED TO CLIPBOARD ***"
    xerox.copy("")
    result = invoke_cli("--copy", "--no-echo", "myphone")
    assert not result.exception and result.exit_code == 0
    assert result.output.strip() == expected.strip()
    assert xerox.paste() == "0000"

    # both copy and echo
    expected = "phones.myphone | 0000 | *** PASSWORD COPIED TO CLIPBOARD ***"
    xerox.copy("")
    result = invoke_cli("--copy", "--echo", "myphone")
    assert not result.exception and result.exit_code == 0
    assert result.output.strip() == expected.strip()
    assert xerox.paste() == "0000"
Exemplo n.º 44
0
def main():
    try:
        text = ""
        if (len(sys.argv) == 1):
            text = raw_input('Enter text -:\n')
        else:
            text = sys.argv[1]
        	
        text_hash = hashlib.md5(text).hexdigest()
        print text_hash
        	
        xerox.copy(text_hash)
        print 'Copied to clipboard!!'
    except Exception as exception:
        print "Error : {exception}".format(exception=exception.message)
Exemplo n.º 45
0
def main():
    try:
        plaintext = ""
        if len(sys.argv) == 1:
            plaintext = raw_input('Enter text -:\n')
        else:
            plaintext = sys.argv[1]

        ciphertext = plaintext.encode('rot13')
        print ciphertext

        xerox.copy(ciphertext)
        print 'Copied to clipboard!!'
    except Exception as exception:
        print "Error : {exception}".format(exception=exception.message)
Exemplo n.º 46
0
def postImage(service, image):
    try:
        with open(image) as rfile:
            response = json.loads(requests.post(
                    url=service["post_url"],
                    files={ "files[]": rfile }
                    ).text)
        file_info = response["files"][0]
        url = os.path.join(service["view_url"], file_info["url"])
        if getOption("notify"):
            notify("Uploaded screenshot: {}".format(url))
        xerox.copy(url)
        print(url)
    except Exception as e:
        if getOption("notify"):
            notify("Error while uploading check, internet connection and service server".format(e))
        print(traceback.format_exc(e))
Exemplo n.º 47
0
    def do_ParameterTest(self,
                         expect,
                         klass,
                         expectKind=None,  # None=one prop, Exception=exception, dict=many props
                         owner='user',
                         value=None, req=None,
                         expectJson=None,
                         **kwargs):

        name = kwargs.setdefault('name', 'p1')

        # construct one if needed
        if isinstance(klass, type):
            prop = klass(**kwargs)
        else:
            prop = klass

        self.assertEqual(prop.name, name)
        self.assertEqual(prop.label, kwargs.get('label', prop.name))
        if expectJson is not None:
            gotJson = json.dumps(prop.getSpec())
            if gotJson != expectJson:
                try:
                    import xerox
                    formated = self.formatJsonForTest(gotJson)
                    print "You may update the test with (copied to clipboard):\n" + formated
                    xerox.copy(formated)
                    input()
                except ImportError:
                    print "Note: for quick fix, pip install xerox"
            self.assertEqual(gotJson, expectJson)

        sched = self.makeScheduler(properties=[prop])

        if not req:
            req = {name: value, 'reason': 'because'}
        try:
            bsid, brids = yield sched.force(owner, builderNames=['a'], **req)
        except Exception, e:
            if expectKind is not Exception:
                # an exception is not expected
                raise
            if not isinstance(e, expect):
                # the exception is the wrong kind
                raise
            defer.returnValue(None)  # success
Exemplo n.º 48
0
def get(ctx, tags):
    """
    Get a gif matching the given set of tags and copy its URL to the clipboard.
    """
    tags = set(tags)
    metadata = get_metadata(
        ctx.obj['dropbox'], get_base_path(ctx.obj['config'])
    )
    matches = [
        item for item, item_tags in metadata.items()
        if item_tags >= tags
    ]

    if matches:
        gif = random.choice(matches)
        gif_url = get_gif_url(get_base_url(ctx.obj['config']), gif)
        xerox.copy(gif_url)
    else:
        print("No gif found :(")
Exemplo n.º 49
0
def output_from_argparse(output, parsed_args): # TODO: argparse functions need better name.
    parsed_args = parsed_args.copy()

    commands = parsed_args.get('to_command')
    if commands is None:
        commands = []

    if parsed_args.get('say'):
        commands.append("say")

    for c in commands:
        hexchat.command(" ".join((c, output)))
    if parsed_args.get('guard_inputbox_cmd') and (parsed_args.get('to_inputbox') or parsed_args.get('to_inputbox_replace')):
        ibx.set(" ".join((parsed_args['guard_inputbox_cmd'][0], output)))
    elif parsed_args.get("to_inputbox"):
        ibx.add_at_cursor(output)
    elif parsed_args.get("to_inputbox_replace"):
        ibx.set(output)
    if parsed_args.get("to_clipboard") and HAVE_XEROX:
        xerox.copy(output)
Exemplo n.º 50
0
def set_clipboard(text, datatype=None):
    """Set system clipboard to the given text.

    This function tries a range of modules and methods to find a suitable way to set the clipboard.

    Args:
        text: A string with text to copy to the clipboard.
        datatype: currently not used. Will generally assumed to be unicode text.

    Examples:
        >>> set_clipboard("hello there")

    References:
        From http://stackoverflow.com/questions/579687/how-do-i-copy-a-string-to-the-clipboard-on-windows-using-python
    """
    if 'xerox' in sys.modules.keys():
        xerox.copy(text)
    elif 'pyperclip' in sys.modules.keys():
        pyperclip.copy(text)
    elif 'gtk' in sys.modules.keys():
        clipboard = gtk.clipboard_get()
        text = clipboard.set_text(text)
    elif 'win32clipboard' in sys.modules.keys():
        wcb = win32clipboard
        wcb.OpenClipboard()
        wcb.EmptyClipboard()
        # wcb.SetClipboardText(text)  # doesn't work
        # SetClipboardData Usage:
        # >>> wcb.SetClipboardData(<type>, <data>)
        # wcb.SetClipboardData(wcb.CF_TEXT, text.encode('utf-8')) # doesn't work
        wcb.SetClipboardData(wcb.CF_UNICODETEXT, text)  # works
        wcb.CloseClipboard()  # User cannot use clipboard until it is closed.
    else:
        # If code is run from within e.g. an ipython qt console, invoking Tk root's mainloop() may hang the console.
        tkroot = Tk()
        # r.withdraw()
        tkroot.clipboard_clear()
        tkroot.clipboard_append(text)
        tkroot.mainloop()  # the Tk root's mainloop() must be invoked.
        tkroot.destroy()
Exemplo n.º 51
0
def main():
    parser = argparse.ArgumentParser(description="Securely retrieve password \
                                                 and copy to clipboard")
    parser.add_argument("-u", "--update",  action='store_true',
                        help="Update passwords")
    parser.add_argument("-d", "--display",  action='store_true',
                        help="Dispaly on screen")
    parser.add_argument("type", nargs="?", help="console or root")

    args = parser.parse_args()
    if not args.type and not args.update:
        parser.print_help()
        exit(1)

    pstore = Pdb()

    if args.update:
        pstore.update()

    elif args.type:
        if args.display:
            clipboard = False
        else:
            try:
                import xerox
                clipboard = True
            except ImportError:
                clipboard = False

        passwd = pstore.get(args.type)
        if isinstance(passwd, list):
            if clipboard:
                xerox.copy(passwd[0])
            for pw in passwd:
                print pw
        else:
            if clipboard:
                xerox.copy(passwd)
            print passwd
Exemplo n.º 52
0
def main(argv={}):
    password = Password(argv).generate()

    """ Copy the password to clipboard? """
    if not argv['--no-clipboard']:
        try:
            import xerox
            xerox.copy(password)
        except ImportError:
            print no_xerox_error

    """ Print the password? """
    if argv['--print'] or argv['--no-clipboard']:
        print password

    """ Print password strength """
    try:
        from zxcvbn import password_strength
        strength = password_strength(password)
        print 'crack time: %s, score: %s out of 4' % (strength['crack_time_display'], str(strength['score']))
    except ImportError:
        print no_zxcvbn_error
Exemplo n.º 53
0
    def capture_event(self, event):
        """ Capture our system events, and perform actions 
            based on what they are.
        """
        # event masks:
        # 2   => update
        # 64  => move_from
        # 128 => move_to
        # 256 => create
        # 512 => delete

        filename = str(event.name)
        fileextension = os.path.splitext(event.name)[1]

        if event.mask in [128, 256] \
            and self.settings['local']['file_match'] in filename \
            and os.path.basename(filename)[0] is not '.':
            hash_str = self.hash_for_file(filename)
            newname = hash_str[0:6] + fileextension

            web_url = ""
            if not self.settings['s3']['use_s3']:
                web_url = self.upload_file(filename, newname)
                if web_url == None:
                    self.growl(
                            'Error uploading: %s' % sys.exc_info()[1].message,
                            'Failure'
                            )
                    return
            else:
                web_url = self.copy_to_s3(filename, newname)

            xerox.copy(web_url)

            self.growl("%s uploaded to %s" % (filename, web_url))

            if self.settings['local']['delete_after_upload']:
                os.remove(filename)
    def do_ParameterTest(self,
                         expect,
                         klass,
                         expectKind=None,  # None=one prop, Exception=exception, dict=many props
                         owner='user',
                         value=None, req=None,
                         expectJson=None,
                         **kwargs):

        name = kwargs.setdefault('name', 'p1')

        # construct one if needed
        if isinstance(klass, type):
            prop = klass(**kwargs)
        else:
            prop = klass

        self.assertEqual(prop.name, name)
        self.assertEqual(prop.label, kwargs.get('label', prop.name))
        if expectJson is not None:
            gotJson = json.dumps(prop.getSpec())
            if gotJson != expectJson:
                try:
                    import xerox
                    formated = self.formatJsonForTest(gotJson)
                    print("You may update the test with (copied to clipboard):\n" + formated)
                    xerox.copy(formated)
                    input()
                except ImportError:
                    print("Note: for quick fix, pip install xerox")
            self.assertEqual(gotJson, expectJson)

        sched = self.makeScheduler(properties=[prop])

        if not req:
            req = {name: value, 'reason': 'because'}
        try:
            bsid, brids = yield sched.force(owner, builderNames=['a'], **req)
        except Exception as e:
            if expectKind is not Exception:
                # an exception is not expected
                raise
            if not isinstance(e, expect):
                # the exception is the wrong kind
                raise
            defer.returnValue(None)  # success

        expect_props = {
            'owner': ('user', 'Force Build Form'),
            'reason': ('because', 'Force Build Form'),
        }

        if expectKind is None:
            expect_props[name] = (expect, 'Force Build Form')
        elif expectKind is dict:
            for k, v in iteritems(expect):
                expect_props[k] = (v, 'Force Build Form')
        else:
            self.fail("expectKind is wrong type!")

        self.assertEqual((bsid, brids), (500, {1000: 100}))  # only forced on 'a'
        self.assertEqual(self.addBuildsetCalls, [
            ('addBuildsetForSourceStampsWithDefaults', dict(
                builderNames=['a'],
                waited_for=False,
                properties=expect_props,
                reason=u"A build was forced by 'user': because",
                sourcestamps=[
                    {'branch': '', 'project': '', 'repository': '',
                     'revision': '', 'codebase': ''},
                ])),
        ])
Exemplo n.º 55
0
    def searchLink(self):
        try:
            bsLink = BeautifulSoup(self.getPage(self.url))        
        except InvalidProtocol:
            print 'You must provide a valid protocol. Ej. HTTP'
            while not self.url:
                self.url = raw_input('Insert URL: ')
                bsLink = BeautifulSoup(self.getPage(self.url))
        allLinks = bsLink.findAll('a')
        # print allLinks
        for link in allLinks:
            try:
                href = link['href']                
            except KeyError: 
                href = ''
                pass
            if href:
                for ext in self.extension:
                                 
                    if ext in href:
                        
                        if len(self.forbidden) == 0:                            
                            for forb in self.forbidden:
                                if forb not in href:
                                    print href                               
                                    self.insertInList(href)                                       
                        else:                            
                            # print href
                            self.insertInList(href)      
        
        try:
           xerox.copy(self.linkList)
           print 'Links copied on clipboard'
           print self.linkList 
        except XclipNotFound:
            print self.linkList
        
        if self.syn:
            self.syn.addDownload(self.commaList)


# class main():
#     url = ''
#     synology = ''
#     while not url:
#         url = raw_input('Insert URL: ')
#         url = URLChecking(url).checkURL()        
    
#     extensions = raw_input('Insert search extensions (comma separated): ')
#     extensions = re.split(',',extensions)
#     # print extensions
#     forbidden = raw_input('Insert forbidden keywords on URL (comma separated): ')
#     forbidden = re.split(',', forbidden)
    
#     synology = raw_input('Do you want to send links to synology: (Y/N) ')
#     if synology == 'Y' or synology == 'y':
#         ip = raw_input('Input URL of Synology DiskStation: ')
#         username = raw_input('Insert username of synology (You must have rights to DownloadStation): ')
#         password = base64.b64encode(raw_input('Input your password: '******'ip': ip, 'username': username, 'password': password}
#         u = urlExtension(url,extensions, forbidden, synology, syndata)
#     else:
#         u = urlExtension(url,extensions, forbidden)
#     u.searchLink()
    
# if __name__ == '__main__':
#     main()
Exemplo n.º 56
0
	def card_detected(self, card):
		xerox.copy(card.name)
Exemplo n.º 57
0
 def test_empty(self):
     xerox.copy('')
     self.assertEqual(xerox.paste(), '')
Exemplo n.º 58
0
payload["syntax"] = "text"

args = get_args()
content = None
syntax = None

if args.file != None:
	content,syntax = get_data_from_file(args.file)
else:
	content = sys.stdin.read()

payload["content"] = content

if syntax != None:
	payload["syntax"] = syntax

if args.poster != None:
	payload["poster"] = args.poster

if args.syntax != None:
	payload["syntax"] = args.syntax

print payload
	
res = requests.post('http://paste.ubuntu.com',data=payload)
link=res.url
print "link is " + link
xerox.copy(link)
print "It's copied to the clipboard !"

Exemplo n.º 59
0
 def test_paste(self):
     xerox.copy(self.text)
     self.assertEqual(xerox.paste(), self.text)