Exemplo n.º 1
0
def num_8_divisors(max_n):
    total = 0
    primes = primesfrom2to(max_n/6)
    a_max = max_n**(1./3)
    for idx_a,a in enumerate(primes): # abc, all unique
        if (a > a_max):
            break
        else:
            for idx_b,b in enumerate(primes[idx_a+1:]):
                c_max = max_n/(a*b)
                if (c_max<=a or c_max<=b):
                    break
                else:
                    nearest_prime_to_c_max_index = bisect(primes[idx_a+1:],c_max)-1
                    index_diff = nearest_prime_to_c_max_index-idx_b
                    total += index_diff
                    #for c in primes:
                        #if (c<=b):
                            #continue
                        #else:
                            #if (a*b*c > max_n):
                                #break
                            #else:
                                #total += 1
    b_max = (max_n/2.)**(1./3)
    for b in primes: # ab^3, a,b unique
        if (b > b_max):
            break
        else:
            a_max = max_n/b**3
            if (a_max<=1):
                break
            else:
                nearest_prime_to_a_max_index = bisect(primes,a_max)-1
                #print nearest_prime_to_a_max_index
                if (nearest_prime_to_a_max_index>=0):
                    if (a_max>=b):
                        total += (nearest_prime_to_a_max_index)
                    elif (a_max<b):
                        total += (nearest_prime_to_a_max_index+1)
                else:
                    break
            
            #for a in primes:
                #if (a==b):
                    #continue
                #elif (a > (max_n/8)):
                    #break
                #else:
                    #if (a*b**3 > max_n):
                        #break
                    #else:
                        #total += 1
    for a in primes:
        if (a**7 > max_n):
            break
        else:
            total += 1
                
    return total
Exemplo n.º 2
0
def compute_interval_chi2(ts_obj, file_obj, curr_dir, meas_file, chi2_range, data_label):
    logger = logging.getLogger(LOGGING_NAME)
    
    meas_obj = ts_obj.get_cached_file(curr_dir, meas_file)

    if meas_obj == None:
        logger.error('Can not compute interval chi^2 since measured radiance file does not exist for run: %s' % curr_dir)
        return None

    try:
        wl_conv = file_obj[WAVELENGTH_COLUMN][:,0]
    except LookupError:
        logger.error('Could not retrieve column: %s from file: %s' % (WAVELENGTH_COLUMN, file_obj.filename))
        return None

    try:
        wl_meas = meas_obj[WAVELENGTH_COLUMN][:,0]
    except LookupError:
        logger.error('Could not retrieve column: %s from file: %s' % (WAVELENGTH_COLUMN, meas_obj.filename))
        return None

    conv_beg = bisect.bisect(wl_conv, chi2_range[0])
    conv_end = bisect.bisect(wl_conv, chi2_range[1])
    
    meas_beg = bisect.bisect(wl_meas, chi2_range[0])
    meas_end = bisect.bisect(wl_meas, chi2_range[1])

    residual = meas_obj[RADIANCE_COLUMN][meas_beg:meas_end, 0] - file_obj[RADIANCE_COLUMN][conv_beg:conv_end, 0]

    interval_chi2 = numpy.sum( numpy.power(residual / meas_obj[ERROR_COLUMN][meas_beg:meas_end, 0], 2) )

    return [ (data_label, interval_chi2) ]
Exemplo n.º 3
0
def read_read(r, frags, frag_chunk):
    name, seq, _, _, ali = r.split('\t')[:5]
    crm, strand, pos = ali.split(':')[:3]
    positive = strand == '+'
    len_seq  = len(seq)
    if positive:
        pos = int(pos)
    else:
        pos = int(pos) + len_seq - 1 # remove 1 because all inclusive
    frag_piece = frags[crm][pos / frag_chunk]
    idx = bisect(frag_piece, pos)
    try:
        next_re = frag_piece[idx]
    except IndexError:
        # case where part of the read is mapped outside chromosome
        count = 0
        while idx >= len(frag_piece) and count < len_seq:
            pos -= 1
            count += 1
            frag_piece = frags[crm][pos / frag_chunk]
            idx = bisect(frag_piece, pos)
        if count >= len_seq:
            raise Exception('Read mapped mostly outside ' +
                            'chromosome\n')
        next_re = frag_piece[idx]
    prev_re = frag_piece[idx - 1 if idx else 0]
    return ('%s\t%s\t%d\t%d\t%d\t%d\t%d\n' % (
        name, crm, pos, positive, len_seq, prev_re, next_re))
Exemplo n.º 4
0
    def get_middle(self, cid, val_l, val_r, l=True, r=True):
        if val_l > val_r:
            val_l, val_r = val_r, val_l
            l, r = r, l
            reverse = True
        else:
            reverse = False

        if l is True:
            i = bisect.bisect_left(self.sorted_values[cid], val_l)
        else:
            i = bisect.bisect(self.sorted_values[cid], val_l)
        if r is True:
            i2 = bisect.bisect(self.sorted_values[cid], val_r)
        else:
            i2 = bisect.bisect_left(self.sorted_values[cid], val_r)

        altids = self.sorted_altid[cid][i:i2]
        values = self.sorted_values[cid][i:i2]

        if reverse is True:
            altids.reverse()
            values.reverse()

        return altids, values
Exemplo n.º 5
0
    def get_slice(self, val, upper_val=None):
        """
        Get sub-histogram by slicing the axis at this value.

        returns a tuple (histogram, (low, high)) where low and high
        are the bounds of the slice taken.
        """
        warnings.warn('This method will be replaced by slice()',
                      FutureWarning, stacklevel=2)
        bin_bounds = np.linspace(self.min,self.max,self.bins + 1)
        bin_n = bisect.bisect(bin_bounds, val)
        extent = self._get_bounds(bin_bounds, bin_n)
        if upper_val is not None:
            if not upper_val > val:
                raise ValueError('upper_val must be > val')
            # should add 1 to ensure that the upper bin is counted
            upper_bin = bisect.bisect(bin_bounds, upper_val) + 1
            upper_extent = self._get_bounds(bin_bounds, upper_bin)
            extent = (extent[0], upper_extent[1])
        else:
            upper_bin = None

        # _get_slice should take care of copying
        subhist = self._hist._get_slice(self.name, bin_n, upper_bin)
        return subhist, extent
Exemplo n.º 6
0
def solve(n, i_min, free, curr_board, pieces_left, solutions, fps=fps, se_nh=se_nh, bisect=bisect):

    fp_i_cands = fps[i_min]
    for p in pieces_left:
        fp_cands = fp_i_cands[p]
        for fp in fp_cands:
            if fp <= free:
                n_curr_board = curr_board[:]
                for ci in fp:
                    n_curr_board[ci] = p
                if len(pieces_left) > 1:
                    n_free = free - fp
                    n_i_min = min(n_free)
                    if len(n_free & se_nh[n_i_min]) > 0:
                        n_pieces_left = pieces_left[:]
                        n_pieces_left.remove(p)
                        solve(n, n_i_min, n_free, n_curr_board, n_pieces_left, solutions)
                else:
                    s = "".join(map(str, n_curr_board))
                    solutions.insert(bisect(solutions, s), s)
                    rs = s[::-1]
                    solutions.insert(bisect(solutions, rs), rs)
                    if len(solutions) >= n:
                        return
        if len(solutions) >= n:
            return
    return
Exemplo n.º 7
0
    def _Truncate(dc, text, maxWidth, ellipse, ellipseChars):
        """
        Return a string that will fit within the given width.
        """
        line = text.split("\n")[0] # only consider the first line
        if not line:
            return ""

        pte = dc.GetPartialTextExtents(line)

        # Does the whole thing fit within our given width?
        stringWidth = pte[-1]
        if stringWidth <= maxWidth:
            return line

        # We (probably) have to ellipse the text so allow for ellipse
        maxWidthMinusEllipse = maxWidth - dc.GetTextExtent(ellipseChars)[0]

        if ellipse == wx.LEFT:
            i = bisect.bisect(pte, stringWidth - maxWidthMinusEllipse)
            return ellipseChars + line[i+1:]

        if ellipse == wx.CENTER:
            i = bisect.bisect(pte, maxWidthMinusEllipse / 2)
            j = bisect.bisect(pte, stringWidth - maxWidthMinusEllipse / 2)
            return line[:i] + ellipseChars + line[j+1:]

        if ellipse == wx.RIGHT:
            i = bisect.bisect(pte, maxWidthMinusEllipse)
            return line[:i] + ellipseChars

        # No ellipsing, just truncating is the default
        i = bisect.bisect(pte, maxWidth)
        return line[:i]
