Example #1
0
    def enable_rafs_blobcache(self, is_compressed=False, work_dir=None):
        self._device_conf.device.cache = Namespace(
            type="blobcache",
            config=Namespace(
                work_dir=self.anchor.blobcache_dir if work_dir is None else work_dir
            ),
            compressed=is_compressed,
        )

        return self
Example #2
0
def ResolveDependency(p):
    return {
        "Latin":
        Namespace(family="Noto", width=notoWidthMap[p.width], weight=p.weight),
        "CJK":
        Namespace(
            family="Source",
            weight=p.weight,
            width=5,
        ),
    }
Example #3
0
def ResolveDependency(p):
    result = {
        "Latin":
        Namespace(family="Noto", width=notoWidthMap[p.width], weight=p.weight)
    }
    if p.family in ["WarcraftSans", "WarcraftUI"]:
        result["Numeral"] = Namespace(family="Noto", width=3, weight=p.weight)
    if p.family in ["Sans", "UI", "WarcraftSans", "WarcraftUI"]:
        result["CJK"] = Namespace(family="Source",
                                  weight=p.weight,
                                  width=5,
                                  region=regionSourceMap[p.region])
    return result
Example #4
0
class Config:
	version = "0.1.0"
	fontRevision = 0.0100
	vendor = "Nowar Typeface"
	vendorId = "NOWR"
	vendorUrl = "https://github.com/nowar-fonts"
	copyright = "Copyright © 2019 Cyano Hao and Nowar Typeface, with reserved font name “Nowar”, “有爱”, and “有愛”. Portions Copyright 2015 Google Inc. Portions Copyright © 2017 Adobe Systems Incorporated (http://www.adobe.com/)."
	designer = "Cyano Hao (character set definition & modification for World of Warcraft); Monotype Design Team (Latin, Greek & Cyrillic); Ryoko NISHIZUKA 西塚涼子 (kana & ideographs); Wenlong ZHANG 张文龙 (bopomofo); Sandoll Communications 산돌커뮤니케이션, Soohyun PARK 박수현, Yejin WE 위예진 & Donghoon HAN 한동훈 (hangul elements, letters & syllables); Dr. Ken Lunde (project architect, glyph set definition & overall production); Masataka HATTORI 服部正貴 (production & ideograph elements)"
	designerUrl = "https://github.com/CyanoHao"
	license = "This Font Software is licensed under the SIL Open Font License, Version 1.1. This Font Software is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the SIL Open Font License for the specific language, permissions and limitations governing your use of this Font Software."
	licenseUrl = "https://scripts.sil.org/OFL"

	fontPackWeight = [ 200, 300, 400, 500, 600 ]
	fontPackRegion = [ "CN", "TW", "JP", "KR", "CL", "OSF", "GB", "RP" ]

	fontProviderWeight = [ 200, 300, 400, 500, 600 ]
	fontProviderWidth = [ 3, 5, 7 ]
	fontProviderInstance = {
		# seperate western to 2 parts, avoid sed argument strips
		"western1": [ Namespace(
			weight = w,
			width = wd,
			family = "UI",
			region = r,
		) for w, wd, r in product(fontProviderWeight, fontProviderWidth, [ "CN", "TW", "JP" ]) ],
		"western2": [ Namespace(
			weight = w,
			width = wd,
			family = "UI",
			region = r,
		) for w, wd, r in product(fontProviderWeight, fontProviderWidth, [ "CL", "OSF" ]) ],
		"zhCN": [ Namespace(
			weight = w,
			width = wd,
			family = "Sans",
			region = r,
		) for w, wd, r in product(fontProviderWeight, fontProviderWidth, [ "CN", "CL" ]) ],
		"zhTW": [ Namespace(
			weight = w,
			width = wd,
			family = "Sans",
			region = r,
		) for w, wd, r in product(fontProviderWeight, fontProviderWidth, [ "TW", "CL" ]) ],
		"koKR": [ Namespace(
			weight = w,
			width = wd,
			family = "Sans",
			region = r,
		) for w, wd, r in product(fontProviderWeight, fontProviderWidth, [ "KR" ]) ],
	}
