Python math.floor() Examples

The following are code examples for showing how to use math.floor(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: Adafruit_Python_PCA9685   Author: adafruit   File: PCA9685.py    (MIT License) View Source Project 7 votes vote down vote up
def set_pwm_freq(self, freq_hz):
        """Set the PWM frequency to the provided value in hertz."""
        prescaleval = 25000000.0    # 25MHz
        prescaleval /= 4096.0       # 12-bit
        prescaleval /= float(freq_hz)
        prescaleval -= 1.0
        logger.debug('Setting PWM frequency to {0} Hz'.format(freq_hz))
        logger.debug('Estimated pre-scale: {0}'.format(prescaleval))
        prescale = int(math.floor(prescaleval + 0.5))
        logger.debug('Final pre-scale: {0}'.format(prescale))
        oldmode = self._device.readU8(MODE1);
        newmode = (oldmode & 0x7F) | 0x10    # sleep
        self._device.write8(MODE1, newmode)  # go to sleep
        self._device.write8(PRESCALE, prescale)
        self._device.write8(MODE1, oldmode)
        time.sleep(0.005)
        self._device.write8(MODE1, oldmode | 0x80) 
Example 2
Project: Blender-power-sequencer   Author: GDquest   File: video_editing_mouse.py    (license) View Source Project 6 votes vote down vote up
def invoke(self, context, event):
        sequencer = bpy.ops.sequencer

        # get current frame and channel the mouse hovers
        x, y = context.region.view2d.region_to_view(
            x=event.mouse_region_x,
            y=event.mouse_region_y)
        frame, channel = round(x), floor(y)

        # Strip selection
        sequencer.select_all(action='DESELECT')
        to_select = find_strips_mouse(frame, channel)

        if not to_select:
            return {"CANCELLED"}

        for s in to_select:
            s.mute = not s.mute
        return {"FINISHED"} 
Example 3
Project: PyPlanet   Author: PyPlanet   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def create_vote(self, action, player, finished_event):
		new_vote = Vote()
		new_vote.action = action
		new_vote.requester = player
		new_vote.votes_current = []
		needed_votes = math.ceil(self.instance.player_manager.count_players / 2)
		if needed_votes == math.floor(self.instance.player_manager.count_players / 2):
			needed_votes += 1
		if needed_votes > self.instance.player_manager.count_players:
			needed_votes = self.instance.player_manager.count_players
		new_vote.votes_required = needed_votes
		new_vote.vote_added = self.vote_added
		new_vote.vote_removed = self.vote_removed
		new_vote.vote_finished = finished_event

		asyncio.ensure_future(self.vote_reminder(new_vote))

		return new_vote 
Example 4
Project: PyPlanet   Author: PyPlanet   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def pay_to_player(self, player, data, **kwargs):
		try:
			amount = abs(int(data.amount))

			planets = await self.instance.gbx('GetServerPlanets')
			if amount <= (planets - 2 - math.floor(amount * 0.05)):
				async with self.lock:
					bill_id = await self.instance.gbx('Pay', data.login, amount, 'Payment from the server')
					self.current_bills[bill_id] = dict(bill=bill_id, admin=player, player=data.login, amount=-amount)
			else:
				message = '$i$f00Insufficient balance for paying $fff{}$f00 ($fff{}$f00 inc. tax) planets, only got $fff{}$f00.'.format(
					amount, (amount + 2 + math.floor(amount * 0.05)), planets
				)
				await self.instance.chat(message, player)
		except ValueError:
			message = '$z$s$fff» $i$f00The amount should be a numeric value.'
			await self.instance.chat(message, player) 
Example 5
Project: PyPlanet   Author: PyPlanet   File: times.py    (license) View Source Project 6 votes vote down vote up
def format_time(time):
	"""
	Format time from integer milliseconds to string format that could be displayed to the end-user.
	
	:param time: Integer time in milliseconds.
	:type time: int
	:return: String output
	:rtype: str
	"""
	hours = math.floor((time / 1000 / 60 / 60))
	minutes = math.floor((time - (hours * 60 * 60 * 1000)) / 1000 / 60)
	seconds = math.floor((time - (hours * 60 * 60 * 1000) - (minutes * 60 * 1000)) / 1000)
	millis = (time - (hours * 60 * 60 * 1000) - (minutes * 60 * 1000) - (seconds * 1000))

	formatted_time = ''
	if hours > 0:
		formatted_time += '{:02d}:{:02d}:'.format(hours, minutes)
	else:
		formatted_time += '{}:'.format(str(minutes))
	return formatted_time + '{:02d}.{:03d}'.format(seconds, millis) 
Example 6
Project: human-rl   Author: gsastry   File: classifier_tf.py    (MIT License) View Source Project 6 votes vote down vote up
def split_episodes(self, episode_paths, n_train, n_valid, n_test, seed=None, use_all=True):
        """Split episodes between training, validation and test sets.

        seed: random seed (have split performed consistently every time)"""
        if seed is not None:
            random_state = np.random.get_state()
            np.random.seed(seed)
            np.random.shuffle(episode_paths)
            np.random.set_state(random_state)
        else:
            np.random.shuffle(episode_paths)
        if use_all:
            multiplier = float(len(episode_paths)) / float(n_train + n_valid + n_test)
            n_train = int(math.floor(multiplier * n_train))
            n_valid = int(math.floor(multiplier * n_valid))
            n_test = int(math.floor(multiplier * n_test))

        assert n_train + n_valid + n_test <= len(episode_paths)
        return (episode_paths[:n_train], episode_paths[n_train:n_train + n_valid],
                episode_paths[n_train + n_test:n_train + n_test + n_test]) 
Example 7
Project: human-rl   Author: gsastry   File: classifier_tf.py    (MIT License) View Source Project 6 votes vote down vote up
def split_episodes(self, episode_paths, n_train, n_valid, n_test, seed=None, use_all=True):
        """Split episodes between training, validation and test sets.

        seed: random seed (have split performed consistently every time)"""
        if seed is not None:
            random_state = np.random.get_state()
            np.random.seed(seed)
            np.random.shuffle(episode_paths)
            np.random.set_state(random_state)
        else:
            np.random.shuffle(episode_paths)
        if use_all:
            multiplier = float(len(episode_paths)) / float(n_train + n_valid + n_test)
            n_train = int(math.floor(multiplier * n_train))
            n_valid = int(math.floor(multiplier * n_valid))
            n_test = int(math.floor(multiplier * n_test))

        assert n_train + n_valid + n_test <= len(episode_paths)
        return (episode_paths[:n_train], episode_paths[n_train:n_train + n_valid],
                episode_paths[n_train + n_test:n_train + n_test + n_test]) 
Example 8
Project: human-rl   Author: gsastry   File: classifier_tf.py    (MIT License) View Source Project 6 votes vote down vote up
def split_episodes(self, episode_paths, n_train, n_valid, n_test, seed=None, use_all=True):
        """Split episodes between training, validation and test sets.

        seed: random seed (have split performed consistently every time)"""
        if seed is not None:
            random_state = np.random.get_state()
            np.random.seed(seed)
            np.random.shuffle(episode_paths)
            np.random.set_state(random_state)
        else:
            np.random.shuffle(episode_paths)
        if use_all:
            multiplier = float(len(episode_paths)) / float(n_train + n_valid + n_test)
            n_train = int(math.floor(multiplier * n_train))
            n_valid = int(math.floor(multiplier * n_valid))
            n_test = int(math.floor(multiplier * n_test))

        assert n_train + n_valid + n_test <= len(episode_paths)
        return (episode_paths[:n_train], episode_paths[n_train:n_train + n_valid],
                episode_paths[n_train + n_test:n_train + n_test + n_test]) 
Example 9
Project: human-rl   Author: gsastry   File: classifier_tf.py    (MIT License) View Source Project 6 votes vote down vote up
def split_episodes(self, episode_paths, n_train, n_valid, n_test, seed=None, use_all=True):
        """Split episodes between training, validation and test sets.

        seed: random seed (have split performed consistently every time)"""
        if seed is not None:
            random_state = np.random.get_state()
            np.random.seed(seed)
            np.random.shuffle(episode_paths)
            np.random.set_state(random_state)
        else:
            np.random.shuffle(episode_paths)
        if use_all:
            multiplier = float(len(episode_paths)) / float(n_train + n_valid + n_test)
            n_train = int(math.floor(multiplier * n_train))
            n_valid = int(math.floor(multiplier * n_valid))
            n_test = int(math.floor(multiplier * n_test))

        assert n_train + n_valid + n_test <= len(episode_paths)
        return (episode_paths[:n_train], episode_paths[n_train:n_train + n_valid],
                episode_paths[n_train + n_test:n_train + n_test + n_test]) 
Example 10
Project: Tencent2017_Final_Rank28_code   Author: Dojocat-GO   File: 5_trick_feature.py    (license) View Source Project 6 votes vote down vote up
def interclick(clicktime1, clicktime2):
    second1 = clicktime1 % 100
    clicktime1 = clicktime1 // 100
    min1 = clicktime1 % 100
    hour1 = math.floor((clicktime1 % 10000) / 100)
    day1 = math.floor(clicktime1 / 10000)

    second2 = clicktime2 % 100
    clicktime2 = clicktime2 // 100
    min2 = clicktime2 % 100
    hour2 = math.floor((clicktime2 % 10000) / 100)
    day2 = math.floor(clicktime2 / 10000)
    interclicktime_min = ((day2 * 1440 + hour2 * 60 + min2) - (day1 * 1440 + hour1 * 60 + min1))
    interclicktime_second = ((day2 * 1440 + hour2 * 60 + min2) * 60 + second2) - (
    (day1 * 1440 + hour1 * 60 + min1) * 60 + second1)
    return interclicktime_min, interclicktime_second 
Example 11
Project: findcve   Author: garethr   File: findcve.py    (license) View Source Project 6 votes vote down vote up
def lumogon(file):
    """
    Lumogon scans the output from the lumogon container
    inspection tool
    """
    cve_data = load_vulnerability_database()
    containers = load_data(file)["containers"]
    for container in containers:
        click.secho("==> Scanning %s" % containers[container]["container_name"], fg="blue")
        packages = containers[container]["capabilities"]["dpkg"]["payload"]
        host = containers[container]["capabilities"]["host"]["payload"]
        os = DEBIAN_CODENAMES[math.floor(float(host["platformversion"]))]
        for package in sorted(packages):
            version = packages[package]
            vulns = determine_cves(package, version, os, cve_data)
            print_vulns(package, vulns) 
Example 12
Project: NeoAnalysis   Author: neoanalysis   File: graphics.py    (license) View Source Project 6 votes vote down vote up
def __nearest_pow_2(self,x):
        """
        Find power of two nearest to x
        >>> _nearest_pow_2(3)
        2.0
        >>> _nearest_pow_2(15)
        16.0
        :type x: float
        :param x: Number
        :rtype: Int
        :return: Nearest power of 2 to x
        """
        a = math.pow(2, math.ceil(np.log2(x)))
        b = math.pow(2, math.floor(np.log2(x)))
        if abs(a - x) < abs(b - x):
            return a
        else:
            return b
    
    # calculate spectrogram of signals 
Example 13
Project: NeoAnalysis   Author: neoanalysis   File: func_tools.py    (license) View Source Project 6 votes vote down vote up
def _nearest_pow_2(x):
    """
    Find power of two nearest to x
    >>> _nearest_pow_2(3)
    2.0
    >>> _nearest_pow_2(15)
    16.0
    :type x: float
    :param x: Number
    :rtype: Int
    :return: Nearest power of 2 to x
    """
    a = M.pow(2, M.ceil(np.log2(x)))
    b = M.pow(2, M.floor(np.log2(x)))
    if abs(a - x) < abs(b - x):
        return a
    else:
        return b 
Example 14
Project: NeoAnalysis   Author: neoanalysis   File: func_tools.py    (license) View Source Project 6 votes vote down vote up
def _nearest_pow_2(x):
    """
    Find power of two nearest to x
    >>> _nearest_pow_2(3)
    2.0
    >>> _nearest_pow_2(15)
    16.0
    :type x: float
    :param x: Number
    :rtype: Int
    :return: Nearest power of 2 to x
    """
    a = M.pow(2, M.ceil(np.log2(x)))
    b = M.pow(2, M.floor(np.log2(x)))
    if abs(a - x) < abs(b - x):
        return a
    else:
        return b 
Example 15
Project: Projects   Author: it2school   File: util.py    (license) View Source Project 6 votes vote down vote up
def compute_logarithmic_scale(min_, max_, min_scale, max_scale):
    """Compute an optimal scale for logarithmic"""
    if max_ <= 0 or min_ <= 0:
        return []
    min_order = int(floor(log10(min_)))
    max_order = int(ceil(log10(max_)))
    positions = []
    amplitude = max_order - min_order
    if amplitude <= 1:
        return []
    detail = 10.
    while amplitude * detail < min_scale * 5:
        detail *= 2
    while amplitude * detail > max_scale * 3:
        detail /= 2
    for order in range(min_order, max_order + 1):
        for i in range(int(detail)):
            tick = (10 * i / detail or 1) * 10 ** order
            tick = round_to_scale(tick, tick)
            if min_ <= tick <= max_ and tick not in positions:
                positions.append(tick)
    return positions 
Example 16
Project: code   Author: ActiveState   File: recipe-511478.py    (MIT License) View Source Project 6 votes vote down vote up
def percentile(N, percent, key=lambda x:x):
    """
    Find the percentile of a list of values.

    @parameter N - is a list of values. Note N MUST BE already sorted.
    @parameter percent - a float value from 0.0 to 1.0.
    @parameter key - optional key function to compute value from each element of N.

    @return - the percentile of the values
    """
    if not N:
        return None
    k = (len(N)-1) * percent
    f = math.floor(k)
    c = math.ceil(k)
    if f == c:
        return key(N[int(k)])
    d0 = key(N[int(f)]) * (c-k)
    d1 = key(N[int(c)]) * (k-f)
    return d0+d1

# median is 50th percentile. 
Example 17
Project: BookCloud   Author: livro-aberto   File: __init__.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def package():
    sent_package = {}
    sent_package['get_requests'] = get_requests
    def has_requests(project, branch):
        return len(get_requests(project, branch)) > 0
    sent_package['has_requests'] = has_requests
    sent_package['get_log_diff'] = get_log_diff
    sent_package['last_modified'] = last_modified
    sent_package['get_branch_by_name'] = get_branch_by_name
    sent_package['hash'] = lambda x: hashlib.sha256(x).hexdigest()
    sent_package['_'] = _
    sent_package['url_encode'] = lambda x: urllib.quote(x, safe='')
    sent_package['current_user'] = current_user
    sent_package['floor'] = math.floor
    sent_package['len'] = len
    sent_package['getattr'] = getattr
    sent_package['commit_diff'] = commit_diff
    return sent_package 
Example 18
Project: Harmonbot   Author: Harmon758   File: adventure.py    (license) View Source Project 6 votes vote down vote up
def stop_foraging(self):
		if self.last_action and self.last_action[0] == "foraging":
			item = self.last_action[1]
			time_spent = math.ceil(time.time() - self.last_action_time) / 60
			self.last_action = None
			self.last_action_time = None
			item_amount = math.floor(time_spent * self.foraging_rate)
			self.inventory[item] = self.inventory.get(item, 0) + item_amount
			if self.inventory[item] == 0:
				del self.inventory[item]
			self.foraging_xp += item_amount
			secondary_item = forageables[item][0]
			tertiary_item = forageables[item][1]
			secondary_amount = random.randint(0, item_amount)
			tertiary_amount = math.floor(random.randint(0, item_amount) / 100)
			self.inventory[secondary_item] = self.inventory.get(secondary_item, 0) + secondary_amount
			if self.inventory[secondary_item] == 0:
				del self.inventory[secondary_item]
			self.inventory[tertiary_item] = self.inventory.get(tertiary_item, 0) + tertiary_amount
			if self.inventory[tertiary_item] == 0:
				del self.inventory[tertiary_item]
			self.write_data()
			return item, time_spent, item_amount, secondary_amount, tertiary_amount
		else:
			return False, self.last_action 
Example 19
Project: Harmonbot   Author: Harmon758   File: adventure.py    (license) View Source Project 6 votes vote down vote up
def stop_woodcutting(self):
		if self.last_action and self.last_action[0] == "woodcutting":
			wood_type = self.last_action[1]
			time_spent = math.ceil(time.time() - self.last_action_time) / 60
			self.last_action = None
			self.last_action = None
			current_wood_lvl = wood_lvl(wood_type)
			wood_amount = math.floor(time_spent * self.wood_rate(wood_type) * self.woodcutting_rate)
			xp_amount = current_wood_lvl * wood_amount
			self.inventory[wood_type] = self.inventory.get(wood_type, 0) + wood_amount
			if self.inventory[wood_type] == 0:
				del self.inventory[wood_type]
			self.woodcutting_xp += xp_amount
			self.write_data()
			return wood_type, time_spent, wood_amount, xp_amount
		else:
			return False, self.last_action 
Example 20
Project: supremm   Author: ubccr   File: supremm_testharness.py    (GNU Lesser General Public License v3.0) View Source Project 6 votes vote down vote up
def __init__(self, archivelist):
        self.node_archives = archivelist
        self.jobdir = os.path.dirname(archivelist[0])
        self.job_id = "1"
        self.end_str = "end"
        self.walltime = 9751
        self.nodecount = len(archivelist)
        self.acct = {"end_time": 12312, "id": 1, "uid": "sdf", "user": "werqw"}
        self.nodes = ["node" + str(i) for i in xrange(len(archivelist))]
        self._data = {}

        archive_starts = []
        archive_ends = []
        for archive in archivelist:
            context = pmapi.pmContext(c_pmapi.PM_CONTEXT_ARCHIVE, archive)
            mdata = context.pmGetArchiveLabel()
            archive_starts.append(datetime.datetime.utcfromtimestamp(math.floor(mdata.start)))
            archive_ends.append(datetime.datetime.utcfromtimestamp(math.ceil(context.pmGetArchiveEnd())))

        self.start_datetime = min(archive_starts)
        self.end_datetime = max(archive_ends) 
Example 21
Project: supremm   Author: ubccr   File: pcparchive.py    (GNU Lesser General Public License v3.0) View Source Project 6 votes vote down vote up
def adjust_job_start_end(job):
    """ Set the job node start and end times based on the presence of the special
     job-X-begin and job-X-end archives. Do nothing if these archives are absent
    """

    startarchive = "job-{0}-begin".format(job.job_id)
    endarchive = "job-{0}-end".format(job.job_id)

    for nodename, filepaths in job.rawarchives():
        begin = None
        end = None
        for fname in filepaths:
            filename = os.path.basename(fname)
            if filename.startswith(startarchive):
                context = pmapi.pmContext(c_pmapi.PM_CONTEXT_ARCHIVE, fname)
                mdata = context.pmGetArchiveLabel()
                begin = datetime.datetime.utcfromtimestamp(math.floor(mdata.start))

            if filename.startswith(endarchive):
                context = pmapi.pmContext(c_pmapi.PM_CONTEXT_ARCHIVE, fname)
                end = datetime.datetime.utcfromtimestamp(math.ceil(context.pmGetArchiveEnd()))

        job.setnodebeginend(nodename, begin, end) 
Example 22
Project: TFCommon   Author: MU94W   File: util.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, data, batch_size, big_batch=10):
        self.data_inp       = [item + [_EOS_ID] for item in data['input']]
        self.data_spc       = data['speaker_code']
        self.data_out       = data['output']
        self.samples        = len(self.data_inp)
        self.batch_size     = batch_size
        self.big_batch      = big_batch
        self.big_batch_step = 0
        if batch_size == 'all':
            self.batch_size = self.samples
            self.big_batch = 1
        if self.samples < self.big_batch * self.batch_size:
            self.max_batch_step = ceil(self.samples / (self.big_batch * self.batch_size))
        else:
            self.max_batch_step = floor(self.samples / (self.big_batch * self.batch_size)) - 1
        self.run_through    = 0
        self.perm           = None
        self.perm_index     = np.arange(min(self.big_batch * self.batch_size, self.samples))
        self.batch          = None 