Exemplo n.º 8
0
    def _parseindex(self, seq, all):
        """Internal: parse a message number (or cur, first, etc.)."""
        if isnumeric(seq):
            try:
                return int(seq)
            except (OverflowError, ValueError):
                return sys.maxint

        if seq in ('cur', '.'):
            return self.getcurrent()
        elif seq == 'first':
            return all[0]
        elif seq == 'last':
            return all[-1]
        else:
            if seq == 'next':
                n = self.getcurrent()
                i = bisect(all, n)
                try:
                    return all[i]
                except IndexError:
                    raise Error, 'no next message'

            if seq == 'prev':
                n = self.getcurrent()
                i = bisect(all, n - 1)
                if i == 0:
                    raise Error, 'no prev message'
                try:
                    return all[i - 1]
                except IndexError:
                    raise Error, 'no prev message'

            raise Error, None
            return
Exemplo n.º 9
0
    def add_field(self, field, private=False):
        # Insert the given field in the order in which it was created, using
        # the "creation_counter" attribute of the field.
        # Move many-to-many related fields from self.fields into
        # self.many_to_many.
        if private:
            self.private_fields.append(field)
        elif field.is_relation and field.many_to_many:
            self.local_many_to_many.insert(bisect(self.local_many_to_many, field), field)
        else:
            self.local_fields.insert(bisect(self.local_fields, field), field)
            self.setup_pk(field)

        # If the field being added is a relation to another known field,
        # expire the cache on this field and the forward cache on the field
        # being referenced, because there will be new relationships in the
        # cache. Otherwise, expire the cache of references *to* this field.
        # The mechanism for getting at the related model is slightly odd -
        # ideally, we'd just ask for field.related_model. However, related_model
        # is a cached property, and all the models haven't been loaded yet, so
        # we need to make sure we don't cache a string reference.
        if field.is_relation and hasattr(field.remote_field, 'model') and field.remote_field.model:
            try:
                field.remote_field.model._meta._expire_cache(forward=False)
            except AttributeError:
                pass
            self._expire_cache()
        else:
            self._expire_cache(reverse=False)
Exemplo n.º 10
0
def plot_distributions(distributions, bucket_pct, axes, out_file):
	x_max, y_max = axes
	pp = PdfPages(out_file)
	variances = sorted(distributions)
	subsamples = sorted(distributions[variances[-1]])
	if x_max == 0.:
		x_max = distributions[0][-1]
	bucket_width = x_max * bucket_pct
	bucket_boundaries = np.arange(0, x_max + bucket_width / 2., bucket_width)
	x_axis_points = np.arange(bucket_width / 2., x_max, bucket_width)
	for i,v in enumerate(variances):
		plt.figure(i)
		plt.xlabel("regret distribution")
		if v == 0:
			plt.title("true game")
			cum_dist = np.array([bisect(distributions[0], b) for b in \
								bucket_boundaries])
			plt.plot(x_axis_points, (cum_dist[1:] - cum_dist[:-1]) / \
					float(cum_dist[-1]), label="true game")
		else:
			plt.title("$\sigma \\approx$" +str(v))
			for s in subsamples:
				cum_dist = np.array([bisect(distributions[v][s], b) for b in \
									bucket_boundaries])
				plt.plot(x_axis_points, (cum_dist[1:] - cum_dist[:-1]) / \
						float(cum_dist[-1]), label=str(s)+" samples")
		plt.legend(loc="upper right", prop={'size':6})
		if y_max != 0.:
			plt.axis([0, x_max, 0, y_max])
		pp.savefig()
	pp.close()
Exemplo n.º 11
0
    def add_field(self, field):
        # Insert the given field in the order in which it was created, using
        # the "creation_counter" attribute of the field.
        # Move many-to-many related fields from self.fields into
        # self.many_to_many.
        if field.rel and isinstance(field.rel, ManyToManyRel):
            self.local_many_to_many.insert(bisect(self.local_many_to_many, field), field)
            if hasattr(self, '_m2m_cache'):
                del self._m2m_cache
        else:
            self.local_fields.insert(bisect(self.local_fields, field), field)
            self.setup_pk(field)
            if hasattr(self, '_field_cache'):
                del self._field_cache
                del self._field_name_cache
                # The fields, concrete_fields and local_concrete_fields are
                # implemented as cached properties for performance reasons.
                # The attrs will not exists if the cached property isn't
                # accessed yet, hence the try-excepts.
                try:
                    del self.fields
                except AttributeError:
                    pass
                try:
                    del self.concrete_fields
                except AttributeError:
                    pass
                try:
                    del self.local_concrete_fields
                except AttributeError:
                    pass

        if hasattr(self, '_name_map'):
            del self._name_map
Exemplo n.º 12
0
def p187():
    N=10**8
    total=0
    for x in range(bisect(primes, sqrt(N))):
        p = primes[x]
        total += bisect(primes, N/p) - x
    return total
Exemplo n.º 13
0
def getMotifAnno(annoIntvlDict,intervalStartDict,intervalEndDict,motifChrom,motifStart,motifEnd,window):
    """push excluded regions from BED6 into a list
	if motif falls into it"""
    regionList = []
    valueList = []
    #itl = IntervalList( intv for intv in geneRangeDict[motifChrom])
    try:
	startList = [start for (start,end) in intervalStartDict[motifChrom]]
	endList = [end for (start,end) in intervalEndDict[motifChrom]]
	intervalStartList = [(start,end) for (start,end) in intervalStartDict[motifChrom]]
	intervalEndList = [(start,end) for (start,end) in intervalEndDict[motifChrom]]
	iStart = bisect(startList, motifEnd)
	iEnd = bisect(endList,motifStart)
	s = intervalStartList[:iStart]
	e = intervalEndList[iEnd:]
	overlapping = list(set(s)&set(e))
        #intervals = intervalDict[motifChrom]##for short list of Bed6 Anno, brute force is Ok
        #motifInterval = Interval(motifStart, motifEnd)
        #overlapping = [ x for x in intervals \
	#	if ((x[1]+window)>motifInterval[0] and (x[0]-window)<motifInterval[0]) \
	#	or ((x[1]+window)>motifInterval[1] and (x[0]-window)<motifInterval[1]) ]

        #print 'overlapping',overlapping
        if not len(overlapping) == 0:
            for x in overlapping:
                (anno, value) = annoIntvlDict[motifChrom][x]
                if not anno in regionList:
                    regionList.append(anno)
                if not (anno, value) in valueList:
                    valueList.append((anno,value))
        #if len(targetList) > 1:
            #print targetList, motifChrom, motifInterval
    except KeyError:
        pass
    return regionList, valueList
Exemplo n.º 14
0
def colored(p, pallete=None, inverse=False):
    """ return a color code for the percentage. """
    pallete = pallete or DEFUALT_PALLETE
    if inverse:
        return pallete['colors'][len(pallete['colors']) -
                                 bisect(pallete['limits'], p)]
    return pallete['colors'][bisect(pallete['limits'], p)]
Exemplo n.º 15
0
    def _delta_to_next(self, last_run_at, next_hour, next_minute):
        """
        Takes a datetime of last run, next minute and hour, and
        returns a relativedelta for the next scheduled day and time.
        Only called when day_of_month and/or month_of_year cronspec
        is specified to further limit scheduled task execution.
        """
        from bisect import bisect, bisect_left

        datedata = AttributeDict(year=last_run_at.year)
        days_of_month = sorted(self.day_of_month)
        months_of_year = sorted(self.month_of_year)

        def day_out_of_range(year, month, day):
            try:
                datetime(year=year, month=month, day=day)
            except ValueError:
                return True
            return False

        def roll_over():
            while 1:
                flag = datedata.dom == len(days_of_month) or day_out_of_range(
                    datedata.year, months_of_year[datedata.moy], days_of_month[datedata.dom]
                )
                if flag:
                    datedata.dom = 0
                    datedata.moy += 1
                    if datedata.moy == len(months_of_year):
                        datedata.moy = 0
                        datedata.year += 1
                else:
                    break

        if last_run_at.month in self.month_of_year:
            datedata.dom = bisect(days_of_month, last_run_at.day)
            datedata.moy = bisect_left(months_of_year, last_run_at.month)
        else:
            datedata.dom = 0
            datedata.moy = bisect(months_of_year, last_run_at.month)
            if datedata.moy == len(months_of_year):
                datedata.moy = 0
        roll_over()

        while 1:
            th = datetime(year=datedata.year, month=months_of_year[datedata.moy], day=days_of_month[datedata.dom])
            if th.isoweekday() % 7 in self.day_of_week:
                break
            datedata.dom += 1
            roll_over()

        return ffwd(
            year=datedata.year,
            month=months_of_year[datedata.moy],
            day=days_of_month[datedata.dom],
            hour=next_hour,
            minute=next_minute,
            second=0,
            microsecond=0,
        )