Example #5
0
def ResolveDependency(p):
    result = {
        "Latin":
        Namespace(family="Noto", width=notoWidthMap[p.width], weight=p.weight)
    }
    if p.family in ["WarcraftSans", "WarcraftUI"]:
        result["Numeral"] = Namespace(family="Noto", width=80, weight=p.weight)
    if p.family in ["Sans", "UI", "WarcraftSans", "WarcraftUI"]:
        result["CJK"] = Namespace(
            family="Milan",
            width=5,
            weight=GetMilanWeight(p.weight),
        )
    return result
Example #6
0
def GetKoreanDisplayFont(weight, region, feature):
    return Namespace(weight=weight,
                     width=3,
                     family="UI",
                     region=regionalVariant[region]["ko"],
                     feature=feature,
                     encoding="korean")
Example #7
0
def GetHantChatFont(weight, region, feature):
    return Namespace(weight=weight,
                     width=3,
                     family="Sans",
                     region=regionalVariant[region]["Hant"],
                     feature=feature,
                     encoding="big5")
Example #8
0
def GetHansCombatFont(weight, region, feature):
    return Namespace(weight=weight,
                     width=7,
                     family="Sans",
                     region=regionalVariant[region]["Hans"],
                     feature=feature,
                     encoding="gbk")
Example #9
0
def GetLatinChatFont(weight, region, feature):
    return Namespace(weight=weight,
                     width=3,
                     family="UI",
                     region=regionalVariant[region]["Latn"],
                     feature=feature,
                     encoding="unspec")
Example #10
0
    def ms_get_image_data(self, byteImage):
        try:
            r = requests.post(ms_cognitive_url,
                              params=ms_cognitive_params,
                              headers=ms_cognitive_headers_byteimg,
                              data=byteImage)
            faces = json.loads(r.text, object_hook=lambda d: Namespace(**d))

            if r.status_code == 200 and len(faces) > 0:
                self.currentMood.divide_all_by(
                    2)  # decrease importance of previous mood
                for face in faces:
                    evaluate_face(face, self.currentMood)
                self.currentMood.divide_all_by(len(faces))
                #print(self.currentMood)
                return True
            elif r.status_code == 200:
                print("No faces found")
                return False
            else:
                ErrorHandler.handle_error_response(r, "MS Cognitive Services")
                return False

        except ConnectionError:
            print("connection error")
            return False
Example #11
0
 def wrapper(*args, **kwargs):
     beginEvent(func.__name__, getRealIP(request), request.full_path,
                request.args)
     rd = Namespace()
     if 'sid' in session:
         kwargs['user'] = _get_user_obj(session['sid'])
     else:
         kwargs['user'] = None
     rd._user = kwargs['user']
     if rd._user:
         setEventUser(rd._user)
     rd._version = _VERSION
     rd._version_url = _VERSION_URL
     kwargs['rd'] = rd
     try:
         ret = func(*args, **kwargs)
         return _handle_return(ret, rd)
     except HTTPException as e:
         log(level='WARN', obj={'ex': e})
         raise e
     except UserError as ue:
         log(level='WARN', obj={'ue': str(ue)})
         if 'NOT_EXIST' in ue.msg:
             abort(404)
         elif ue.msg == 'UNAUTHORISED_OPERATION':
             abort(403)
         else:
             abort(400)
     except Exception as ex:
         log(level='ERR', obj={'ex': str(ex)})
         abort(400)
Example #12
0
    def browse_for_mood(self, mood):
        """

        :type mood: FaceMood
        """
        try:
            if self.authToken == "":
                self.get_auth_token()
            header = {"Authorization": "Bearer " + self.authToken}
            r = requests.get(spotify_browse_url,
                             headers=header,
                             params=mood.get_spotify_targets())

            if r.status_code == 200:
                results = json.loads(r.text,
                                     object_hook=lambda d: Namespace(**d))
                print
                print("received songs:")
                for track in results.tracks:
                    #print(results)
                    print(track.name)
                    self.send_to_rabbit(track.uri)
                    print(track.uri)
                    print(track.external_urls)
                    print
        except ConnectionError:
            print("error connecting to spotify")