Example 23
Project: lib-gatilegrid   Author: geoadmin   File: tilegrids.py    (MIT License) View Source Project 6 votes vote down vote up
def tileAddress(self, zoom, point):
        "Returns a tile address based on a zoom level and \
        a point in the tile"
        [x, y] = point
        assert x <= self.extent[2] and x >= self.extent[0]
        assert y <= self.extent[3] and y >= self.extent[1]
        assert zoom in range(0, len(self.RESOLUTIONS))

        tileS = self.tileSize(zoom)
        offsetX = abs(x - self.MINX)
        if self.originCorner == 'bottom-left':
            offsetY = abs(y - self.MINY)
        elif self.originCorner == 'top-left':
            offsetY = abs(self.MAXY - y)
        col = offsetX / tileS
        row = offsetY / tileS
        # We are exactly on the edge of a tile and the extent
        if x in (self.MINX, self.MAXX) and col.is_integer():
            col = max(0, col - 1)
        if y in (self.MINY, self.MAXY) and row.is_integer():
            row = max(0, row - 1)
        return [
            int(math.floor(col)),
            int(math.floor(row))
        ] 
Example 24
Project: ResNeXt-DenseNet   Author: D-X-Y   File: resnext.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, inplanes, planes, cardinality, base_width, stride=1, downsample=None):
    super(ResNeXtBottleneck, self).__init__()

    D = int(math.floor(planes * (base_width/64.0)))
    C = cardinality

    self.conv_reduce = nn.Conv2d(inplanes, D*C, kernel_size=1, stride=1, padding=0, bias=False)
    self.bn_reduce = nn.BatchNorm2d(D*C)

    self.conv_conv = nn.Conv2d(D*C, D*C, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False)
    self.bn = nn.BatchNorm2d(D*C)

    self.conv_expand = nn.Conv2d(D*C, planes*4, kernel_size=1, stride=1, padding=0, bias=False)
    self.bn_expand = nn.BatchNorm2d(planes*4)

    self.downsample = downsample 