Exemplo n.º 16
0
    def run(self, edit):
        # Filter out any cursors that are larger than a single point.
        cursor_pts = tuple(cursor.a for cursor in self.view.sel() if cursor.a == cursor.b)

        diff_starts = tuple(region.a for region in self.view.find_all("^diff"))
        hunk_starts = tuple(region.a for region in self.view.find_all("^@@"))

        for cursor_pt in cursor_pts:
            diff_start = diff_starts[bisect.bisect(diff_starts, cursor_pt) - 1]
            diff_start_line = self.view.substr(self.view.line(diff_start))

            hunk_start = hunk_starts[bisect.bisect(hunk_starts, cursor_pt) - 1]
            hunk_line_str = self.view.substr(self.view.line(hunk_start))
            hunk_line, _ = self.view.rowcol(hunk_start)
            cursor_line, _ = self.view.rowcol(cursor_pt)
            additional_lines = cursor_line - hunk_line - 1

            # Example: "diff --git a/src/js/main.spec.js b/src/js/main.spec.js" --> "src/js/main.spec.js"
            use_prepix = re.search(r" b/(.+?)$", diff_start_line)
            if use_prepix is None:
                filename = diff_start_line.split(" ")[-1]
            else:
                filename = use_prepix.groups()[0]

            # Example: "@@ -9,6 +9,7 @@" --> 9
            lineno = int(re.search(r"^@@ \-\d+(,-?\d+)? \+(\d+)", hunk_line_str).groups()[1])
            lineno = lineno + additional_lines

            self.load_file_at_line(filename, lineno)
Exemplo n.º 17
0
    def search(self, seq):
        """
        search for first occurrence of given sequence(s) in the UniProtDB objects collection returning (each) the fasta
        header front part of the first occurrence.

        :param seq: a string interpreted as a single sequence or a list (of str) interpreted as a coll. of sequences
        :return: a dictionary of sequences to lists (of ids, 'null' if n/a)
        """
        if isinstance(seq, str):
            ids = 'null'
            index = self.searchstring.find(seq)
            if index >= 0:
                j = bisect.bisect(self.idx, index) - 1
                ids = self.accs[j]
            return {seq: ids}
        if isinstance(seq, list):
            ids = list()
            for i in seq:
                ids.append('null')
            for i, v in enumerate(seq):
                index = self.searchstring.find(v)
                if index >= 0:
                    j = bisect.bisect(self.idx, index) - 1
                    ids[i] = self.accs[j]
            return dict(zip(seq, ids))
        return None
Exemplo n.º 18
0
def wrs(ws,k,debug=False,return_rs=False):
    """Weighted reservoir sampling for k items"""
    _dbg = lambda x:_dbg(x,debug)
    js = []
    rs = []
    for j,w in enumerate(ws):
        r = random.random()**(1.0/w)
        #dbg( "considering j:%s, w:%s, r:%s" % (j,w,r))
        if j < k:
            #dbg( "preinserting j:%s, w:%s, r:%s" % (j,w,r))
            pos = bisect.bisect(rs,r)
            js.insert(pos,j)
            rs.insert(pos,r)
        else:
            #dbg( "comparing r: %s to rs:%s" % (r,rs))
            pos = bisect.bisect(rs,r)
            #dbg( "pos: %s" % pos)
            if pos > 0:
                #dbg( "inserting")
                js.insert(pos,j)
                rs.insert(pos,r)
                js = js[-k:]
                rs = rs[-k:]
    if return_rs:
        return js,rs
    else:
        return js
Exemplo n.º 19
0
 def add(self, region):
     if len(self) == 0:
         self.append(region)
         return
     # merge the rest
     check_items = self
     tmp = []
     start = bisect(self, sublime.Region(region.begin(), region.begin())) - 1
     start = 0 if start < 0 else start
     end = bisect(self, sublime.Region(region.end(), region.end()))
     end = 0 if end < 0 else end
     if end == 0:
         self.insert(0, region)
         return
     elif start == len(self):
         self.append(region)
         return
     check_items = self[start:end]
     start_time = perf_counter()
     for item in check_items:
         if region.intersects(item):
             region = region.cover(item)
         else:
             tmp.append(item)
     self[start:end] = tmp
     # insert new region
     i = bisect_left(self, region)
     self.insert(i, region)
Exemplo n.º 20
0
def getTargetGene(geneRangeDict, intervalStartDict, intervalEndDict, motifChrom, motifStart, motifEnd, txWindow):
    """push motif target genes into a list"""
    targetList = []
    transcriptList = []
    #itl = IntervalList( intv for intv in geneRangeDict[motifChrom])
    #itl.sort()
    try:
    	startList = [start-1-txWindow for (start,end) in intervalStartDict[motifChrom]]
	##-1 changes 1-based encoding into 0-based
	endList = [end+txWindow for (start,end) in intervalEndDict[motifChrom]]
	intervalStartList = [(start,end) for (start,end) in intervalStartDict[motifChrom]]
	intervalEndList = [(start,end) for (start,end) in intervalEndDict[motifChrom]]
	iStart = bisect(startList, motifEnd)
	iEnd = bisect(endList, motifStart)
	s = intervalStartList[:iStart]##bed intervals are 0-based, so overlapping with bed start is not accounted for
	e = intervalEndList[iEnd:]##motifStart is 1-based, so overlapping with bed end is acccounted for
	overlapping = list(set(s)&set(e))
    	#motifInterval = Interval(motifStart, motifEnd)
    	#overlapping = [ x for x in intervals if (x[1]>motifInterval[0] and x[0]<motifInterval[0]) \
	#or (x[1]>motifInterval[1] and x[0]<motifInterval[1]) ]
        #print 'overlapping',overlapping
	
    	if not len(overlapping) == 0:
	    for x in overlapping:
		#print x
	    	(geneName, transcriptId) = geneRangeDict[motifChrom][x]
	    	if not geneName in targetList:
	            targetList.append(geneName)
		if not (geneName,transcriptId) in transcriptList:
		    transcriptList.append((geneName,transcriptId))
	#if len(targetList) > 1:
	    #print targetList, motifChrom, motifInterval
    except KeyError:
	pass
    return targetList, transcriptList
Exemplo n.º 21
0
    def addValue(self, row, col, size, colour_value):
        """add a dot in row/col.
        """

        # decide the size of the box
        pos = bisect.bisect(self.mThresholdsSize, size)

        if self.mRevertSize:
            size = self.mMaxBoxSize * \
                (1.0 - float(pos) / len(self.mThresholdsSize))
        else:
            size = self.mMaxBoxSize * float(pos) / len(self.mThresholdsSize)

        d = (self.mMaxBoxSize - size) / 2

        x = self.mMapCol2Position[col] + d
        try:
            y = self.mMapRow2Position[row] + d
        except KeyError:
            return

        # determine the colour of the box
        pos = bisect.bisect(self.mThresholdsColour, colour_value)
        colour = self.mColours[pos]

        e = SVGdraw.rect(x, y,
                         size, size,
                         stroke="black",
                         fill="rgb(%i,%i,%i)" % colour)

        self.mElements.append(e)
