Read and execute a .dql file
559137
def do_file(self, filename):
        
        with open(filename, "r") as infile:
            self._run_cmd(infile.read())
713518
protected function getStatement($glue, array $dqlHandlers)
    {
        if ($this->isApplied) {
            throw new \LogicException('Query was already applied to query builder');
        }
        $dqlStatement = [];
        $parameters = [];
        foreach ($dqlHandlers as $dqlHandler) {
            if (!$dqlHandler instanceof DQLHandlerInterface) {
                throw new \UnexpectedValueException('$dqlHandlers parameters must be an array of DQLHandlerInterface');
            }
            $dqlStatement[] = '('.$dqlHandler->getDQL().')';

            foreach ($dqlHandler->getParameters() as $key => $value) {
                $parameters[$key] = $value;
            }
        }

        return new DQLHandler(implode($glue, $dqlStatement), $parameters);
    }
701792
def execute_call_xml(url)
			doc = REXML::Document.new(execute_call_plain(url))
			raise create_error(doc) unless doc.elements["rsp"].attributes["stat"] == "ok"
			doc
		end
1321934
def execute(args):
    """"""

    def info(*message):
        """Displays a message unless -q was specified."""
        if not args['-q']:
            print ' '.join(map(str, message))

    if args['init']:
        try:
            repo = init(args['<directory>'])
            info('Initialized Gitpress repository in', repo)
        except RepositoryAlreadyExistsError as ex:
            info('Gitpress repository already exists in', ex.repo)
        return 0

    if args['preview']:
        directory, address = resolve(args['<directory>'], args['<address>'])
        host, port = split_address(address)
        if address and not host and not port:
            error('Invalid address', repr(address))
        return preview(directory, host=host, port=port)

    if args['build']:
        require_repo(args['<directory>'])
        info('Building site', os.path.abspath(args['<directory>'] or '.'))
        try:
            out_directory = build(args['<directory>'], args['--out'])
        except NotADirectoryError as ex:
            error(ex)
        info('Site built in', os.path.abspath(out_directory))
        return 0

    if args['themes']:
        theme = args['<theme>']
        if args['use']:
            try:
                switched = use_theme(theme)
            except ConfigSchemaError as ex:
                error('Could not modify config:', ex)
                return 1
            except ThemeNotFoundError as ex:
                error('Theme %s is not currently installed.' % repr(theme))
                return 1
            info('Switched to theme %s' if switched else 'Already using %s' % repr(theme))
        elif args['install']:
            # TODO: implement
            raise NotImplementedError()
        elif args['uninstall']:
            # TODO: implement
            raise NotImplementedError()
        else:
            themes = list_themes()
            if themes:
                info('Installed themes:')
                info('  ' + '\n  '.join(themes))
            else:
                info('No themes installed.')
        return 0

    if args['plugins']:
        plugin = args['<plugin>']
        if args['add']:
            try:
                added = add_plugin(plugin)
            except ConfigSchemaError as ex:
                error('Could not modify config:', ex)
                return 1
            info(('Added plugin %s' if added else
                'Plugin %s has already been added.') % repr(plugin))
        elif args['remove']:
            settings = get_plugin_settings(plugin)
            if not args['-f'] and settings and isinstance(settings, dict):
                warning = 'Plugin %s contains settings. Remove?' % repr(plugin)
                if not yes_or_no(warning):
                    return 0
            try:
                removed = remove_plugin(plugin)
            except ConfigSchemaError as ex:
                error('Error: Could not modify config:', ex)
            info(('Removed plugin %s' if removed else
                'Plugin %s has already been removed.') % repr(plugin))
        else:
            plugins = list_plugins()
            info('Installed plugins:\n  ' + '\n  '.join(plugins) if plugins else
                'No plugins installed.')
        return 0

    return 1