Example 25
Project: MLPractices   Author: carefree0910   File: Networks.py    (MIT License) View Source Project 6 votes vote down vote up
def predict(self, x):
        x = NNDist._transfer_x(np.asarray(x))
        rs = []
        batch_size = floor(1e6 / np.prod(x.shape[1:]))
        epoch = int(ceil(len(x) / batch_size))
        output = self._sess.graph.get_tensor_by_name(self._output)
        bar = ProgressBar(max_value=epoch, name="Predict")
        bar.start()
        for i in range(epoch):
            if i == epoch - 1:
                rs.append(self._sess.run(output, {
                    self._entry: x[i * batch_size:]
                }))
            else:
                rs.append(self._sess.run(output, {
                    self._entry: x[i * batch_size:(i + 1) * batch_size]
                }))
            bar.update()
        return np.vstack(rs).astype(np.float32) 
Example 26
Project: Qkou_kit   Author: pddg   File: jholiday.py    (MIT License) View Source Project 6 votes vote down vote up
def _vernal_equinox(y):
    """???????????????????3???????????
"""
    if y <= 1947:
        d = 0
    elif y <= 1979:
        d = math.floor(
            20.8357 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    elif y <= 2099:
        d = math.floor(
            20.8431 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    elif y <= 2150:
        d = math.floor(
            21.8510 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    else:
        d = 99

    return d 
Example 27
Project: Qkou_kit   Author: pddg   File: jholiday.py    (MIT License) View Source Project 6 votes vote down vote up
def _autumn_equinox(y):
    """???????????????????9???????????
"""
    if y <= 1947:
        d = 0
    elif y <= 1979:
        d = math.floor(
            23.2588 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    elif y <= 2099:
        d = math.floor(
            23.2488 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    elif y <= 2150:
        d = math.floor(
            24.2488 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    else:
        d = 99

    return d 
Example 28
Project: workflows.kyoyue   Author: wizyoung   File: util.py    (MIT License) View Source Project 6 votes vote down vote up
def mask_func(pattern):
    """
    Return the mask function for the given mask pattern.
    """
    if pattern == 0:   # 000
        return lambda i, j: (i + j) % 2 == 0
    if pattern == 1:   # 001
        return lambda i, j: i % 2 == 0
    if pattern == 2:   # 010
        return lambda i, j: j % 3 == 0
    if pattern == 3:   # 011
        return lambda i, j: (i + j) % 3 == 0
    if pattern == 4:   # 100
        return lambda i, j: (math.floor(i / 2) + math.floor(j / 3)) % 2 == 0
    if pattern == 5:  # 101
        return lambda i, j: (i * j) % 2 + (i * j) % 3 == 0
    if pattern == 6:  # 110
        return lambda i, j: ((i * j) % 2 + (i * j) % 3) % 2 == 0
    if pattern == 7:  # 111
        return lambda i, j: ((i * j) % 3 + (i + j) % 2) % 2 == 0
    raise TypeError("Bad mask pattern: " + pattern)  # pragma: no cover 
Example 29
Project: Solo-Mapper   Author: Escadrone   File: Adafruit_PWM_Servo_Driver.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def setPWMFreq(self, freq):
    "Sets the PWM frequency"
    prescaleval = 25000000.0    # 25MHz
    prescaleval /= 4096.0       # 12-bit
    prescaleval /= float(freq)
    prescaleval -= 1.0
    if (self.debug):
      print "Setting PWM frequency to %d Hz" % freq      
      print "Estimated pre-scale: %d" % prescaleval      
    prescale = math.floor(prescaleval + 0.5)
    if (self.debug):
      print "Final pre-scale: %d" % prescale      

    oldmode = self.i2c.readU8(self.__MODE1);
    newmode = (oldmode & 0x7F) | 0x10             # sleep
    self.i2c.write8(self.__MODE1, newmode)        # go to sleep
    self.i2c.write8(self.__PRESCALE, int(math.floor(prescale)))
    self.i2c.write8(self.__MODE1, oldmode)
    time.sleep(0.005)
    self.i2c.write8(self.__MODE1, oldmode | 0x80) 
Example 30
Project: pytorch-dist   Author: apaszke   File: SpatialFractionalMaxPooling.py    (license) View Source Project 6 votes vote down vote up
def _getOutputSizes(self, input):
        outW = self.outW
        outH = self.outH
        if self.ratioW != None and self.ratioH != None:
            assert input.ndimension() == 4
            outW = int(math.floor(input.size(3) * self.ratioW))
            outH = int(math.floor(input.size(2) * self.ratioH))

            # Neither can be smaller than 1
            assert outW > 0
            assert outH > 0
        else:
            assert outW != None and outH != None

        return outW, outH

    # Call this to turn off regeneration of random pooling regions each
    # updateOutput call. 
Example 31
Project: pytorch-dist   Author: apaszke   File: test_utils.py    (license) View Source Project 6 votes vote down vote up
def test_plugin_interval(self):
        for interval in self.intervals:
            self.setUp()
            simple_plugin = SimplePlugin(interval)
            self.trainer.register_plugin(simple_plugin)
            self.trainer.run(epochs=self.num_epochs)
            units = {
                ('iteration', self.num_iters),
                ('epoch', self.num_epochs),
                ('batch', self.num_iters),
                ('update', self.num_iters)
            }
            for unit, num_triggers in units:
                call_every = None
                for i, i_unit in interval:
                    if i_unit == unit:
                        call_every = i
                        break
                if call_every:
                    expected_num_calls = math.floor(num_triggers / call_every)
                else:
                    expected_num_calls = 0
                num_calls = getattr(simple_plugin, 'num_' + unit)
                self.assertEqual(num_calls, expected_num_calls, 0) 
Example 32
Project: pytorch-dist   Author: apaszke   File: test_dataloader.py    (license) View Source Project 6 votes vote down vote up
def _test_shuffle(self, loader):
        found_data = {i: 0 for i in range(self.data.size(0))}
        found_labels = {i: 0 for i in range(self.labels.size(0))}
        batch_size = loader.batch_size
        for i, (batch_samples, batch_targets) in enumerate(loader):
            for sample, target in zip(batch_samples, batch_targets):
                for data_point_idx, data_point in enumerate(self.data):
                    if data_point.eq(sample).all():
                        self.assertFalse(found_data[data_point_idx])
                        found_data[data_point_idx] += 1
                        break
                self.assertEqual(target, self.labels.narrow(0, data_point_idx, 1))
                found_labels[data_point_idx] += 1
            self.assertEqual(sum(found_data.values()), (i+1) * batch_size)
            self.assertEqual(sum(found_labels.values()), (i+1) * batch_size)
        self.assertEqual(i, math.floor((len(self.dataset)-1) / batch_size)) 
Example 33
Project: pytorch-dist   Author: apaszke   File: test_torch.py    (license) View Source Project 6 votes vote down vote up
def test_abs(self):
        size = 1000
        max_val = 1000
        original = torch.rand(size).mul(max_val)
        # Tensor filled with values from {-1, 1}
        switch = torch.rand(size).mul(2).floor().mul(2).add(-1)

        types = ['torch.DoubleTensor', 'torch.FloatTensor', 'torch.LongTensor', 'torch.IntTensor']
        for t in types:
            data = original.type(t)
            switch = switch.type(t)
            res = torch.mul(data, switch)
            self.assertEqual(res.abs(), data, 1e-16)

        # Checking that the right abs function is called for LongTensor
        bignumber = 2^31 + 1
        res = torch.LongTensor((-bignumber,))
        self.assertGreater(res.abs()[0], 0) 
Example 34
Project: Stitch   Author: nathanlopez   File: fileinfo.py    (license) View Source Project 5 votes vote down vote up
def convertSize(size):
   if (size == 0):
       return '0 Bytes'
   size_name = ("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
   i = int(math.floor(math.log(size,1024)))
   p = math.pow(1024,i)
   s = round(size/p,2)
   return '{} {}'.format(s,size_name[i])

#http://stackoverflow.com/questions/1392413/calculating-a-directory-size-using-python 
Example 35
Project: Stitch   Author: nathanlopez   File: stitch_utils.py    (license) View Source Project 5 votes vote down vote up
def convertSize(size):
   if (size == 0):
       return '0 Bytes'
   size_name = ("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
   i = int(math.floor(math.log(size,1024)))
   p = math.pow(1024,i)
   s = round(size/p,2)
   return '{} {}'.format(s,size_name[i]) 
Example 36
Project: IntroToDeepLearning   Author: robb-brown   File: TensorFlowInterface.py    (MIT License) View Source Project 5 votes vote down vote up
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
	# Receptive Fields Summary
	try:
		W = layer.W
	except:
		W = layer
	wp = W.eval().transpose();
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)	
	else:			# Convolutional layer already has shape
		features, channels, iy, ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))

	fig = mpl.figure(figOffset); mpl.clf()
	
	# Using image grid
	from mpl_toolkits.axes_grid1 import ImageGrid
	grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
	for i in range(0,np.shape(fields)[0]):
		im = grid[i].imshow(fields[i],cmap=cmap); 

	grid.cbar_axes[0].colorbar(im)
	mpl.title('%s Receptive Fields' % layer.name)
	
	# old way
	# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	# tiled = []
	# for i in range(0,perColumn*perRow,perColumn):
	# 	tiled.append(np.hstack(fields2[i:i+perColumn]))
	# 
	# tiled = np.vstack(tiled)
	# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
	mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar() 
Example 37
Project: IntroToDeepLearning   Author: robb-brown   File: TensorFlowInterface.py    (MIT License) View Source Project 5 votes vote down vote up
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
	# Output summary
	try:
		W = layer.output
	except:
		W = layer
	wp = W.eval(feed_dict=feed_dict);
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
		fields = np.reshape(temp,[1]+fieldShape)
	else:			# Convolutional layer already has shape
		wp = np.rollaxis(wp,3,0)
		features, channels, iy,ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
	fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	tiled = []
	for i in range(0,perColumn*perRow,perColumn):
		tiled.append(np.hstack(fields2[i:i+perColumn]))

	tiled = np.vstack(tiled)
	if figOffset is not None:
		mpl.figure(figOffset); mpl.clf(); 

	mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar(); 
Example 38
Project: IntroToDeepLearning   Author: robb-brown   File: TensorFlowInterface.py    (MIT License) View Source Project 5 votes vote down vote up
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
	# Receptive Fields Summary
	W = layer.W
	wp = W.eval().transpose();
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
	else:			# Convolutional layer already has shape
		features, channels, iy, ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	fieldsN = min(fields.shape[0],maxFields)
	perRow = int(math.floor(math.sqrt(fieldsN)))
	perColumn = int(math.ceil(fieldsN/float(perRow)))

	fig = mpl.figure(figName); mpl.clf()

	# Using image grid
	from mpl_toolkits.axes_grid1 import ImageGrid
	grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
	for i in range(0,fieldsN):
		im = grid[i].imshow(fields[i],cmap=cmap);

	grid.cbar_axes[0].colorbar(im)
	mpl.title('%s Receptive Fields' % layer.name)

	# old way
	# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	# tiled = []
	# for i in range(0,perColumn*perRow,perColumn):
	# 	tiled.append(np.hstack(fields2[i:i+perColumn]))
	#
	# tiled = np.vstack(tiled)
	# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
	mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar() 
Example 39
Project: IntroToDeepLearning   Author: robb-brown   File: TensorFlowInterface.py    (MIT License) View Source Project 5 votes vote down vote up
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
	# Output summary
	W = layer.output
	wp = W.eval(feed_dict=feed_dict);
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
		fields = np.reshape(temp,[1]+fieldShape)
	else:			# Convolutional layer already has shape
		wp = np.rollaxis(wp,3,0)
		features, channels, iy,ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
	fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	tiled = []
	for i in range(0,perColumn*perRow,perColumn):
		tiled.append(np.hstack(fields2[i:i+perColumn]))

	tiled = np.vstack(tiled)
	if figOffset is not None:
		mpl.figure(figOffset); mpl.clf();

	mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar(); 
Example 40
Project: PGO-mapscan-opt   Author: seikur0   File: maplib.py    (license) View Source Project 5 votes vote down vote up
def cover_region_simple(self, location1, location2):  # lat values must be between -90 and +90, lng values must be between -180 and 180
        l_lat1 = location1[0]
        l_lat2 = location2[0]
        l_lng1 = location1[1]
        l_lng2 = location2[1]

        ind_lat_f = 0
        while l_lat1 > self.grid[ind_lat_f][0]:
            ind_lat_f += 1

        ind_lat_t = ind_lat_f + 1
        while ind_lat_t < len(self.grid) and l_lat2 >= self.grid[ind_lat_t][0]:
            ind_lat_t += 1
        points = []
        for ind_lat in range(ind_lat_f, ind_lat_t):
            d_lng = 360.0 / self.grid[ind_lat][1]
            if self.grid[ind_lat][2]:
                c_lng = 0.0
            else:
                c_lng = 0.5

            ind_lng_f = int(ceil(l_lng1 / d_lng - c_lng))
            ind_lng_t = int(floor(l_lng2 / d_lng - c_lng))
            for ind_lng in range(ind_lng_f, ind_lng_t + 1):
                points.append([self.grid[ind_lat][0], d_lng * (ind_lng + c_lng)])

        return points 
Example 41
Project: YellowFin_Pytorch   Author: JianGoForIt   File: long_stress_test.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def timeSince(since):
    now = time.time()
    s = now - since
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s)


# In[14]: 
Example 42
Project: YellowFin_Pytorch   Author: JianGoForIt   File: nn1_stress_test.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def timeSince(since):
    now = time.time()
    s = now - since
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s) 
Example 43
Project: YellowFin_Pytorch   Author: JianGoForIt   File: test-ckpt-disk.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def timeSince(since):
    now = time.time()
    s = now - since
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s) 
Example 44
Project: YellowFin_Pytorch   Author: JianGoForIt   File: test-ckpt-memory.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def timeSince(since):
    now = time.time()
    s = now - since
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s) 
Example 45
Project: YellowFin_Pytorch   Author: JianGoForIt   File: nn1.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def timeSince(since):
    now = time.time()
    s = now - since
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s) 
Example 46
Project: Blender-power-sequencer   Author: GDquest   File: video_editing_mouse.py    (license) View Source Project 5 votes vote down vote up
def find_cut_and_handles_closest_to_mouse(mouse_x, mouse_y):
    """
    takes the mouse's coordinates in the sequencer area and returns the two strips
    who share the cut closest to the mouse, or the strip with the closest handle.
    Use it to find the handle(s) to select with the grab on the fly operator
    """
    view2d = bpy.context.region.view2d

    closest_cut = (None, None)
    distance_to_closest_cut = 1000000.0

    for s in bpy.context.sequences:
        channel_offset = s.channel + 0.5
        start_x, start_y = view2d.view_to_region(s.frame_final_start, channel_offset)
        end_x, end_y = view2d.view_to_region(s.frame_final_start, channel_offset)

        distance_to_start = calculate_distance(start_x, start_y, mouse_x, mouse_y)
        distance_to_end = calculate_distance(end_x, end_y, mouse_x, mouse_y)

        if distance_to_start < distance_to_closest_cut:
            closest_cut = (start_x, start_y)
            distance_to_closest_cut = distance_to_start
        if distance_to_end < distance_to_closest_cut:
            closest_cut = (end_x, end_y)
            distance_to_closest_cut = distance_to_end

    closest_cut_local_coords = view2d.region_to_view(closest_cut[0], closest_cut[1])
    frame, channel = round(closest_cut_local_coords[0]), floor(closest_cut_local_coords[1])
    return frame, channel 