Exemplo n.º 22
0
 def _parseindex(self, seq, all):
     """Internal: parse a message number (or cur, first, etc.)."""
     if isnumeric(seq):
         try:
             return int(seq)
         except (OverflowError, ValueError):
             return sys.maxint
     if seq in ("cur", "."):
         return self.getcurrent()
     if seq == "first":
         return all[0]
     if seq == "last":
         return all[-1]
     if seq == "next":
         n = self.getcurrent()
         i = bisect(all, n)
         try:
             return all[i]
         except IndexError:
             raise Error, "no next message"
     if seq == "prev":
         n = self.getcurrent()
         i = bisect(all, n - 1)
         if i == 0:
             raise Error, "no prev message"
         try:
             return all[i - 1]
         except IndexError:
             raise Error, "no prev message"
     raise Error, None
Exemplo n.º 23
0
def add_geospatial_info(iploc,inbound,outbound,twoway):
    iplist = ''
    if os.path.isfile(iploc):
        iplist = np.loadtxt(iploc,dtype=np.uint32,delimiter=',',usecols={0},\
        converters={0: lambda s: np.uint32(s.replace('"',''))})
    else:
        print "No iploc.csv file was found, Map View map won't be created"


    # get geospatial info, only when iplocation file is available
    if iplist != '':
        for srcip in outbound:
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,outbound[srcip]['ip_int'])).replace('\n','')])

            outbound[srcip]['geo'] = reader.next()
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,outbound[srcip]['dst_ip_int'])).replace('\n','')])
            outbound[srcip]['geo_dst'] = reader.next()

        for dstip in twoway:
            reader = csv.reader([linecache.getline(\
            iploc,bisect.bisect(iplist,twoway[dstip]['ip_int'])).replace('\n','')])
            twoway[dstip]['geo'] = reader.next()

        for srcip in inbound:
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,inbound[srcip]['ip_int'])).replace('\n','')])

            inbound[srcip]['geo'] = reader.next()
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,inbound[srcip]['src_ip_int'])).replace('\n','')])
            inbound[srcip]['geo_src'] = reader.next()

    return inbound,outbound,twoway
Exemplo n.º 24
0
def PlotNode(data,key=None,t0=None,t1=None):
    from Utility import Time
    from bisect import bisect
    import matplotlib.pyplot as plt
    t = data['times']
    if t0 is None:
        t0i = 0
    else:
        t0i = bisect(t,Time(t0).as_msec())
    if t1 is None:
        t1i = len(t)
    else:
        t1i = bisect(t,Time(t1).as_msec())+1

    plt.figure()
    if key is None:
        N=len(data)-2
        i=1
        for key,value in data.iteritems():
            if key not in ['times','senders']:
                plt.subplot(N,1,i)
                plt.plot(t[t0i:t1i],value[t0i:t1i])
                plt.xlim(t[t0i],t[t1i-1])
                plt.xlabel(key)
                i=i+1
    else:
        assert(key in data.keys())
        plt.plot(t,data[key])
    plt.show()
Exemplo n.º 25
0
 def on_key_press(symbol, modifiers):
     if symbol == pyglet.window.key.SPACE: # pause / unpause
         if player.playing:
             player.pause()
         else:
             player.play()
     elif symbol == pyglet.window.key.LEFT: # jump back 5 seconds
         player.seek(player.time - 5.0)
         if player.playing:
             player.play()
     elif symbol == pyglet.window.key.RIGHT: # jump forward 5 seconds
         player.seek(player.time + 5.0)
         if player.playing:
             player.play()
     elif symbol == pyglet.window.key.UP: # jump to shortly before next cut
         current_segment_idx = bisect(points_of_interest[1:], player.time)
         try:
             player.seek(max(points_of_interest[current_segment_idx + 1], 0.0))
             if player.playing:
                 player.play()
         except IndexError:
             pass
     elif symbol == pyglet.window.key.DOWN: # jump to shortly before last cut
         current_segment_idx = bisect(points_of_interest[1:], player.time)
         if current_segment_idx:
             if player.time - points_of_interest[current_segment_idx] < 1.0:
                 player.seek(max(points_of_interest[current_segment_idx - 1], 0.0))
             else:
                 player.seek(max(points_of_interest[current_segment_idx], 0.0))
         else:
             player.seek(0)
         if player.playing:
             player.play()
Exemplo n.º 26
0
 def searchMatrix(self, matrix, target):
     line = bisect.bisect([matrix[i][0] for i in xrange(len(matrix))], target)
     if line > 0:
         col = bisect.bisect(matrix[line - 1], target)
         if matrix[line - 1][col - 1] == target:
             return True
     return False
Exemplo n.º 27
0
    def _buildReviewKeys(self, timestamp):
        """Builds an ordered list of untrained message keys, ready for output
        in the Review list.  Returns a 5-tuple: the keys, the formatted date
        for the list (eg. "Friday, November 15, 2002"), the start of the prior
        page or zero if there isn't one, likewise the start of the given page,
        and likewise the start of the next page."""
        # Fetch all the message keys
        allKeys = state.unknownCorpus.keys()

        # The default start timestamp is derived from the most recent message,
        # or the system time if there are no messages (not that it gets used).
        if not timestamp:
            if allKeys:
                timestamp = self._keyToTimestamp(allKeys[-1])
            else:
                timestamp = time.time()
        start, end, date = self._getTimeRange(timestamp)

        # Find the subset of the keys within this range.
        startKeyIndex = bisect.bisect(allKeys, "%d" % long(start))
        endKeyIndex = bisect.bisect(allKeys, "%d" % long(end))
        keys = allKeys[startKeyIndex:endKeyIndex]
        keys.reverse()

        # What timestamps to use for the prior and next days?  If there any
        # messages before/after this day's range, use the timestamps of those
        # messages - this will skip empty days.
        prior = end = 0
        if startKeyIndex != 0:
            prior = self._keyToTimestamp(allKeys[startKeyIndex-1])
        if endKeyIndex != len(allKeys):
            end = self._keyToTimestamp(allKeys[endKeyIndex])

        # Return the keys and their date.
        return keys, date, prior, start, end
Exemplo n.º 28
0
    def _setPAS(self, juman_format):
        """ 各基本句にPASを設定 """
        tag_list = self.tag_list()
        if juman_format != JUMAN_FORMAT.DEFAULT:
            for pinfo in self._pinfos:
                pinfo = json.loads(pinfo)

                tag_idx = pinfo.get("tid")
                if tag_idx is None:
                    end = pinfo["head_token_end"]
                    tag_idx = bisect.bisect(self.tag_positions, end) - 1

                tag = tag_list[tag_idx]
                tag.pas = Pas()
                tag.pas.cfid = pinfo["cfid"]

                for casename, args in pinfo["args"].items():
                    for arg in args:
                        arg_tag_idx = arg.get("tid")
                        if arg_tag_idx is None:
                            arg_tag_idx = bisect.bisect(self.tag_positions, arg["head_token_end"]) - 1
                        arg_sid = arg.get("sid")
                        if (arg_sid is None) or (len(arg["sid"]) == 0):
                            arg_sid = self.sid

                        arg = Argument(sid=arg_sid, tid=arg_tag_idx, midasi=arg["rep"])
                        tag.pas.arguments[casename].append(arg)
        else:
            # KNPの述語項構造をparse
            for tag in tag_list:
                if ("格解析結果" in tag.features) or ("述語項構造" in tag.features):
                    tag.pas = Pas(tag.tag_id, self)
Exemplo n.º 29
0
    def moves(self):
        if self.next_move is MOVE_TYPE.TOF:
            min_tof = ASTEROID_TOF[0]
            max_tof = ASTEROID_TOF[-1]
	    if len(self.tof) < 1:
		cur_t = T_SCALE[658][self.t0]
	    else: 
		cur_t = T_SCALE[self.seq[-2]][self.tof[-1]]	  

            lb = bisect.bisect(T_SCALE[self.seq[-1]], cur_t + min_tof)
            
	    if (cur_t + max_tof) > (T_SCALE[658][self.t0] + MAX_MISSION_TIME):
		ub = bisect.bisect(T_SCALE[self.seq[-1]], self.t0 + MAX_MISSION_TIME)

	    else:
	        ub = bisect.bisect(T_SCALE[self.seq[-1]], cur_t + max_tof)

	    return [i for i in range(lb-1, ub)] #return upper and lower bounds on t2

	elif self.next_move is MOVE_TYPE.ASTEROID:
	    mov = copy.copy(MOVES[self.next_move])	     
	    for ast in self.seq:
	        if ast in mov:
		    mov.remove(ast)
	    return mov		
	    
	else:	
            return MOVES[self.next_move]