Example #13
0
def load_json(file_name):
    data = {}
    if os.path.exists(file_name):
        with open(file_name) as open_file:
            data = json.loads(open_file.read(),
                              object_hook=lambda d: Namespace(**d))
    return data
Example #14
0
def auth_user(request):
    if request.method == 'POST':
        data = json.loads(request.body, object_hook=lambda d: Namespace(**d))
        user = User.objects.filter(email=data.email).get()

        try:
            hashed = bcrypt.hashpw(data.password.encode('utf8'),
                                   bcrypt.gensalt())
            response_data = {}
            if not checkPassword(user.password.encode('utf8'), hashed):
                response_data = [{"status": '401'}]
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json")
            else:
                response_data = [{
                    "status": '200',
                    "user": {
                        'id': user.id,
                        'username': user.username,
                        'email': user.email,
                    }
                }]
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json")

        except KeyError:
            return HttpResponseServerError('error')
    def loadItemsProperty(self, itemsPropertyFile):
        """This method allows to feed the RS with items properties

            For the sake of this unit test, I chose to test if the title was present.
            the object contains all the attributes, only the title was shown for the
            sake of visualisation.

         >>> engine = BaselineRecommenderSystem()
         >>> engine.loadItemsProperty("meta_example.json")
         >>> items = sorted(engine.itemsProperty.items())
         >>> [(item, html.unescape(object.title)) for item, object in items]
         ... #doctest: +NORMALIZE_WHITESPACE
         [('item1', 'Barnes & Noble HDTV Adapter Kit for NOOK HD and NOOK HD+'),
         ('item2', 'Barnes & Noble OV/HB-ADP Universal Power Kit'),
         ('item3', 'Audiovox Surface SURF402 Wet/Dry Screen Wipes'),
         ('item4', 'VideoSecu 24" Long Arm TV Wall Mount Low Profile Full Motion Cantilever Swing & Tilt wall bracket for most 22" to 55" LED LCD TV Monitor Flat Panel Screen VESA 200x200 400x400 up to 600x400mm - Articulating Arm Extend up to 24" MAH'),
         ('item5', 'Barnes & Noble Nook eReader - no 3G'),
         ('item6', 'Barnes & Noble Nook Simple Touch eBook Reader (Wi-Fi Only)')]
        """
        # Parse Json file
        with open(itemsPropertyFile, 'r', encoding="utf-8") as f:
            for line in f:
                # For each line, create a dict object out of the JSON line
                item = json.loads(line, object_hook=lambda d: Namespace(**d))
                # Check if item exists in the items property list
                if item.asin not in self.itemsProperty:
                    # assign the asin as the key and the object item as value
                    self.itemsProperty[item.asin] = item
Example #16
0
def main():
    args_cmd = extract_args()
    if (args_cmd.input_args_dir != None):
        args_list = []
        path = args_cmd.input_args_dir
        print(f'Extracting possible args from directory {path}')
        for json_file_name in glob(f'{args_cmd.input_args_dir}/*.json'):
            print(f'Loading json file {json_file_name}')
            with open(json_file_name, 'r') as json_file:
                args_list += [
                    json.load(json_file, object_hook=lambda d: Namespace(**d))
                ]
    else:
        print(f'Extracting args from command line')
        args_list = [args_cmd]

    print(f'Running on {len(args_list)} possible args')
    for args in args_list:
        create_dirs(args)
        dump_args(args)
        setup_logging(args)
        download_data_unzip(args)
        train(args)

    # save graphs
    print_graphs_results(args_list)
