Get a list of shards belonging to this instance.

        :param bool add_shard: A boolean indicating whether to add a new shard to the specified
            instance.
505339
def shards(self, add_shard=False):
        
        url = self._service_url + 'shards/'
        if add_shard:
            response = requests.post(url, **self._instances._default_request_kwargs)
        else:
            response = requests.get(url, **self._instances._default_request_kwargs)

        return response.json()
464449
def _bool_list(self, k=None):
        
        n = len(self.func_list)
        if k is None:
            bool_list = [True] * n
        elif isinstance(k, (int, np.integer)):
            bool_list = [False] * n
            bool_list[k] = True
        else:
            bool_list = [False] * n
            for i, k_i in enumerate(k):
                if k_i is not False:
                    if k_i is True:
                        bool_list[i] = True
                    elif k_i < n:
                        bool_list[k_i] = True
                    else:
                        raise ValueError("k as set by %s is not convertable in a bool string!" % k)
        if self._foreground_shear is True:
            bool_list[self._foreground_shear_idex] = False
        return bool_list
1234378
public java.util.List<Shard> getShards() {
        if (shards == null) {
            shards = new com.amazonaws.internal.SdkInternalList<Shard>();
        }
        return shards;
    }
693298
static function shard($collector = null) {
      if (func_num_args()) {
        if ($collector) {
          static::$_shards[static::class] = $collector;
        } else {
          unset(static::$_shards[static::class]);
        }
        return;
      }
      if (!isset(static::$_shards[static::class])) {
        static::$_shards[static::class] = new Map();
      }
      return static::$_shards[static::class];
    }
194100
int numShardsIOwn() {
        final boolean[] shards = iOwn.get();
        if (shards == null)
            return 0;
        return (int) IntStream.range(0, shards.length).mapToObj(i -> Boolean.valueOf(shards[i])).filter(b -> b.booleanValue()).count();
    }
1175768
def _split_one_shard_to_multiple(client, project, logstore, shard_info, count, current_shard_count):
    
    distance = shard_info['length'] // count
    if distance <= 0 or count <= 1:
        return [shard_info['info']], 0

    rw_shards, increased_shard_count = {shard_info['id']: shard_info['info']}, 0
    for x in range(1, count):
        new_hash = shard_info['start'] + distance * x
        new_hash = hex(new_hash)[2:].strip('lL')
        new_hash = '0' * (TOTAL_HASH_LENGTH - len(new_hash)) + new_hash
        try:
            if x == 1:
                res = client.split_shard(project, logstore, shard_info['id'], new_hash)
            else:
                res = client.split_shard(project, logstore, current_shard_count - 1, new_hash)

            # new rw_shards
            for shard in res.shards:
                if shard['status'] == 'readonly':
                    del rw_shards[shard['shardID']]
                else:
                    rw_shards[shard['shardID']] = shard

            current_shard_count += res.count - 1
            increased_shard_count += res.count - 1
            logger.info("split shard: project={0}, logstore={1}, shard_info={2}, count={3}, current_shard_count={4}".format(project, logstore, shard_info, count, current_shard_count))
        except Exception as ex:
            print(ex)
            print(x, project, logstore, shard_info, count, current_shard_count)
            raise

    return rw_shards.values(), increased_shard_count
403611
private boolean updateShardedObjectMove(DBObject dbObj) {
        DBObject currDBObj = SpiderService.instance().getObject(m_tableDef, dbObj.getObjectID());
        m_logger.debug("Update forcing move of object {} from shard {} to shard {}",
                       new Object[]{dbObj.getObjectID(),
                                    m_tableDef.getShardNumber(currDBObj),
                                    m_tableDef.getShardNumber(dbObj)});
        
        deleteObject(currDBObj);
        mergeAllFieldValues(dbObj, currDBObj);
        addBrandNewObject(currDBObj);
        return true;
    }
1195436
def _get_shard_names(self, args):
        
        if 'sharded' in args and args['sharded']:
            if len(args['sharded']) == 1:
                try:
                    # --sharded was a number, name shards shard01, shard02,
                    # ... (only works with replica sets)
                    n_shards = int(args['sharded'][0])
                    shard_names = ['shard%.2i'
                                   % (i + 1) for i in range(n_shards)]
                except ValueError:
                    # --sharded was a string, use it as name for the one shard
                    shard_names = args['sharded']
            else:
                shard_names = args['sharded']
        else:
            shard_names = [None]
        return shard_names
942669
def create_db_in_shard(db_name, shard, client=None):
    
    client = client or pymongo.MongoClient()
    # flush the router config to ensure it's not stale
    res = client.admin.command('flushRouterConfig')
    if not res.get('ok'):
        raise RuntimeError("unable to flush router config")
    if shard not in get_ids(client.config.shards):
        raise ValueError(f"Unknown shard {shard}")
    if db_name in get_ids(client.config.databases):
        raise ValueError("database already exists")
    # MongoDB doesn't have a 'create database' command, so insert an
    #  item into a collection and then drop the collection.
    client[db_name].foo.insert({'foo': 1})
    client[db_name].foo.drop()
    if client[db_name].collection_names():
        raise ValueError("database has collections")
    primary = client['config'].databases.find_one(db_name)['primary']
    if primary != shard:
        res = client.admin.command(
            'movePrimary', value=db_name, to=shard)
        if not res.get('ok'):
            raise RuntimeError(str(res))
    return (
        f"Successfully created {db_name} in {shard} via {client.nodes} "
        f"from {hostname}")
1033163
public function getShards(): array
    {
        $shards = [];
        foreach ($this->_data['shards'] as $shardNumber => $shard) {
            $shards[] = new Shard($shardNumber, $shard);
        }

        return $shards;
    }
307050
def _get_next_open_shard(stream_details, shard_id):
    '''
    
    '''
    found = False
    for shard in stream_details["OpenShards"]:
        current_shard_id = shard["ShardId"]
        if current_shard_id == shard_id:
            found = True
            continue
        if found:
            return current_shard_id
1309436
def _add(self, shard_uri, name):
        """"""
        return self.router_command("addShard", (shard_uri, {"name": name}), is_eval=False)
1024201
def query(self, query):
    ''''''
    cursor = Cursor(query, self.shard_query_generator(query))
    cursor.apply_order()  # ordering sharded queries is expensive (no generator)
    return cursor
945180
def _read_undone_shard_from_datastore(self, shard_id=None):
    """"""
    self._work = {}
    client = self._datastore_client
    parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id)
    filters = [('is_completed', '=', False)]
    if shard_id is not None:
      filters.append(('shard_id', '=', shard_id))
    for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key,
                                     filters=filters):
      work_id = entity.key.flat_path[-1]
      self.work[work_id] = dict(entity)
      if len(self._work) >= MAX_WORK_RECORDS_READ:
        break
1265667
def _wiki_urls_for_shard(shard_id, urls_dir=None):
  """"""
  urls_dir = urls_dir or WIKI_URLS_DIR
  urls_filepath = os.path.join(urls_dir, WIKI_URLS_FILE % shard_id)
  with tf.gfile.GFile(urls_filepath) as f:
    return json.loads(f.read())
339522
def get_shard_map(self, force_refresh=False):
        
        now = datetime.utcnow()
        if force_refresh is True or \
                        self.shard_map is None or \
                        (now - self.last_refresh).total_seconds() > self.refresh_ttl:
            self.last_refresh = now
            self.refresh_shard_map()
        return self.shard_map
60088
def cdbs(client, event, channel, nick, rest):
	
	db_name, shard = shlex.split(rest)
	return sharding.create_db_in_shard(db_name, shard, client=get_client())