Example 47
Project: RasterFairy   Author: Quasimondo   File: prime.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def isPrime(self,n):
        if (n & 1) == 0 or (n > 5 and n % 5 == 0):
            return False

        maxCheck = math.sqrt(n)
        if maxCheck == math.floor(maxCheck):
            return False
        
        p = self.firstPrime
        while p != None:
            if p.n > maxCheck:
                return True
            if n % p.n == 0:
                return False
            p = p.nextPrime

        divisor = self.lastPrime.n + 2
        while divisor <= maxCheck:
            if not self.isPrime(divisor):
                divisor += 2
                continue
            self.lastPrime = self.lastPrime.setNext(divisor)
            if divisor > maxCheck:
                return True
            if n % divisor == 0:
                return False
            divisor += 2
        return True 
Example 48
Project: RasterFairy   Author: Quasimondo   File: rasterfairy.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def getShiftedTriangularArrangement(n):

    t = math.sqrt(8 * n + 1);
    if t != math.floor(t):
        return []
    
    arrangement = []
    i = 1
    while n>0:
        arrangement.append(i)
        n-=i
        i+=1
    
    return [{'hex':True,'rows':arrangement,'type':'triangular'}] 
Example 49
Project: RasterFairy   Author: Quasimondo   File: rasterfairy.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def getTriangularArrangement(n):

    t = math.sqrt(n);
    if t != math.floor(t):
        return []
    
    arrangement = []
    i = 1
    while n>0:
        arrangement.append(i)
        n-=i
        i+=2
    
    return [{'hex':False,'rows':arrangement,'type':'triangular'}] 
Example 50
Project: tashaphyne   Author: linuxscout   File: number.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def _written_block(self, number):
        """
         * Spell sub block number of three digits max in Arabic idiom
         *
         * @param integer number Sub block number of three digits max you want to
         *                        spell in Arabic idiom
         *
         * @return string The Arabic idiom that spells inserted sub block
         * @author Khaled Al-Shamaa <[email protected]>
         """
        items = []
        string = u''
        number = int(number)
        if (number > 99):
            hundred = math.floor(number / 100) * 100
            number = number % 100

            if (hundred  ==  200):
                items.append( self._individual[hundred][self._format])
            else:
                items.append( self._individual[hundred])
        if (number  ==  2 or number  ==  12):
            items.append(self._individual[number][self._feminine][self._format])
        elif (number < 20):
            items.append(self._individual[int(number)][self._feminine])
        else :
            ones = number % 10
            tens = math.floor(number / 10) * 10
            tens = int(tens)

            if (ones  ==  2) :
                items.append(\
                  self._individual[ones][self._feminine][self._format])
            elif (ones > 0) :
                items.append( self._individual[ones][self._feminine])
            items.append( self._individual[tens][self._format])

        if u'' in items:
            items.remove(u'')
        string = u' ? '.join(items)
        return string