Example #17
0
    def move_window(self, session_name):
        session_path = Path(self.base_location_of_sessions, session_name)
        if not session_path.exists():
            raise FileNotFoundError('Session file [%s] was not found.' %
                                    session_path)

        with open(session_path, 'r') as file:
            namespace_objs: XSessionConfig = json.load(
                file, object_hook=lambda d: Namespace(**d))

        x_session_config_objects: List[
            XSessionConfigObject] = namespace_objs.x_session_config_objects
        x_session_config_objects.sort(key=attrgetter('desktop_number'))

        if self.session_filters is not None:
            for session_filter in self.session_filters:
                if session_filter is None:
                    continue
                x_session_config_objects[:] = session_filter(
                    x_session_config_objects)

        if len(x_session_config_objects) == 0:
            print('No application to move.')
            return

        max_desktop_number = self._get_max_desktop_number(
            x_session_config_objects)
        with self.create_enough_workspaces(max_desktop_number):
            for namespace_obj in x_session_config_objects:
                try:
                    self._move_window(namespace_obj, need_retry=False)
                except:  # Catch all exceptions to be able to restore other apps
                    import traceback
                    print(traceback.format_exc())
    def handle_event(self, message):
        """
        Send a notification for the received event

        Args:
            message: the message
        """
        if self.message_type == message.get("message_type"):
            operation = message.get("operation")
            for event in self.events:
                if event == operation:
                    meta = message.get("meta", {})
                    app_name = meta.get("app_name", "")
                    description = meta.get("description", "")
                    obj = json.loads(json.dumps(message.get("resource")),
                                     object_hook=lambda d: Namespace(**d))
                    log.info(
                        f"{app_name} sent {operation} {self.message_type} {description} message"
                    )
                    send(operation=operation,
                         context={
                             "app_name": app_name,
                             "message_type": self.message_type,
                             "user": meta.get("user", {}),
                             "description": description,
                             "obj": obj
                         })
Example #19
0
    async def mining_statistics(self, ctx: commands.Context,
                                selector: Optional[str]):
        cumulative_data = None
        data_entries = []
        addresses_to_merge = None
        async with aiohttp.ClientSession() as cs:
            if selector is None or selector == "":
                addresses_to_merge = [
                    self.ethermine_addresses.get(
                        str(ctx.author.id),
                        self.ethermine_addresses.get("264213620026638336"))
                ]
            elif selector in {"all", "acc", "total"}:
                addresses_to_merge = self.ethermine_addresses.values()

            for addr in addresses_to_merge:
                async with cs.get(
                        f"https://api.ethermine.org/miner/:{addr}/currentStats"
                ) as ethermine:
                    ethermine_json = json.dumps(await ethermine.json())
                    curr_data = json.loads(
                        ethermine_json,
                        object_hook=lambda d: Namespace(**d)).data
                    curr_data.addr = addr
                    if cumulative_data is None:
                        cumulative_data = curr_data
                        data_entries.append(copy.deepcopy(curr_data))
                    else:
                        cumulative_data.reportedHashrate += curr_data.reportedHashrate
                        cumulative_data.currentHashrate += curr_data.currentHashrate
                        cumulative_data.averageHashrate += curr_data.averageHashrate
                        cumulative_data.unpaid += curr_data.unpaid
                        cumulative_data.usdPerMin += curr_data.usdPerMin
                        data_entries.append(copy.deepcopy(curr_data))

        headers = ["Wallet", "Avg. HR", "USD/Day"]
        table = []

        for data in data_entries:
            table.append([
                f"{data.addr[:6]}...{data.addr[-4:]}",
                round(data.averageHashrate / 1e6, 2),
                round(data.usdPerMin * 60 * 24, 2)
            ])

        if len(data_entries) > 1:
            table.append([
                f"Cumulative",
                round(cumulative_data.averageHashrate / 1e6, 2),
                round(cumulative_data.usdPerMin * 60 * 24, 2)
            ])

        desc = tabulate(table, headers=headers)

        embed: discord.Embed = discord.Embed(
            title=f"Ethermine report",
            description=f"```{desc}```",
            timestamp=datetime.datetime.utcnow(),
            colour=ctx.author.colour)
        await ctx.send(embed=embed)