Exemplo n.º 30
0
def solve(n, i_min, free, curr_board, pieces_left, solutions, fps, se_nh,
          # Hack to use a fast local variable to avoid a global lookup
          bisect=bisect):

    fp_i_cands = fps[i_min]
    for p in pieces_left:
        fp_cands = fp_i_cands[p]
        for fp in fp_cands:
            if fp <= free:
                n_curr_board = curr_board[:]
                for ci in fp:
                    n_curr_board[ci] = p

                if len(pieces_left) > 1:
                    n_free = free - fp
                    n_i_min = min(n_free)
                    if len(n_free & se_nh[n_i_min]) > 0:
                        n_pieces_left = pieces_left[:]
                        n_pieces_left.remove(p)
                        solve(n, n_i_min, n_free, n_curr_board,
                              n_pieces_left, solutions, fps, se_nh)
                else:
                    s = ''.join(map(str, n_curr_board))
                    solutions.insert(bisect(solutions, s), s)
                    rs = s[::-1]
                    solutions.insert(bisect(solutions, rs), rs)
                    if len(solutions) >= n:
                        return

        if len(solutions) >= n:
            return
Exemplo n.º 31
0
 def getPartition(self, key):
     idx = bisect.bisect(self.keys, key)
     return len(self.keys) - idx if self.reverse else idx
Exemplo n.º 32
0
 def __call__(self, offset):
     if not self.starts:
         return False
     q = bisect(self.starts, offset) - 1
     return q >= 0 and self.starts[q] <= offset <= self.ends[q]
import bisect

value = [14, 85, 77, 77, 26, 50, 45, 66, 79, 10, 3, 84, 77, 1]

print('New  Pos  Contents')
print('---  ---  --------')

l = []

for i in value:
    position = bisect.bisect(l, i)
    bisect.insort(l, i)
    print('{:3}  {:3}  '.format(i, position), l)
Exemplo n.º 34
0
def pos2lineno(pos, offsets):
    line = bisect(offsets, pos, 0, len(offsets) - 1)
    if line == 1: offset = pos
    else: offset = pos - offsets[line - 1]
    return line, offset
Exemplo n.º 35
0
def _choice(population, weights):
    assert len(population) == len(weights)
    cdf_vals = _cdf(weights)
    x = random.random()
    idx = bisect.bisect(cdf_vals, x)
    return population[idx]
def tripletsViaBisect(a, b, c):
    a = sorted(list(set(a)))
    b = sorted(list(set(b)))
    c = sorted(list(set(c)))
    return sum((bisect.bisect(a, x) * bisect.bisect(c, x) for x in b))
Exemplo n.º 37
0
def ecdf(x, sample):
    sample.sort(
    )  # sample HAS TO BE SORTED in the ASCENDING (NON-DESCENDING) order
    i = bisect(sample, x)
    return float(i) / len(sample)
Exemplo n.º 38
0
            pass

# 在readme文件中添加题目
with open("../README.md") as f:
    data = f.readlines()

tData = data[6:]
insertData = [ID, '[' + name + ']' + '(' + url + ')', 'c']
for p in prog[1:]:
    fileName = './src/' + dirName + '/' + ID + '.' + p
    if p == 'cpp':
        p = 'c++'
    elif p == 'py':
        p = 'python'
    insertData.append('[' + p + ']' + '(' + fileName + ')')

insertData.append(difficult)
insertData = '|' + '|'.join(insertData) + '|'
index = bisect.bisect(tData, insertData)
if index == len(tData):
    insertData = '\n' + insertData
else:
    insertData += '\n'

target_org_str, insert_org_str = tData[index - 1].strip(
    "\n")[:6], insertData.strip("\n")[:6]
if target_org_str != insert_org_str:
    tData.insert(index, insertData)
    with open("../README.md", 'w') as f:
        f.writelines(data[:6] + tData)
Exemplo n.º 39
0
 def __new__(cls, value):
     index = bisect(cls.breakpoints, value)
     score = cls.scores[index]
     score_col = colors.fg(cls.colors_[index])
     score = '[' + score.center(cls.max_scores_len) + ']'
     return score_col | score
Exemplo n.º 40
0
    def __call__(
        self,
        q_event_sequence: QEventSequence,
        grace_handler: GraceHandler | None = None,
        heuristic: Heuristic | None = None,
        job_handler: JobHandler | None = None,
        attack_point_optimizer: AttackPointOptimizer | None = None,
        attach_tempos: bool = True,
    ):
        """
        Calls q-target.
        """
        assert isinstance(q_event_sequence, QEventSequence)

        if grace_handler is None:
            grace_handler = ConcatenatingGraceHandler()
        assert isinstance(grace_handler, GraceHandler)

        if heuristic is None:
            heuristic = DistanceHeuristic()
        assert isinstance(heuristic, Heuristic)

        if job_handler is None:
            job_handler = SerialJobHandler()
        assert isinstance(job_handler, JobHandler)

        if attack_point_optimizer is None:
            attack_point_optimizer = NaiveAttackPointOptimizer()
        assert isinstance(attack_point_optimizer, AttackPointOptimizer)
        if isinstance(self, BeatwiseQTarget) and isinstance(
                attack_point_optimizer, MeasurewiseAttackPointOptimizer):
            message = "{} is not supposed to be used together with {}.".format(
                self.__class__.__name__,
                attack_point_optimizer.__class__.__name__)
            raise TypeError(message)

        # TODO: this step seems unnecessary now (23/09/2021), (maybe) write more tests to verify

        # if next-to-last QEvent is silent, pop the TerminalQEvent,
        # in order to prevent rest-tuplets
        # q_events = q_event_sequence
        # if isinstance(q_event_sequence[-2], SilentQEvent):
        #     q_events = q_event_sequence[:-1]

        # parcel QEvents out to each beat
        beats = self.beats
        offsets = sorted([beat.offset_in_ms for beat in beats])
        for q_event in q_event_sequence:
            index = bisect.bisect(offsets, q_event.offset) - 1
            beat = beats[index]
            beat.q_events.append(q_event)

        # generate QuantizationJobs and process with the JobHandler
        jobs = [beat(i) for i, beat in enumerate(beats)]
        jobs = [job for job in jobs if job]
        jobs = job_handler(jobs)
        for job in jobs:
            assert job is not None
            beats[job.job_id]._q_grids = job.q_grids

        # for i, beat in enumerate(beats):
        #    print i, len(beat.q_grids)
        #    for q_event in beat.q_events:
        #        print '\t{}'.format(q_event.offset)

        # select the best QGrid for each beat, according to the Heuristic
        beats = heuristic(beats)

        # shift QEvents attached to each QGrid's "next downbeat"
        # over to the next QGrid's first leaf - the real downbeat
        orphaned_q_events_proxies = self._shift_downbeat_q_events_to_next_q_grid(
        )

        #  TODO: handle a final QGrid with QEvents attached to its
        #        next_downbeat.
        #  TODO: remove a final QGrid with no QEvents

        self._regroup_q_grid_with_unnecessary_divisions()

        # convert the QGrid representation into notation,
        # handling grace-note behavior with the GraceHandler
        notation = self._notate(
            attach_tempos=attach_tempos,
            attack_point_optimizer=attack_point_optimizer,
            grace_handler=grace_handler,
        )

        handle_orphaned_q_events = getattr(grace_handler,
                                           "handle_orphaned_q_event_proxies",
                                           None)
        if callable(handle_orphaned_q_events) and orphaned_q_events_proxies:
            last_leaf = abjad.get.leaf(notation, -1)
            handle_orphaned_q_events(last_leaf, orphaned_q_events_proxies)

        return notation
Exemplo n.º 41
0
            currentBattery = matchObj.group(2)
            if (currentBattery != previousBattery):
                previousBattery = currentBattery
                datetime_obj = datetime.strptime(matchObj.group(1),
                                                 "%b %d,%Y %H:%M:%S")
                batteryChangeIntervals.append(datetime_obj)
                #print currentBattery, " ", matchObj.group(1)