1059713
public void executeSqlFile( File file, int chunks, boolean eachLineAnSql ) throws Exception {
        execOnConnection(mConn -> {
            boolean autoCommit = mConn.getAutoCommit();
            mConn.setAutoCommit(false);

            Predicate<String> validSqlLine = s -> s.length() != 0 //
                    && !s.startsWith("BEGIN") //
                    && !s.startsWith("COMMIT") //
            ;
            Predicate<String> commentPredicate = s -> !s.startsWith("--");

            try (IHMStatement pStmt = mConn.createStatement()) {
                final int[] counter = {1};
                Stream<String> linesStream = null;
                if (eachLineAnSql) {
                    linesStream = Files.lines(Paths.get(file.getAbsolutePath())).map(s -> s.trim()).filter(commentPredicate)
                            .filter(validSqlLine);
                } else {
                    linesStream = Arrays.stream(Files.lines(Paths.get(file.getAbsolutePath())).filter(commentPredicate)
                            .collect(Collectors.joining()).split(";")).filter(validSqlLine);
                }

                Consumer<String> executeAction = s -> {
                    try {
                        pStmt.executeUpdate(s);
                        counter[0]++;
                        if (counter[0] % chunks == 0) {
                            mConn.commit();
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                };
                linesStream.forEach(executeAction);
                mConn.commit();
            }
            mConn.setAutoCommit(autoCommit);

            return null;
        });

    }
43011
def execute(self, proxy, method, args):
        """"""
        try:
            result = getattr(proxy, method)(raw_xml=self.options.xml, *tuple(args))
        except xmlrpc.ERRORS as exc:
            self.LOG.error("While calling %s(%s): %s" % (method, ", ".join(repr(i) for i in args), exc))
            self.return_code = error.EX_NOINPUT if "not find" in getattr(exc, "faultString", "") else error.EX_DATAERR
        else:
            if not self.options.quiet:
                if self.options.repr:
                    # Pretty-print if requested, or it's a collection and not a scalar
                    result = pformat(result)
                elif hasattr(result, "__iter__"):
                    result = '\n'.join(i if isinstance(i, basestring) else pformat(i) for i in result)
                print(fmt.to_console(result))
639221
def find_DQ_extension(self):
        
        dqfile = None
        dq_suffix=None
        if(self.maskExt is not None):
            for hdu in self._image:
                # Look for DQ extension in input file
                if 'extname' in hdu.header and hdu.header['extname'].lower() == self.maskExt.lower():
                    dqfile = self._filename
                    dq_suffix=self.maskExt
                    break

        return dqfile,dq_suffix
673882
public function getDQL()
    {
        if (null === $this->dql) {
            $msg = "No condition applied on attribute query builder for attribute {$this->attribute->getCode()}";
            throw new \LogicException($msg);
        }
        if (!$this->joinApplied) {
            $this->applyJoin();
        }

        return $this->dql;
    }
432323
function runQuery(client, queryString, args, callback) {
  if (activeBackend === 'mysql') {
    queryString = queryString.replace(/\$\d+/, '?');
  }

  client.query(queryString, args, function (err, result) {
    if (err) {
      callback(err, null);
      return;
    }
    if (activeBackend === 'mysql') {
      callback(err, result);
    }
    else if (activeBackend === 'pgsql') {
      var rows = [];
      if (result.rows) {
        rows = result.rows;
      }
      callback(err, rows);
    }
  });
}
856682
private function executeQuery(QueryBuilder $qb, $document)
    {
        $identifier = $qb->class->createIdentifier($document);

        $qb->update();
        $qb->setIdentifier($identifier);

        if ($qb->class->isVersioned) {
            $versionMapping   = $qb->class->getPropertyMetadata($qb->class->versionAttribute);
            $versionAttribute = $qb->attr($versionMapping->name);
            $version          = $versionMapping->getValue($document);

            $versionAttribute->equals($version);
        }

        try {
            $qb->getQuery()->execute();
        } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) {
            if ($qb->class->isVersioned && $e->getAwsErrorCode() === 'ConditionalCheckFailedException') {
                throw LockException::lockFailed($document);
            }

            throw $e;
        }
    }
550001
def run_apidoc(_):
    """"""
    import better_apidoc
    better_apidoc.main([
        'better-apidoc',
        '-t',
        os.path.join('.', '_templates'),
        '--force',
        '--no-toc',
        '--separate',
        '-o',
        os.path.join('.', 'API'),
        os.path.join('..', 'src', 'qnet'),
    ])
252459
def main(filepath, in_debug_mode):
    """"""

    with open(filepath) as file:

        try:

            # Lexical analysis
            lexer = Lexer(file.read())

            # Syntax analysis
            parser = Parser(lexer)
            tree = parser.parse()

            # Sementic analysis
            symtab_builder = SymbolTableBuilder(tree)
            symtab_builder.build()

            # Program evaluation
            interpreter = Interpreter(tree)
            interpreter.interpret()

            # Display internal variables if debug option is enabled
            if in_debug_mode:
                print(f"SYMBOL TABLE: {symtab_builder.table}")
                print(f"GLOBAL MEMORY: {interpreter.memory}")

        except Exception as gibica_exception:

            # Display the full trace if debug option is enabled
            if in_debug_mode:
                raise

            # In classic mode, just display the interpreter trace
            else:
                print(f"{gibica_exception.__class__.__name__}: {gibica_exception}")
852799
def run_apidoc(_):
    """"""
    current_directory = os.path.abspath(os.path.dirname(__file__))
    output_path = os.path.join(current_directory, 'source')
    cmd_path = 'sphinx-apidoc'
    if hasattr(sys, 'real_prefix'):  # Check to see if we are in a virtualenv
        # If we are, assemble the path manually
        cmd_path = os.path.abspath(os.path.join(sys.prefix, 'bin', 'sphinx-apidoc'))
    main([cmd_path, '-e', '-o', output_path, '../cinder_data', '--force'])
83315
def _execute_backend_on_spec(self):
        """"""

        api_no_aliases_cache = None
        for attr_key in dir(self.backend_module):
            attr_value = getattr(self.backend_module, attr_key)
            if (inspect.isclass(attr_value) and
                    issubclass(attr_value, Backend) and
                    not inspect.isabstract(attr_value)):
                self._logger.info('Running backend: %s', attr_value.__name__)
                backend = attr_value(self.build_path, self.backend_args)

                if backend.preserve_aliases:
                    api = self.api
                else:
                    if not api_no_aliases_cache:
                        api_no_aliases_cache = remove_aliases_from_api(self.api)
                    api = api_no_aliases_cache

                try:
                    backend.generate(api)
                except Exception:
                    # Wrap this exception so that it isn't thought of as a bug
                    # in the stone parser, but rather a bug in the backend.
                    # Remove the last char of the traceback b/c it's a newline.
                    raise BackendException(
                        attr_value.__name__, traceback.format_exc()[:-1])
396871
def main():
    
    import jsonschema
    parser = argparse.ArgumentParser(version=__version__)
    parser.add_argument(
        '--verbose', action='store_true', default=False,
        help='Turn on verbose output.')
    parser.add_argument(
        '--header', action='store_true', default=False,
        help='Turn on header.')
    parser.add_argument(
        'playbooks', metavar='PLAYBOOKS', type=str, nargs='+',
        help='The playbook(s) to lint.')

    args = parser.parse_args()

    validation_results = {}
    all_valid = True
    # Load the playbook schema
    with open(resource_filename(
            'relent', 'schemas/playbook_schema.json'), 'r') as schema_fp:
        schema = json.load(schema_fp)
        # Do checks against playbooks
        for playbook in args.playbooks:
            try:
                with open(playbook, 'r') as pb:
                    # Schema check
                    jsonschema.validate(json.load(pb), schema)
            except jsonschema.ValidationError, e:
                all_valid = False
                validation_results[playbook] = (
                    False, e.message, list(e.schema_path), str(e))
            except ValueError, e:
                all_valid = False
                validation_results[playbook] = (
                    False, 'JSON is invalid.', str(e), str(e))

    # If all_valid is True then return back happy results
    if all_valid is True:
        if args.verbose or args.header:
            parser._print_message('Found 0 issues.\n')
        raise SystemExit(0)
    else:
        if args.verbose or args.header:
            parser._print_message('Found %s issues.\n\n' % len(
                validation_results))
        for problem_playbook in validation_results.keys():
            parser._print_message('%s: E: %s %s\n' % (
                problem_playbook,
                validation_results[problem_playbook][1],
                validation_results[problem_playbook][2]))
            if args.verbose:
                parser._print_message(
                    validation_results[problem_playbook][3] + '\n--\n')
        raise SystemExit(1)
379276
def execute(cls, uri, http_verb, extra_headers=None, batch=False, _body=None, **kw):
        
        if batch:
            urlsplitter = urlparse(API_ROOT).netloc
            ret = {"method": http_verb, "path": uri.split(urlsplitter, 1)[1]}
            if kw:
                ret["body"] = kw
            return ret

        if not ('app_id' in ACCESS_KEYS and 'rest_key' in ACCESS_KEYS):
            raise core.ParseError('Missing connection credentials')

        app_id = ACCESS_KEYS.get('app_id')
        rest_key = ACCESS_KEYS.get('rest_key')
        master_key = ACCESS_KEYS.get('master_key')

        url = uri if uri.startswith(API_ROOT) else cls.ENDPOINT_ROOT + uri
        if _body is None:
            data = kw and json.dumps(kw, default=date_handler) or "{}"
        else:
            data = _body
        if http_verb == 'GET' and data:
            url += '?%s' % urlencode(kw)
            data = None
        else:
            if cls.__name__ == 'File':
                data = data
            else:
                data = data.encode('utf-8')

        headers = {
            'Content-type': 'application/json',
            'X-Parse-Application-Id': app_id,
            'X-Parse-REST-API-Key': rest_key
        }
        headers.update(extra_headers or {})

        if cls.__name__ == 'File':
            request = Request(url.encode('utf-8'), data, headers)
        else:
            request = Request(url, data, headers)

        if ACCESS_KEYS.get('session_token'):
            request.add_header('X-Parse-Session-Token', ACCESS_KEYS.get('session_token'))
        elif master_key:
            request.add_header('X-Parse-Master-Key', master_key)

        request.get_method = lambda: http_verb

        try:
            response = urlopen(request, timeout=CONNECTION_TIMEOUT)
        except HTTPError as e:
            exc = {
                400: core.ResourceRequestBadRequest,
                401: core.ResourceRequestLoginRequired,
                403: core.ResourceRequestForbidden,
                404: core.ResourceRequestNotFound
                }.get(e.code, core.ParseError)
            raise exc(e.read())

        return json.loads(response.read().decode('utf-8'))
921917
def evaluate(str, file = '<in QML::Engine#evaluate>', lineno = 1)
      evaluate_impl(str, file, lineno).tap do |result|
        raise result.to_error if result.is_a?(JSObject) && result.error?
      end
    end