Example #20
0
    def __init__(self, log=None):
        self.__ssl_context = None
        dbs = ISEServer.objects.filter(pxgrid_enable=True)
        c = '{"hostname": [], "nodename": "", "clientcert": "", "clientkey": "", "clientkeypassword": "",' \
            '"servercert": "", "password": "", "description": "", "id": null, "verbose": true, "services": null,' \
            '"port": 8910, "service_details": null, "service": "com.cisco.ise.config.trustsec",' \
            '"topic": "securityGroupTopic,securityGroupAclTopic", "session_dedup": false,' \
            '"subscribe_all": false}'
        self.config = json.loads(c, object_hook=lambda d: Namespace(**d))

        if len(dbs) > 0:
            append_log(
                log,
                "pxgrid_monitor::pxgrid_config::Establishing websocket for pxGrid..."
            )
            db = dbs[0]
            self.config.hostname = [db.pxgrid_ip]
            self.config.nodename = db.pxgrid_cliname
            self.config.clientcert = str(db.pxgrid_clicert.file)
            self.config.clientkey = str(db.pxgrid_clikey.file)
            self.config.clientkeypassword = db.pxgrid_clipw
            self.config.servercert = str(db.pxgrid_isecert.file)
            self.config.id = db.id
        else:
            self.config.id = None
            append_log(
                log,
                "pxgrid_monitor::pxgrid_config::No pxGrid servers configured..."
            )
Example #21
0
def Index(request):
    #tname , jsonstr = excel_to_json_new('D:/Work/Project/80_ServerProject/Source/ServerPatchUtil/WebGMTool_mvc/GameServerTableNew/ModuleItemTable.xlsm');
    #print(tname,jsonstr)
    #find_all_excel_file('D:/Work/Project/80_ServerProject/Source/ServerPatchUtil/WebGMTool_mvc/GameServerTableNew')
    #tsting = json_table_file_read('../NewTable/GameResultReward.json')
    #print(tsting)
    cbq = CouchbaseManager.instance()
    db_size = cbq.Get_DBPool_Size()

    if ( 0 == db_size) :
        InitCouchBase()

    if request.method =='POST' :
        return LoginProcess(request)

    #login_user = request.COOKIES.get('LoginUser', 'None')
    #login_user = request.session.get('LoginUser', 'None')
    #if 'None' != login_user :
    if (3 < db_size):
        return LoginMain(request)

    cbq = CouchbaseManager.instance()

    cbq.select_db(eDataBase.GM_Tool)
    list = []
    cresult = cbq.get_server_list()
    for row in cresult:
        strjson = str(row)
        cMessage = json.JSONEncoder().encode(row)
        objServer = json.loads(cMessage, object_hook=lambda d: Namespace(**d))
        list.append(objServer.name)
        cbq.AddServerInfo(objServer.name, objServer)

    return render(request,'WebTool/Index.html',{'server_list':json.dumps(list)})
Example #22
0
def callback_ensure_file(value):
    """

	:param ctx:
	:type ctx:
	:param param:
	:type param:
	:param value:
	:type value:
	:return:
	:rtype:
	"""
    container = Namespace(files=[], cwd=None)
    pref = []
    if not os.path.exists(value):
        value = os.getcwd()
        container.files.append(value)
        container.cwd = value

    elif isinstance(value, (list, tuple, set)):
        container.files = value

    elif os.path.isdir(value):
        container.files.append(value)
    try:
        source_files = expand_source_files(container.files, cwd=container.cwd)
    except (TypeError, FileNotFoundError) as exc:
        click.echo(
            'the `file` input couldnt resolve; passing [] as last-ditch.')
        source_files = []
    return source_files
Example #23
0
 def read_secrets(self):
     with open((self.path_to_secrets.absolute()), "r") as json_data:
         data = json_data.read()
         x = json.loads(data, object_hook=lambda d: Namespace(**d))
         self.client_id = x.twitch_con.client_id
         self.token = x.twitch_con.token
         return x
Example #24
0
 def wrapper(*args, **kwargs):
     beginEvent(func.__name__, getRealIP(request), request.full_path,
                request.args)
     if 'sid' in session:
         rd = Namespace()
         kwargs['user'] = _get_user_obj(session['sid'])
         if kwargs['user'] is None:
             log('login_check',
                 level='SEC',
                 obj={
                     'action': 'denied',
                     'path': request.full_path,
                     'sid': session['sid']
                 })
             return jsonResponse(
                 makeResponseError("UNAUTHORISED_OPERATION"))
         rd._user = kwargs['user']
         setEventUser(rd._user)
         kwargs['rd'] = rd
         ret = func(*args, **kwargs)
         return _handle_return(ret, rd)
     else:
         log('login_check',
             level='SEC',
             obj={
                 'action': 'denied',
                 'path': request.full_path
             })
         return jsonResponse(makeResponseError("UNAUTHORISED_OPERATION"))