batteryChangeIntervals.append(end_datetime)
previous_datetime = start_datetime
next_datetime = start_datetime + timedelta(seconds=interval)
#print start_datetime, " ", next_datetime, " ", end_datetime
#print len(batteryChangeIntervals), end_datetime
intervalBatteryFraction = []
while (next_datetime <= end_datetime):
    i = bisect.bisect(batteryChangeIntervals, previous_datetime)
    j = bisect.bisect(batteryChangeIntervals, next_datetime)
    #print previous_datetime, " ", i, " ", next_datetime, " ", j
    lenBatteryChangeIntervals = len(batteryChangeIntervals)
    if (i == j and
        (next_datetime == batteryChangeIntervals[lenBatteryChangeIntervals - 2]
         or j < (lenBatteryChangeIntervals - 1))):
        #print previous_datetime, " ", i, " ", i-1
        batteryduration = batteryChangeIntervals[i] - batteryChangeIntervals[
            i - 1]
        fraction = interval / batteryduration.total_seconds()
        print fraction
        intervalBatteryFraction.append(fraction)
    elif (
            i == j - 1 and
        (next_datetime == batteryChangeIntervals[lenBatteryChangeIntervals - 2]
Exemplo n.º 42
0
 def color(cls, value):
     """task value/score color"""
     index = bisect(cls.breakpoints, value)
     return colors.fg(cls.colors_[index])
Exemplo n.º 43
0
 def select_crossover(self):
     # Implementation from https://docs.python.org/3/library/random.html -- Ctrl+F "weights"
     choices, weights = zip(*self.crossovers.items())
     cumdist = list(accumulate(weights))
     x = random.random() * cumdist[-1]
     self.selected_crossover = choices[bisect(cumdist, x)]
Exemplo n.º 44
0
class Folder:
    """Class representing a particular folder."""

    def __init__(self, mh, name):
        """Constructor."""
        self.mh = mh
        self.name = name
        if not os.path.isdir(self.getfullname()):
            raise Error, 'no folder %s' % name

    def __repr__(self):
        """String representation."""
        return 'Folder(%s, %s)' % (`self.mh`, `self.name`)

    def error(self, *args):
        """Error message handler."""
        apply(self.mh.error, args)

    def getfullname(self):
        """Return the full pathname of the folder."""
        return os.path.join(self.mh.path, self.name)

    def getsequencesfilename(self):
        """Return the full pathname of the folder's sequences file."""
        return os.path.join(self.getfullname(), MH_SEQUENCES)

    def getmessagefilename(self, n):
        """Return the full pathname of a message in the folder."""
        return os.path.join(self.getfullname(), str(n))

    def listsubfolders(self):
        """Return list of direct subfolders."""
        return self.mh.listsubfolders(self.name)

    def listallsubfolders(self):
        """Return list of all subfolders."""
        return self.mh.listallsubfolders(self.name)

    def listmessages(self):
        """Return the list of messages currently present in the folder.
        As a side effect, set self.last to the last message (or 0)."""
        messages = []
        match = numericprog.match
        append = messages.append
        for name in os.listdir(self.getfullname()):
            if match(name):
                append(name)
        messages = map(int, messages)
        messages.sort()
        if messages:
            self.last = messages[-1]
        else:
            self.last = 0
        return messages

    def getsequences(self):
        """Return the set of sequences for the folder."""
        sequences = {}
        fullname = self.getsequencesfilename()
        try:
            f = open(fullname, 'r')
        except IOError:
            return sequences
        while 1:
            line = f.readline()
            if not line: break
            fields = line.split(':')
            if len(fields) != 2:
                self.error('bad sequence in %s: %s' %
                          (fullname, line.strip()))
            key = fields[0].strip()
            value = IntSet(fields[1].strip(), ' ').tolist()
            sequences[key] = value
        return sequences

    def putsequences(self, sequences):
        """Write the set of sequences back to the folder."""
        fullname = self.getsequencesfilename()
        f = None
        for key in sequences.keys():
            s = IntSet('', ' ')
            s.fromlist(sequences[key])
            if not f: f = open(fullname, 'w')
            f.write('%s: %s\n' % (key, s.tostring()))
        if not f:
            try:
                os.unlink(fullname)
            except os.error:
                pass
        else:
            f.close()

    def getcurrent(self):
        """Return the current message.  Raise Error when there is none."""
        seqs = self.getsequences()
        try:
            return max(seqs['cur'])
        except (ValueError, KeyError):
            raise Error, "no cur message"

    def setcurrent(self, n):
        """Set the current message."""
        updateline(self.getsequencesfilename(), 'cur', str(n), 0)

    def parsesequence(self, seq):
        """Parse an MH sequence specification into a message list.
        Attempt to mimic mh-sequence(5) as close as possible.
        Also attempt to mimic observed behavior regarding which
        conditions cause which error messages."""
        # XXX Still not complete (see mh-format(5)).
        # Missing are:
        # - 'prev', 'next' as count
        # - Sequence-Negation option
        all = self.listmessages()
        # Observed behavior: test for empty folder is done first
        if not all:
            raise Error, "no messages in %s" % self.name
        # Common case first: all is frequently the default
        if seq == 'all':
            return all
        # Test for X:Y before X-Y because 'seq:-n' matches both
        i = seq.find(':')
        if i >= 0:
            head, dir, tail = seq[:i], '', seq[i+1:]
            if tail[:1] in '-+':
                dir, tail = tail[:1], tail[1:]
            if not isnumeric(tail):
                raise Error, "bad message list %s" % seq
            try:
                count = int(tail)
            except (ValueError, OverflowError):
                # Can't use sys.maxint because of i+count below
                count = len(all)
            try:
                anchor = self._parseindex(head, all)
            except Error, msg:
                seqs = self.getsequences()
                if not seqs.has_key(head):
                    if not msg:
                        msg = "bad message list %s" % seq
                    raise Error, msg, sys.exc_info()[2]
                msgs = seqs[head]
                if not msgs:
                    raise Error, "sequence %s empty" % head
                if dir == '-':
                    return msgs[-count:]
                else:
                    return msgs[:count]
            else:
                if not dir:
                    if head in ('prev', 'last'):
                        dir = '-'
                if dir == '-':
                    i = bisect(all, anchor)
                    return all[max(0, i-count):i]
                else:
                    i = bisect(all, anchor-1)
                    return all[i:i+count]
        # Test for X-Y next
        i = seq.find('-')
        if i >= 0:
            begin = self._parseindex(seq[:i], all)
            end = self._parseindex(seq[i+1:], all)
            i = bisect(all, begin-1)
            j = bisect(all, end)
            r = all[i:j]
            if not r:
                raise Error, "bad message list %s" % seq
            return r
        # Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence
        try:
            n = self._parseindex(seq, all)
        except Error, msg:
            seqs = self.getsequences()
            if not seqs.has_key(seq):
                if not msg:
                    msg = "bad message list %s" % seq
                raise Error, msg
            return seqs[seq]
def decode(y):
    #------------------------------------------------------------------------------------
    #INITIALISAITION
    #------------------------------------------------------------------------------------

    #implementing Laplace estimator, intialising frequencies range
    frequencies = []
    for i in range(kappa):
        frequencies.append({})
    frequencies[0]['escape'] = 1
    #frequencies have the following structure: frequencies[number of context alphabets][context name][alphabet][frequency]

    #initialising precisions
    precision = 32
    one = int(2**precision - 1)
    quarter = int(ceil(one / 4))
    half = 2 * quarter
    threequarters = 3 * quarter

    y.extend(precision *
             [0])  # dummy zeros to prevent index out of bound errors
    x = []
    a = [''] * kappa

    # initialise by taking first 'precision' bits from y and converting to a number
    value = int(''.join(str(a) for a in y[0:precision]), 2)
    position = precision  # position where currently reading y

    lo, hi = 0, one  # initialise lo and hi to be [0,1.0)

    #------------------------------------------------------------------------------------
    #CALCULATION
    #------------------------------------------------------------------------------------

    while True:  # for every symbol
        p = update_prob(frequencies, a)
        f = update_culm_prob_dec(p)

        #print(f)
        lohi_range = hi - lo + 1

        decoded_symbol = bisect(f, (value - lo) / lohi_range) - 1

        a.insert(0, decoded_symbol)
        #print(chr(decoded_symbol))

        if len(a) > kappa:
            a.pop(-1)

        # debugging
        #print(a[0])

        lo = lo + int(ceil(f[a[0]] * lohi_range))
        hi = lo + int(floor(p[a[0]] * lohi_range))

        if (lo > one or hi > one):
            raise ValueError('Probabilities greater than one!')

        if (lo == hi):
            raise NameError('Zero interval!')

        while True:
            if hi < half:
                # do nothing
                pass
            elif lo >= half:
                lo = lo - half
                hi = hi - half
                value = value - half
            elif lo >= quarter and hi < threequarters:
                lo = lo - quarter
                hi = hi - quarter
                value = value - quarter
            else:
                break
            lo = 2 * lo
            hi = 2 * hi + 1
            value = 2 * value + y[position]
            position += 1
            if position >= len(y):
                return (x)

        #------------------------------------------------------------------------------------
        #UPDATE
        #------------------------------------------------------------------------------------
        x.append(decoded_symbol)

        update_freq(a, frequencies)

        #debugging
        # if len(x) <= 10:
        #     print(x[-1])
        #     print(a)
        #     print(frequencies)

    return ("Compression Failed")
 def __search_index(self, x):
     """
     search data segment index
     """
     return bisect.bisect(self.x, x) - 1
Exemplo n.º 47
0
def CalcSolarPosition(lat, lon, hour, min, sec, offset, JDC, radial_samples):
    toRadians = pi/180.0
    toDegrees = 180.0/pi
    MeanObliquity = 23.0 + (26.0 + ((21.448 - JDC * (46.815 + JDC * (0.00059 - JDC * 0.001813))) / 60.0)) / 60.0
    Obliquity = MeanObliquity + 0.00256 * cos(toRadians*(125.04 - 1934.136 * JDC))
    Eccentricity = 0.016708634 - JDC * (0.000042037 + 0.0000001267 * JDC)
    GeoMeanLongSun = 280.46646 + JDC * (36000.76983 + 0.0003032 * JDC)

    while GeoMeanLongSun < 0:
        GeoMeanLongSun += 360
    while GeoMeanLongSun > 360:
        GeoMeanLongSun -= 360
    GeoMeanAnomalySun = 357.52911 + JDC * (35999.05029 - 0.0001537 * JDC)

    Dummy1 = toRadians*GeoMeanAnomalySun
    Dummy2 = sin(Dummy1)
    Dummy3 = sin(Dummy2 * 2)
    Dummy4 = sin(Dummy3 * 3)
    SunEqofCenter = Dummy2 * (1.914602 - JDC * (0.004817 + 0.000014 * JDC)) + Dummy3 * (0.019993 - 0.000101 * JDC) + Dummy4 * 0.000289
    SunApparentLong = (GeoMeanLongSun + SunEqofCenter) - 0.00569 - 0.00478 * sin(toRadians*((125.04 - 1934.136 * JDC)))

    Dummy1 = sin(toRadians*Obliquity) * sin(toRadians*SunApparentLong)
    Declination = toDegrees*(atan(Dummy1 / sqrt(-Dummy1 * Dummy1 + 1)))

    SunRadVector = (1.000001018 * (1 - pow(Eccentricity,2))) / (1 + Eccentricity * cos(toRadians*(GeoMeanAnomalySun + SunEqofCenter)))

    #======================================================
    #Equation of time (minutes)
    Dummy = pow((tan(Obliquity * pi / 360)),2)
    Dummy1 = sin(toRadians*(2 * GeoMeanLongSun))
    Dummy2 = sin(toRadians*(GeoMeanAnomalySun))
    Dummy3 = cos(toRadians*(2 * GeoMeanLongSun))
    Dummy4 = sin(toRadians*(4 * GeoMeanLongSun))
    Dummy5 = sin(toRadians*(2 * GeoMeanAnomalySun))
    Et = toDegrees*(4 * (Dummy * Dummy1 - 2 * Eccentricity * Dummy2 + 4 * Eccentricity * Dummy * Dummy2 * Dummy3 - 0.5 * pow(Dummy,2) * Dummy4 - 1.25 * pow(Eccentricity,2) * Dummy5))

    SolarTime = (hour*60.0) + min + (sec/60.0) + (Et - 4.0 * -lon + (offset*60.0))

    while SolarTime > 1440.0:
        SolarTime -= 1440.0
    HourAngle = SolarTime / 4.0 - 180.0
    if HourAngle < -180.0:
        HourAngle += 360.0

    Dummy = sin(toRadians*lat) * sin(toRadians*Declination) + cos(toRadians*lat) * cos(toRadians*Declination) * cos(toRadians*HourAngle)
    if Dummy > 1.0:
        Dummy = 1.0
    elif Dummy < -1.0:
        Dummy = -1.0

    Zenith = toDegrees*(acos(Dummy))
    Dummy = cos(toRadians*lat) * sin(toRadians*Zenith)
    if abs(Dummy) >= 0.000999:
        Azimuth = (sin(toRadians*lat) * cos(toRadians*Zenith) - sin(toRadians*Declination)) / Dummy
        if abs(Azimuth) > 1.0:
            if Azimuth < 0:
                Azimuth = -1.0
            else:
                Azimuth = 1.0

        Azimuth = 180 - toDegrees*(acos(Azimuth))
        if HourAngle > 0:
            Azimuth *= -1.0
    else:
        if lat > 0:
            Azimuth = 180.0
        else:
            Azimuth = 0.0
    if Azimuth < 0:
        Azimuth += 360.0

    AtmElevation = 90 - Zenith
    if AtmElevation > 85:
        RefractionCorrection = 0
    else:
        Dummy = tan(toRadians*(AtmElevation))
        if AtmElevation > 5:
            RefractionCorrection = 58.1 / Dummy - 0.07 / pow(Dummy,3) + 0.000086 / pow(Dummy,5)
        elif AtmElevation > -0.575:
            RefractionCorrection = 1735 + AtmElevation * (-518.2 + AtmElevation * (103.4 + AtmElevation * (-12.79 + AtmElevation * 0.711)))
        else:
            RefractionCorrection = -20.774 / Dummy
        RefractionCorrection = RefractionCorrection / 3600

    Zenith = Zenith - RefractionCorrection
    Altitude = 90 - Zenith
    Daytime = 0
    if Altitude > 0.0:
            Daytime = 1
    if radial_samples == -999:  #-999 is a code indicating that the numver of radial samples was blank, so we assumed old methods.
        dir = bisect((0.0,67.5,112.5,157.5,202.5,247.5,292.5),Azimuth)-1
    else: #using terms from GIS sampling routine
        WedgeZones = radial_samples
        Angle_Incr = 360.0 / WedgeZones
        WedgeNumbers = range(1,WedgeZones)
        WedgeAngleStart = [x*Angle_Incr-Angle_Incr/2 for x in WedgeNumbers]
        if Azimuth < WedgeAngleStart[0]:
            Azimuth_mod = Azimuth + 360
        else:
            Azimuth_mod = Azimuth
        dir = bisect(WedgeAngleStart,Azimuth_mod)-1
    return Altitude, Zenith, Daytime, dir
Exemplo n.º 48
0
    def get_daily_backlog_history(self, start_date, end_date):
        """
            returns list of tuple (date,stats)
                date is date value in epoc time
                stats is dictionary of {'created':[], 'opened':[], 'closed':[]}
        """

        # this is array of date in numpy
        numdates = drange(start_date, end_date + timedelta(days=1),
                          timedelta(days=1))

        #        for date in numdates:
        #            self.env.log.info(num2date(date))

        end_date = end_date.replace(hour=23, minute=59, second=59)

        # each key is the list of list of ticket.  The index of the list is corresponding
        # to the index of the date in numdates list.
        backlog_stats = {'created': [], 'opened': [], 'closed': []}

        # initialize backlog_stats

        for date in numdates:
            for key in backlog_stats:
                backlog_stats[key].append([])

        # start by getting the list of opened ticket at the end of the start date.
        backlog_stats['opened'][0] = self.get_remaning_opened_ticket_on(
            start_date)

        for ticket in self.tickets:

            # only consider the ticket that was created before end dates.
            if ticket.time_created <= end_date:

                # only track the ticket that create since start_date
                if ticket.time_created >= start_date:
                    # determine index
                    date = ticket.time_created.date()
                    #get index of day in the dates list
                    index = bisect(numdates, date2num(date)) - 1

                    # add ticket created ticket list
                    backlog_stats['created'][index].append(ticket.id)

                for t, author, field, oldvalue, newvalue, permanent in ticket.get_changelog(
                ):

                    # determine index
                    date = t.date()
                    #get index of day in the dates list
                    index = bisect(numdates, date2num(date)) - 1

                    if field == 'status' and start_date <= t <= end_date:

                        if newvalue == 'closed':
                            # add ticket created ticket list
                            backlog_stats['closed'][index].append(ticket.id)

                        elif newvalue == 'reopen':
                            backlog_stats['opened'][index].append(ticket.id)

        # update opened ticket list
        for idx, list in enumerate(backlog_stats['opened']):

            if idx > 0:

                # merge list of opened ticket from previous day
                list.extend(backlog_stats['opened'][idx - 1])

                # add created ticket to opened ticket list
                list.extend(backlog_stats['created'][idx])

                # remove closed ticket from opened ticket list.
                for id in backlog_stats['closed'][idx]:
                    try:
                        list.remove(id)
                    except ValueError, e:
                        pass

                list.sort()
Exemplo n.º 49
0
 def get(self):
     r = random.random() * self.total_weight
     index = bisect.bisect(self.cumulative_weights, r)
     return self.net._edges[index]
Exemplo n.º 50
0
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
    i = bisect.bisect(breakpoints, score)
    return grades[i]
Exemplo n.º 51
0
 def stratum_idx_for_score(self, x):
     return bisect.bisect(self.bounds, x) - 1
Exemplo n.º 52
0
def weighted_sampler(seq, weights):
    "Return a random-sample function that picks from seq weighted by weights."
    totals = []
    for w in weights:
        totals.append(w + totals[-1] if totals else w)
    return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]
Exemplo n.º 53
0
from bisect import bisect_right,bisect
C, D = map( int, input().split())
m = C//140
M = D//170
ans = 0
L = []
for i in range(1,6):
    L.append(140*i)
    L.append(170*i)
S = [30*i for i in range(1,6)]
if C >= 140*6:
    ans = D - C
elif D >= 170*5:

else:
    k = bisect_right(L,C)
    u = bisect(L,D)
    if k%2 == 0:
        if u%2 == 1:
            for i in range(k/2+1,(u+1)/2):
                ans += 30*i
        else:
            
            
            
    
    
    
    
Exemplo n.º 54
0
def parent_selection(accum):
    s = set()
    while len(s) < 2:
        s.add(bisect(accum, random()))
    return tuple(s)
Exemplo n.º 55
0
def bisect_in(seq, item):
    pos = bisect(seq, item)
    return seq[pos - 1] == item if seq else False
Exemplo n.º 56
0
def uniform_strata_method(scores, n_strata):
    bounds = [i / n_strata for i in range(n_strata + 1)]
    allocations = [bisect.bisect(bounds, x) - 1 for x in scores]
    print(Counter(allocations))
    return allocations, bounds
Exemplo n.º 57
0
    def from_pcm(cls,
                 filename,
                 pcmreader,
                 compression=None,
                 total_pcm_frames=None):
        from audiotools import __default_quality__
        from audiotools import PCMConverter
        from audiotools import ChannelMask
        from audiotools.encoders import encode_mpc

        if (compression is None) or (compression not in cls.COMPRESSION_MODES):
            compression = __default_quality__(cls.NAME)

        if pcmreader.bits_per_sample not in {8, 16, 24}:
            from audiotools import UnsupportedBitsPerSample
            pcmreader.close()
            raise UnsupportedBitsPerSample(filename, pcmreader.bits_per_sample)

        if pcmreader.sample_rate in (32000, 37800, 44100, 48000):
            sample_rate = pcmreader.sample_rate

            if total_pcm_frames is not None:
                from audiotools import CounterPCMReader
                pcmreader = CounterPCMReader(pcmreader)
        else:
            from bisect import bisect

            sample_rate = [32000, 32000, 37800, 44100,
                           48000][bisect([32000, 37800, 44100, 4800],
                                         pcmreader.sample_rate)]

            total_pcm_frames = None

        try:
            encode_mpc(
                filename,
                PCMConverter(pcmreader,
                             sample_rate=sample_rate,
                             channels=min(pcmreader.channels, 2),
                             channel_mask=int(
                                 ChannelMask.from_channels(
                                     min(pcmreader.channels, 2))),
                             bits_per_sample=16), float(compression),
                total_pcm_frames if (total_pcm_frames is not None) else 0)

            # ensure PCM frames match, if indicated
            if ((total_pcm_frames is not None)
                    and (total_pcm_frames != pcmreader.frames_written)):
                from audiotools.text import ERR_TOTAL_PCM_FRAMES_MISMATCH
                from audiotools import EncodingError
                raise EncodingError(ERR_TOTAL_PCM_FRAMES_MISMATCH)

            return MPCAudio(filename)
        except (IOError, ValueError) as err:
            from audiotools import EncodingError
            cls.__unlink__(filename)
            raise EncodingError(str(err))
        except Exception:
            cls.__unlink__(filename)
            raise
        finally:
            pcmreader.close()
Exemplo n.º 58
0
    def get_example(self, i):
        tgt = bisect.bisect(self._zpaths_accumlens, i) - 1

        lidx = i - self._zpaths_accumlens[tgt]
        return self._zfs[tgt].get_example(lidx)
Exemplo n.º 59
0
    def __complete_braces(self, event):
        """Complete () [] and {} using a mild inteligence to see if corresponds
        and also do some more magic such as complete in classes and functions.
        """
        brace = event.text()
        if brace not in settings.BRACES:
            # Thou shalt not waste cpu cycles if this brace compleion dissabled
            return
        line, index = self.getCursorPosition()
        text = self.text(line)
        complementary_brace = BRACE_DICT.get(brace)
        token_buffer = []
        _, tokens = self.__tokenize_text(text)
        is_unbalance = 0
        for tkn_type, tkn_rep, tkn_begin, tkn_end in tokens:
            if tkn_rep == brace:
                is_unbalance += 1
            elif tkn_rep == complementary_brace:
                is_unbalance -= 1
            if tkn_rep.strip() != "":
                token_buffer.append((tkn_rep, tkn_end[1]))
            is_unbalance = (is_unbalance >= 0) and is_unbalance or 0

        if (self.lang == "python") and (len(token_buffer) == 3) and \
                (token_buffer[2][0] == brace) and (token_buffer[0][0] in
                                                   ("def", "class")):
            self.insertAt("):", line, index)
            # are we in presence of a function?
            # TODO: IMPROVE THIS AND GENERALIZE IT WITH INTELLISENSEI
            if token_buffer[0][0] == "def":
                symbols_handler = handlers.get_symbols_handler('py')
                split_source = self.text().split("\n")
                indent = re.match('^\\s+', str(split_source[line]))
                indentation = (indent.group() + " " * self._indent
                               if indent is not None else " " * self._indent)
                new_line = "%s%s" % (indentation, 'pass')
                split_source.insert(line + 1, new_line)
                source = '\n'.join(split_source)
                source = source.encode(self.encoding)
                _, symbols_simplified = symbols_handler.obtain_symbols(
                    source, simple=True, only_simple=True)
                symbols_index = sorted(symbols_simplified.keys())
                symbols_simplified = sorted(
                    list(symbols_simplified.items()), key=lambda x: x[0])
                index_symbol = bisect.bisect(symbols_index, line)
                if (index_symbol >= len(symbols_index) or
                        symbols_index[index_symbol] > (line + 1)):
                    index -= 1
                belongs_to_class = symbols_simplified[index_symbol][1][2]
                if belongs_to_class:
                    self.insertAt("self", line, index)
                    index += 4
                    if self.selected_text != "":
                        self.insertAt(", ", line, index)
                        index += 2
            self.insertAt(self.selected_text, line, index)
            self.setCursorPosition(line, index)
        elif (token_buffer and (not is_unbalance) and
              self.selected_text):
            self.insertAt(self.selected_text, line, index)
        elif is_unbalance:
            next_char = text[index:index + 1].strip()
            if self.selected_text or next_char == "":
                self.insertAt(complementary_brace, line, index)
                self.insertAt(self.selected_text, line, index)
Exemplo n.º 60
0
 def __getitem__(self, i):
     if not 0 <= i < len(self):
         raise IndexError(i)
     return self.population[bisect.bisect(self.cumweights, i)]