def __init__(self, time, radius=None): """ Creates a new TimePoint instance. Parameters: - time (float) time value in seconds. - radius (Radius) is required to compare 2 instances. """ try: time = float(time) except ValueError: raise TypeError("float argument required, not %r" % time) if time < 0.0: raise ValueError("A time point can't be negative: %r" % time) if radius is None: radius = Radius() if isinstance(radius, Radius) is False: raise TypeError("Radius argument required, not %r" % radius) if time < radius.Value: radius.Value = time self.__time = time self.__radius = radius
def authenticate(self,username,password): 'Authenticate a username/password combination against the Radius server' if self._v_radius is None: self._v_radius = Radius(self._secret,self._host,self._port) self._v_radius.retries = int(self._retries) self._v_radius.timeout = self._timeout return self._v_radius.authenticate(username,password)
def radius_parse(packed_message, secret, radius_lifecycle): """Parses a RADIUS packet Returns: RadiusPacket Raises: MessageParseError: the packed_message cannot be parsed""" parsed_radius = Radius.parse(packed_message, secret, radius_lifecycle=radius_lifecycle) return parsed_radius
def authenticate(self, username, password, **kwargs): # """Authentication method of LDAP repository, which returns dict of specified attributes:their values # :param username: String with username # :param password: String with password # :param oauth2_attributes: List of attributes to retrieve # :return: None and raise if failure, server message otherwise # """ logger.debug("Trying to authenticate username {}".format( username.encode('utf-8'))) # try: # Create client srv = Radius(self.secret, host=self.host, port=self.port, retries=self.max_retry, timeout=self.max_timeout) # Authentication if not srv.authenticate(username, password): logger.error( "RADIUS_CLI::authenticate: Authentication failure for user '{}'" .format(username)) raise AuthenticationError( "Authentication failure on Radius backend for user '{}'". format(username)) logger.info( "RADIUS_CLI::authenticate: Autentication succeed for user '{}'". format(username)) # except Timeout: # raise Timeout # except Exception, e: # logger.error("Unable to authenticate username {} : exception : {}".format(username, str(e))) return { 'dn': username, 'user_phone': 'N/A', 'user_email': 'N/A', 'password_expired': False, 'account_locked': False }
def __init__(self, x, y, tower_type): self.x = x self.y = y self.rect = (x, y, x + CELL_SIZE, y + CELL_SIZE) self.type = tower_type self.image = None self.choose_image_name() self.level = 1 self.damage = 1 self.radius = Radius(x, y, 48) self.is_blast = False self.attacked_creep = None
def __init__(self, parent=None, width=4, height=3, view_option=ViewOption.QUERY): # Figure表示一个图,axes相当于子图,一个fig可以有多个axes,在这里只有一个 self.fig = Figure(figsize=(width, height), dpi=100) FigureCanvas.__init__(self, self.fig) self.setParent(parent) self.axes = self.fig.add_subplot(111) # 子图 self.point = None # 把查询到的点集初始化为空,方便后续处理 # top-k相关的类 self.top_k = TopK() # 以下三个列表只在查询视图中有效,为了实现查询的子集索引到csv文件索引的映射 self.index_list = [] # 储存经纬度所对应的csv文件中的索引 self.lon_list = [] self.lat_list = [] # 距离查询相关的类 self.radius = Radius() # 视图选项 self.view_option = view_option # 查询视图的map if self.view_option == ViewOption.QUERY: # 地图 self.m = Basemap(ax=self.axes, projection='mill', area_thresh=10000, llcrnrlat=-65, llcrnrlon=-180, urcrnrlat=80, urcrnrlon=180, resolution='c') self.m.fillcontinents(color='#DEDEDE', lake_color='#DEDEDE', zorder=0.1) self.m.drawcoastlines(linewidth=0.2, color='k') self.m.drawcountries(linewidth=0.5, color='k') self.m.drawmapboundary(fill_color='#A0CFDF') # 选中某个点后显示的信息提示框 self.annot = self.axes.annotate("", xy=(0, 0), xytext=(-50, 20), textcoords="offset points", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->")) self.annot.set_visible(False) # 更新信息提示框 def update_annot(ind): index = self.index_list[ind["ind"][0]] # 这里返回的是csv中对应经纬度的索引 pos = self.point.get_offsets()[ind["ind"][0]] self.annot.xy = pos text = marker_label[index] # 设置提示文本 self.annot.set_text(text) self.annot.get_bbox_patch().set_alpha(0.8) # 鼠标移动到某个点的响应函数 def hover(event): if event.inaxes == self.axes and self.point is not None: cont, ind = self.point.contains(event) if cont: update_annot(ind) self.annot.set_visible(True) self.fig.canvas.draw_idle() else: vis = self.annot.get_visible() if vis: self.annot.set_visible(False) self.fig.canvas.draw_idle() # 绑定响应函数 self.fig.canvas.mpl_connect("motion_notify_event", hover) self.axes.set_title('店铺查询') self.axes.title.set_y(1.05) # 时区视图的map if self.view_option == ViewOption.TIMEZONE: self.m = Basemap(ax=self.axes, projection='mill', area_thresh=10000, llcrnrlat=-65, llcrnrlon=-180, urcrnrlat=80, urcrnrlon=180, resolution='c') self.m.fillcontinents(color='#DEDEDE', lake_color='#DEDEDE', zorder=0.1) self.m.drawcoastlines(linewidth=0.2, color='k') self.m.drawcountries(linewidth=0.5, color='k') self.m.drawmapboundary(fill_color='#A0CFDF') zone_dict = {} label = list() xpt, ypt = self.m(lon, lat) # 把经纬度转换为x, y坐标,因为图像输出需要用到坐标 for item in timezone: tz = item.split()[0] if not zone_dict.__contains__(tz): zone_dict[tz] = 1 else: zone_dict[tz] += 1 for item in timezone: tz = item.split()[0] count = zone_dict[tz] # label对应colormap的索引 if count < 1500: label.append(0) elif count < 3000: label.append(1) elif count < 4500: label.append(2) else: label.append(3) def colormap(): return mpl.colors.LinearSegmentedColormap.from_list( 'cmap', ['#FB7C5C', '#F6563E', '#E42F28', '#C3161A'], 256) self.point = self.m.scatter(xpt, ypt, marker='o', s=3, c=label, cmap=colormap(), zorder=1) self.point.set_visible(True) self.annot = self.axes.annotate("", xy=(0, 0), xytext=(-50, 20), textcoords="offset points", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->")) self.annot.set_visible(False) def update_annot(ind): index = ind['ind'][0] pos = self.point.get_offsets()[ind["ind"][0]] self.annot.xy = pos text = marker_label[index] self.annot.set_text(text) self.annot.get_bbox_patch().set_alpha(0.8) def hover(event): vis = self.annot.get_visible() if event.inaxes == self.axes: cont, ind = self.point.contains(event) if cont: update_annot(ind) self.annot.set_visible(True) self.fig.canvas.draw_idle() else: if vis: self.annot.set_visible(False) self.fig.canvas.draw_idle() self.fig.canvas.mpl_connect("motion_notify_event", hover) bounds = [0, 1500, 3000, 4500, 6000] norm = mpl.colors.BoundaryNorm(bounds, colormap().N) ax_cbar = self.fig.add_axes([0.3, 0.17, 0.4, 0.02]) cbar = mpl.colorbar.ColorbarBase(ax_cbar, cmap=colormap(), norm=norm, spacing='uniform', ticks=bounds, boundaries=bounds, orientation='horizontal') cbar.outline.set_linewidth(0.2) cbar.ax.tick_params(labelsize=8, labelcolor='#666666') self.axes.set_title('时区分布') self.axes.title.set_y(1.05) # 密度视图的map if self.view_option == ViewOption.DESTINY: gnc = GeonamesCache() countries = gnc.get_countries() counts = stb_file['Country'].value_counts() country_dict = {} for k, v in counts.iteritems(): # print(k, round(v/countries[k]['areakm2']*1000000)) country_dict[countries[k]['iso3']] = round( v / countries[k]['areakm2'] * 1000000) self.m = Basemap(ax=self.axes, projection='mill', llcrnrlat=-65, llcrnrlon=-180, urcrnrlat=80, urcrnrlon=180, resolution='c') self.m.fillcontinents(color='#DEDEDE', lake_color='#DEDEDE', zorder=0) # m.drawcoastlines(linewidth=0.2, color='k') self.m.drawcountries(linewidth=0.5, color='k') self.m.drawmapboundary(fill_color='#A0CFDF') shapefile = 'ne_110m_admin_0_countries/ne_110m_admin_0_countries' # setup color bar color_num = 5 cmap = mpl.cm.get_cmap('Reds') color_range = [ cmap(i / (color_num + 1)) for i in range(color_num + 1) ] bounds = [0, 10, 100, 1000, 10000, 100000] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) def colormap(): return mpl.colors.LinearSegmentedColormap.from_list( 'cmap', ['#FBA083', '#FB7C5C', '#F6563E', '#E42F28', '#C3161A'], 256) # Read shapefile self.m.readshapefile(shapefile, 'units', color='#DDDDDD', linewidth=0.1) # Add patches for info, shape in zip(self.m.units_info, self.m.units): code = info['ADM0_A3'] if not country_dict.__contains__(code): color = '#DDDDDD' else: if code == 'CHN' or code == 'TWN': color = '#F6563E' elif country_dict[code] < 10: color = '#FBA083' elif country_dict[code] < 100: color = '#FB7C5C' elif country_dict[code] < 1000: color = '#F6563E' elif country_dict[code] < 10000: color = '#E42F28' else: color = '#C3161A' patches = [Polygon(np.array(shape), True)] pc = PatchCollection(patches, facecolor=color, edgecolor='None', linewidth=0) self.axes.add_collection(pc) ax_cbar = self.fig.add_axes([0.3, 0.15, 0.4, 0.02]) cbar = mpl.colorbar.ColorbarBase(ax_cbar, cmap=colormap(), norm=norm, spacing='uniform', ticks=bounds, boundaries=bounds, orientation='horizontal') cbar.outline.set_linewidth(0.2) cbar.ax.tick_params(labelsize=8, labelcolor='#666666') self.axes.set_title('密度分布') self.axes.title.set_y(1.05)
def test_user_connection(self, username, password): """ Method used to perform test search over RADIUS Repository :param username: String with username :param password: String with password """ logger.debug( "Radius_authentication_test::Trying to authenticate username {}". format(username.encode('utf-8'))) response = {'status': None, 'reason': None} try: # Create client srv = Radius(self.secret, host=self.host, port=self.port, retries=self.max_retry, timeout=self.max_timeout) # We do NOT use authenticate, to retrieve the server' answer reply = srv.send_message( srv.access_request_message(username, password)) logger.debug( "Radius_authentication_test:: Username:{}, return code:{}". format(username, reply.code)) msg = "" if reply.code == CODE_ACCESS_ACCEPT: response['status'] = True reply_msg = reply.attributes.get(ATTR_REPLY_MESSAGE) if not isinstance(reply_msg, list): reply_msg = [reply_msg] for r in reply_msg: if isinstance(r, bytes): msg += r.decode('utf8') logger.info( "RADIUS::Auth: Authentication succeed for user {}, reply = {}" .format(username, msg)) else: response['status'] = False msg = "Authentication failed" logger.info( "RADIUS::Auth: Authentication failure for user {}".format( username)) response['reason'] = msg except SocketError: response['status'] = False logger.info( "RADIUS::Auth: Authentication failure for user {} : Timeout expired while connecting" .format(username)) response['reason'] = "Timeout expired while connecting" except Exception as e: response['status'] = False logger.error( "Radius_authentication_test::Unable to authenticate username:{}, exception:{}" .format(username, str(e))) response['reason'] = "Exception : " + str(e) return response
def __init__(self, x, y, way, speed): super().__init__(x, y, way, speed) self.image = 'images/helper.png' self.radius = Radius(x, y, 100)
def _decode_radius_response(self, packed_message): return Radius.parse(packed_message, self.radius_secret, self.packet_id_to_request_authenticator)
class ZRadius( OFS.SimpleItem.Item, Persistent, Acquisition.Implicit, AccessControl.Role.RoleManager): 'A Radius Authenticator' meta_type = 'ZRadius' manage_options = ( {'label':'Test', 'action':''}, {'label':'Properties', 'action':'manage_main'}, {'label':'Security', 'action':'manage_access'} ) __ac_permissions__ = ( ('ZRadius authenticate', ('authenticate', 'manage_test', 'index_html','__call__')), ('Manage properties', ('manage_main','host','port','retries','timeout', 'manage_edit')), ) _v_radius = None def __init__(self,id,title,host,port,secret,retries,timeout): self.id = id self.title = title self.manage_main = HTMLFile('manage_main',globals()) self.index_html = HTMLFile('index',globals()) self._host = host self._port = port self._secret = secret self._retries = int(retries) self._timeout = float(timeout) def host(self): return self._host def port(self): return self._port def retries(self): return self._retries def timeout(self): return self._timeout def manage_edit(self,title,REQUEST=None): '''Handle output of manage_main - change ZRadius instance properties. If REQUEST.secret is None, old secret will be used.''' self.title = title self._host = REQUEST.host self._port = int(REQUEST.port) if hasattr(REQUEST,'secret') and len(REQUEST.secret) > 0: # So we don't code it in form source self._secret = REQUEST.secret self._retries = int(REQUEST.retries) self._timeout = float(REQUEST.timeout) # Reset the Radius object so new values take effect. This is # why we don't allow direct access to the attributes self._v_radius = None if REQUEST is not None: return self.MessageDialog(self,REQUEST=REQUEST, title = 'Edited', message = "Properties for %s changed." % self.id, action = './manage_main') def manage_test(self,REQUEST): 'Handle submission from index_html' username = REQUEST.username password = REQUEST.password if self.authenticate(username,password): return self.MessageDialog(self,REQUEST=REQUEST, title = 'Succeded', message = "Successfully authenticated '%s'" % username, action = './index_html') else: return self.MessageDialog(self,REQUEST=REQUEST, title = 'Failed', message = "Failed to authenticate '%s'" % username, action = './index_html') def __call__(self,username,password): 'Call authenticate' return self.authenticate(username,password) def authenticate(self,username,password): 'Authenticate a username/password combination against the Radius server' if self._v_radius is None: self._v_radius = Radius(self._secret,self._host,self._port) self._v_radius.retries = int(self._retries) self._v_radius.timeout = self._timeout return self._v_radius.authenticate(username,password)