Example #25
0
def load_json(jsonstr):
    try:
        from types import SimpleNamespace as Namespace
    except ImportError:
        # Python 2.x fallback
        from argparse import Namespace
    return json.loads(jsonstr, object_hook=lambda d: vars(Namespace(**d)))
Example #26
0
def process_json_file(zip, file_name):
    with zip.open(file_name, "r") as json_file:
        json_obj = json.loads(json_file.read(), object_hook=lambda d: Namespace(**d))
        people = json_obj.people
        people_count = len(people)
        recognized_faces = people_count
        recognized_hands = people_count * 2
        total_pose_points = 0
        total_face_points = 0
        total_hand_points = 0
        for person in people:
            pose_key_points = count_key_points(person.pose_keypoints_2d, 0.05)
            face_key_points = count_key_points(person.face_keypoints_2d, 0.4)
            left_hand_key_points = count_key_points(person.hand_left_keypoints_2d, 0.2)
            right_hand_key_points = count_key_points(person.hand_right_keypoints_2d, 0.2)
            if face_key_points == 0:
                recognized_faces -= 1
            if left_hand_key_points == 0:
                recognized_hands -= 1
            if right_hand_key_points == 0:
                recognized_hands -= 1
            total_pose_points += pose_key_points
            total_face_points += face_key_points
            total_hand_points += left_hand_key_points + right_hand_key_points
    return people_count, total_pose_points, recognized_faces, total_face_points, recognized_hands, total_hand_points
Example #27
0
    def extract_log_metadata(self, filename):
        # load JSON parser config
        json_fp = os.path.join(PROJECT_DIR, "resources",
                               "log_metadata_config.json")

        with open(json_fp, 'r') as json_file:
            # data = json.loads(json_file.read(), object_hook=lambda d: Namespace(**d))
            # print data
            schema = json.load(json_file, object_hook=lambda d: Namespace(**d))
            # print schema

        global metadata_obj, tag_descriptions
        # convert JSON object into a standard dictionary
        metadata_obj = ast.literal_eval(
            json.dumps(
                schema,
                default=lambda o: getattr(o, '__dict__', str(o))))["sections"]
        tag_descriptions = ast.literal_eval(
            json.dumps(
                schema,
                default=lambda o: getattr(o, '__dict__', str(o))))["tags"]
        # print metadata_obj

        # print schema.time_point.label
        # print schema.time_point.regex

        # x = json2obj(json.dumps(data, encoding="UTF-8"))
        # print x

        self.parse_metadata(schema, filename)

        log_metadata = self.create_log_metadata_obj(metadata_obj)
        return log_metadata
Example #28
0
def GetMorpheus(weight, feature):
    return Namespace(
        weight=morpheusWeightMap[weight],
        width=3,
        family="Latin",
        feature=feature,
    )
Example #29
0
 def wrapper(*args, **kwargs):
     beginEvent(func.__name__, getRealIP(request), request.full_path,
                request.args)
     rd = Namespace()
     rd._version = _VERSION
     rd._version_url = _VERSION_URL
     kwargs['rd'] = rd
     if 'data' not in kwargs:
         kwargs['data'] = {}
     kwargs['data']['param'] = request.args
     try:
         ret = func(*args, **kwargs)
         return _handle_return(ret, rd)
     except HTTPException as e:
         log(level='WARN', obj={'ex': e})
         raise e
     except Exception as ex:
         import traceback
         log(level='ERR',
             obj={
                 'ex': str(ex),
                 'tb1': repr(traceback.format_exc()),
                 'tb2': repr(traceback.extract_stack())
             })
         abort(400)
Example #30
0
def GetSkurri(weight, feature):
    return Namespace(
        weight=weight,
        width=7,
        family="Latin",
        feature=feature,
    )