code
stringlengths
4
1.01M
language
stringclasses
2 values
""" Room Typeclasses for the TutorialWorld. This defines special types of Rooms available in the tutorial. To keep everything in one place we define them together with the custom commands needed to control them. Those commands could also have been in a separate module (e.g. if they could have been re-used elsewhere.) """ from __future__ import print_function import random from evennia import TICKER_HANDLER from evennia import CmdSet, Command, DefaultRoom from evennia import utils, create_object, search_object from evennia import syscmdkeys, default_cmds from evennia.contrib.tutorial_world.objects import LightSource # the system error-handling module is defined in the settings. We load the # given setting here using utils.object_from_module. This way we can use # it regardless of if we change settings later. from django.conf import settings _SEARCH_AT_RESULT = utils.object_from_module(settings.SEARCH_AT_RESULT) # ------------------------------------------------------------- # # Tutorial room - parent room class # # This room is the parent of all rooms in the tutorial. # It defines a tutorial command on itself (available to # all those who are in a tutorial room). # # ------------------------------------------------------------- # # Special command available in all tutorial rooms class CmdTutorial(Command): """ Get help during the tutorial Usage: tutorial [obj] This command allows you to get behind-the-scenes info about an object or the current location. """ key = "tutorial" aliases = ["tut"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """ All we do is to scan the current location for an Attribute called `tutorial_info` and display that. """ caller = self.caller if not self.args: target = self.obj # this is the room the command is defined on else: target = caller.search(self.args.strip()) if not target: return helptext = target.db.tutorial_info if helptext: caller.msg("|G%s|n" % helptext) else: caller.msg("|RSorry, there is no tutorial help available here.|n") # for the @detail command we inherit from MuxCommand, since # we want to make use of MuxCommand's pre-parsing of '=' in the # argument. class CmdTutorialSetDetail(default_cmds.MuxCommand): """ sets a detail on a room Usage: @detail <key> = <description> @detail <key>;<alias>;... = description Example: @detail walls = The walls are covered in ... @detail castle;ruin;tower = The distant ruin ... This sets a "detail" on the object this command is defined on (TutorialRoom for this tutorial). This detail can be accessed with the TutorialRoomLook command sitting on TutorialRoom objects (details are set as a simple dictionary on the room). This is a Builder command. We custom parse the key for the ;-separator in order to create multiple aliases to the detail all at once. """ key = "@detail" locks = "cmd:perm(Builder)" help_category = "TutorialWorld" def func(self): """ All this does is to check if the object has the set_detail method and uses it. """ if not self.args or not self.rhs: self.caller.msg("Usage: @detail key = description") return if not hasattr(self.obj, "set_detail"): self.caller.msg("Details cannot be set on %s." % self.obj) return for key in self.lhs.split(";"): # loop over all aliases, if any (if not, this will just be # the one key to loop over) self.obj.set_detail(key, self.rhs) self.caller.msg("Detail set: '%s': '%s'" % (self.lhs, self.rhs)) class CmdTutorialLook(default_cmds.CmdLook): """ looks at the room and on details Usage: look <obj> look <room detail> look *<account> Observes your location, details at your location or objects in your vicinity. Tutorial: This is a child of the default Look command, that also allows us to look at "details" in the room. These details are things to examine and offers some extra description without actually having to be actual database objects. It uses the return_detail() hook on TutorialRooms for this. """ # we don't need to specify key/locks etc, this is already # set by the parent. help_category = "TutorialWorld" def func(self): """ Handle the looking. This is a copy of the default look code except for adding in the details. """ caller = self.caller args = self.args if args: # we use quiet=True to turn off automatic error reporting. # This tells search that we want to handle error messages # ourself. This also means the search function will always # return a list (with 0, 1 or more elements) rather than # result/None. looking_at_obj = caller.search(args, # note: excludes room/room aliases candidates=caller.location.contents + caller.contents, use_nicks=True, quiet=True) if len(looking_at_obj) != 1: # no target found or more than one target found (multimatch) # look for a detail that may match detail = self.obj.return_detail(args) if detail: self.caller.msg(detail) return else: # no detail found, delegate our result to the normal # error message handler. _SEARCH_AT_RESULT(None, caller, args, looking_at_obj) return else: # we found a match, extract it from the list and carry on # normally with the look handling. looking_at_obj = looking_at_obj[0] else: looking_at_obj = caller.location if not looking_at_obj: caller.msg("You have no location to look at!") return if not hasattr(looking_at_obj, 'return_appearance'): # this is likely due to us having an account instead looking_at_obj = looking_at_obj.character if not looking_at_obj.access(caller, "view"): caller.msg("Could not find '%s'." % args) return # get object's appearance caller.msg(looking_at_obj.return_appearance(caller)) # the object's at_desc() method. looking_at_obj.at_desc(looker=caller) return class TutorialRoomCmdSet(CmdSet): """ Implements the simple tutorial cmdset. This will overload the look command in the default CharacterCmdSet since it has a higher priority (ChracterCmdSet has prio 0) """ key = "tutorial_cmdset" priority = 1 def at_cmdset_creation(self): """add the tutorial-room commands""" self.add(CmdTutorial()) self.add(CmdTutorialSetDetail()) self.add(CmdTutorialLook()) class TutorialRoom(DefaultRoom): """ This is the base room type for all rooms in the tutorial world. It defines a cmdset on itself for reading tutorial info about the location. """ def at_object_creation(self): """Called when room is first created""" self.db.tutorial_info = "This is a tutorial room. It allows you to use the 'tutorial' command." self.cmdset.add_default(TutorialRoomCmdSet) def at_object_receive(self, new_arrival, source_location): """ When an object enter a tutorial room we tell other objects in the room about it by trying to call a hook on them. The Mob object uses this to cheaply get notified of enemies without having to constantly scan for them. Args: new_arrival (Object): the object that just entered this room. source_location (Object): the previous location of new_arrival. """ if new_arrival.has_account and not new_arrival.is_superuser: # this is a character for obj in self.contents_get(exclude=new_arrival): if hasattr(obj, "at_new_arrival"): obj.at_new_arrival(new_arrival) def return_detail(self, detailkey): """ This looks for an Attribute "obj_details" and possibly returns the value of it. Args: detailkey (str): The detail being looked at. This is case-insensitive. """ details = self.db.details if details: return details.get(detailkey.lower(), None) def set_detail(self, detailkey, description): """ This sets a new detail, using an Attribute "details". Args: detailkey (str): The detail identifier to add (for aliases you need to add multiple keys to the same description). Case-insensitive. description (str): The text to return when looking at the given detailkey. """ if self.db.details: self.db.details[detailkey.lower()] = description else: self.db.details = {detailkey.lower(): description} # ------------------------------------------------------------- # # Weather room - room with a ticker # # ------------------------------------------------------------- # These are rainy weather strings WEATHER_STRINGS = ( "The rain coming down from the iron-grey sky intensifies.", "A gust of wind throws the rain right in your face. Despite your cloak you shiver.", "The rainfall eases a bit and the sky momentarily brightens.", "For a moment it looks like the rain is slowing, then it begins anew with renewed force.", "The rain pummels you with large, heavy drops. You hear the rumble of thunder in the distance.", "The wind is picking up, howling around you, throwing water droplets in your face. It's cold.", "Bright fingers of lightning flash over the sky, moments later followed by a deafening rumble.", "It rains so hard you can hardly see your hand in front of you. You'll soon be drenched to the bone.", "Lightning strikes in several thundering bolts, striking the trees in the forest to your west.", "You hear the distant howl of what sounds like some sort of dog or wolf.", "Large clouds rush across the sky, throwing their load of rain over the world.") class WeatherRoom(TutorialRoom): """ This should probably better be called a rainy room... This sets up an outdoor room typeclass. At irregular intervals, the effects of weather will show in the room. Outdoor rooms should inherit from this. """ def at_object_creation(self): """ Called when object is first created. We set up a ticker to update this room regularly. Note that we could in principle also use a Script to manage the ticking of the room; the TickerHandler works fine for simple things like this though. """ super(WeatherRoom, self).at_object_creation() # subscribe ourselves to a ticker to repeatedly call the hook # "update_weather" on this object. The interval is randomized # so as to not have all weather rooms update at the same time. self.db.interval = random.randint(50, 70) TICKER_HANDLER.add(interval=self.db.interval, callback=self.update_weather, idstring="tutorial") # this is parsed by the 'tutorial' command on TutorialRooms. self.db.tutorial_info = \ "This room has a Script running that has it echo a weather-related message at irregular intervals." def update_weather(self, *args, **kwargs): """ Called by the tickerhandler at regular intervals. Even so, we only update 20% of the time, picking a random weather message when we do. The tickerhandler requires that this hook accepts any arguments and keyword arguments (hence the *args, **kwargs even though we don't actually use them in this example) """ if random.random() < 0.2: # only update 20 % of the time self.msg_contents("|w%s|n" % random.choice(WEATHER_STRINGS)) SUPERUSER_WARNING = "\nWARNING: You are playing as a superuser ({name}). Use the {quell} command to\n" \ "play without superuser privileges (many functions and puzzles ignore the \n" \ "presence of a superuser, making this mode useful for exploring things behind \n" \ "the scenes later).\n" \ # ------------------------------------------------------------ # # Intro Room - unique room # # This room marks the start of the tutorial. It sets up properties on # the player char that is needed for the tutorial. # # ------------------------------------------------------------- class IntroRoom(TutorialRoom): """ Intro room properties to customize: char_health - integer > 0 (default 20) """ def at_object_creation(self): """ Called when the room is first created. """ super(IntroRoom, self).at_object_creation() self.db.tutorial_info = "The first room of the tutorial. " \ "This assigns the health Attribute to "\ "the account." def at_object_receive(self, character, source_location): """ Assign properties on characters """ # setup character for the tutorial health = self.db.char_health or 20 if character.has_account: character.db.health = health character.db.health_max = health if character.is_superuser: string = "-" * 78 + SUPERUSER_WARNING + "-" * 78 character.msg("|r%s|n" % string.format(name=character.key, quell="|w@quell|r")) # ------------------------------------------------------------- # # Bridge - unique room # # Defines a special west-eastward "bridge"-room, a large room that takes # several steps to cross. It is complete with custom commands and a # chance of falling off the bridge. This room has no regular exits, # instead the exitings are handled by custom commands set on the account # upon first entering the room. # # Since one can enter the bridge room from both ends, it is # divided into five steps: # westroom <- 0 1 2 3 4 -> eastroom # # ------------------------------------------------------------- class CmdEast(Command): """ Go eastwards across the bridge. Tutorial info: This command relies on the caller having two Attributes (assigned by the room when entering): - east_exit: a unique name or dbref to the room to go to when exiting east. - west_exit: a unique name or dbref to the room to go to when exiting west. The room must also have the following Attributes - tutorial_bridge_posistion: the current position on on the bridge, 0 - 4. """ key = "east" aliases = ["e"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """move one step eastwards""" caller = self.caller bridge_step = min(5, caller.db.tutorial_bridge_position + 1) if bridge_step > 4: # we have reached the far east end of the bridge. # Move to the east room. eexit = search_object(self.obj.db.east_exit) if eexit: caller.move_to(eexit[0]) else: caller.msg("No east exit was found for this room. Contact an admin.") return caller.db.tutorial_bridge_position = bridge_step # since we are really in one room, we have to notify others # in the room when we move. caller.location.msg_contents("%s steps eastwards across the bridge." % caller.name, exclude=caller) caller.execute_cmd("look") # go back across the bridge class CmdWest(Command): """ Go westwards across the bridge. Tutorial info: This command relies on the caller having two Attributes (assigned by the room when entering): - east_exit: a unique name or dbref to the room to go to when exiting east. - west_exit: a unique name or dbref to the room to go to when exiting west. The room must also have the following property: - tutorial_bridge_posistion: the current position on on the bridge, 0 - 4. """ key = "west" aliases = ["w"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """move one step westwards""" caller = self.caller bridge_step = max(-1, caller.db.tutorial_bridge_position - 1) if bridge_step < 0: # we have reached the far west end of the bridge. # Move to the west room. wexit = search_object(self.obj.db.west_exit) if wexit: caller.move_to(wexit[0]) else: caller.msg("No west exit was found for this room. Contact an admin.") return caller.db.tutorial_bridge_position = bridge_step # since we are really in one room, we have to notify others # in the room when we move. caller.location.msg_contents("%s steps westwards across the bridge." % caller.name, exclude=caller) caller.execute_cmd("look") BRIDGE_POS_MESSAGES = ("You are standing |wvery close to the the bridge's western foundation|n." " If you go west you will be back on solid ground ...", "The bridge slopes precariously where it extends eastwards" " towards the lowest point - the center point of the hang bridge.", "You are |whalfways|n out on the unstable bridge.", "The bridge slopes precariously where it extends westwards" " towards the lowest point - the center point of the hang bridge.", "You are standing |wvery close to the bridge's eastern foundation|n." " If you go east you will be back on solid ground ...") BRIDGE_MOODS = ("The bridge sways in the wind.", "The hanging bridge creaks dangerously.", "You clasp the ropes firmly as the bridge sways and creaks under you.", "From the castle you hear a distant howling sound, like that of a large dog or other beast.", "The bridge creaks under your feet. Those planks does not seem very sturdy.", "Far below you the ocean roars and throws its waves against the cliff," " as if trying its best to reach you.", "Parts of the bridge come loose behind you, falling into the chasm far below!", "A gust of wind causes the bridge to sway precariously.", "Under your feet a plank comes loose, tumbling down. For a moment you dangle over the abyss ...", "The section of rope you hold onto crumble in your hands," " parts of it breaking apart. You sway trying to regain balance.") FALL_MESSAGE = "Suddenly the plank you stand on gives way under your feet! You fall!" \ "\nYou try to grab hold of an adjoining plank, but all you manage to do is to " \ "divert your fall westwards, towards the cliff face. This is going to hurt ... " \ "\n ... The world goes dark ...\n\n" class CmdLookBridge(Command): """ looks around at the bridge. Tutorial info: This command assumes that the room has an Attribute "fall_exit", a unique name or dbref to the place they end upp if they fall off the bridge. """ key = 'look' aliases = ["l"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """Looking around, including a chance to fall.""" caller = self.caller bridge_position = self.caller.db.tutorial_bridge_position # this command is defined on the room, so we get it through self.obj location = self.obj # randomize the look-echo message = "|c%s|n\n%s\n%s" % (location.key, BRIDGE_POS_MESSAGES[bridge_position], random.choice(BRIDGE_MOODS)) chars = [obj for obj in self.obj.contents_get(exclude=caller) if obj.has_account] if chars: # we create the You see: message manually here message += "\n You see: %s" % ", ".join("|c%s|n" % char.key for char in chars) self.caller.msg(message) # there is a chance that we fall if we are on the western or central # part of the bridge. if bridge_position < 3 and random.random() < 0.05 and not self.caller.is_superuser: # we fall 5% of time. fall_exit = search_object(self.obj.db.fall_exit) if fall_exit: self.caller.msg("|r%s|n" % FALL_MESSAGE) self.caller.move_to(fall_exit[0], quiet=True) # inform others on the bridge self.obj.msg_contents("A plank gives way under %s's feet and " "they fall from the bridge!" % self.caller.key) # custom help command class CmdBridgeHelp(Command): """ Overwritten help command while on the bridge. """ key = "help" aliases = ["h", "?"] locks = "cmd:all()" help_category = "Tutorial world" def func(self): """Implements the command.""" string = "You are trying hard not to fall off the bridge ..." \ "\n\nWhat you can do is trying to cross the bridge |weast|n" \ " or try to get back to the mainland |wwest|n)." self.caller.msg(string) class BridgeCmdSet(CmdSet): """This groups the bridge commands. We will store it on the room.""" key = "Bridge commands" priority = 1 # this gives it precedence over the normal look/help commands. def at_cmdset_creation(self): """Called at first cmdset creation""" self.add(CmdTutorial()) self.add(CmdEast()) self.add(CmdWest()) self.add(CmdLookBridge()) self.add(CmdBridgeHelp()) BRIDGE_WEATHER = ( "The rain intensifies, making the planks of the bridge even more slippery.", "A gust of wind throws the rain right in your face.", "The rainfall eases a bit and the sky momentarily brightens.", "The bridge shakes under the thunder of a closeby thunder strike.", "The rain pummels you with large, heavy drops. You hear the distinct howl of a large hound in the distance.", "The wind is picking up, howling around you and causing the bridge to sway from side to side.", "Some sort of large bird sweeps by overhead, giving off an eery screech. Soon it has disappeared in the gloom.", "The bridge sways from side to side in the wind.", "Below you a particularly large wave crashes into the rocks.", "From the ruin you hear a distant, otherwordly howl. Or maybe it was just the wind.") class BridgeRoom(WeatherRoom): """ The bridge room implements an unsafe bridge. It also enters the player into a state where they get new commands so as to try to cross the bridge. We want this to result in the account getting a special set of commands related to crossing the bridge. The result is that it will take several steps to cross it, despite it being represented by only a single room. We divide the bridge into steps: self.db.west_exit - - | - - self.db.east_exit 0 1 2 3 4 The position is handled by a variable stored on the character when entering and giving special move commands will increase/decrease the counter until the bridge is crossed. We also has self.db.fall_exit, which points to a gathering location to end up if we happen to fall off the bridge (used by the CmdLookBridge command). """ def at_object_creation(self): """Setups the room""" # this will start the weather room's ticker and tell # it to call update_weather regularly. super(BridgeRoom, self).at_object_creation() # this identifies the exits from the room (should be the command # needed to leave through that exit). These are defaults, but you # could of course also change them after the room has been created. self.db.west_exit = "cliff" self.db.east_exit = "gate" self.db.fall_exit = "cliffledge" # add the cmdset on the room. self.cmdset.add_default(BridgeCmdSet) # since the default Character's at_look() will access the room's # return_description (this skips the cmdset) when # first entering it, we need to explicitly turn off the room # as a normal view target - once inside, our own look will # handle all return messages. self.locks.add("view:false()") def update_weather(self, *args, **kwargs): """ This is called at irregular intervals and makes the passage over the bridge a little more interesting. """ if random.random() < 80: # send a message most of the time self.msg_contents("|w%s|n" % random.choice(BRIDGE_WEATHER)) def at_object_receive(self, character, source_location): """ This hook is called by the engine whenever the player is moved into this room. """ if character.has_account: # we only run this if the entered object is indeed a player object. # check so our east/west exits are correctly defined. wexit = search_object(self.db.west_exit) eexit = search_object(self.db.east_exit) fexit = search_object(self.db.fall_exit) if not (wexit and eexit and fexit): character.msg("The bridge's exits are not properly configured. " "Contact an admin. Forcing west-end placement.") character.db.tutorial_bridge_position = 0 return if source_location == eexit[0]: # we assume we enter from the same room we will exit to character.db.tutorial_bridge_position = 4 else: # if not from the east, then from the west! character.db.tutorial_bridge_position = 0 character.execute_cmd("look") def at_object_leave(self, character, target_location): """ This is triggered when the player leaves the bridge room. """ if character.has_account: # clean up the position attribute del character.db.tutorial_bridge_position # ------------------------------------------------------------------------------- # # Dark Room - a room with states # # This room limits the movemenets of its denizens unless they carry an active # LightSource object (LightSource is defined in # tutorialworld.objects.LightSource) # # ------------------------------------------------------------------------------- DARK_MESSAGES = ("It is pitch black. You are likely to be eaten by a grue.", "It's pitch black. You fumble around but cannot find anything.", "You don't see a thing. You feel around, managing to bump your fingers hard against something. Ouch!", "You don't see a thing! Blindly grasping the air around you, you find nothing.", "It's totally dark here. You almost stumble over some un-evenness in the ground.", "You are completely blind. For a moment you think you hear someone breathing nearby ... " "\n ... surely you must be mistaken.", "Blind, you think you find some sort of object on the ground, but it turns out to be just a stone.", "Blind, you bump into a wall. The wall seems to be covered with some sort of vegetation," " but its too damp to burn.", "You can't see anything, but the air is damp. It feels like you are far underground.") ALREADY_LIGHTSOURCE = "You don't want to stumble around in blindness anymore. You already " \ "found what you need. Let's get light already!" FOUND_LIGHTSOURCE = "Your fingers bump against a splinter of wood in a corner." \ " It smells of resin and seems dry enough to burn! " \ "You pick it up, holding it firmly. Now you just need to" \ " |wlight|n it using the flint and steel you carry with you." class CmdLookDark(Command): """ Look around in darkness Usage: look Look around in the darkness, trying to find something. """ key = "look" aliases = ["l", 'feel', 'search', 'feel around', 'fiddle'] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """ Implement the command. This works both as a look and a search command; there is a random chance of eventually finding a light source. """ caller = self.caller if random.random() < 0.8: # we don't find anything caller.msg(random.choice(DARK_MESSAGES)) else: # we could have found something! if any(obj for obj in caller.contents if utils.inherits_from(obj, LightSource)): # we already carry a LightSource object. caller.msg(ALREADY_LIGHTSOURCE) else: # don't have a light source, create a new one. create_object(LightSource, key="splinter", location=caller) caller.msg(FOUND_LIGHTSOURCE) class CmdDarkHelp(Command): """ Help command for the dark state. """ key = "help" locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """ Replace the the help command with a not-so-useful help """ string = "Can't help you until you find some light! Try looking/feeling around for something to burn. " \ "You shouldn't give up even if you don't find anything right away." self.caller.msg(string) class CmdDarkNoMatch(Command): """ This is a system command. Commands with special keys are used to override special sitations in the game. The CMD_NOMATCH is used when the given command is not found in the current command set (it replaces Evennia's default behavior or offering command suggestions) """ key = syscmdkeys.CMD_NOMATCH locks = "cmd:all()" def func(self): """Implements the command.""" self.caller.msg("Until you find some light, there's not much you can do. Try feeling around.") class DarkCmdSet(CmdSet): """ Groups the commands of the dark room together. We also import the default say command here so that players can still talk in the darkness. We give the cmdset the mergetype "Replace" to make sure it completely replaces whichever command set it is merged onto (usually the default cmdset) """ key = "darkroom_cmdset" mergetype = "Replace" priority = 2 def at_cmdset_creation(self): """populate the cmdset.""" self.add(CmdTutorial()) self.add(CmdLookDark()) self.add(CmdDarkHelp()) self.add(CmdDarkNoMatch()) self.add(default_cmds.CmdSay) class DarkRoom(TutorialRoom): """ A dark room. This tries to start the DarkState script on all objects entering. The script is responsible for making sure it is valid (that is, that there is no light source shining in the room). The is_lit Attribute is used to define if the room is currently lit or not, so as to properly echo state changes. Since this room (in the tutorial) is meant as a sort of catch-all, we also make sure to heal characters ending up here, since they may have been beaten up by the ghostly apparition at this point. """ def at_object_creation(self): """ Called when object is first created. """ super(DarkRoom, self).at_object_creation() self.db.tutorial_info = "This is a room with custom command sets on itself." # the room starts dark. self.db.is_lit = False self.cmdset.add(DarkCmdSet, permanent=True) def at_init(self): """ Called when room is first recached (such as after a reload) """ self.check_light_state() def _carries_light(self, obj): """ Checks if the given object carries anything that gives light. Note that we do NOT look for a specific LightSource typeclass, but for the Attribute is_giving_light - this makes it easy to later add other types of light-giving items. We also accept if there is a light-giving object in the room overall (like if a splinter was dropped in the room) """ return obj.is_superuser or obj.db.is_giving_light or any(o for o in obj.contents if o.db.is_giving_light) def _heal(self, character): """ Heal a character. """ health = character.db.health_max or 20 character.db.health = health def check_light_state(self, exclude=None): """ This method checks if there are any light sources in the room. If there isn't it makes sure to add the dark cmdset to all characters in the room. It is called whenever characters enter the room and also by the Light sources when they turn on. Args: exclude (Object): An object to not include in the light check. """ if any(self._carries_light(obj) for obj in self.contents if obj != exclude): self.locks.add("view:all()") self.cmdset.remove(DarkCmdSet) self.db.is_lit = True for char in (obj for obj in self.contents if obj.has_account): # this won't do anything if it is already removed char.msg("The room is lit up.") else: # noone is carrying light - darken the room self.db.is_lit = False self.locks.add("view:false()") self.cmdset.add(DarkCmdSet, permanent=True) for char in (obj for obj in self.contents if obj.has_account): if char.is_superuser: char.msg("You are Superuser, so you are not affected by the dark state.") else: # put players in darkness char.msg("The room is completely dark.") def at_object_receive(self, obj, source_location): """ Called when an object enters the room. """ if obj.has_account: # a puppeted object, that is, a Character self._heal(obj) # in case the new guy carries light with them self.check_light_state() def at_object_leave(self, obj, target_location): """ In case people leave with the light, we make sure to clear the DarkCmdSet if necessary. This also works if they are teleported away. """ # since this hook is called while the object is still in the room, # we exclude it from the light check, to ignore any light sources # it may be carrying. self.check_light_state(exclude=obj) # ------------------------------------------------------------- # # Teleport room - puzzles solution # # This is a sort of puzzle room that requires a certain # attribute on the entering character to be the same as # an attribute of the room. If not, the character will # be teleported away to a target location. This is used # by the Obelisk - grave chamber puzzle, where one must # have looked at the obelisk to get an attribute set on # oneself, and then pick the grave chamber with the # matching imagery for this attribute. # # ------------------------------------------------------------- class TeleportRoom(TutorialRoom): """ Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while teleporting to success failure_teleport_to - where to teleport to in case of failure failure_teleport_msg - message to echo while teleporting to failure """ def at_object_creation(self): """Called at first creation""" super(TeleportRoom, self).at_object_creation() # what character.db.puzzle_clue must be set to, to avoid teleportation. self.db.puzzle_value = 1 # target of successful teleportation. Can be a dbref or a # unique room name. self.db.success_teleport_msg = "You are successful!" self.db.success_teleport_to = "treasure room" # the target of the failure teleportation. self.db.failure_teleport_msg = "You fail!" self.db.failure_teleport_to = "dark cell" def at_object_receive(self, character, source_location): """ This hook is called by the engine whenever the player is moved into this room. """ if not character.has_account: # only act on player characters. return # determine if the puzzle is a success or not is_success = str(character.db.puzzle_clue) == str(self.db.puzzle_value) teleport_to = self.db.success_teleport_to if is_success else self.db.failure_teleport_to # note that this returns a list results = search_object(teleport_to) if not results or len(results) > 1: # we cannot move anywhere since no valid target was found. character.msg("no valid teleport target for %s was found." % teleport_to) return if character.is_superuser: # superusers don't get teleported character.msg("Superuser block: You would have been teleported to %s." % results[0]) return # perform the teleport if is_success: character.msg(self.db.success_teleport_msg) else: character.msg(self.db.failure_teleport_msg) # teleport quietly to the new place character.move_to(results[0], quiet=True, move_hooks=False) # we have to call this manually since we turn off move_hooks # - this is necessary to make the target dark room aware of an # already carried light. results[0].at_object_receive(character, self) # ------------------------------------------------------------- # # Outro room - unique exit room # # Cleans up the character from all tutorial-related properties. # # ------------------------------------------------------------- class OutroRoom(TutorialRoom): """ Outro room. Called when exiting the tutorial, cleans the character of tutorial-related attributes. """ def at_object_creation(self): """ Called when the room is first created. """ super(OutroRoom, self).at_object_creation() self.db.tutorial_info = "The last room of the tutorial. " \ "This cleans up all temporary Attributes " \ "the tutorial may have assigned to the "\ "character." def at_object_receive(self, character, source_location): """ Do cleanup. """ if character.has_account: del character.db.health_max del character.db.health del character.db.last_climbed del character.db.puzzle_clue del character.db.combat_parry_mode del character.db.tutorial_bridge_position for obj in character.contents: if obj.typeclass_path.startswith("evennia.contrib.tutorial_world"): obj.delete() character.tags.clear(category="tutorial_world")
Java
<?php namespace asdfstudio\admin\helpers; use Yii; use asdfstudio\admin\Module; use asdfstudio\admin\base\Admin; use yii\db\ActiveRecord; class AdminHelper { /** * @param string $entity Admin class name or Id * @return Admin|null */ public static function getEntity($entity) { /* @var Module $module */ $module = Yii::$app->controller->module; if (isset($module->entities[$entity])) { return $module->entities[$entity]; } elseif (isset($module->entitiesClasses[$entity])) { return static::getEntity($module->entitiesClasses[$entity]); } return null; } /** * Return value of nested attribute. * * ```php * // e.g. $post is Post model. We need to get a name of owmer. Owner is related model. * * AdminHelper::resolveAttribute('owner.username', $post); // it returns username from owner attribute * ``` * * @param string $attribute * @param ActiveRecord $model * @return string */ public static function resolveAttribute($attribute, $model) { $path = explode('.', $attribute); $attr = $model; foreach ($path as $a) { $attr = $attr->{$a}; } return $attr; } }
Java
#include <core/Runtime.h> #include <stdlib.h> #include <math.h> int runtime_f32_mul(Stack stack) { Value* operand1 = NULL; Value* operand2 = NULL; pop_Value(stack, &operand2); pop_Value(stack, &operand1); if(isnan(operand1->value.f32) || isnan(operand2->value.f32)) { push_Value(stack, new_f32Value(nanf(""))); } else if(isinf(operand1->value.f32) || isinf(operand2->value.f32)) { if(operand1->value.f32 == 0 || operand2->value.f32 == 0) { push_Value(stack, new_f32Value(nanf(""))); } else if(signbit(operand1->value.f32) ^ signbit(operand2->value.f32)) { push_Value(stack, new_f32Value(-strtof("INF", NULL))); } else { push_Value(stack, new_f32Value(strtof("INF", NULL))); } } else if(operand1->value.f32 == 0 && operand2->value.f32 == 0) { if(signbit(operand1->value.f32) ^ signbit(operand2->value.f32)) { push_Value(stack, new_f32Value(-0.0f)); } else { push_Value(stack, new_f32Value(+0.0f)); } } else { push_Value(stack, new_f32Value(operand1->value.f32 * operand2->value.f32)); } free_Value(operand1); free_Value(operand2); return 0; }
Java
package tools; /* * Extremely Compiler Collection * Copyright (c) 2015-2020, Jianping Zeng. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ import java.io.PrintStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * This owns the files read by a parser, handles include stacks, * and handles diagnostic wrangling. * * @author Jianping Zeng * @version 0.4 */ public final class SourceMgr { public enum DiagKind { DK_Error, DK_Warning, DK_Remark, DK_Note } private DiagKind getDiagKindByName(String name) { switch (name) { case "error": return DiagKind.DK_Error; case "warning": return DiagKind.DK_Warning; case "remark": return DiagKind.DK_Remark; case "note": return DiagKind.DK_Note; default: Util.assertion("Unknown diagnostic kind!"); return null; } } public static class SMLoc { private MemoryBuffer buffer; private int startPos; @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() != obj.getClass()) return false; SMLoc loc = (SMLoc) obj; return loc.buffer.equals(buffer) && startPos == loc.startPos; } public static SMLoc get(MemoryBuffer buf, int start) { SMLoc loc = new SMLoc(); loc.buffer = buf; loc.startPos = start; return loc; } public static SMLoc get(MemoryBuffer buf) { SMLoc loc = new SMLoc(); loc.buffer = buf; loc.startPos = buf.getBufferStart(); return loc; } public boolean isValid() { return buffer != null; } public int getPointer() { return startPos; } } static class SrcBuffer { MemoryBuffer buffer; /** * This is the location of the parent include, or * null if it is in the top level. */ SMLoc includeLoc; } private static class LineNoCache { int lastQueryBufferID; MemoryBuffer lastQuery; int lineNoOfQuery; } /** * This is all of the buffers that we are reading from. */ private ArrayList<SrcBuffer> buffers = new ArrayList<>(); /** * This is the list of directories we should search for * include files in. */ private LinkedList<String> includeDirs; /** * This s cache for line number queries. */ private LineNoCache lineNoCache; public void setIncludeDirs(List<String> dirs) { includeDirs = new LinkedList<>(dirs); } public SrcBuffer getBufferInfo(int i) { Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!"); return buffers.get(i); } public MemoryBuffer getMemoryBuffer(int i) { Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!"); return buffers.get(i).buffer; } public SMLoc getParentIncludeLoc(int i) { Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!"); return buffers.get(i).includeLoc; } public int addNewSourceBuffer(MemoryBuffer buf, SMLoc includeLoc) { SrcBuffer buffer = new SrcBuffer(); buffer.buffer = buf; buffer.includeLoc = includeLoc; buffers.add(buffer); return buffers.size() - 1; } /** * Search for a file with the specified name in the current directory or * in one of the {@linkplain #includeDirs}. If no such file found, this return * ~0, otherwise it returns the buffer ID of the stacked file. * * @param filename * @param includeLoc * @return */ public int addIncludeFile(String filename, SMLoc includeLoc) { MemoryBuffer newBuf = MemoryBuffer.getFile(filename); for (int i = 0, e = includeDirs.size(); i < e && newBuf == null; i++) { String incFile = includeDirs.get(i) + "/" + filename; newBuf = MemoryBuffer.getFile(incFile); } if (newBuf == null) return ~0; return addNewSourceBuffer(newBuf, includeLoc); } /** * Return the ID of the buffer containing the specified location, return -1 * if not found. * * @param loc * @return */ public int findBufferContainingLoc(SMLoc loc) { for (int i = 0, e = buffers.size(); i < e; i++) { MemoryBuffer buf = buffers.get(i).buffer; if (buf.contains(loc.buffer)) return i; } return ~0; } /** * Find the line number for the specified location in the specified file. * * @param loc * @param bufferID * @return */ public int findLineNumber(SMLoc loc, int bufferID) { if (bufferID == -1) bufferID = findBufferContainingLoc(loc); Util.assertion(bufferID != -1, "Invalid location!"); int lineNo = 1; MemoryBuffer buf = getBufferInfo(bufferID).buffer; if (lineNoCache != null) { if (lineNoCache.lastQueryBufferID == bufferID && lineNoCache.lastQuery.getCharBuffer().equals(buf.getCharBuffer()) && lineNoCache.lastQuery.getBufferStart() <= buf.getBufferStart()) { buf = lineNoCache.lastQuery; lineNo = lineNoCache.lineNoOfQuery; } } for (; !SMLoc.get(buf).equals(loc); buf.advance()) { if (buf.getCurChar() == '\n') ++lineNo; } if (lineNoCache == null) lineNoCache = new LineNoCache(); lineNoCache.lastQueryBufferID = bufferID; lineNoCache.lastQuery = buf; lineNoCache.lineNoOfQuery = lineNo; return lineNo; } public int findLineNumber(SMLoc loc) { return findLineNumber(loc, -1); } /** * Emit a message about the specified location with the specified string. * This method is deprecated, you should use {@linkplain Error#printMessage(SMLoc, String, DiagKind)} instead. * * @param loc * @param msg * @param type If not null, it specified the kind of message to be emitted (e.g. "error") * which is prefixed to the message. */ @Deprecated public void printMessage(SMLoc loc, String msg, String type) { Error.printMessage(loc, msg, getDiagKindByName(type)); } /** * Return an SMDiagnostic at the specified location with the specified string. * * @param loc * @param msg * @param kind If not null, it specified the kind of message to be emitted (e.g. "error") * which is prefixed to the message. * @return */ public SMDiagnostic getMessage(SMLoc loc, String msg, DiagKind kind) { int curBuf = findBufferContainingLoc(loc); Util.assertion(curBuf != -1, "Invalid or unspecified location!"); MemoryBuffer curMB = getBufferInfo(curBuf).buffer; Util.assertion(curMB.getCharBuffer() == loc.buffer.getCharBuffer()); int columnStart = loc.getPointer(); while (columnStart >= curMB.getBufferStart() && curMB.getCharAt(columnStart) != '\n' && curMB.getCharAt(columnStart) != '\r') --columnStart; int columnEnd = loc.getPointer(); while (columnEnd < curMB.length() && curMB.getCharAt(columnEnd) != '\n' && curMB.getCharAt(columnEnd) != '\r') ++columnEnd; String printedMsg = ""; switch (kind) { case DK_Error: printedMsg = "error: "; break; case DK_Remark: printedMsg = "remark: "; break; case DK_Note: printedMsg = "note: "; break; case DK_Warning: printedMsg = "warning: "; break; } printedMsg += msg; return new SMDiagnostic(curMB.getBufferIdentifier(), findLineNumber(loc, curBuf), curMB.getBufferStart() - columnStart, printedMsg, curMB.getSubString(columnStart, columnEnd)); } private void printIncludeStack(SMLoc includeLoc, PrintStream os) { // Top stack. if (includeLoc.buffer == null) return; int curBuf = findBufferContainingLoc(includeLoc); Util.assertion(curBuf != -1, "Invalid or unspecified location!"); printIncludeStack(getBufferInfo(curBuf).includeLoc, os); os.printf("Included from %s:%d:\n", getBufferInfo(curBuf).buffer.getBufferIdentifier(), findLineNumber(includeLoc, curBuf)); } }
Java
package com.logicalpractice.collections; import static org.junit.Assert.*; import static org.hamcrest.Matchers.* ; import org.junit.Test; public class ExpressionTest { @Test public void script1() throws Exception { Person billy = new Person("Billy", "Smith"); Expression<Person,String> testObject = new Expression<Person,String>(){{ each(Person.class).getFirstName(); }}; String result = testObject.apply(billy); assertThat(result, equalTo("Billy")); } }
Java
<?php declare(strict_types=1); namespace LizardsAndPumpkins\Context\Country; use LizardsAndPumpkins\Context\ContextPartBuilder; class IntegrationTestContextCountry implements ContextPartBuilder { private $defaultCountryCode = 'DE'; /** * @param mixed[] $inputDataSet * @return string */ public function getValue(array $inputDataSet) : string { if (isset($inputDataSet[Country::CONTEXT_CODE])) { return (string) $inputDataSet[Country::CONTEXT_CODE]; } return $this->defaultCountryCode; } public function getCode() : string { return Country::CONTEXT_CODE; } }
Java
Backend ======= stack build managemytime to run the server, just invoke the executable (it's inside .stack-work) or stack exec managemytime-exe it ships with a builtin self-signed certificate for localhost to run the integration tests, you'll want unencrypted http, which you can select with the "test" argument stack exec managemytime-exe test stack test managemytime:functional-tests Don't store any important data in the sqlite.db created by default in the project directory since it will be erased by the testrunner To create a "production" build (with a proper tls certificate, encrypted inside `tls.yml`) ansible-playbook --ask-vault-pass build.yml Frontend ======== Install the flow type checker: opam install flowtype Install bower and jstransform: npm install -g bower jstransform Typecheck javascript: flow check frontend/src/ Parse js and strip signatures: jstransform --strip-types --es6module --watch frontend/src frontend/scripts Install the frontend dependencies (you'll have to symlink them manually): bower install
Java
const initialState = { country: 'es', language: 'es-ES' } const settings = (state = initialState, action) => { switch (action.type) { default: return state } } export default settings
Java
<?php // This is the configuration for yiic console application. // Any writable CConsoleApplication properties can be configured here. return array( 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 'name'=>'My Console Application', // autoloading model and component classes 'import'=>array( 'application.models.*', 'application.components.*', ), // preloading 'log' component 'preload'=>array('log'), // application components 'components'=>array( // database settings are configured in database.php 'db'=>require(dirname(__FILE__).'/database.php'), 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), ), ), ), );
Java
#based on SilkJS Makefile ARCH := $(shell getconf LONG_BIT) COREMQ= mqdb.o OBJ= HMQ = include/lru_cache/lru_cache.h include/lru_cache/scoped_mutex.h fstools.cc CORECL= client.o OBJ= V8DIR= ./v8-read-only V8LIB_64 := $(V8DIR)/out/x64.release/obj.target/tools/gyp V8LIB_32 := $(V8DIR)/out/ia32.release/obj.target/tools/gyp V8LIB_DIR := $(V8LIB_$(ARCH)) V8VERSION_64 := x64.release V8VERSION_32 := ia32.release V8VERSION := $(V8VERSION_$(ARCH)) V8= $(V8LIB_DIR)/libv8_base.a $(V8LIB_DIR)/libv8_snapshot.a CFLAGS = -O6 -fomit-frame-pointer -fdata-sections -ffunction-sections -fno-strict-aliasing -fno-rtti -fno-exceptions -fvisibility=hidden -Wall -W -Wno-unused-parameter -Wnon-virtual-dtor -m$(ARCH) -O3 -fomit-frame-pointer -fdata-sections -ffunction-sections -ansi -fno-strict-aliasing -fexceptions all: mqdb client mqdb2 tasksink taskvent taskvs asclient %.o: %.cpp Makefile g++ $(CFLAGS) -c -I./include -I$(V8DIR)/include -g -o $*.o $*.cpp mqdb: $(V8) $(COREMQ) $(OBJ) $(HMQ) Makefile g++ $(CFLAGS) -I./include -I$(V8DIR)/include -o mqdb mqdb.cpp -L$(V8LIB_DIR)/ -L./leveldb/ -lv8_base -lv8_snapshot -lmm -lpthread -lzmq -lleveldb #-lgd client: $(V8) $(CORECL) $(OBJ) Makefile g++ $(CFLAGS) -o client $(CORECL) $(OBJ) -L$(V8LIB_DIR)/ -lmm -lpthread -lzmq $(V8): cd $(V8DIR) && make dependencies && GYP_GENERATORS=make make $(V8VERSION) update: cd $(V8DIR) && svn update && make dependencies && GYP_GENERATORS=make make $(V8VERSION) git pull
Java
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Justin Madsen // ============================================================================= // // model a single track chain system, as part of a tracked vehicle. // TODO: read in subsystem data w/ JSON input files // // ============================================================================= #include <cstdio> #include <sstream> #include "subsys/trackSystem/TrackSystem.h" namespace chrono { // ----------------------------------------------------------------------------- // Static variables // idler, right side const ChVector<> TrackSystem::m_idlerPos(-2.1904, -0.1443, 0.2447); // relative to local csys const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT); // drive gear, right side const ChVector<> TrackSystem::m_gearPos(1.7741, -0.0099, 0.2447); // relative to local csys const ChQuaternion<> TrackSystem::m_gearRot(QUNIT); // suspension const int TrackSystem::m_numSuspensions = 5; TrackSystem::TrackSystem(const std::string& name, int track_idx, const double idler_preload) : m_track_idx(track_idx), m_name(name), m_idler_preload(idler_preload) { // FILE* fp = fopen(filename.c_str(), "r"); // char readBuffer[65536]; // fclose(fp); Create(track_idx); } // Create: 1) load/set the subsystem data, resize vectors 2) BuildSubsystems() // TODO: replace hard-coded junk with JSON input files for each subsystem void TrackSystem::Create(int track_idx) { /* // read idler info assert(d.HasMember("Idler")); m_idlerMass = d["Idler"]["Mass"].GetDouble(); m_idlerPos = loadVector(d["Idler"]["Location"]); m_idlerInertia = loadVector(d["Idler"]["Inertia"]); m_idlerRadius = d["Spindle"]["Radius"].GetDouble(); m_idlerWidth = d["Spindle"]["Width"].GetDouble(); m_idler_K = d["Idler"]["SpringK"].GetDouble(); m_idler_C = d["Idler"]["SpringC"].GetDouble(); */ /* // Read Drive Gear data assert(d.HasMember("Drive Gear")); assert(d["Drive Gear"].IsObject()); m_gearMass = d["Drive Gear"]["Mass"].GetDouble(); m_gearPos = loadVector(d["Drive Gear"]["Location"]); m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]); m_gearRadius = d["Drive Gear"]["Radius"].GetDouble(); m_gearWidth = d["Drive Gear"]["Width"].GetDouble(); // Read Suspension data assert(d.HasMember("Suspension")); assert(d["Suspension"].IsObject()); assert(d["Suspension"]["Location"].IsArray() ); m_suspensionFilename = d["Suspension"]["Input File"].GetString(); m_NumSuspensions = d["Suspension"]["Location"].Size(); */ m_suspensions.resize(m_numSuspensions); m_suspensionLocs.resize(m_numSuspensions); // hard-code positions relative to trackSystem csys. Start w/ one nearest sprocket m_suspensionLocs[0] = ChVector<>(1.3336, 0, 0); m_suspensionLocs[1] = ChVector<>(0.6668, 0, 0); // trackSystem c-sys aligned with middle suspension subsystem arm/chassis revolute constraint position m_suspensionLocs[2] = ChVector<>(0, 0, 0); m_suspensionLocs[3] = ChVector<>(-0.6682, 0, 0); m_suspensionLocs[4] = ChVector<>(-1.3368, 0, 0); /* for(int j = 0; j < m_numSuspensions; j++) { m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]); } // Read Track Chain data assert(d.HasMember("Track Chain")); assert(d["Track Chain"].IsObject()); m_trackChainFilename = d["Track Chain"]["Input File"].GetString() */ // create the various subsystems, from the hardcoded static variables in each subsystem class BuildSubsystems(); } void TrackSystem::BuildSubsystems() { std::stringstream gearName; gearName << "drive gear " << m_track_idx; // build one of each of the following subsystems. VisualizationType and CollisionType defaults are PRIMITIVES m_driveGear = ChSharedPtr<DriveGear>(new DriveGear(gearName.str(), VisualizationType::Mesh, // CollisionType::Primitives) ); // VisualizationType::Primitives, CollisionType::CallbackFunction)); std::stringstream idlerName; idlerName << "idler " << m_track_idx; m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple(idlerName.str(), VisualizationType::Mesh, CollisionType::Primitives)); std::stringstream chainname; chainname << "chain " << m_track_idx; m_chain = ChSharedPtr<TrackChain>(new TrackChain(chainname.str(), // VisualizationType::Primitives, VisualizationType::CompoundPrimitives, CollisionType::Primitives)); // CollisionType::CompoundPrimitives) ); // build suspension/road wheel subsystems for (int i = 0; i < m_numSuspensions; i++) { std::stringstream susp_name; susp_name << "suspension " << i << ", chain " << m_track_idx; m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>( new TorsionArmSuspension(susp_name.str(), VisualizationType::Primitives, CollisionType::Primitives, 0, i )); } } void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis, const ChVector<>& local_pos, ChTrackVehicle* vehicle, double pin_damping) { m_local_pos = local_pos; m_gearPosRel = m_gearPos; m_idlerPosRel = m_idlerPos; // if we're on the left side of the vehicle, switch lateral z-axis on all relative positions if (m_local_pos.z < 0) { m_gearPosRel.z *= -1; m_idlerPosRel.z *= -1; } // Create list of the center location of the rolling elements and their clearance. // Clearance is a sphere shaped envelope at each center location, where it can // be guaranteed that the track chain geometry will not penetrate the sphere. std::vector<ChVector<> > rolling_elem_locs; // w.r.t. chassis ref. frame std::vector<double> clearance; // 1 per rolling elem std::vector<ChVector<> > rolling_elem_spin_axis; /// w.r.t. abs. frame // initialize 1 of each of the following subsystems. // will use the chassis ref frame to do the transforms, since the TrackSystem // local ref. frame has same rot (just difference in position) // NOTE: move drive Gear Init() AFTER the chain of shoes is created, since // need the list of shoes to be passed in to create custom collision w/ gear // HOWEVER, still add the info to the rolling element lists passed into TrackChain Init(). // drive sprocket is First added to the lists passed into TrackChain Init() rolling_elem_locs.push_back(m_local_pos + Get_gearPosRel()); clearance.push_back(m_driveGear->GetRadius()); rolling_elem_spin_axis.push_back(m_driveGear->GetBody()->GetRot().GetZaxis()); // initialize the torsion arm suspension subsystems for (int s_idx = 0; s_idx < m_suspensionLocs.size(); s_idx++) { m_suspensions[s_idx]->Initialize(chassis, chassis->GetFrame_REF_to_abs(), ChCoordsys<>(m_local_pos + m_suspensionLocs[s_idx], QUNIT)); // add to the lists passed into the track chain, find location of each wheel center w.r.t. chassis coords. rolling_elem_locs.push_back(m_local_pos + m_suspensionLocs[s_idx] + m_suspensions[s_idx]->GetWheelPosRel()); clearance.push_back(m_suspensions[s_idx]->GetWheelRadius()); rolling_elem_spin_axis.push_back(m_suspensions[s_idx]->GetWheelBody()->GetRot().GetZaxis()); } // last control point: the idler body m_idler->Initialize(chassis, chassis->GetFrame_REF_to_abs(), ChCoordsys<>(m_local_pos + Get_idlerPosRel(), Q_from_AngAxis(CH_C_PI, VECT_Z)), m_idler_preload); // add to the lists passed into the track chain Init() rolling_elem_locs.push_back(m_local_pos + Get_idlerPosRel()); clearance.push_back(m_idler->GetRadius()); rolling_elem_spin_axis.push_back(m_idler->GetBody()->GetRot().GetZaxis()); // After all rolling elements have been initialized, now able to setup the TrackChain. // Assumed that start_pos is between idler and gear control points, e.g., on the top // of the track chain. ChVector<> start_pos = (rolling_elem_locs.front() + rolling_elem_locs.back()) / 2.0; start_pos.y += (clearance.front() + clearance.back()) / 2.0; // Assumption: start_pos should lie close to where the actual track chain would // pass between the idler and driveGears. // MUST be on the top part of the chain so the chain wrap rotation direction can be assumed. m_chain->Initialize(chassis, chassis->GetFrame_REF_to_abs(), rolling_elem_locs, clearance, rolling_elem_spin_axis, start_pos); // add some initial damping to the inter-shoe pin joints if (pin_damping > 0) m_chain->Set_pin_friction(pin_damping); // chain of shoes available for gear init m_driveGear->Initialize(chassis, chassis->GetFrame_REF_to_abs(), ChCoordsys<>(m_local_pos + Get_gearPosRel(), QUNIT), m_chain->GetShoeBody(), vehicle); } const ChVector<> TrackSystem::Get_idler_spring_react() { return m_idler->m_shock->Get_react_force(); } } // end namespace chrono
Java
# eXist Book Example Code [![Build Status](https://travis-ci.org/eXist-book/book-code.png?branch=master)](https://travis-ci.org/eXist-book/book-code) [![Java 7](https://img.shields.io/badge/java-7-blue.svg)](http://java.oracle.com) [![License](https://img.shields.io/badge/license-BSD%203-blue.svg)](http://www.opensource.org/licenses/BSD-3-Clause) This repository contains all (except the [Using eXist 101 chapter](https://github.com/eXist-book/using-exist-101)) of the code and examples discussed in the [eXist book](http://shop.oreilly.com/product/0636920026525.do) published by O'Reilly. This version contains code compatible with eXist-db 2.1 which was the latest version at the time the book was authored. Versions for eXist-db [3.0.RC1](https://github.com/eXist-book/book-code/tree/eXist-3.0.RC1), [3.0](https://github.com/eXist-book/book-code/tree/eXist-3.0), and [4.0.0](https://github.com/eXist-book/book-code/tree/eXist-4.0.0) are also available. The repository has the following layout: * [chapters/](https://github.com/eXist-book/book-code/tree/master/chapters) Under this folder each chapter of the book that has example code is represented. * [xml-examples-xar/](https://github.com/eXist-book/book-code/tree/master/xml-examples-xar) These are the files needed to build an EXPath Package XAR from other files distributed in the chapters folders. In particular the content of the XAR package is assembled using the the `fileSet`s set out in the assembly [xml-examples-xar/expath-pkg.assembly.xml](https://github.com/eXist-book/book-code/blob/master/xml-examples-xar/expath-pkg.assembly.xml) All other files are related to the Maven build process. Building ======== The EXPath Package XAR and the Java projects are all built using Apache Maven. You will need to have Git and at least Maven 3.1.1 installed. Git can be downloaded and installed from http://git-scm.com and you can download and install Maven from http://maven.apache.org. Once you have Maven installed you can simply run the following from your Unix/Linux/Mac terminal or Windows command prompt: ```bash git clone https://github.com/eXist-book/book-code.git cd book-code mvn clean install ``` You should then find the EXPath PKG XAR located at `xml-examples-xar/target/exist-book.xar`. The Java projects artifacts will be located within the `target` sub-folders of each Java project respectively.
Java
<?php // uncomment the following to define a path alias // Yii::setPathOfAlias('local','path/to/local-folder'); // This is the main Web application configuration. Any writable // CWebApplication properties can be configured here. return array( 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 'name'=>'Plataforma LAEL', 'language'=>'es', 'sourceLanguage'=>'en', 'charset'=>'utf-8', 'theme'=>'classic', // preloading 'log' component 'preload'=>array('log'), // autoloading model and component classes 'import'=>array( 'application.models.*', 'application.components.*', ), 'modules'=>array( // uncomment the following to enable the Gii tool /* 'gii'=>array( 'class'=>'system.gii.GiiModule', 'password'=>'Enter Your Password Here', // If removed, Gii defaults to localhost only. Edit carefully to taste. 'ipFilters'=>array('127.0.0.1','::1'), ), */ ), // application components 'components'=>array( 'user'=>array( // enable cookie-based authentication 'allowAutoLogin'=>true, ), // uncomment the following to enable URLs in path-format /* 'urlManager'=>array( 'urlFormat'=>'path', 'rules'=>array( '<controller:\w+>/<id:\d+>'=>'<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>', '<controller:\w+>/<action:\w+>'=>'<controller>/<action>', ), ), */ 'db'=>array( 'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db', ), // uncomment the following to use a MySQL database /* 'db'=>array( 'connectionString' => 'mysql:host=localhost;dbname=testdrive', 'emulatePrepare' => true, 'username' => 'root', 'password' => '', 'charset' => 'utf8', ), */ 'errorHandler'=>array( // use 'site/error' action to display errors 'errorAction'=>'site/error', ), 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), // uncomment the following to show log messages on web pages /* array( 'class'=>'CWebLogRoute', ), */ ), ), ), // application-level parameters that can be accessed // using Yii::app()->params['paramName'] 'params'=>array( // this is used in contact page 'adminEmail'=>'webmaster@example.com', ), );
Java
# $FreeBSD: releng/9.3/sys/modules/drm2/radeonkmsfw/R300_cp/Makefile 254885 2013-08-25 19:37:15Z dumbbell $ KMOD= radeonkmsfw_R300_cp IMG= R300_cp .include <bsd.kmod.mk>
Java
/** Copyright (c) 2014, Nathan Carver All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file Code to run the TEETH Smart Toothbrush Holder on Intel Edison board. * * Code is maintained at https://github.com/ncarver/TEETH-IotToothbrushHolder. * * All code and modules are defined in this file, main.js. * * @author Nathan Carver * @copyright Nathan Carver 2014 * @version 0.0.1 */ /* * Required libraries * * You will need these libraries to interface with the services and hardware. */ var MRAA = require('mraa'); //require MRAA for communicating with hardware pins var LCD = require('jsupm_i2clcd'); //require LCD libraries for signaling the LCD screen var LED = require('jsupm_grove'); //require SEEED Grove library for photoresister var BUZZ = require("jsupm_buzzer"); //require SEEED Grove library for buzzer var MAILER = require('nodemailer'); //require for sending emails over SMTP var NET = require('net'); //require for sending cloud data to Edison service on TCP /** * Change the constants properties to customize the operation of the TEETH Smart Toothbrush Timer * @global */ var constants = { 'LOG_LEVEL': 3, //Change this value to limit loggin output: 0-none, 1-err, 2-warn, 3-info, 4-debug, 5-all 'USE_SOUND': true, 'PINS': { //Change these values to match the pins on your Edison build 'brushSwitch': [8, 4], //digital pins monitoring switches for toothbrushes 'buzzer': 3, //digital pin for signaling the buzzer 'roomLightSensor': 0, //analog pin for getting room light readings from photoresister on 10K external pullup 'roomLightThreshold' : 80 //value that indicates that room is dark }, 'MAIL': { //Change these values based on documentation at nodemailer to use your SMTP account 'service': 'Gmail', //Account service name, ex. "Gmail" 'user': 'your.name@gmail.com', //user name to login to your service 'pass': 'pass****', //password to login to your service 'from': 'TEETH <teeth@server.com>', //appears in the "From:" section of your emails 'brushTo': ['brush.1@gmail.com', 'brush.2@gmail.com'], //email value for each toothbrush 'subject': 'Great job on TEETH!', //appears as the subject of your emails 'body': 'You met the goal today. Way to go!' //the body text of your emails }, 'METRICS': { //Change these values to match the custom components of your Intel Cloud Analytics 'brushComponent': ['brush1', 'brush2'] //component value for each toothbrush }, 'SCREEN_MSG': { //Messages that appear on the LCD screen during the timer prep and countdown 'ready': '...get ready', //message to display during start of prep time 'set': '.....get set', //message to display last five seconds of prep time 'countdown': 'Countdown:', //message to display during countdown 'percent25': '...almost there!', //message to display 25% of the way through countdown 'percent50': 'good...halfway ', //message to display 50% of the way through countdown 'percent75': 'you\'re doing it ', //message to display 75% of the way through countdown 'finish': 'GREAT JOB!', //message to display at the end of countdown 'brushName': ['Nathan', 'Sarah'] //name to display during countdwon, one value for each toothbrush }, 'TIME': { //Time focused constants for timer, buzzer sounds 'brushPreptime': [10, 30], //seconds of prep time for each toothbrush 'brushGoaltime': [30, 120], //seconds of countdown time for each toothbrush 'buzzDuration': 20, //milliseconds of buzzer time for start and stop sounds 'buzzInterval': 150 //milliseconds between buzzer sounds for start and stop signals }, 'COLOR': { //Colors to use on the LCD screen 'off': [ 0, 0, 0], //black - use when LCD is off 'ready': [100, 100, 100], //light grey - use during prep time 'percent0': [255, 68, 29], //red - use at start of countdown 'percent25': [232, 114, 12], //brown - use when countdown is 25% finished 'percent50': [255, 179, 0], //orange - use when countdown is 50% finished 'percent75': [232, 211, 12], //yellow - use when countdown is 75% finished 'finish': [ 89, 132, 13], //green - use when countdown is finished 'colorFadeDuration': 1000, //milliseconds to fade to new color during countdown mode 'fadeSteps': 100 //number of fading steps to take during colorFadeDuration } }; /** * These values hold the setTimeout and setInterval handles so they can be cleared as part of a timer interuption * @global */ var timers = { 'fadeColor': null, //timer fading the color on the LCD screen 'buzzerPlay': null, //timer playing the buzzer sounds 'buzzerWait': null, //timer waiting in between buzzer sounds 'prepCountdown': null, //timer for the main prep time 'startCountdown': null, //timer for the last five seconds of prep time 'countdown': null, //timer for the main countdown 'lightsOut': null //timer lookin for "lights out" interuption }; /** * Creates a new Logger object and the helper methods used to send messages to console. * Highest level of logging, ERR (1), only outputs errors during code execution. * Lowest level DEBUG (4) outputs all logging messages. * * @see constants.LOG_LEVEL Use the constant constants.LOG_LEVEL to adjust the level of output. * @class */ var Logger = function () { this.ERR = 1; this.WARN = 2; this.INFO = 3; this.DEBUG = 4; /** * @private */ var logLevels = ['', 'err', 'warn', 'info', 'debug']; /** * @param {string} msg message to send to logger * @param {int} level log level for this message * @public */ this.it = function (msg, level) { if (constants.LOG_LEVEL >= level || level === undefined) { console.log('%s - %s: %s', new Date(), logLevels[level], msg); } }; /* * @param {string} msg message to send to logger at log level ERR (1) * @public */ this.err = function (msg) { this.it(msg, this.ERR); }; /* * @param {string} msg message to send to logger at log level WARN (2) * @public */ this.warn = function (msg) { this.it(msg, this.WARN); }; /* * @param {string} msg message to send to logger at log level INFO (3) * @public */ this.info = function (msg) { this.it(msg, this.INFO); }; /* * @param {string} msg message to send to logger at log level DEBUG (4) * @public */ this.debug = function (msg) { this.it(msg, this.DEBUG); }; }; /** * Creates a new Sensors object to monitor the hardware connected to the Edison * @requires mraa:Gpio * @requires mraa:Aio * @param {Logger} log object for logging output * @see constants.PINS Use the constant constants.PINS to identify the hardware connections * @class */ var Sensors = function (log) { log.info('instatiate Sensors'); /** * @private */ var i; /** * the array of switches associated with each toothbrush are initialized * as INPUT pins during instatiation. * @public */ this.brushSwitch = []; for (i = 0; i < constants.PINS.brushSwitch.length; i = i + 1) { this.brushSwitch[i] = new MRAA.Gpio(constants.PINS.brushSwitch[i]); this.brushSwitch[i].dir(MRAA.DIR_IN); } /** * the analog pin for monitoring the phototransister is initialized * during instatiation. Expected that this photo cell will have a 10K * external pulldown resistor. * @public */ // this.roomLightSensor = new MRAA.Aio(constants.PINS.roomLightSensor); }; /** * Creates a new Buzzer object to play a sound on the buzzer connected to the Edison * @requires jsupm_buzzer:Buzzer * @param {Logger} log object for logging output * @see constants.TIME Use the properties of constants.TIME to adjust the buzzer sounds * @class */ var Buzzer = function (log) { log.info('instatiate Buzzer'); var buzzer = new BUZZ.Buzzer(constants.PINS.buzzer); /** * play calls the playSound method of the low-level buzzer class for a simple tone value * @private */ function play(buzzingTime) { log.debug('(buzzer.play for ' + buzzingTime + ')'); if (!constants.USE_SOUND) { return; } buzzer.playSound(BUZZ.DO, 5000); timers.buzzerPlay = setTimeout(function () { buzzer.playSound(BUZZ.DO, 0); }, buzzingTime); } /** * plays the standard sound for the buzz duration, then waits, and plays again * expected to be called at the beginning of the countdown * @public */ this.playStartSound = function () { log.info('buzzer.playStartSound'); play(constants.TIME.buzzDuration); timers.buzzerWait = setTimeout(function () { play(constants.TIME.buzzDuration); }, constants.TIME.buzzInterval); }; /** * plays the standard sound for the buzz duration, then waits, and plays again * expected to be called at the end of the countdown * @public */ this.playStopSound = function () { log.info('buzzer.playStopSound'); play(constants.TIME.buzzDuration); timers.buzzerWait = setTimeout(function () { play(constants.TIME.buzzDuration); }, constants.TIME.buzzInterval); }; }; /** * Creates a new Screen object to display messages and colors RGB LCD connected to the Edison over I2C * @requires jsupm_i2clcd:Jhd1313m1 * @param {Logger} log object for logging output * @see constants.COLOR Use the properties of constants.COLOR to adjust the screen background colors * @see constants.SCREEN_MSG Use the properties of constants.SCREEN_MSG to change the messages displayed on screen * @class */ var Screen = function (log) { log.info('instatiate Screen'); /** * Instance variables to connect to LCD screen and manage the color fading * @private */ var lcd = new LCD.Jhd1313m1(6, 0x3E, 0x62), //standard I2C bus interval = constants.COLOR.colorFadeDuration / constants.COLOR.fadeSteps, lastColor = constants.COLOR.off, steps = constants.COLOR.fadeSteps; /** * getRemainingSteps identifies how many more steps are needed before fade is finished * @returns {int} number of steps remaining * @private */ function getRemainingSteps() { log.debug('(screen.getRemainingSteps)'); return steps; } /** * setRemainingSteps sets how many more steps are needed before fade is finished * @params {int} remainingSteps new number of steps remaining * @private */ function setRemainingSteps(remainingSteps) { log.debug('(screen.setRemainingSteps: ' + remainingSteps + ')'); steps = remainingSteps; } /** * setScreen color calls low-level methods to set RGB values of screen background * also sets the instance variable "lastColor" to help with fade control * @param {array} colorArray array of decimal color values in Red Green Blue order [r,g,b] * @private */ function setScreenColor(colorArray) { log.debug('(screen.setScreenColor to ' + colorArray + ')'); lcd.setColor(colorArray[0], colorArray[1], colorArray[2]); lastColor = colorArray; } /** * Inner method called by timeouts to fade background color from current color to the * updated color passed RGB color array * @private */ function _fadeColor(colorArray) { log.debug('(screen._fadeColor: ' + colorArray + ')'); var step = getRemainingSteps(); if (step > 0) { var diffRed = colorArray[0] - lastColor[0], diffGrn = colorArray[1] - lastColor[1], diffBlu = colorArray[2] - lastColor[2], stepRed = parseInt(diffRed / step, 10), stepGrn = parseInt(diffGrn / step, 10), stepBlu = parseInt(diffBlu / step, 10), nextRed = lastColor[0] + stepRed, nextGrn = lastColor[1] + stepGrn, nextBlu = lastColor[2] + stepBlu; setScreenColor([nextRed, nextGrn, nextBlu]); setRemainingSteps(step - 1); timers.fadeColor = setTimeout(function () { _fadeColor(colorArray); }, interval); } } /** * Starts a timout sequence to slowy change the LCD RGB screen background from its current * color to the one passed in the parameters. The speed and number of steps used for fading * are controlled by the constants. * * @param {array} colorArray a 3-member array of decimal numbers describing the color to display * on the screen background: [r,g,b] * @public */ this.fadeColor = function (colorArray) { log.info('screen.fadeColor: ' + colorArray); setRemainingSteps(constants.COLOR.fadeSteps); _fadeColor(colorArray); }; /** * Helper method combines clearing the screen of all text content and returning the cursor * position back to the top left. * @public */ this.reset = function () { log.info('screen.reset'); lcd.clear(); lcd.setCursor(0, 0); }; /** * Helper method combines reseting the screen and returning the screen color to "off" * @public */ this.resetAndTurnOff = function () { log.info('screen.resetAndTurnOff'); this.reset(); setScreenColor(constants.COLOR.off); }; /** * Turns the screen on and displays the "ready" message defined in constants for the given toothbrush * * @param {int} componentIndex identifies the toothbrush by it's array index * @public */ this.displayReady = function (componentIndex) { log.info('screen.displayReady for ' + componentIndex); lcd.clear(); setScreenColor(constants.COLOR.ready); this.write(constants.SCREEN_MSG.brushName[componentIndex], 0, 0); this.write(constants.SCREEN_MSG.ready, 1, 0); }; /** * Changes the "ready" message to the "set" message defined in constants for the given toothbrush * * @param {int} componentIndex identifies the toothbrush by it's array index * @public */ this.displaySet = function (componentIndex) { log.info('screen.displaySet for ' + componentIndex); this.write(constants.SCREEN_MSG.set, 1, 0); }; /** * Helper message combines writing the given message to the screen at (optional) given coordinates * * @param {string} msg the string to ouput to the screen * @param {int} col (optional) 0-indexed column number to set the cursor * @param {int} row (optional) 0-indexed row number to set the cursor * @public */ this.write = function (msg, col, row) { //log.info('screen.write msg ' + msg); var i; if (!(col === undefined || row === undefined)) { lcd.setCursor(col, row); for (i = 0; i < 10000000; i = i + 1) { //wait for slow LCD } } lcd.write(msg); }; //initialize the LCD screen during instatiation this.resetAndTurnOff(); }; /** * Creates a new Mailer object to send mail over SMTP * @requires nodemailer * @param {Logger} log object for logging output * @see constants.MAIL Use the properties of constants.MAIL to configure your SMTP service * @class */ var Mailer = function (log) { log.info('instatiate Mailer'); /** * Instance options taken from constants.MAIL are used by createTransport to authenticate SMTP * @private */ var mailOptions = { from: constants.MAIL.from, // sender address to: constants.MAIL.brushTo[0], // list of receivers subject: constants.MAIL.subject, // Subject line text: constants.MAIL.body, // plaintext body html: constants.MAIL.body // html body }, transporter = MAILER.createTransport({ service: constants.MAIL.service, auth: { user: constants.MAIL.user, pass: constants.MAIL.pass } }); /** * Sends the message defined in constants.MAIL for the given toothbrush. * Errors are sent to the log Logger object. * @param {int} componentIndex identifies the toothbrush by it's array index in constants * @public */ this.sendCongratsEmail = function (componentIndex) { log.info('mailer.sendCongratsEmail for ' + componentIndex); mailOptions.to = constants.MAIL.brushTo[componentIndex]; transporter.sendMail(mailOptions, function (error, info) { if (error) { log.err('mail error ' + error + '.'); } else { log.info('mail sent.'); } }); }; }; /** * Creates a new Metrics object to connect to Intel Cloud Analytics over TCP * @requires net:socket * @param {Logger} log object for logging output * @class */ var Metrics = function (log) { log.info('instatiate metrics'); /** * instance objects and options to connect over TCP to Edison iot-agent * @private */ var client = new NET.Socket(), options = { host : 'localhost', //use the Intel analytics client running locally on the Edison port : 7070 //on default TCP port }; /** * sendObservation concatenates the string expected by cloud analytics based on the parameter values * @param {string} name custom component name registered with Intel analytics * @param {float} value data value to send to cloud * @private */ function sendObservation(name, value) { log.debug('(metrics.sendObservation for ' + name + ', ' + value + ')'); var msg = JSON.stringify({ n: name, v: value }), sentMsg = msg.length + "#" + msg; //syntax for Intel analytics client.write(sentMsg); } /** * Method combines the activity of connecting to the Edision service and then sending data to the cloud * @param {int} itemIndex array index of component names registered with Intel analytics * @param {float} timeValue data value to send to cloud, expecting fractional number of seconds * @public */ this.addDataToCloud = function (itemIndex, timeValue) { log.info('metrics.addDataToCloud for ' + itemIndex + ', ' + timeValue); client.on('error', function () { log.err('Could not connect to cloud'); }); client.connect(options.port, options.host, function () { sendObservation(constants.METRICS.brushComponent[itemIndex], timeValue); }); }; }; /** * Creates a new Teeth object to manage the countdown timer * @param {Logger} log object for logging output * @param {Sensors} sensor object for listening to hardware sensors * @param {Buzzer} buzzer object for controlling the sounds * @param {Screen} screen object for display on the RGB LCD screen * @param {Mailer} mailer object for sending email * @param {Metrics} metrics object for sending data to cloud * @see constants.TIME Use the properties of constants.TIME to adjust the length of the countdown * @class */ var Teeth = function (log, sensors, buzzer, lcdScreen, mailer, metrics) { log.info('instatiate teeth'); /** * flags to make sure fadeColor only called once for each color * @private */ var fades = [], currentComponent = -1, timeSpent = 0; /** * clearAllTimers loops through all timers in constants to clear them and set to null * @private */ function clearAllTimers() { log.debug('(teeth.clearAllTimers)'); var key, timer; for (key in timers) { if (timers.hasOwnProperty(key)) { timer = timers[key]; if (timer !== null) { clearTimeout(timer); timer = null; } } } fades = []; currentComponent = -1; } /** * finishCountdown clears the screen, plays the stop sound, and starts the waiting process again * @param {int} componentIndex array index number of the toothbrush that is finishing the countdown * @private */ function finishCountdown(componentIndex) { log.debug('(teeth.finishCountdown for ' + componentIndex + ')'); clearAllTimers(); lcdScreen.reset(); buzzer.playStopSound(); mailer.sendCongratsEmail(componentIndex); lcdScreen.write(constants.SCREEN_MSG.finish); metrics.addDataToCloud(componentIndex, constants.TIME.brushGoaltime[componentIndex]); setTimeout(function () { lcdScreen.resetAndTurnOff(); wait(); }, 1000); } /** * countdown generates messages and colors to the screen during the countdown, * called continuously until time is over * @param {int} componentIndex array index number of the toothbrush that is in the middle of the countdown * @param {int} timeRemaining the amount of time remaining in seconds before the countdown is over * @private */ function countdown(componentIndex, timeRemaining) { log.debug('(teeth.countdown for ' + componentIndex + ': ' + timeRemaining + ')'); var originalValue = constants.TIME.brushGoaltime[componentIndex]; timeSpent = originalValue - timeRemaining; if (timeRemaining > 0) { lcdScreen.write(constants.SCREEN_MSG.countdown + timeRemaining + ' ', 0, 0); if (timeRemaining <= (0.25 * originalValue)) { lcdScreen.write(constants.SCREEN_MSG.percent25, 1, 0); if (fades[constants.COLOR.percent25] !== 1) { lcdScreen.fadeColor(constants.COLOR.percent25); fades[constants.COLOR.percent25] = 1; } } else if (timeRemaining <= (0.5 * originalValue)) { lcdScreen.write(constants.SCREEN_MSG.percent50, 1, 0); if (fades[constants.COLOR.percent50] !== 1) { lcdScreen.fadeColor(constants.COLOR.percent50); fades[constants.COLOR.percent50] = 1; } } else if (timeRemaining <= (0.75 * originalValue)) { lcdScreen.write(constants.SCREEN_MSG.percent75, 1, 0); if (fades[constants.COLOR.percent75] !== 1) { lcdScreen.fadeColor(constants.COLOR.percent75); fades[constants.COLOR.percent75] = 1; } } timers.countdown = setTimeout(function () { countdown(componentIndex, timeRemaining - 1); }, 1000); } else { finishCountdown(componentIndex); } } /** * startCountdown plays the sound and begins the first call to countdown * @param {int} componentIndex array index number of the toothbrush that is starting the countdown * @private */ function startCountdown(componentIndex) { log.info('(teeth.startCountdown for ' + componentIndex + ')'); buzzer.playStartSound(); lcdScreen.reset(); currentComponent = componentIndex; countdown(componentIndex, constants.TIME.brushGoaltime[componentIndex]); } /** * prepCountdown prepares the screen and waits for real countdown to begin, displays * an additional warning with five seconds to go * @param {int} componentIndex array index number of the toothbrush that is starting the countdown * @private */ function prepCountdown(componentIndex) { log.debug('(teeth.prepCountdown for ' + componentIndex + ')'); lcdScreen.displayReady(componentIndex); var prepTime = constants.TIME.brushPreptime[componentIndex]; timers.prepCountdown = setTimeout(function () { log.debug('setTimeout: prepCountdown'); lcdScreen.displaySet(componentIndex); }, (prepTime - 5) * 1000); timers.startCountdown = setTimeout(function () { log.debug('setTimeout: startCountdown'); startCountdown(componentIndex); }, prepTime * 1000); } /** * watchForLightsOut polls the photoresistor to see if the room is dark, then stops all activity * @private */ function watchForLightsOut() { //do not log.debug >> called every 50ms return; var val = sensors.roomLightSensor.read(); if (val < constants.PINS.roomLightThreshold) { log.info('Trigger for lights out: Stop Timer (early) then wait 5 seconds to start again'); if (currentComponent >= 0) { metrics.addDataToCloud(currentComponent, timeSpent); } clearAllTimers(); lcdScreen.resetAndTurnOff(); setTimeout(wait, 5000); } } /** * wait is the main entry to this class, it polls the switches regularly to see if it should start the countdown * @private */ function wait() { //do not log.debug >> called every 100ms var i, val; for (i = 0; i < sensors.brushSwitch.length; i = i + 1) { val = sensors.brushSwitch[i].read(); if (val === 0) { //0 for NO (normally open switch), 1 for NC (normally closed) log.info('Trigger for toothbrush ' + i + ': Start Timer'); prepCountdown(i); timers.lightsOut = setInterval(watchForLightsOut, 50); break; } } if (i >= sensors.brushSwitch.length) { setTimeout(wait, 100); } } /** * Entry point to Teeth, the start command initiates the Smart Toothbrush Holder and begins the process of waiting for a countdown * @public */ this.start = function () { log.info('Teeth.start waiting for toothbrush events'); wait(); }; }; /* Create instance objects of the classes needed by TEETH */ var log = new Logger(), sensors = new Sensors(log), buzzer = new Buzzer(log), lcdScreen = new Screen(log), mailer = new Mailer(log), metrics = new Metrics(log), teeth = new Teeth(log, sensors, buzzer, lcdScreen, mailer, metrics); /* Get the code running by invoking the start method of the Teeth controller */ teeth.start();
Java
<?php use app\core\helpers\Html; use app\core\helpers\Url; $this->title = '权限管理 在此页面添加名修改权限项注释'; $this->params['breadcrumbs'][] = $this->title; ?> <style type="text/css"> .nopad{padding-left: 0} .panel-default>.panel-heading{ padding: 10px 15px; background-color: #f5f5f5; border-color: #ddd; } </style> <div class="page-content"> <!-- /section:settings.box --> <div class="page-content-area"> <div class="page-header"> <h1> <small> <a data-loading-text="数据更新中, 请稍后..." href="<?=Url::toRoute('sync')?>" class="btn btn-danger auth-sync">权限初始化</a> </small> <?= $this->render('@app/modules/sys/views/admin/layout/_nav.php') ?> </h1> </div><!-- /.page-header --> <div class="row"> <div class="col-md-12"> <?php foreach ($classes as $key => $value):?> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <?=$key;?> </h4> </div> <div class="panel-body"> <?php foreach ($value as $ke => $val):?> <dl class="col-md-12 col-sm-12 nopad"> <dt><?php echo $ke;?> </dt> <?php foreach ($val as $k => $v):?> <dd class="col-md-3 nopad"> <span class="lbl "> <?php echo $k?> <input value="<?= $v['title']?>" class="action_des input-small form-control" key="<?=$v['name']?>" /> </span> </dd> <?php endforeach;?> </dl> <hr/> <?php endforeach;?> </div> </div> <?php endforeach;?> </div> </div><!-- /.row --> </div><!-- /.page-content-area --> </div><!-- /.page-content --> <?php $this->beginBlock('auth') ?> $(function(){ $('.auth-sync').click(function(e){ e.preventDefault(); var btn = $(this).button('loading'); $.get($(this).attr('href'),null,function(xhr){ if (xhr.status) { location.reload(); }; btn.button('reset'); },'json'); }); $('.action_des').change(function(e){ e.preventDefault(); var url = "<?=Url::toRoute('title')?>"; var csrf = $('meta[name=csrf-token]').attr('content'); var data = {name:$(this).attr('key'), title:$(this).val(), _csrf:csrf}; $.post(url, data, function(xhr){ if (!xhr.status) { alert(xhr.info); }; },'json'); }); }) <?php $this->endBlock() ?> <?php $this->registerJs($this->blocks['auth'], \yii\web\View::POS_END); ?>
Java
<!doctype html> <html> <head> <meta charset="utf-8"> <title>System\Browser\assets\scripts\Flash.js 源码</title> <link href="../../assets/styles/prettify.css" type="text/css" rel="stylesheet" /> <script src="../../assets/scripts/prettify.js" type="text/javascript"></script> <style type="text/css">.highlight { display: block; background-color: #ddd; }</style> </head> <body onload="setTimeout('prettyPrint()', 0);var node = document.getElementById(location.hash.replace(/#/, ''));if(node)node.className = 'highlight';"><pre class="prettyprint lang-js">//=========================================== // Swf swiff.js A //=========================================== using(&quot;System.Controls.Control&quot;); namespace(&quot;.Swiff&quot;, JPlus.Control.extend({ options: { id: null, height: 1, width: 1, container: null, properties: {}, params: { quality: 'high', allowScriptAccess: 'always', wMode: 'window', swLiveConnect: true }, callBacks: {}, vars: {} }, constructor: function (path, options) { this.instance = 'Swiff_' + String.uniqueID(); this.setOptions(options); options = this.options; var id = this.id = options.id || this.instance; var container = document.id(options.container); Swiff.CallBacks[this.instance] = {}; var params = options.params, vars = options.vars, callBacks = options.callBacks; var properties = Object.append({ height: options.height, width: options.width }, options.properties); var self = this; for (var callBack in callBacks) { Swiff.CallBacks[this.instance][callBack] = (function (option) { return function () { return option.apply(self.object, arguments); }; })(callBacks[callBack]); vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack; } params.flashVars = Object.toQueryString(vars); if (Browser.ie) { properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'; params.movie = path; } else { properties.type = 'application/x-shockwave-flash'; } properties.data = path; var build = '&lt;object id=&quot;' + id + '&quot;'; for (var property in properties) build += ' ' + property + '=&quot;' + properties[property] + '&quot;'; build += '&gt;'; for (var param in params) { if (params[param]) build += '&lt;param name=&quot;' + param + '&quot; value=&quot;' + params[param] + '&quot; /&gt;'; } build += '&lt;/object&gt;'; this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild; }, remote: function () { return Swiff.remote.apply(Swiff, [this.node || this].append(arguments)); } })); Swiff.CallBacks = {}; Swiff.remote = function (obj, fn) { var rs = obj.CallFunction('&lt;invoke name=&quot;' + fn + '&quot; returntype=&quot;javascript&quot;&gt;' + __flash__argumentsToXML(arguments, 2) + '&lt;/invoke&gt;'); return eval(rs); };</pre> </body> </html>
Java
define(['App', 'jquery', 'underscore', 'backbone', 'hbs!template/subreddit-picker-item', 'view/basem-view'], function(App, $, _, Backbone, SRPitemTmpl, BaseView) { return BaseView.extend({ template: SRPitemTmpl, events: { 'click .add': 'subscribe', 'click .remove': 'unsubscribe' }, initialize: function(data) { this.model = data.model; }, subscribe: function(e) { e.preventDefault() e.stopPropagation() var target = this.$(e.currentTarget) target.removeClass('add').addClass('remove').html('unsubscribe') var params = { action: 'sub', sr: this.model.get('name'), sr_name: this.model.get('name'), uh: $.cookie('modhash') }; console.log(params) this.api("api/subscribe", 'POST', params, function(data) { console.log("subscribe done", data) //edit the window and cookie App.trigger('header:refreshSubreddits') }); }, unsubscribe: function(e) { e.preventDefault() e.stopPropagation() var target = this.$(e.currentTarget) target.removeClass('remove').addClass('add').html('subscribe') var params = { action: 'unsub', sr: this.model.get('name'), uh: $.cookie('modhash') }; console.log(params) this.api("api/subscribe", 'POST', params, function(data) { console.log("unsubscribe done", data) App.trigger('header:refreshSubreddits') }); } }); });
Java
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\helpers; use Yii; use yii\base\InvalidParamException; use yii\db\ActiveRecordInterface; use yii\validators\StringValidator; use yii\web\Request; use yii\base\Model; /** * BaseHtml provides concrete implementation for [[Html]]. * * Do not use BaseHtml. Use [[Html]] instead. * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class BaseHtml { /** * @var array list of void elements (element name => 1) * @see http://www.w3.org/TR/html-markup/syntax.html#void-element */ public static $voidElements = [ 'area' => 1, 'base' => 1, 'br' => 1, 'col' => 1, 'command' => 1, 'embed' => 1, 'hr' => 1, 'img' => 1, 'input' => 1, 'keygen' => 1, 'link' => 1, 'meta' => 1, 'param' => 1, 'source' => 1, 'track' => 1, 'wbr' => 1, ]; /** * @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes * that are rendered by [[renderTagAttributes()]]. */ public static $attributeOrder = [ 'type', 'id', 'class', 'name', 'value', 'href', 'src', 'action', 'method', 'selected', 'checked', 'readonly', 'disabled', 'multiple', 'size', 'maxlength', 'width', 'height', 'rows', 'cols', 'alt', 'title', 'rel', 'media', ]; /** * @var array list of tag attributes that should be specially handled when their values are of array type. * In particular, if the value of the `data` attribute is `['name' => 'xyz', 'age' => 13]`, two attributes * will be generated instead of one: `data-name="xyz" data-age="13"`. * @since 2.0.3 */ public static $dataAttributes = ['data', 'data-ng', 'ng']; /** * Encodes special characters into HTML entities. * The [[\yii\base\Application::charset|application charset]] will be used for encoding. * @param string $content the content to be encoded * @param boolean $doubleEncode whether to encode HTML entities in `$content`. If false, * HTML entities in `$content` will not be further encoded. * @return string the encoded content * @see decode() * @see http://www.php.net/manual/en/function.htmlspecialchars.php */ public static function encode($content, $doubleEncode = true) { return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app ? Yii::$app->charset : 'UTF-8', $doubleEncode); } /** * Decodes special HTML entities back to the corresponding characters. * This is the opposite of [[encode()]]. * @param string $content the content to be decoded * @return string the decoded content * @see encode() * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php */ public static function decode($content) { return htmlspecialchars_decode($content, ENT_QUOTES); } /** * Generates a complete HTML tag. * @param string $name the tag name * @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded. * If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks. * @param array $options the HTML tag attributes (HTML options) in terms of name-value pairs. * These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * * For example when using `['class' => 'my-class', 'target' => '_blank', 'value' => null]` it will result in the * html attributes rendered like this: `class="my-class" target="_blank"`. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated HTML tag * @see beginTag() * @see endTag() */ public static function tag($name, $content = '', $options = []) { $html = "<$name" . static::renderTagAttributes($options) . '>'; return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content</$name>"; } /** * Generates a start tag. * @param string $name the tag name * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated start tag * @see endTag() * @see tag() */ public static function beginTag($name, $options = []) { return "<$name" . static::renderTagAttributes($options) . '>'; } /** * Generates an end tag. * @param string $name the tag name * @return string the generated end tag * @see beginTag() * @see tag() */ public static function endTag($name) { return "</$name>"; } /** * Generates a style tag. * @param string $content the style content * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated style tag */ public static function style($content, $options = []) { return static::tag('style', $content, $options); } /** * Generates a script tag. * @param string $content the script content * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated script tag */ public static function script($content, $options = []) { return static::tag('script', $content, $options); } /** * Generates a link tag that refers to an external CSS file. * @param array|string $url the URL of the external CSS file. This parameter will be processed by [[Url::to()]]. * @param array $options the tag options in terms of name-value pairs. The following option is specially handled: * * - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified, * the generated `link` tag will be enclosed within the conditional comments. This is mainly useful * for supporting old versions of IE browsers. * - noscript: if set to true, `link` tag will be wrapped into `<noscript>` tags. * * The rest of the options will be rendered as the attributes of the resulting link tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated link tag * @see Url::to() */ public static function cssFile($url, $options = []) { if (!isset($options['rel'])) { $options['rel'] = 'stylesheet'; } $options['href'] = Url::to($url); if (isset($options['condition'])) { $condition = $options['condition']; unset($options['condition']); return self::wrapIntoCondition(static::tag('link', '', $options), $condition); } elseif (isset($options['noscript']) && $options['noscript'] === true) { unset($options['noscript']); return "<noscript>" . static::tag('link', '', $options) . "</noscript>"; } else { return static::tag('link', '', $options); } } /** * Generates a script tag that refers to an external JavaScript file. * @param string $url the URL of the external JavaScript file. This parameter will be processed by [[Url::to()]]. * @param array $options the tag options in terms of name-value pairs. The following option is specially handled: * * - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified, * the generated `script` tag will be enclosed within the conditional comments. This is mainly useful * for supporting old versions of IE browsers. * * The rest of the options will be rendered as the attributes of the resulting script tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated script tag * @see Url::to() */ public static function jsFile($url, $options = []) { $options['src'] = Url::to($url); if (isset($options['condition'])) { $condition = $options['condition']; unset($options['condition']); return self::wrapIntoCondition(static::tag('script', '', $options), $condition); } else { return static::tag('script', '', $options); } } /** * Wraps given content into conditional comments for IE, e.g., `lt IE 9`. * @param string $content raw HTML content. * @param string $condition condition string. * @return string generated HTML. */ private static function wrapIntoCondition($content, $condition) { if (strpos($condition, '!IE') !== false) { return "<!--[if $condition]><!-->\n" . $content . "\n<!--<![endif]-->"; } return "<!--[if $condition]>\n" . $content . "\n<![endif]-->"; } /** * Generates the meta tags containing CSRF token information. * @return string the generated meta tags * @see Request::enableCsrfValidation */ public static function csrfMetaTags() { $request = Yii::$app->getRequest(); if ($request instanceof Request && $request->enableCsrfValidation) { return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n " . static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n"; } else { return ''; } } /** * Generates a form start tag. * @param array|string $action the form action URL. This parameter will be processed by [[Url::to()]]. * @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive). * Since most browsers only support "post" and "get", if other methods are given, they will * be simulated using "post", and a hidden input will be added which contains the actual method type. * See [[\yii\web\Request::methodParam]] for more details. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated form start tag. * @see endForm() */ public static function beginForm($action = '', $method = 'post', $options = []) { $action = Url::to($action); $hiddenInputs = []; $request = Yii::$app->getRequest(); if ($request instanceof Request) { if (strcasecmp($method, 'get') && strcasecmp($method, 'post')) { // simulate PUT, DELETE, etc. via POST $hiddenInputs[] = static::hiddenInput($request->methodParam, $method); $method = 'post'; } if ($request->enableCsrfValidation && !strcasecmp($method, 'post')) { $hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken()); } } if (!strcasecmp($method, 'get') && ($pos = strpos($action, '?')) !== false) { // query parameters in the action are ignored for GET method // we use hidden fields to add them back foreach (explode('&', substr($action, $pos + 1)) as $pair) { if (($pos1 = strpos($pair, '=')) !== false) { $hiddenInputs[] = static::hiddenInput( urldecode(substr($pair, 0, $pos1)), urldecode(substr($pair, $pos1 + 1)) ); } else { $hiddenInputs[] = static::hiddenInput(urldecode($pair), ''); } } $action = substr($action, 0, $pos); } $options['action'] = $action; $options['method'] = $method; $form = static::beginTag('form', $options); if (!empty($hiddenInputs)) { $form .= "\n" . implode("\n", $hiddenInputs); } return $form; } /** * Generates a form end tag. * @return string the generated tag * @see beginForm() */ public static function endForm() { return '</form>'; } /** * Generates a hyperlink tag. * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code * such as an image tag. If this is coming from end users, you should consider [[encode()]] * it to prevent XSS attacks. * @param array|string|null $url the URL for the hyperlink tag. This parameter will be processed by [[Url::to()]] * and will be used for the "href" attribute of the tag. If this parameter is null, the "href" attribute * will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated hyperlink * @see \yii\helpers\Url::to() */ public static function a($text, $url = null, $options = []) { if ($url !== null) { $options['href'] = Url::to($url); } return static::tag('a', $text, $options); } /** * Generates a mailto hyperlink. * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code * such as an image tag. If this is coming from end users, you should consider [[encode()]] * it to prevent XSS attacks. * @param string $email email address. If this is null, the first parameter (link body) will be treated * as the email address and used. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated mailto link */ public static function mailto($text, $email = null, $options = []) { $options['href'] = 'mailto:' . ($email === null ? $text : $email); return static::tag('a', $text, $options); } /** * Generates an image tag. * @param array|string $src the image URL. This parameter will be processed by [[Url::to()]]. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated image tag */ public static function img($src, $options = []) { $options['src'] = Url::to($src); if (!isset($options['alt'])) { $options['alt'] = ''; } return static::tag('img', '', $options); } /** * Generates a label tag. * @param string $content label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code * such as an image tag. If this is is coming from end users, you should [[encode()]] * it to prevent XSS attacks. * @param string $for the ID of the HTML element that this label is associated with. * If this is null, the "for" attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated label tag */ public static function label($content, $for = null, $options = []) { $options['for'] = $for; return static::tag('label', $content, $options); } /** * Generates a button tag. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, * you should consider [[encode()]] it to prevent XSS attacks. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated button tag */ public static function button($content = 'Button', $options = []) { if (!isset($options['type'])) { $options['type'] = 'button'; } return static::tag('button', $content, $options); } /** * Generates a submit button tag. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, * you should consider [[encode()]] it to prevent XSS attacks. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated submit button tag */ public static function submitButton($content = 'Submit', $options = []) { $options['type'] = 'submit'; return static::button($content, $options); } /** * Generates a reset button tag. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, * you should consider [[encode()]] it to prevent XSS attacks. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated reset button tag */ public static function resetButton($content = 'Reset', $options = []) { $options['type'] = 'reset'; return static::button($content, $options); } /** * Generates an input type of the given type. * @param string $type the type attribute. * @param string $name the name attribute. If it is null, the name attribute will not be generated. * @param string $value the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated input tag */ public static function input($type, $name = null, $value = null, $options = []) { if (!isset($options['type'])) { $options['type'] = $type; } $options['name'] = $name; $options['value'] = $value === null ? null : (string) $value; return static::tag('input', '', $options); } /** * Generates an input button. * @param string $label the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated button tag */ public static function buttonInput($label = 'Button', $options = []) { $options['type'] = 'button'; $options['value'] = $label; return static::tag('input', '', $options); } /** * Generates a submit input button. * @param string $label the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated button tag */ public static function submitInput($label = 'Submit', $options = []) { $options['type'] = 'submit'; $options['value'] = $label; return static::tag('input', '', $options); } /** * Generates a reset input button. * @param string $label the value attribute. If it is null, the value attribute will not be generated. * @param array $options the attributes of the button tag. The values will be HTML-encoded using [[encode()]]. * Attributes whose value is null will be ignored and not put in the tag returned. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated button tag */ public static function resetInput($label = 'Reset', $options = []) { $options['type'] = 'reset'; $options['value'] = $label; return static::tag('input', '', $options); } /** * Generates a text input field. * @param string $name the name attribute. * @param string $value the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated text input tag */ public static function textInput($name, $value = null, $options = []) { return static::input('text', $name, $value, $options); } /** * Generates a hidden input field. * @param string $name the name attribute. * @param string $value the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated hidden input tag */ public static function hiddenInput($name, $value = null, $options = []) { return static::input('hidden', $name, $value, $options); } /** * Generates a password input field. * @param string $name the name attribute. * @param string $value the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated password input tag */ public static function passwordInput($name, $value = null, $options = []) { return static::input('password', $name, $value, $options); } /** * Generates a file input field. * To use a file input field, you should set the enclosing form's "enctype" attribute to * be "multipart/form-data". After the form is submitted, the uploaded file information * can be obtained via $_FILES[$name] (see PHP documentation). * @param string $name the name attribute. * @param string $value the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated file input tag */ public static function fileInput($name, $value = null, $options = []) { return static::input('file', $name, $value, $options); } /** * Generates a text area input. * @param string $name the input name * @param string $value the input value. Note that it will be encoded using [[encode()]]. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated text area tag */ public static function textarea($name, $value = '', $options = []) { $options['name'] = $name; return static::tag('textarea', static::encode($value), $options); } /** * Generates a radio button input. * @param string $name the name attribute. * @param boolean $checked whether the radio button should be checked. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - uncheck: string, the value associated with the uncheck state of the radio button. When this attribute * is present, a hidden input will be generated so that if the radio button is not checked and is submitted, * the value of this attribute will still be submitted to the server via the hidden input. * - label: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks. * When this option is specified, the radio button will be enclosed by a label tag. * - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option. * * The rest of the options will be rendered as the attributes of the resulting radio button tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated radio button tag */ public static function radio($name, $checked = false, $options = []) { $options['checked'] = (bool) $checked; $value = array_key_exists('value', $options) ? $options['value'] : '1'; if (isset($options['uncheck'])) { // add a hidden field so that if the radio button is not selected, it still submits a value $hidden = static::hiddenInput($name, $options['uncheck']); unset($options['uncheck']); } else { $hidden = ''; } if (isset($options['label'])) { $label = $options['label']; $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : []; unset($options['label'], $options['labelOptions']); $content = static::label(static::input('radio', $name, $value, $options) . ' ' . $label, null, $labelOptions); return $hidden . $content; } else { return $hidden . static::input('radio', $name, $value, $options); } } /** * Generates a checkbox input. * @param string $name the name attribute. * @param boolean $checked whether the checkbox should be checked. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute * is present, a hidden input will be generated so that if the checkbox is not checked and is submitted, * the value of this attribute will still be submitted to the server via the hidden input. * - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks. * When this option is specified, the checkbox will be enclosed by a label tag. * - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option. * * The rest of the options will be rendered as the attributes of the resulting checkbox tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated checkbox tag */ public static function checkbox($name, $checked = false, $options = []) { $options['checked'] = (bool) $checked; $value = array_key_exists('value', $options) ? $options['value'] : '1'; if (isset($options['uncheck'])) { // add a hidden field so that if the checkbox is not selected, it still submits a value $hidden = static::hiddenInput($name, $options['uncheck']); unset($options['uncheck']); } else { $hidden = ''; } if (isset($options['label'])) { $label = $options['label']; $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : []; unset($options['label'], $options['labelOptions']); $content = static::label(static::input('checkbox', $name, $value, $options) . ' ' . $label, null, $labelOptions); return $hidden . $content; } else { return $hidden . static::input('checkbox', $name, $value, $options); } } /** * Generates a drop-down list. * @param string $name the input name * @param string $selection the selected value * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using * [[\yii\helpers\ArrayHelper::map()]]. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - prompt: string, a prompt text to be displayed as the first option; * - options: array, the attributes for the select option tags. The array keys must be valid option values, * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ * [ * 'value1' => ['disabled' => true], * 'value2' => ['label' => 'value 2'], * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', * except that the array keys represent the optgroup labels specified in $items. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character. * Defaults to false. * - encode: bool, whether to encode option prompt and option value characters. * Defaults to `true`. This option is available since 2.0.3. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated drop-down list tag */ public static function dropDownList($name, $selection = null, $items = [], $options = []) { if (!empty($options['multiple'])) { return static::listBox($name, $selection, $items, $options); } $options['name'] = $name; unset($options['unselect']); $selectOptions = static::renderSelectOptions($selection, $items, $options); return static::tag('select', "\n" . $selectOptions . "\n", $options); } /** * Generates a list box. * @param string $name the input name * @param string|array $selection the selected value(s) * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using * [[\yii\helpers\ArrayHelper::map()]]. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - prompt: string, a prompt text to be displayed as the first option; * - options: array, the attributes for the select option tags. The array keys must be valid option values, * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ * [ * 'value1' => ['disabled' => true], * 'value2' => ['label' => 'value 2'], * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', * except that the array keys represent the optgroup labels specified in $items. * - unselect: string, the value that will be submitted when no option is selected. * When this attribute is set, a hidden field will be generated so that if no option is selected in multiple * mode, we can still obtain the posted unselect value. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character. * Defaults to false. * - encode: bool, whether to encode option prompt and option value characters. * Defaults to `true`. This option is available since 2.0.3. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated list box tag */ public static function listBox($name, $selection = null, $items = [], $options = []) { if (!array_key_exists('size', $options)) { $options['size'] = 4; } if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2, 2)) { $name .= '[]'; } $options['name'] = $name; if (isset($options['unselect'])) { // add a hidden field so that if the list box has no option being selected, it still submits a value if (!empty($name) && substr_compare($name, '[]', -2, 2) === 0) { $name = substr($name, 0, -2); } $hidden = static::hiddenInput($name, $options['unselect']); unset($options['unselect']); } else { $hidden = ''; } $selectOptions = static::renderSelectOptions($selection, $items, $options); return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options); } /** * Generates a list of checkboxes. * A checkbox list allows multiple selection, like [[listBox()]]. * As a result, the corresponding submitted value is an array. * @param string $name the name attribute of each checkbox. * @param string|array $selection the selected value(s). * @param array $items the data item used to generate the checkboxes. * The array keys are the checkbox values, while the array values are the corresponding labels. * @param array $options options (name => config) for the checkbox list container tag. * The following options are specially handled: * * - tag: string, the tag name of the container element. * - unselect: string, the value that should be submitted when none of the checkboxes is selected. * By setting this option, a hidden input will be generated. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. * This option is ignored if `item` option is set. * - separator: string, the HTML code that separates items. * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]]. * - item: callable, a callback that can be used to customize the generation of the HTML code * corresponding to a single item in $items. The signature of this callback must be: * * ~~~ * function ($index, $label, $name, $checked, $value) * ~~~ * * where $index is the zero-based index of the checkbox in the whole list; $label * is the label for the checkbox; and $name, $value and $checked represent the name, * value and the checked status of the checkbox input, respectively. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated checkbox list */ public static function checkboxList($name, $selection = null, $items = [], $options = []) { if (substr($name, -2) !== '[]') { $name .= '[]'; } $formatter = isset($options['item']) ? $options['item'] : null; $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : []; $encode = !isset($options['encode']) || $options['encode']; $lines = []; $index = 0; foreach ($items as $value => $label) { $checked = $selection !== null && (!is_array($selection) && !strcmp($value, $selection) || is_array($selection) && in_array($value, $selection)); if ($formatter !== null) { $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value); } else { $lines[] = static::checkbox($name, $checked, array_merge($itemOptions, [ 'value' => $value, 'label' => $encode ? static::encode($label) : $label, ])); } $index++; } if (isset($options['unselect'])) { // add a hidden field so that if the list box has no option being selected, it still submits a value $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name; $hidden = static::hiddenInput($name2, $options['unselect']); } else { $hidden = ''; } $separator = isset($options['separator']) ? $options['separator'] : "\n"; $tag = isset($options['tag']) ? $options['tag'] : 'div'; unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']); return $hidden . static::tag($tag, implode($separator, $lines), $options); } /** * Generates a list of radio buttons. * A radio button list is like a checkbox list, except that it only allows single selection. * @param string $name the name attribute of each radio button. * @param string|array $selection the selected value(s). * @param array $items the data item used to generate the radio buttons. * The array keys are the radio button values, while the array values are the corresponding labels. * @param array $options options (name => config) for the radio button list container tag. * The following options are specially handled: * * - tag: string, the tag name of the container element. * - unselect: string, the value that should be submitted when none of the radio buttons is selected. * By setting this option, a hidden input will be generated. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. * This option is ignored if `item` option is set. * - separator: string, the HTML code that separates items. * - itemOptions: array, the options for generating the radio button tag using [[radio()]]. * - item: callable, a callback that can be used to customize the generation of the HTML code * corresponding to a single item in $items. The signature of this callback must be: * * ~~~ * function ($index, $label, $name, $checked, $value) * ~~~ * * where $index is the zero-based index of the radio button in the whole list; $label * is the label for the radio button; and $name, $value and $checked represent the name, * value and the checked status of the radio button input, respectively. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated radio button list */ public static function radioList($name, $selection = null, $items = [], $options = []) { $encode = !isset($options['encode']) || $options['encode']; $formatter = isset($options['item']) ? $options['item'] : null; $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : []; $lines = []; $index = 0; foreach ($items as $value => $label) { $checked = $selection !== null && (!is_array($selection) && !strcmp($value, $selection) || is_array($selection) && in_array($value, $selection)); if ($formatter !== null) { $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value); } else { $lines[] = static::radio($name, $checked, array_merge($itemOptions, [ 'value' => $value, 'label' => $encode ? static::encode($label) : $label, ])); } $index++; } $separator = isset($options['separator']) ? $options['separator'] : "\n"; if (isset($options['unselect'])) { // add a hidden field so that if the list box has no option being selected, it still submits a value $hidden = static::hiddenInput($name, $options['unselect']); } else { $hidden = ''; } $tag = isset($options['tag']) ? $options['tag'] : 'div'; unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']); return $hidden . static::tag($tag, implode($separator, $lines), $options); } /** * Generates an unordered list. * @param array|\Traversable $items the items for generating the list. Each item generates a single list item. * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true. * @param array $options options (name => config) for the radio button list. The following options are supported: * * - encode: boolean, whether to HTML-encode the items. Defaults to true. * This option is ignored if the `item` option is specified. * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified. * - item: callable, a callback that is used to generate each individual list item. * The signature of this callback must be: * * ~~~ * function ($item, $index) * ~~~ * * where $index is the array key corresponding to `$item` in `$items`. The callback should return * the whole list item tag. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated unordered list. An empty list tag will be returned if `$items` is empty. */ public static function ul($items, $options = []) { $tag = isset($options['tag']) ? $options['tag'] : 'ul'; $encode = !isset($options['encode']) || $options['encode']; $formatter = isset($options['item']) ? $options['item'] : null; $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : []; unset($options['tag'], $options['encode'], $options['item'], $options['itemOptions']); if (empty($items)) { return static::tag($tag, '', $options); } $results = []; foreach ($items as $index => $item) { if ($formatter !== null) { $results[] = call_user_func($formatter, $item, $index); } else { $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions); } } return static::tag($tag, "\n" . implode("\n", $results) . "\n", $options); } /** * Generates an ordered list. * @param array|\Traversable $items the items for generating the list. Each item generates a single list item. * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true. * @param array $options options (name => config) for the radio button list. The following options are supported: * * - encode: boolean, whether to HTML-encode the items. Defaults to true. * This option is ignored if the `item` option is specified. * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified. * - item: callable, a callback that is used to generate each individual list item. * The signature of this callback must be: * * ~~~ * function ($item, $index) * ~~~ * * where $index is the array key corresponding to `$item` in `$items`. The callback should return * the whole list item tag. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated ordered list. An empty string is returned if `$items` is empty. */ public static function ol($items, $options = []) { $options['tag'] = 'ol'; return static::ul($items, $options); } /** * Generates a label tag for the given model attribute. * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]]. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * The following options are specially handled: * * - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]]. * If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display * (after encoding). * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated label tag */ public static function activeLabel($model, $attribute, $options = []) { $for = array_key_exists('for', $options) ? $options['for'] : static::getInputId($model, $attribute); $attribute = static::getAttributeName($attribute); $label = isset($options['label']) ? $options['label'] : static::encode($model->getAttributeLabel($attribute)); unset($options['label'], $options['for']); return static::label($label, $for, $options); } /** * Generates a hint tag for the given model attribute. * The hint text is the hint associated with the attribute, obtained via [[Model::getAttributeHint()]]. * If no hint content can be obtained, method will return an empty string. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * The following options are specially handled: * * - hint: this specifies the hint to be displayed. Note that this will NOT be [[encode()|encoded]]. * If this is not set, [[Model::getAttributeHint()]] will be called to get the hint for display * (without encoding). * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated hint tag * @since 2.0.4 */ public static function activeHint($model, $attribute, $options = []) { $attribute = static::getAttributeName($attribute); $hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute); if (empty($hint)) { return ''; } $tag = ArrayHelper::remove($options, 'tag', 'div'); unset($options['hint']); return static::tag($tag, $hint, $options); } /** * Generates a summary of the validation errors. * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden. * @param Model|Model[] $models the model(s) whose validation errors are to be displayed * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - header: string, the header HTML for the error summary. If not set, a default prompt string will be used. * - footer: string, the footer HTML for the error summary. * - encode: boolean, if set to false then the error messages won't be encoded. * * The rest of the options will be rendered as the attributes of the container tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * @return string the generated error summary */ public static function errorSummary($models, $options = []) { $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>'; $footer = isset($options['footer']) ? $options['footer'] : ''; $encode = !isset($options['encode']) || $options['encode'] !== false; unset($options['header'], $options['footer'], $options['encode']); $lines = []; if (!is_array($models)) { $models = [$models]; } foreach ($models as $model) { /* @var $model Model */ foreach ($model->getFirstErrors() as $error) { $lines[] = $encode ? Html::encode($error) : $error; } } if (empty($lines)) { // still render the placeholder for client-side validation use $content = "<ul></ul>"; $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none'; } else { $content = "<ul><li>" . implode("</li>\n<li>", $lines) . "</li></ul>"; } return Html::tag('div', $header . $content . $footer, $options); } /** * Generates a tag that contains the first validation error of the specified model attribute. * Note that even if there is no validation error, this method will still return an empty error tag. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * * The following options are specially handled: * * - tag: this specifies the tag name. If not set, "div" will be used. * - encode: boolean, if set to false then the error message won't be encoded. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated label tag */ public static function error($model, $attribute, $options = []) { $attribute = static::getAttributeName($attribute); $error = $model->getFirstError($attribute); $tag = isset($options['tag']) ? $options['tag'] : 'div'; $encode = !isset($options['encode']) || $options['encode'] !== false; unset($options['tag'], $options['encode']); return Html::tag($tag, $encode ? Html::encode($error) : $error, $options); } /** * Generates an input tag for the given model attribute. * This method will generate the "name" and "value" tag attributes automatically for the model attribute * unless they are explicitly specified in `$options`. * @param string $type the input type (e.g. 'text', 'password') * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated input tag */ public static function activeInput($type, $model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute); if (!array_key_exists('id', $options)) { $options['id'] = static::getInputId($model, $attribute); } return static::input($type, $name, $value, $options); } /** * If `maxlength` option is set true and the model attribute is validated by a string validator, * the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]]. * @param Model $model the model object * @param string $attribute the attribute name or expression. * @param array $options the tag options in terms of name-value pairs. */ private static function normalizeMaxLength($model, $attribute, &$options) { if (isset($options['maxlength']) && $options['maxlength'] === true) { unset($options['maxlength']); $attrName = static::getAttributeName($attribute); foreach ($model->getActiveValidators($attrName) as $validator) { if ($validator instanceof StringValidator && $validator->max !== null) { $options['maxlength'] = $validator->max; break; } } } } /** * Generates a text input tag for the given model attribute. * This method will generate the "name" and "value" tag attributes automatically for the model attribute * unless they are explicitly specified in `$options`. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * The following special options are recognized: * * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]]. * This is available since version 2.0.3. * * @return string the generated input tag */ public static function activeTextInput($model, $attribute, $options = []) { self::normalizeMaxLength($model, $attribute, $options); return static::activeInput('text', $model, $attribute, $options); } /** * Generates a hidden input tag for the given model attribute. * This method will generate the "name" and "value" tag attributes automatically for the model attribute * unless they are explicitly specified in `$options`. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated input tag */ public static function activeHiddenInput($model, $attribute, $options = []) { return static::activeInput('hidden', $model, $attribute, $options); } /** * Generates a password input tag for the given model attribute. * This method will generate the "name" and "value" tag attributes automatically for the model attribute * unless they are explicitly specified in `$options`. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * The following special options are recognized: * * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]]. * This option is available since version 2.0.6. * * @return string the generated input tag */ public static function activePasswordInput($model, $attribute, $options = []) { self::normalizeMaxLength($model, $attribute, $options); return static::activeInput('password', $model, $attribute, $options); } /** * Generates a file input tag for the given model attribute. * This method will generate the "name" and "value" tag attributes automatically for the model attribute * unless they are explicitly specified in `$options`. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated input tag */ public static function activeFileInput($model, $attribute, $options = []) { // add a hidden field so that if a model only has a file field, we can // still use isset($_POST[$modelClass]) to detect if the input is submitted return static::activeHiddenInput($model, $attribute, ['id' => null, 'value' => '']) . static::activeInput('file', $model, $attribute, $options); } /** * Generates a textarea tag for the given model attribute. * The model attribute value will be used as the content in the textarea. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * The following special options are recognized: * * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]]. * This option is available since version 2.0.6. * * @return string the generated textarea tag */ public static function activeTextarea($model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); if (isset($options['value'])) { $value = $options['value']; unset($options['value']); } else { $value = static::getAttributeValue($model, $attribute); } if (!array_key_exists('id', $options)) { $options['id'] = static::getInputId($model, $attribute); } self::normalizeMaxLength($model, $attribute, $options); return static::textarea($name, $value, $options); } /** * Generates a radio button tag together with a label for the given model attribute. * This method will generate the "checked" tag attribute according to the model attribute value. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - uncheck: string, the value associated with the uncheck state of the radio button. If not set, * it will take the default value '0'. This method will render a hidden input so that if the radio button * is not checked and is submitted, the value of this attribute will still be submitted to the server * via the hidden input. If you do not want any hidden input, you should explicitly set this option as null. * - label: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks. * The radio button will be enclosed by the label tag. Note that if you do not specify this option, a default label * will be used based on the attribute label declaration in the model. If you do not want any label, you should * explicitly set this option as null. * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated radio button tag */ public static function activeRadio($model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $value = static::getAttributeValue($model, $attribute); if (!array_key_exists('value', $options)) { $options['value'] = '1'; } if (!array_key_exists('uncheck', $options)) { $options['uncheck'] = '0'; } if (!array_key_exists('label', $options)) { $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute))); } $checked = "$value" === "{$options['value']}"; if (!array_key_exists('id', $options)) { $options['id'] = static::getInputId($model, $attribute); } return static::radio($name, $checked, $options); } /** * Generates a checkbox tag together with a label for the given model attribute. * This method will generate the "checked" tag attribute according to the model attribute value. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - uncheck: string, the value associated with the uncheck state of the radio button. If not set, * it will take the default value '0'. This method will render a hidden input so that if the radio button * is not checked and is submitted, the value of this attribute will still be submitted to the server * via the hidden input. If you do not want any hidden input, you should explicitly set this option as null. * - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks. * The checkbox will be enclosed by the label tag. Note that if you do not specify this option, a default label * will be used based on the attribute label declaration in the model. If you do not want any label, you should * explicitly set this option as null. * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated checkbox tag */ public static function activeCheckbox($model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $value = static::getAttributeValue($model, $attribute); if (!array_key_exists('value', $options)) { $options['value'] = '1'; } if (!array_key_exists('uncheck', $options)) { $options['uncheck'] = '0'; } if (!array_key_exists('label', $options)) { $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute))); } $checked = "$value" === "{$options['value']}"; if (!array_key_exists('id', $options)) { $options['id'] = static::getInputId($model, $attribute); } return static::checkbox($name, $checked, $options); } /** * Generates a drop-down list for the given model attribute. * The selection of the drop-down list is taken from the value of the model attribute. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using * [[\yii\helpers\ArrayHelper::map()]]. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - prompt: string, a prompt text to be displayed as the first option; * - options: array, the attributes for the select option tags. The array keys must be valid option values, * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ * [ * 'value1' => ['disabled' => true], * 'value2' => ['label' => 'value 2'], * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', * except that the array keys represent the optgroup labels specified in $items. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character. * Defaults to false. * - encode: bool, whether to encode option prompt and option value characters. * Defaults to `true`. This option is available since 2.0.3. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated drop-down list tag */ public static function activeDropDownList($model, $attribute, $items, $options = []) { if (empty($options['multiple'])) { return static::activeListInput('dropDownList', $model, $attribute, $items, $options); } else { return static::activeListBox($model, $attribute, $items, $options); } } /** * Generates a list box. * The selection of the list box is taken from the value of the model attribute. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using * [[\yii\helpers\ArrayHelper::map()]]. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - prompt: string, a prompt text to be displayed as the first option; * - options: array, the attributes for the select option tags. The array keys must be valid option values, * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ * [ * 'value1' => ['disabled' => true], * 'value2' => ['label' => 'value 2'], * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', * except that the array keys represent the optgroup labels specified in $items. * - unselect: string, the value that will be submitted when no option is selected. * When this attribute is set, a hidden field will be generated so that if no option is selected in multiple * mode, we can still obtain the posted unselect value. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character. * Defaults to false. * - encode: bool, whether to encode option prompt and option value characters. * Defaults to `true`. This option is available since 2.0.3. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated list box tag */ public static function activeListBox($model, $attribute, $items, $options = []) { return static::activeListInput('listBox', $model, $attribute, $items, $options); } /** * Generates a list of checkboxes. * A checkbox list allows multiple selection, like [[listBox()]]. * As a result, the corresponding submitted value is an array. * The selection of the checkbox list is taken from the value of the model attribute. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $items the data item used to generate the checkboxes. * The array keys are the checkbox values, and the array values are the corresponding labels. * Note that the labels will NOT be HTML-encoded, while the values will. * @param array $options options (name => config) for the checkbox list container tag. * The following options are specially handled: * * - tag: string, the tag name of the container element. * - unselect: string, the value that should be submitted when none of the checkboxes is selected. * You may set this option to be null to prevent default value submission. * If this option is not set, an empty string will be submitted. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. * This option is ignored if `item` option is set. * - separator: string, the HTML code that separates items. * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]]. * - item: callable, a callback that can be used to customize the generation of the HTML code * corresponding to a single item in $items. The signature of this callback must be: * * ~~~ * function ($index, $label, $name, $checked, $value) * ~~~ * * where $index is the zero-based index of the checkbox in the whole list; $label * is the label for the checkbox; and $name, $value and $checked represent the name, * value and the checked status of the checkbox input. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated checkbox list */ public static function activeCheckboxList($model, $attribute, $items, $options = []) { return static::activeListInput('checkboxList', $model, $attribute, $items, $options); } /** * Generates a list of radio buttons. * A radio button list is like a checkbox list, except that it only allows single selection. * The selection of the radio buttons is taken from the value of the model attribute. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $items the data item used to generate the radio buttons. * The array keys are the radio values, and the array values are the corresponding labels. * Note that the labels will NOT be HTML-encoded, while the values will. * @param array $options options (name => config) for the radio button list container tag. * The following options are specially handled: * * - tag: string, the tag name of the container element. * - unselect: string, the value that should be submitted when none of the radio buttons is selected. * You may set this option to be null to prevent default value submission. * If this option is not set, an empty string will be submitted. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. * This option is ignored if `item` option is set. * - separator: string, the HTML code that separates items. * - itemOptions: array, the options for generating the radio button tag using [[radio()]]. * - item: callable, a callback that can be used to customize the generation of the HTML code * corresponding to a single item in $items. The signature of this callback must be: * * ~~~ * function ($index, $label, $name, $checked, $value) * ~~~ * * where $index is the zero-based index of the radio button in the whole list; $label * is the label for the radio button; and $name, $value and $checked represent the name, * value and the checked status of the radio button input. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated radio button list */ public static function activeRadioList($model, $attribute, $items, $options = []) { return static::activeListInput('radioList', $model, $attribute, $items, $options); } /** * Generates a list of input fields. * This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckBoxList()]]. * @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $items the data item used to generate the input fields. * The array keys are the input values, and the array values are the corresponding labels. * Note that the labels will NOT be HTML-encoded, while the values will. * @param array $options options (name => config) for the input list. The supported special options * depend on the input type specified by `$type`. * @return string the generated input list */ protected static function activeListInput($type, $model, $attribute, $items, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $selection = static::getAttributeValue($model, $attribute); if (!array_key_exists('unselect', $options)) { $options['unselect'] = ''; } if (!array_key_exists('id', $options)) { $options['id'] = static::getInputId($model, $attribute); } return static::$type($name, $selection, $items, $options); } /** * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]]. * @param string|array $selection the selected value(s). This can be either a string for single selection * or an array for multiple selections. * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using * [[\yii\helpers\ArrayHelper::map()]]. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call. * This method will take out these elements, if any: "prompt", "options" and "groups". See more details * in [[dropDownList()]] for the explanation of these elements. * * @return string the generated list options */ public static function renderSelectOptions($selection, $items, &$tagOptions = []) { $lines = []; $encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false); $encode = ArrayHelper::remove($tagOptions, 'encode', true); if (isset($tagOptions['prompt'])) { $prompt = $encode ? static::encode($tagOptions['prompt']) : $tagOptions['prompt']; if ($encodeSpaces) { $prompt = str_replace(' ', '&nbsp;', $prompt); } $lines[] = static::tag('option', $prompt, ['value' => '']); } $options = isset($tagOptions['options']) ? $tagOptions['options'] : []; $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : []; unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']); $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces); $options['encode'] = ArrayHelper::getValue($options, 'encode', $encode); foreach ($items as $key => $value) { if (is_array($value)) { $groupAttrs = isset($groups[$key]) ? $groups[$key] : []; if (!isset($groupAttrs['label'])) { $groupAttrs['label'] = $key; } $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode]; $content = static::renderSelectOptions($selection, $value, $attrs); $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs); } else { $attrs = isset($options[$key]) ? $options[$key] : []; $attrs['value'] = (string) $key; $attrs['selected'] = $selection !== null && (!is_array($selection) && !strcmp($key, $selection) || is_array($selection) && in_array($key, $selection)); $text = $encode ? static::encode($value) : $value; if ($encodeSpaces) { $text = str_replace(' ', '&nbsp;', $text); } $lines[] = static::tag('option', $text, $attrs); } } return implode("\n", $lines); } /** * Renders the HTML tag attributes. * * Attributes whose values are of boolean type will be treated as * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes). * * Attributes whose values are null will not be rendered. * * The values of attributes will be HTML-encoded using [[encode()]]. * * The "data" attribute is specially handled when it is receiving an array value. In this case, * the array will be "expanded" and a list data attributes will be rendered. For example, * if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered: * `data-id="1" data-name="yii"`. * Additionally `'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` will be rendered as: * `data-params='{"id":1,"name":"yii"}' data-status="ok"`. * * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]]. * @return string the rendering result. If the attributes are not empty, they will be rendered * into a string with a leading white space (so that it can be directly appended to the tag name * in a tag. If there is no attribute, an empty string will be returned. */ public static function renderTagAttributes($attributes) { if (count($attributes) > 1) { $sorted = []; foreach (static::$attributeOrder as $name) { if (isset($attributes[$name])) { $sorted[$name] = $attributes[$name]; } } $attributes = array_merge($sorted, $attributes); } $html = ''; foreach ($attributes as $name => $value) { if (is_bool($value)) { if ($value) { $html .= " $name"; } } elseif (is_array($value)) { if (in_array($name, static::$dataAttributes)) { foreach ($value as $n => $v) { if (is_array($v)) { $html .= " $name-$n='" . Json::htmlEncode($v) . "'"; } else { $html .= " $name-$n=\"" . static::encode($v) . '"'; } } } elseif ($name === 'class') { if (empty($value)) { continue; } $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"'; } elseif ($name === 'style') { if (empty($value)) { continue; } $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"'; } else { $html .= " $name='" . Json::htmlEncode($value) . "'"; } } elseif ($value !== null) { $html .= " $name=\"" . static::encode($value) . '"'; } } return $html; } /** * Adds a CSS class (or several classes) to the specified options. * If the CSS class is already in the options, it will not be added again. * If class specification at given options is an array, and some class placed there with the named (string) key, * overriding of such key will have no effect. For example: * * ~~~php * $options = ['class' => ['persistent' => 'initial']]; * Html::addCssClass($options, ['persistent' => 'override']); * var_dump($options['class']); // outputs: array('persistent' => 'initial'); * ~~~ * * @param array $options the options to be modified. * @param string|array $class the CSS class(es) to be added */ public static function addCssClass(&$options, $class) { if (isset($options['class'])) { if (is_array($options['class'])) { $options['class'] = self::mergeCssClasses($options['class'], (array) $class); } else { $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY); $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class)); } } else { $options['class'] = $class; } } /** * Merges already existing CSS classes with new one. * This method provides the priority for named existing classes over additional. * @param array $existingClasses already existing CSS classes. * @param array $additionalClasses CSS classes to be added. * @return array merge result. */ private static function mergeCssClasses(array $existingClasses, array $additionalClasses) { foreach ($additionalClasses as $key => $class) { if (is_int($key) && !in_array($class, $existingClasses)) { $existingClasses[] = $class; } elseif (!isset($existingClasses[$key])) { $existingClasses[$key] = $class; } } return array_unique($existingClasses); } /** * Removes a CSS class from the specified options. * @param array $options the options to be modified. * @param string|array $class the CSS class(es) to be removed */ public static function removeCssClass(&$options, $class) { if (isset($options['class'])) { if (is_array($options['class'])) { $classes = array_diff($options['class'], (array) $class); if (empty($classes)) { unset($options['class']); } else { $options['class'] = $classes; } } else { $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY); $classes = array_diff($classes, (array) $class); if (empty($classes)) { unset($options['class']); } else { $options['class'] = implode(' ', $classes); } } } } /** * Adds the specified CSS style to the HTML options. * * If the options already contain a `style` element, the new style will be merged * with the existing one. If a CSS property exists in both the new and the old styles, * the old one may be overwritten if `$overwrite` is true. * * For example, * * ```php * Html::addCssStyle($options, 'width: 100px; height: 200px'); * ``` * * @param array $options the HTML options to be modified. * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or * array (e.g. `['width' => '100px', 'height' => '200px']`). * @param boolean $overwrite whether to overwrite existing CSS properties if the new style * contain them too. * @see removeCssStyle() * @see cssStyleFromArray() * @see cssStyleToArray() */ public static function addCssStyle(&$options, $style, $overwrite = true) { if (!empty($options['style'])) { $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']); $newStyle = is_array($style) ? $style : static::cssStyleToArray($style); if (!$overwrite) { foreach ($newStyle as $property => $value) { if (isset($oldStyle[$property])) { unset($newStyle[$property]); } } } $style = array_merge($oldStyle, $newStyle); } $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style; } /** * Removes the specified CSS style from the HTML options. * * For example, * * ```php * Html::removeCssStyle($options, ['width', 'height']); * ``` * * @param array $options the HTML options to be modified. * @param string|array $properties the CSS properties to be removed. You may use a string * if you are removing a single property. * @see addCssStyle() */ public static function removeCssStyle(&$options, $properties) { if (!empty($options['style'])) { $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']); foreach ((array) $properties as $property) { unset($style[$property]); } $options['style'] = static::cssStyleFromArray($style); } } /** * Converts a CSS style array into a string representation. * * For example, * * ```php * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px'])); * // will display: 'width: 100px; height: 200px;' * ``` * * @param array $style the CSS style array. The array keys are the CSS property names, * and the array values are the corresponding CSS property values. * @return string the CSS style string. If the CSS style is empty, a null will be returned. */ public static function cssStyleFromArray(array $style) { $result = ''; foreach ($style as $name => $value) { $result .= "$name: $value; "; } // return null if empty to avoid rendering the "style" attribute return $result === '' ? null : rtrim($result); } /** * Converts a CSS style string into an array representation. * * The array keys are the CSS property names, and the array values * are the corresponding CSS property values. * * For example, * * ```php * print_r(Html::cssStyleToArray('width: 100px; height: 200px;')); * // will display: ['width' => '100px', 'height' => '200px'] * ``` * * @param string $style the CSS style string * @return array the array representation of the CSS style */ public static function cssStyleToArray($style) { $result = []; foreach (explode(';', $style) as $property) { $property = explode(':', $property); if (count($property) > 1) { $result[trim($property[0])] = trim($property[1]); } } return $result; } /** * Returns the real attribute name from the given attribute expression. * * An attribute expression is an attribute name prefixed and/or suffixed with array indexes. * It is mainly used in tabular data input and/or input of array type. Below are some examples: * * - `[0]content` is used in tabular data input to represent the "content" attribute * for the first model in tabular input; * - `dates[0]` represents the first array element of the "dates" attribute; * - `[0]dates[0]` represents the first array element of the "dates" attribute * for the first model in tabular input. * * If `$attribute` has neither prefix nor suffix, it will be returned back without change. * @param string $attribute the attribute name or expression * @return string the attribute name without prefix and suffix. * @throws InvalidParamException if the attribute name contains non-word characters. */ public static function getAttributeName($attribute) { if (preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) { return $matches[2]; } else { throw new InvalidParamException('Attribute name must contain word characters only.'); } } /** * Returns the value of the specified attribute name or expression. * * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`. * See [[getAttributeName()]] for more details about attribute expression. * * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances, * the primary value(s) of the AR instance(s) will be returned instead. * * @param Model $model the model object * @param string $attribute the attribute name or expression * @return string|array the corresponding attribute value * @throws InvalidParamException if the attribute name contains non-word characters. */ public static function getAttributeValue($model, $attribute) { if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) { throw new InvalidParamException('Attribute name must contain word characters only.'); } $attribute = $matches[2]; $value = $model->$attribute; if ($matches[3] !== '') { foreach (explode('][', trim($matches[3], '[]')) as $id) { if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) { $value = $value[$id]; } else { return null; } } } // https://github.com/yiisoft/yii2/issues/1457 if (is_array($value)) { foreach ($value as $i => $v) { if ($v instanceof ActiveRecordInterface) { $v = $v->getPrimaryKey(false); $value[$i] = is_array($v) ? json_encode($v) : $v; } } } elseif ($value instanceof ActiveRecordInterface) { $value = $value->getPrimaryKey(false); return is_array($value) ? json_encode($value) : $value; } return $value; } /** * Generates an appropriate input name for the specified attribute name or expression. * * This method generates a name that can be used as the input name to collect user input * for the specified attribute. The name is generated according to the [[Model::formName|form name]] * of the model and the given attribute name. For example, if the form name of the `Post` model * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`. * * See [[getAttributeName()]] for explanation of attribute expression. * * @param Model $model the model object * @param string $attribute the attribute name or expression * @return string the generated input name * @throws InvalidParamException if the attribute name contains non-word characters. */ public static function getInputName($model, $attribute) { $formName = $model->formName(); if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) { throw new InvalidParamException('Attribute name must contain word characters only.'); } $prefix = $matches[1]; $attribute = $matches[2]; $suffix = $matches[3]; if ($formName === '' && $prefix === '') { return $attribute . $suffix; } elseif ($formName !== '') { return $formName . $prefix . "[$attribute]" . $suffix; } else { throw new InvalidParamException(get_class($model) . '::formName() cannot be empty for tabular inputs.'); } } /** * Generates an appropriate input ID for the specified attribute name or expression. * * This method converts the result [[getInputName()]] into a valid input ID. * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression. * @return string the generated input ID * @throws InvalidParamException if the attribute name contains non-word characters. */ public static function getInputId($model, $attribute) { $name = strtolower(static::getInputName($model, $attribute)); return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name); } /** * Escapes regular expression to use in JavaScript * @param string $regexp the regular expression to be escaped. * @return string the escaped result. * @since 2.0.6 */ public static function escapeJsRegularExpression($regexp) { $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp); $deliminator = substr($pattern, 0, 1); $pos = strrpos($pattern, $deliminator, 1); $flag = substr($pattern, $pos + 1); if ($deliminator !== '/') { $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/'; } else { $pattern = substr($pattern, 0, $pos + 1); } if (!empty($flag)) { $pattern .= preg_replace('/[^igm]/', '', $flag); } return $pattern; } }
Java
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>statsmodels.base.model.GenericLikelihoodModelResults.remove_data &#8212; statsmodels v0.10.0 documentation</title> <link rel="stylesheet" href="../../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="../../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../../about.html" /> <link rel="index" title="Index" href="../../genindex.html" /> <link rel="search" title="Search" href="../../search.html" /> <link rel="next" title="statsmodels.base.model.GenericLikelihoodModelResults.save" href="statsmodels.base.model.GenericLikelihoodModelResults.save.html" /> <link rel="prev" title="statsmodels.base.model.GenericLikelihoodModelResults.pvalues" href="statsmodels.base.model.GenericLikelihoodModelResults.pvalues.html" /> <link rel="stylesheet" href="../../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../../_static/scripts.js"> </script> <script type="text/javascript" src="../../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../../_static/closelabel.png" $.facebox.settings.loadingImage = "../../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../../index.html"> <img src="../../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.base.model.GenericLikelihoodModelResults.save.html" title="statsmodels.base.model.GenericLikelihoodModelResults.save" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.base.model.GenericLikelihoodModelResults.pvalues.html" title="statsmodels.base.model.GenericLikelihoodModelResults.pvalues" accesskey="P">previous</a> |</li> <li><a href ="../../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../index.html" >Developer Page</a> |</li> <li class="nav-item nav-item-2"><a href="../internal.html" >Internal Classes</a> |</li> <li class="nav-item nav-item-3"><a href="statsmodels.base.model.GenericLikelihoodModelResults.html" accesskey="U">statsmodels.base.model.GenericLikelihoodModelResults</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-base-model-genericlikelihoodmodelresults-remove-data"> <h1>statsmodels.base.model.GenericLikelihoodModelResults.remove_data<a class="headerlink" href="#statsmodels-base-model-genericlikelihoodmodelresults-remove-data" title="Permalink to this headline">¶</a></h1> <p>method</p> <dl class="method"> <dt id="statsmodels.base.model.GenericLikelihoodModelResults.remove_data"> <code class="sig-prename descclassname">GenericLikelihoodModelResults.</code><code class="sig-name descname">remove_data</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.base.model.GenericLikelihoodModelResults.remove_data" title="Permalink to this definition">¶</a></dt> <dd><p>remove data arrays, all nobs arrays from result and model</p> <p>This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None.</p> </div> <p>Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible.</p> <p>The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove_data.</p> <p>The attributes to remove are named in:</p> <dl class="simple"> <dt>model._data_attr<span class="classifier">arrays attached to both the model instance</span></dt><dd><p>and the results instance with the same attribute name.</p> </dd> <dt>result.data_in_cache<span class="classifier">arrays that may exist as values in</span></dt><dd><p>result._cache (TODO : should privatize name)</p> </dd> <dt>result._data_attr_model<span class="classifier">arrays attached to the model</span></dt><dd><p>instance but not to the results instance</p> </dd> </dl> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.base.model.GenericLikelihoodModelResults.pvalues.html" title="previous chapter">statsmodels.base.model.GenericLikelihoodModelResults.pvalues</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.base.model.GenericLikelihoodModelResults.save.html" title="next chapter">statsmodels.base.model.GenericLikelihoodModelResults.save</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../_sources/dev/generated/statsmodels.base.model.GenericLikelihoodModelResults.remove_data.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2. </div> </body> </html>
Java
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/foundation.css' %}" /> </head> <body> <div class="row"> <div class="panel"> <h2> You have successfully logged out </h2> <p> You can <a href="/pta/">login</a> again and access the PTA application</p> </div> </div> </body> </html>
Java
/* Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include "CanvasOGL.hpp" #include "ShadersOpenGL.hpp" #include "TextureOpenGL.hpp" namespace KRE { namespace { CanvasPtr& get_instance() { static CanvasPtr res = CanvasPtr(new CanvasOGL()); return res; } } CanvasOGL::CanvasOGL() { handleDimensionsChanged(); } CanvasOGL::~CanvasOGL() { } void CanvasOGL::handleDimensionsChanged() { mvp_ = glm::ortho(0.0f, float(width()), float(height()), 0.0f); } void CanvasOGL::blitTexture(const TexturePtr& tex, const rect& src, float rotation, const rect& dst, const Color& color) const { auto texture = std::dynamic_pointer_cast<OpenGLTexture>(tex); ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type."); const float tx1 = float(src.x()) / texture->width(); const float ty1 = float(src.y()) / texture->height(); const float tx2 = src.w() == 0 ? 1.0f : float(src.x2()) / texture->width(); const float ty2 = src.h() == 0 ? 1.0f : float(src.y2()) / texture->height(); const float uv_coords[] = { tx1, ty1, tx2, ty1, tx1, ty2, tx2, ty2, }; const float vx1 = float(dst.x()); const float vy1 = float(dst.y()); const float vx2 = float(dst.x2()); const float vy2 = float(dst.y2()); const float vtx_coords[] = { vx1, vy1, vx2, vy1, vx1, vy2, vx2, vy2, }; glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vx2)/2.0f,-(vy1+vy2)/2.0f,0.0f)); glm::mat4 mvp = mvp_ * model * getModelMatrix(); auto shader = OpenGL::ShaderProgram::defaultSystemShader(); shader->makeActive(); texture->bind(); shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp)); if(color != KRE::Color::colorWhite()) { shader->setUniformValue(shader->getColorUniform(), (color*getColor()).asFloatVector()); } else { shader->setUniformValue(shader->getColorUniform(), getColor().asFloatVector()); } shader->setUniformValue(shader->getTexMapUniform(), 0); // XXX the following line are only temporary, obviously. //shader->SetUniformValue(shader->GetUniformIterator("discard"), 0); glEnableVertexAttribArray(shader->getVertexAttribute()->second.location); glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords); glEnableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glVertexAttribPointer(shader->getTexcoordAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, uv_coords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glDisableVertexAttribArray(shader->getVertexAttribute()->second.location); } void CanvasOGL::blitTexture(const TexturePtr& tex, const std::vector<vertex_texcoord>& vtc, float rotation, const Color& color) { ASSERT_LOG(false, "XXX CanvasOGL::blitTexture()"); } void CanvasOGL::blitTexture(const MaterialPtr& mat, float rotation, const rect& dst, const Color& color) const { ASSERT_LOG(mat != NULL, "Material was null"); const float vx1 = float(dst.x()); const float vy1 = float(dst.y()); const float vx2 = float(dst.x2()); const float vy2 = float(dst.y2()); const float vtx_coords[] = { vx1, vy1, vx2, vy1, vx1, vy2, vx2, vy2, }; glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vy1)/2.0f,-(vy1+vy1)/2.0f,0.0f)); glm::mat4 mvp = mvp_ * model * getModelMatrix(); auto shader = OpenGL::ShaderProgram::defaultSystemShader(); shader->makeActive(); shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp)); //if(color != KRE::Color::colorWhite()) { shader->setUniformValue(shader->getColorUniform(), color.asFloatVector()); //} shader->setUniformValue(shader->getTexMapUniform(), 0); mat->apply(); for(auto it = mat->getTexture().begin(); it != mat->getTexture().end(); ++it) { auto texture = std::dynamic_pointer_cast<OpenGLTexture>(*it); ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type."); auto uv_coords = mat->getNormalisedTextureCoords(it); texture->bind(); // XXX the following line are only temporary, obviously. //shader->SetUniformValue(shader->GetUniformIterator("discard"), 0); glEnableVertexAttribArray(shader->getVertexAttribute()->second.location); glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords); glEnableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glVertexAttribPointer(shader->getTexcoordAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, &uv_coords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glDisableVertexAttribArray(shader->getVertexAttribute()->second.location); } mat->unapply(); } void CanvasOGL::blitTexture(const MaterialPtr& mat, const rect& src, float rotation, const rect& dst, const Color& color) const { ASSERT_LOG(mat != NULL, "Material was null"); const float vx1 = float(dst.x()); const float vy1 = float(dst.y()); const float vx2 = float(dst.x2()); const float vy2 = float(dst.y2()); const float vtx_coords[] = { vx1, vy1, vx2, vy1, vx1, vy2, vx2, vy2, }; glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vy1)/2.0f,-(vy1+vy1)/2.0f,0.0f)); glm::mat4 mvp = mvp_ * model * getModelMatrix(); auto shader = OpenGL::ShaderProgram::defaultSystemShader(); shader->makeActive(); shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp)); //if(color) { shader->setUniformValue(shader->getColorUniform(), color.asFloatVector()); //} shader->setUniformValue(shader->getTexMapUniform(), 0); mat->apply(); for(auto it = mat->getTexture().begin(); it != mat->getTexture().end(); ++it) { auto texture = std::dynamic_pointer_cast<OpenGLTexture>(*it); ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type."); const float tx1 = float(src.x()) / texture->width(); const float ty1 = float(src.y()) / texture->height(); const float tx2 = src.w() == 0 ? 1.0f : float(src.x2()) / texture->width(); const float ty2 = src.h() == 0 ? 1.0f : float(src.y2()) / texture->height(); const float uv_coords[] = { tx1, ty1, tx2, ty1, tx1, ty2, tx2, ty2, }; texture->bind(); // XXX the following line are only temporary, obviously. //shader->SetUniformValue(shader->GetUniformIterator("discard"), 0); glEnableVertexAttribArray(shader->getVertexAttribute()->second.location); glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords); glEnableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glVertexAttribPointer(shader->getTexcoordAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, &uv_coords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glDisableVertexAttribArray(shader->getVertexAttribute()->second.location); } mat->unapply(); } void CanvasOGL::drawSolidRect(const rect& r, const Color& fill_color, const Color& stroke_color, float rotation) const { rectf vtx = r.as_type<float>(); const float vtx_coords[] = { vtx.x1(), vtx.y1(), vtx.x2(), vtx.y1(), vtx.x1(), vtx.y2(), vtx.x2(), vtx.y2(), }; glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(vtx.mid_x(),vtx.mid_y(),0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-vtx.mid_x(),-vtx.mid_y(),0.0f)); glm::mat4 mvp = mvp_ * model * getModelMatrix(); static OpenGL::ShaderProgramPtr shader = OpenGL::ShaderProgram::factory("simple"); shader->makeActive(); shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp)); // Draw a filled rect shader->setUniformValue(shader->getColorUniform(), fill_color.asFloatVector()); glEnableVertexAttribArray(shader->getVertexAttribute()->second.location); glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Draw stroke if stroke_color is specified. // XXX I think there is an easier way of doing this, with modern GL const float vtx_coords_line[] = { vtx.x1(), vtx.y1(), vtx.x2(), vtx.y1(), vtx.x2(), vtx.y2(), vtx.x1(), vtx.y2(), vtx.x1(), vtx.y1(), }; shader->setUniformValue(shader->getColorUniform(), stroke_color.asFloatVector()); glEnableVertexAttribArray(shader->getVertexAttribute()->second.location); glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords_line); // XXX this may not be right. glDrawArrays(GL_LINE_STRIP, 0, 5); } void CanvasOGL::drawSolidRect(const rect& r, const Color& fill_color, float rotate) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidRect()"); } void CanvasOGL::drawHollowRect(const rect& r, const Color& stroke_color, float rotate) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowRect()"); } void CanvasOGL::drawLine(const point& p1, const point& p2, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLine()"); } void CanvasOGL::drawLines(const std::vector<glm::vec2>& varray, float line_width, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLines()"); } void CanvasOGL::drawLines(const std::vector<glm::vec2>& varray, float line_width, const std::vector<glm::u8vec4>& carray) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLines()"); } void CanvasOGL::drawLineStrip(const std::vector<glm::vec2>& points, float line_width, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLineStrip()"); } void CanvasOGL::drawLineLoop(const std::vector<glm::vec2>& varray, float line_width, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLineLoop()"); } void CanvasOGL::drawLine(const pointf& p1, const pointf& p2, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLine()"); } void CanvasOGL::drawPolygon(const std::vector<glm::vec2>& points, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawPolygon()"); } void CanvasOGL::drawSolidCircle(const point& centre, double radius, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()"); } void CanvasOGL::drawSolidCircle(const point& centre, double radius, const std::vector<uint8_t>& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()"); } void CanvasOGL::drawHollowCircle(const point& centre, double radius, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowCircle()"); } void CanvasOGL::drawSolidCircle(const pointf& centre, double radius, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()"); } void CanvasOGL::drawSolidCircle(const pointf& centre, double radius, const std::vector<uint8_t>& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()"); } void CanvasOGL::drawHollowCircle(const pointf& centre, double radius, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowCircle()"); } void CanvasOGL::drawPoints(const std::vector<glm::vec2>& points, float radius, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawPoints()"); } CanvasPtr CanvasOGL::getInstance() { return get_instance(); } }
Java
// Copyright 2016 Keybase Inc. All rights reserved. // Use of this source code is governed by a BSD // license that can be found in the LICENSE file. package libkey import ( "context" "github.com/keybase/client/go/kbfs/idutil" "github.com/keybase/client/go/kbfs/kbfscrypto" "github.com/keybase/client/go/kbfs/kbfsmd" "github.com/keybase/client/go/protocol/keybase1" ) // KeyOpsConfig is a config object containing the outside helper // instances needed by KeyOps. type KeyOpsConfig interface { KeyServer() KeyServer KBPKI() idutil.KBPKI } // KeyOpsStandard implements the KeyOps interface and relays get/put // requests for server-side key halves from/to the key server. type KeyOpsStandard struct { config KeyOpsConfig } // NewKeyOpsStandard creates a new KeyOpsStandard instance. func NewKeyOpsStandard(config KeyOpsConfig) *KeyOpsStandard { return &KeyOpsStandard{config} } // Test that KeyOps standard fully implements the KeyOps interface. var _ KeyOps = (*KeyOpsStandard)(nil) // GetTLFCryptKeyServerHalf is an implementation of the KeyOps interface. func (k *KeyOpsStandard) GetTLFCryptKeyServerHalf( ctx context.Context, serverHalfID kbfscrypto.TLFCryptKeyServerHalfID, key kbfscrypto.CryptPublicKey) (kbfscrypto.TLFCryptKeyServerHalf, error) { // get the key half from the server serverHalf, err := k.config.KeyServer().GetTLFCryptKeyServerHalf( ctx, serverHalfID, key) if err != nil { return kbfscrypto.TLFCryptKeyServerHalf{}, err } // get current uid and deviceKID session, err := k.config.KBPKI().GetCurrentSession(ctx) if err != nil { return kbfscrypto.TLFCryptKeyServerHalf{}, err } // verify we got the expected key err = kbfscrypto.VerifyTLFCryptKeyServerHalfID( serverHalfID, session.UID, key, serverHalf) if err != nil { return kbfscrypto.TLFCryptKeyServerHalf{}, err } return serverHalf, nil } // PutTLFCryptKeyServerHalves is an implementation of the KeyOps interface. func (k *KeyOpsStandard) PutTLFCryptKeyServerHalves( ctx context.Context, keyServerHalves kbfsmd.UserDeviceKeyServerHalves) error { // upload the keys return k.config.KeyServer().PutTLFCryptKeyServerHalves(ctx, keyServerHalves) } // DeleteTLFCryptKeyServerHalf is an implementation of the KeyOps interface. func (k *KeyOpsStandard) DeleteTLFCryptKeyServerHalf( ctx context.Context, uid keybase1.UID, key kbfscrypto.CryptPublicKey, serverHalfID kbfscrypto.TLFCryptKeyServerHalfID) error { return k.config.KeyServer().DeleteTLFCryptKeyServerHalf( ctx, uid, key, serverHalfID) }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DataExplorer.Domain.Columns; using DataExplorer.Domain.Layouts; namespace DataExplorer.Domain.Maps.SizeMaps { public class SizeMapFactory : ISizeMapFactory { public SizeMap Create(Column column, double targetMin, double targetMax, SortOrder sortOrder) { if (column.DataType == typeof(Boolean)) return new BooleanToSizeMap(targetMin, targetMax, sortOrder); if (column.DataType == typeof(DateTime)) return new DateTimeToSizeMap( (DateTime)column.Min, (DateTime)column.Max, targetMin, targetMax, sortOrder); if (column.DataType == typeof(Double)) return new FloatToSizeMap( (double)column.Min, (double)column.Max, targetMin, targetMax, sortOrder); if (column.DataType == typeof(Int32)) return new IntegerToSizeMap( (int)column.Min, (int)column.Max, targetMin, targetMax, sortOrder); if (column.DataType == typeof(String)) return new StringToSizeMap( column.Values.Cast<string>().ToList(), targetMin, targetMax, sortOrder); throw new ArgumentException("Column data type is not valid data type for an axis map."); } } }
Java
package com.btr.proxy.search.desktop.gnome; import java.io.File; import java.io.IOException; import java.net.ProxySelector; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.btr.proxy.search.ProxySearchStrategy; import com.btr.proxy.selector.direct.NoProxySelector; import com.btr.proxy.selector.fixed.FixedProxySelector; import com.btr.proxy.selector.misc.ProtocolDispatchSelector; import com.btr.proxy.selector.whitelist.ProxyBypassListSelector; import com.btr.proxy.util.EmptyXMLResolver; import com.btr.proxy.util.Logger; import com.btr.proxy.util.PlatformUtil; import com.btr.proxy.util.ProxyException; import com.btr.proxy.util.ProxyUtil; import com.btr.proxy.util.Logger.LogLevel; /***************************************************************************** * Loads the Gnome proxy settings from the Gnome GConf settings. * <p> * The following settings are extracted from the configuration that is stored * in <i>.gconf</i> folder found in the user's home directory: * </p> * <ul> * <li><i>/system/http_proxy/use_http_proxy</i> -> bool used only by gnome-vfs </li> * <li><i>/system/http_proxy/host</i> -> string "my-proxy.example.com" without "http://"</li> * <li><i>/system/http_proxy/port</i> -> int</li> * <li><i>/system/http_proxy/use_authentication</i> -> bool</li> * <li><i>/system/http_proxy/authentication_user</i> -> string</li> * <li><i>/system/http_proxy/authentication_password</i> -> string</li> * <li><i>/system/http_proxy/ignore_hosts</i> -> list-of-string</li> * <li><i>/system/proxy/mode</i> -> string THIS IS THE CANONICAL KEY; SEE BELOW</li> * <li><i>/system/proxy/secure_host</i> -> string "proxy-for-https.example.com"</li> * <li><i>/system/proxy/secure_port</i> -> int</li> * <li><i>/system/proxy/ftp_host</i> -> string "proxy-for-ftp.example.com"</li> * <li><i>/system/proxy/ftp_port</i> -> int</li> * <li><i>/system/proxy/socks_host</i> -> string "proxy-for-socks.example.com"</li> * <li><i>/system/proxy/socks_port</i> -> int</li> * <li><i>/system/proxy/autoconfig_url</i> -> string "http://proxy-autoconfig.example.com"</li> * </ul> * <i>/system/proxy/mode</i> can be either:<br/> * "none" -> No proxy is used<br/> * "manual" -> The user's configuration values are used (/system/http_proxy/{host,port,etc.})<br/> * "auto" -> The "/system/proxy/autoconfig_url" key is used <br/> * <p> * GNOME Proxy_configuration settings are explained * <a href="http://en.opensuse.org/GNOME/Proxy_configuration">here</a> in detail * </p> * @author Bernd Rosstauscher (proxyvole@rosstauscher.de) Copyright 2009 ****************************************************************************/ public class GnomeProxySearchStrategy implements ProxySearchStrategy { /************************************************************************* * ProxySelector * @see java.net.ProxySelector#ProxySelector() ************************************************************************/ public GnomeProxySearchStrategy() { super(); } /************************************************************************* * Loads the proxy settings and initializes a proxy selector for the Gnome * proxy settings. * @return a configured ProxySelector, null if none is found. * @throws ProxyException on file reading error. ************************************************************************/ public ProxySelector getProxySelector() throws ProxyException { Logger.log(getClass(), LogLevel.TRACE, "Detecting Gnome proxy settings"); Properties settings = readSettings(); String type = settings.getProperty("/system/proxy/mode"); ProxySelector result = null; if (type == null) { String useProxy = settings.getProperty("/system/http_proxy/use_http_proxy"); if (useProxy == null) { return null; } type = Boolean.parseBoolean(useProxy)?"manual":"none"; } if ("none".equals(type)) { Logger.log(getClass(), LogLevel.TRACE, "Gnome uses no proxy"); result = NoProxySelector.getInstance(); } if ("manual".equals(type)) { Logger.log(getClass(), LogLevel.TRACE, "Gnome uses manual proxy settings"); result = setupFixedProxySelector(settings); } if ("auto".equals(type)) { String pacScriptUrl = settings.getProperty("/system/proxy/autoconfig_url", ""); Logger.log(getClass(), LogLevel.TRACE, "Gnome uses autodetect script {0}", pacScriptUrl); result = ProxyUtil.buildPacSelectorForUrl(pacScriptUrl); } // Wrap into white-list filter? String noProxyList = settings.getProperty("/system/http_proxy/ignore_hosts", null); if (result != null && noProxyList != null && noProxyList.trim().length() > 0) { Logger.log(getClass(), LogLevel.TRACE, "Gnome uses proxy bypass list: {0}", noProxyList); result = new ProxyBypassListSelector(noProxyList, result); } return result; } /************************************************************************* * Load the proxy settings from the gconf settings XML file. * @return the loaded settings stored in a properties object. * @throws ProxyException on processing error. ************************************************************************/ public Properties readSettings() throws ProxyException { Properties settings = new Properties(); try { parseSettings("/system/proxy/", settings); parseSettings("/system/http_proxy/", settings); } catch (IOException e) { Logger.log(getClass(), LogLevel.ERROR, "Gnome settings file error.", e); throw new ProxyException(e); } return settings; } /************************************************************************* * Finds the Gnome GConf settings file. * @param context the gconf context to parse. * @return a file or null if does not exist. ************************************************************************/ private File findSettingsFile(String context) { // Normally we should inspect /etc/gconf/<version>/path to find out where the actual file is. // But for normal systems this is always stored in .gconf folder in the user's home directory. File userDir = new File(PlatformUtil.getUserHomeDir()); // Build directory path for context StringBuilder path = new StringBuilder(); String[] parts = context.split("/"); for (String part : parts) { path.append(part); path.append(File.separator); } File settingsFile = new File(userDir, ".gconf"+File.separator+path.toString()+"%gconf.xml"); if (!settingsFile.exists()) { Logger.log(getClass(), LogLevel.WARNING, "Gnome settings: {0} not found.", settingsFile); return null; } return settingsFile; } /************************************************************************* * Parse the fixed proxy settings and build an ProxySelector for this a * chained configuration. * @param settings the proxy settings to evaluate. ************************************************************************/ private ProxySelector setupFixedProxySelector(Properties settings) { if (!hasProxySettings(settings)) { return null; } ProtocolDispatchSelector ps = new ProtocolDispatchSelector(); installHttpSelector(settings, ps); if (useForAllProtocols(settings)) { ps.setFallbackSelector(ps.getSelector("http")); } else { installSecureSelector(settings, ps); installFtpSelector(settings, ps); installSocksSelector(settings, ps); } return ps; } /************************************************************************* * Check if the http proxy should also be used for all other protocols. * @param settings to inspect. * @return true if only one proxy is configured else false. ************************************************************************/ private boolean useForAllProtocols(Properties settings) { return Boolean.parseBoolean( settings.getProperty("/system/http_proxy/use_same_proxy", "false")); } /************************************************************************* * Checks if we have Proxy configuration settings in the properties. * @param settings to inspect. * @return true if we have found Proxy settings. ************************************************************************/ private boolean hasProxySettings(Properties settings) { String proxyHost = settings.getProperty("/system/http_proxy/host", null); return proxyHost != null && proxyHost.length() > 0; } /************************************************************************* * Install a http proxy from the given settings. * @param settings to inspect * @param ps the dispatch selector to configure. * @throws NumberFormatException ************************************************************************/ private void installHttpSelector(Properties settings, ProtocolDispatchSelector ps) throws NumberFormatException { String proxyHost = settings.getProperty("/system/http_proxy/host", null); int proxyPort = Integer.parseInt(settings.getProperty("/system/http_proxy/port", "0").trim()); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { Logger.log(getClass(), LogLevel.TRACE, "Gnome http proxy is {0}:{1}", proxyHost, proxyPort); ps.setSelector("http", new FixedProxySelector(proxyHost.trim(), proxyPort)); } } /************************************************************************* * Install a socks proxy from the given settings. * @param settings to inspect * @param ps the dispatch selector to configure. * @throws NumberFormatException ************************************************************************/ private void installSocksSelector(Properties settings, ProtocolDispatchSelector ps) throws NumberFormatException { String proxyHost = settings.getProperty("/system/proxy/socks_host", null); int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/socks_port", "0").trim()); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { Logger.log(getClass(), LogLevel.TRACE, "Gnome socks proxy is {0}:{1}", proxyHost, proxyPort); ps.setSelector("socks", new FixedProxySelector(proxyHost.trim(), proxyPort)); } } /************************************************************************* * @param settings * @param ps * @throws NumberFormatException ************************************************************************/ private void installFtpSelector(Properties settings, ProtocolDispatchSelector ps) throws NumberFormatException { String proxyHost = settings.getProperty("/system/proxy/ftp_host", null); int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/ftp_port", "0").trim()); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { Logger.log(getClass(), LogLevel.TRACE, "Gnome ftp proxy is {0}:{1}", proxyHost, proxyPort); ps.setSelector("ftp", new FixedProxySelector(proxyHost.trim(), proxyPort)); } } /************************************************************************* * @param settings * @param ps * @throws NumberFormatException ************************************************************************/ private void installSecureSelector(Properties settings, ProtocolDispatchSelector ps) throws NumberFormatException { String proxyHost = settings.getProperty("/system/proxy/secure_host", null); int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/secure_port", "0").trim()); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { Logger.log(getClass(), LogLevel.TRACE, "Gnome secure proxy is {0}:{1}", proxyHost, proxyPort); ps.setSelector("https", new FixedProxySelector(proxyHost.trim(), proxyPort)); ps.setSelector("sftp", new FixedProxySelector(proxyHost.trim(), proxyPort)); } } /************************************************************************* * Parse the settings file and extract all network.proxy.* settings from it. * @param context the gconf context to parse. * @param settings the settings object to fill. * @return the parsed properties. * @throws IOException on read error. ************************************************************************/ private Properties parseSettings(String context, Properties settings) throws IOException { // Read settings from file File settingsFile = findSettingsFile(context); if (settingsFile == null) { return settings; } try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); documentBuilder.setEntityResolver(new EmptyXMLResolver()); Document doc = documentBuilder.parse(settingsFile); Element root = doc.getDocumentElement(); Node entry = root.getFirstChild(); while (entry != null) { if ("entry".equals(entry.getNodeName()) && entry instanceof Element) { String entryName = ((Element)entry).getAttribute("name"); settings.setProperty(context+entryName, getEntryValue((Element) entry)); } entry = entry.getNextSibling(); } } catch (SAXException e) { Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e); throw new IOException(e.getMessage()); } catch (ParserConfigurationException e) { Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e); throw new IOException(e.getMessage()); } return settings; } /************************************************************************* * Parse an entry value from a given entry node. * @param entry the XML node to inspect. * @return the value, null if it has no value. ************************************************************************/ private String getEntryValue(Element entry) { String type = entry.getAttribute("type"); if ("int".equals(type) || "bool".equals(type)) { return entry.getAttribute("value"); } if ("string".equals(type)) { NodeList list = entry.getElementsByTagName("stringvalue"); if (list.getLength() > 0) { return list.item(0).getTextContent(); } } if ("list".equals(type)) { StringBuilder result = new StringBuilder(); NodeList list = entry.getElementsByTagName("li"); // Build comma separated list of items for (int i = 0; i < list.getLength(); i++) { if (result.length() > 0) { result.append(","); } result.append(getEntryValue((Element) list.item(i))); } return result.toString(); } return null; } }
Java
/* * Copyright (C) 2014 The Async HBase Authors. All rights reserved. * This file is part of Async HBase. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the StumbleUpon nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.hbase.async; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mock; import java.nio.charset.Charset; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.hbase.async.HBaseClient.ZKClient; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.channel.socket.SocketChannelConfig; import org.jboss.netty.channel.socket.nio.NioClientBossPool; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioWorkerPool; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.TimerTask; import org.junit.Before; import org.junit.Ignore; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.reflect.Whitebox; import com.stumbleupon.async.Deferred; @PrepareForTest({ HBaseClient.class, RegionClient.class, HBaseRpc.class, GetRequest.class, RegionInfo.class, NioClientSocketChannelFactory.class, Executors.class, HashedWheelTimer.class, NioClientBossPool.class, NioWorkerPool.class }) @Ignore // ignore for test runners public class BaseTestHBaseClient { protected static final Charset CHARSET = Charset.forName("ASCII"); protected static final byte[] COMMA = { ',' }; protected static final byte[] TIMESTAMP = "1234567890".getBytes(); protected static final byte[] INFO = getStatic("INFO"); protected static final byte[] REGIONINFO = getStatic("REGIONINFO"); protected static final byte[] SERVER = getStatic("SERVER"); protected static final byte[] TABLE = { 't', 'a', 'b', 'l', 'e' }; protected static final byte[] KEY = { 'k', 'e', 'y' }; protected static final byte[] KEY2 = { 'k', 'e', 'y', '2' }; protected static final byte[] FAMILY = { 'f' }; protected static final byte[] QUALIFIER = { 'q', 'u', 'a', 'l' }; protected static final byte[] VALUE = { 'v', 'a', 'l', 'u', 'e' }; protected static final byte[] EMPTY_ARRAY = new byte[0]; protected static final KeyValue KV = new KeyValue(KEY, FAMILY, QUALIFIER, VALUE); protected static final RegionInfo meta = mkregion(".META.", ".META.,,1234567890"); protected static final RegionInfo region = mkregion("table", "table,,1234567890"); protected static final int RS_PORT = 50511; protected static final String ROOT_IP = "192.168.0.1"; protected static final String META_IP = "192.168.0.2"; protected static final String REGION_CLIENT_IP = "192.168.0.3"; protected static String MOCK_RS_CLIENT_NAME = "Mock RegionClient"; protected static String MOCK_ROOT_CLIENT_NAME = "Mock RootClient"; protected static String MOCK_META_CLIENT_NAME = "Mock MetaClient"; protected HBaseClient client = null; /** Extracted from {@link #client}. */ protected ConcurrentSkipListMap<byte[], RegionInfo> regions_cache; /** Extracted from {@link #client}. */ protected ConcurrentHashMap<RegionInfo, RegionClient> region2client; /** Extracted from {@link #client}. */ protected ConcurrentHashMap<RegionClient, ArrayList<RegionInfo>> client2regions; /** Extracted from {@link #client}. */ protected ConcurrentSkipListMap<byte[], ArrayList<HBaseRpc>> got_nsre; /** Extracted from {@link #client}. */ protected HashMap<String, RegionClient> ip2client; /** Extracted from {@link #client}. */ protected Counter num_nsre_rpcs; /** Fake client supposedly connected to -ROOT-. */ protected RegionClient rootclient; /** Fake client supposedly connected to .META.. */ protected RegionClient metaclient; /** Fake client supposedly connected to our fake test table. */ protected RegionClient regionclient; /** Each new region client is dumped here */ protected List<RegionClient> region_clients = new ArrayList<RegionClient>(); /** Fake Zookeeper client */ protected ZKClient zkclient; /** Fake channel factory */ protected NioClientSocketChannelFactory channel_factory; /** Fake channel returned from the factory */ protected SocketChannel chan; /** Fake timer for testing */ protected FakeTimer timer; @Before public void before() throws Exception { region_clients.clear(); rootclient = mock(RegionClient.class); when(rootclient.toString()).thenReturn(MOCK_ROOT_CLIENT_NAME); metaclient = mock(RegionClient.class); when(metaclient.toString()).thenReturn(MOCK_META_CLIENT_NAME); regionclient = mock(RegionClient.class); when(regionclient.toString()).thenReturn(MOCK_RS_CLIENT_NAME); zkclient = mock(ZKClient.class); channel_factory = mock(NioClientSocketChannelFactory.class); chan = mock(SocketChannel.class); timer = new FakeTimer(); when(zkclient.getDeferredRoot()).thenReturn(new Deferred<Object>()); PowerMockito.mockStatic(Executors.class); PowerMockito.when(Executors.defaultThreadFactory()) .thenReturn(mock(ThreadFactory.class)); PowerMockito.when(Executors.newCachedThreadPool()) .thenReturn(mock(ExecutorService.class)); PowerMockito.whenNew(NioClientSocketChannelFactory.class).withAnyArguments() .thenReturn(channel_factory); PowerMockito.whenNew(HashedWheelTimer.class).withAnyArguments() .thenReturn(timer); PowerMockito.whenNew(NioClientBossPool.class).withAnyArguments() .thenReturn(mock(NioClientBossPool.class)); PowerMockito.whenNew(NioWorkerPool.class).withAnyArguments() .thenReturn(mock(NioWorkerPool.class)); client = PowerMockito.spy(new HBaseClient("test-quorum-spec")); Whitebox.setInternalState(client, "zkclient", zkclient); Whitebox.setInternalState(client, "rootregion", rootclient); Whitebox.setInternalState(client, "jitter_percent", 0); regions_cache = Whitebox.getInternalState(client, "regions_cache"); region2client = Whitebox.getInternalState(client, "region2client"); client2regions = Whitebox.getInternalState(client, "client2regions"); got_nsre = Whitebox.getInternalState(client, "got_nsre"); ip2client = Whitebox.getInternalState(client, "ip2client"); injectRegionInCache(meta, metaclient, META_IP + ":" + RS_PORT); injectRegionInCache(region, regionclient, REGION_CLIENT_IP + ":" + RS_PORT); when(channel_factory.newChannel(any(ChannelPipeline.class))) .thenReturn(chan); when(chan.getConfig()).thenReturn(mock(SocketChannelConfig.class)); when(rootclient.toString()).thenReturn("Mock RootClient"); PowerMockito.doAnswer(new Answer<RegionClient>(){ @Override public RegionClient answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final String endpoint = (String)args[0] + ":" + (Integer)args[1]; final RegionClient rc = mock(RegionClient.class); when(rc.getRemoteAddress()).thenReturn(endpoint); client2regions.put(rc, new ArrayList<RegionInfo>()); region_clients.add(rc); return rc; } }).when(client, "newClient", anyString(), anyInt()); } /** * Injects an entry in the local caches of the client. */ protected void injectRegionInCache(final RegionInfo region, final RegionClient client, final String ip) { regions_cache.put(region.name(), region); region2client.put(region, client); ArrayList<RegionInfo> regions = client2regions.get(client); if (regions == null) { regions = new ArrayList<RegionInfo>(1); client2regions.put(client, regions); } regions.add(region); ip2client.put(ip, client); } // ----------------- // // Helper functions. // // ----------------- // protected void clearCaches(){ regions_cache.clear(); region2client.clear(); client2regions.clear(); } protected static <T> T getStatic(final String fieldname) { return Whitebox.getInternalState(HBaseClient.class, fieldname); } /** * Creates a fake {@code .META.} row. * The row contains a single entry for all keys of {@link #TABLE}. */ protected static ArrayList<KeyValue> metaRow() { return metaRow(HBaseClient.EMPTY_ARRAY, HBaseClient.EMPTY_ARRAY); } /** * Creates a fake {@code .META.} row. * The row contains a single entry for {@link #TABLE}. * @param start_key The start key of the region in this entry. * @param stop_key The stop key of the region in this entry. */ protected static ArrayList<KeyValue> metaRow(final byte[] start_key, final byte[] stop_key) { final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2); row.add(metaRegionInfo(start_key, stop_key, false, false, TABLE)); row.add(new KeyValue(region.name(), INFO, SERVER, "localhost:54321".getBytes())); return row; } protected static KeyValue metaRegionInfo( final byte[] start_key, final byte[] stop_key, final boolean offline, final boolean splitting, final byte[] table) { final byte[] name = concat(table, COMMA, start_key, COMMA, TIMESTAMP); final byte is_splitting = (byte) (splitting ? 1 : 0); final byte[] regioninfo = concat( new byte[] { 0, // version (byte) stop_key.length, // vint: stop key length }, stop_key, offline ? new byte[] { 1 } : new byte[] { 0 }, // boolean: offline Bytes.fromLong(name.hashCode()), // long: region ID (make it random) new byte[] { (byte) name.length }, // vint: region name length name, // region name new byte[] { is_splitting, // boolean: splitting (byte) start_key.length, // vint: start key length }, start_key ); return new KeyValue(region.name(), INFO, REGIONINFO, regioninfo); } protected static RegionInfo mkregion(final String table, final String name) { return new RegionInfo(table.getBytes(), name.getBytes(), HBaseClient.EMPTY_ARRAY); } protected static byte[] anyBytes() { return any(byte[].class); } /** Concatenates byte arrays together. */ protected static byte[] concat(final byte[]... arrays) { int len = 0; for (final byte[] array : arrays) { len += array.length; } final byte[] result = new byte[len]; len = 0; for (final byte[] array : arrays) { System.arraycopy(array, 0, result, len, array.length); len += array.length; } return result; } /** Creates a new Deferred that's already called back. */ protected static <T> Answer<Deferred<T>> newDeferred(final T result) { return new Answer<Deferred<T>>() { public Deferred<T> answer(final InvocationOnMock invocation) { return Deferred.fromResult(result); } }; } /** * A fake {@link Timer} implementation that fires up tasks immediately. * Tasks are called immediately from the current thread and a history of the * various tasks is logged. */ static final class FakeTimer extends HashedWheelTimer { final List<Map.Entry<TimerTask, Long>> tasks = new ArrayList<Map.Entry<TimerTask, Long>>(); final ArrayList<Timeout> timeouts = new ArrayList<Timeout>(); boolean run = true; @Override public Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) { try { tasks.add(new AbstractMap.SimpleEntry<TimerTask, Long>(task, delay)); if (run) { task.run(null); // Argument never used in this code base. } final Timeout timeout = mock(Timeout.class); timeouts.add(timeout); return timeout; // Return value never used in this code base. } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Timer task failed: " + task, e); } } @Override public Set<Timeout> stop() { run = false; return new HashSet<Timeout>(timeouts); } } /** * A fake {@link org.jboss.netty.util.Timer} implementation. * Instead of executing the task it will store that task in a internal state * and provides a function to start the execution of the stored task. * This implementation thus allows the flexibility of simulating the * things that will be going on during the time out period of a TimerTask. * This was mainly return to simulate the timeout period for * alreadyNSREdRegion test, where the region will be in the NSREd mode only * during this timeout period, which was difficult to simulate using the * above {@link FakeTimer} implementation, as we don't get back the control * during the timeout period * * Here it will hold at most two Tasks. We have two tasks here because when * one is being executed, it may call for newTimeOut for another task. */ static final class FakeTaskTimer extends HashedWheelTimer { protected TimerTask newPausedTask = null; protected TimerTask pausedTask = null; @Override public synchronized Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) { if (pausedTask == null) { pausedTask = task; } else if (newPausedTask == null) { newPausedTask = task; } else { throw new IllegalStateException("Cannot Pause Two Timer Tasks"); } return null; } @Override public Set<Timeout> stop() { return null; } public boolean continuePausedTask() { if (pausedTask == null) { return false; } try { if (newPausedTask != null) { throw new IllegalStateException("Cannot be in this state"); } pausedTask.run(null); // Argument never used in this code base pausedTask = newPausedTask; newPausedTask = null; return true; } catch (Exception e) { throw new RuntimeException("Timer task failed: " + pausedTask, e); } } } /** * Generate and return a mocked HBase RPC for testing purposes with a valid * Deferred that can be called on execution. * @param deferred A deferred to watch for results * @return The RPC to pass through unit tests. */ protected HBaseRpc getMockHBaseRpc(final Deferred<Object> deferred) { final HBaseRpc rpc = mock(HBaseRpc.class); rpc.attempt = 0; when(rpc.getDeferred()).thenReturn(deferred); when(rpc.toString()).thenReturn("MockRPC"); PowerMockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { if (deferred != null) { deferred.callback(invocation.getArguments()[0]); } else { System.out.println("Deferred was null!!"); } return null; } }).when(rpc).callback(Object.class); return rpc; } }
Java
#include "gb_thread.hpp" #include "z80.hpp" #include "memory.hpp" #include "rom.hpp" #include "cart_rom_only.hpp" #include "cart_mbc1.hpp" #include "cart_mbc5.hpp" #include "internal_ram.hpp" #include "video.hpp" #include "timer.hpp" #include "joypad.hpp" #include "sound.hpp" #include "debug.hpp" #include "assert.hpp" #include <cstdlib> #include <vector> #include <fstream> #include <memory> #include <chrono> namespace { class stop_exception {}; std::unique_ptr<gb::memory_mapping> init_cartridge(gb::rom rom) { switch (rom.cartridge()) { case 0x00: // ROM only (could have little RAM) return std::make_unique<gb::cart_rom_only>(std::move(rom)); case 0x01: // MBC1 case 0x02: // MBC1+RAM case 0x03: // MBC1+RAM+BATTERY return std::make_unique<gb::cart_mbc1>(std::move(rom)); case 0x19: // MBC5 case 0x1A: // MBC5+RAM case 0x1B: // MBC5+RAM+BATTERY return std::make_unique<gb::cart_mbc5>(std::move(rom)); default: throw gb::unsupported_rom_exception("Unknown cartridge type"); } } std::unique_ptr<gb::z80_cpu> init_cpu(gb::memory_mapping &cart, gb::internal_ram &internal_ram, gb::video &video, gb::timer &timer, gb::joypad &joypad, gb::sound &sound) { // Make Memory gb::memory_map memory; memory.add_mapping(&cart); memory.add_mapping(&internal_ram); memory.add_mapping(&video); memory.add_mapping(&timer); memory.add_mapping(&joypad); memory.add_mapping(&sound); memory.write8(0xff05, 0x00); memory.write8(0xff06, 0x00); memory.write8(0xff07, 0x00); memory.write8(0xff10, 0x80); memory.write8(0xff11, 0xbf); memory.write8(0xff12, 0xf3); memory.write8(0xff14, 0xbf); memory.write8(0xff16, 0x3f); memory.write8(0xff17, 0x00); memory.write8(0xff19, 0xbf); memory.write8(0xff1a, 0x7f); memory.write8(0xff1b, 0xff); memory.write8(0xff1c, 0x9f); memory.write8(0xff1e, 0xbf); memory.write8(0xff20, 0xff); memory.write8(0xff21, 0x00); memory.write8(0xff22, 0x00); memory.write8(0xff23, 0xbf); memory.write8(0xff24, 0x77); memory.write8(0xff25, 0xf3); memory.write8(0xff26, 0xf1); memory.write8(0xff40, 0x91); memory.write8(0xff42, 0x00); memory.write8(0xff43, 0x00); memory.write8(0xff45, 0x00); memory.write8(0xff47, 0xfc); memory.write8(0xff48, 0xff); memory.write8(0xff49, 0xff); memory.write8(0xff4a, 0x00); memory.write8(0xff4b, 0x00); memory.write8(0xffff, 0x00); // Register file gb::register_file registers; registers.write8<gb::register8::a>(0x11); registers.write8<gb::register8::f>(0xb0); registers.write16<gb::register16::bc>(0x0013); registers.write16<gb::register16::de>(0x00d8); registers.write16<gb::register16::hl>(0x014d); registers.write16<gb::register16::sp>(0xfffe); registers.write16<gb::register16::pc>(0x0100); // Make Cpu return std::make_unique<gb::z80_cpu>(std::move(memory), std::move(registers)); } } gb::gb_hardware::gb_hardware(rom arg_rom) : cartridge(init_cartridge(std::move(arg_rom))), cpu(init_cpu(*cartridge, internal_ram, video, timer, joypad, sound)) { } #define HEAVY_DEBUG 0 gb::cputime gb::gb_hardware::tick() { const auto time_fde = cpu->fetch_decode_execute(); #if HEAVY_DEBUG switch (cpu->current_opcode()->extra_bytes) { case 0: debug(cpu->current_opcode()->mnemonic); break; case 1: debug(cpu->current_opcode()->mnemonic, " $=", static_cast<int>(cpu->value8())); break; case 2: debug(cpu->current_opcode()->mnemonic, " $=", static_cast<int>(cpu->value16())); break; default: ASSERT_UNREACHABLE(); } #endif timer.tick(*cpu, time_fde); const auto time_r = cpu->read(); timer.tick(*cpu, time_r); const auto time_w = cpu->write(); timer.tick(*cpu, time_w); const auto time = time_fde + time_r + time_w; video.tick(*cpu, time); #if HEAVY_DEBUG cpu->registers().debug_print(); #endif return time; } gb::gb_thread::gb_thread() : _running(false) { } gb::gb_thread::~gb_thread() { post_stop(); join(); } void gb::gb_thread::start(gb::rom rom) { ASSERT(!_running); _gb = std::make_unique<gb_hardware>(std::move(rom)); _thread = std::thread(&gb_thread::run, this); _running = true; } void gb::gb_thread::join() { if (_running) { _thread.join(); } } void gb::gb_thread::post_stop() { command fn([](){ throw stop_exception(); }); std::lock_guard<std::mutex> lock(_mutex); _command_queue.emplace_back(std::move(fn)); } std::future<gb::video::raw_image> gb::gb_thread::post_get_image() { // TODO use capture by move (Visual Studio 2015/C++14) auto promise = std::make_shared<std::promise<video::raw_image>>(); auto future = promise->get_future(); command fn([this, promise]() { promise->set_value(_gb->video.image()); }); std::lock_guard<std::mutex> lock(_mutex); _command_queue.emplace_back(std::move(fn)); return future; } void gb::gb_thread::post_key_down(gb::key key) { command fn([this, key]() { _gb->joypad.down(key); }); std::lock_guard<std::mutex> lock(_mutex); _command_queue.emplace_back(std::move(fn)); } void gb::gb_thread::post_key_up(gb::key key) { command fn([this, key]() { _gb->joypad.up(key); }); std::lock_guard<std::mutex> lock(_mutex); _command_queue.emplace_back(std::move(fn)); } void gb::gb_thread::run() { using namespace std::chrono; using clock = steady_clock; static_assert(clock::is_steady, "clock not steady"); static_assert(std::ratio_less_equal<clock::period, std::ratio_multiply<std::ratio<100>, std::nano>>::value, "clock too inaccurate (period > 100ns)"); if (ASSERT_ENABLED) debug("WARNING: asserts are enabled!"); debug("====================================================="); // Let's go :) std::vector<command> current_commands; cputime gb_time(0); auto real_time_start = clock::now(); cputime performance_gb_time(0); nanoseconds performance_sleep_time(0); auto performance_start = clock::now(); try { while (true) { // Command stream { std::lock_guard<std::mutex> lock(_mutex); if (!_command_queue.empty()) { std::swap(current_commands, _command_queue); } } if (!current_commands.empty()) { for (const auto &command : current_commands) { command(); } current_commands.clear(); } // Simulation itself const auto time = _gb->tick(); // Time bookkeeping gb_time += time; const auto real_time = clock::now() - real_time_start; const auto drift = duration_cast<nanoseconds>(gb_time) - real_time; if (drift > milliseconds(5)) { // Simulation is too fast const auto sleep_start = clock::now(); std::this_thread::sleep_for(drift); performance_sleep_time += (clock::now() - sleep_start); const auto new_current_time = clock::now(); const auto new_real_time = new_current_time - real_time_start; const auto new_drift = gb_time - duration_cast<cputime>(new_real_time); gb_time = new_drift; real_time_start = new_current_time; } else if (drift < milliseconds(-100)) { // Simulation is too slow (reset counter to avoid an endless accumulation of negaitve time) // This is a resync-attempt in case of a spike and avoids underflow gb_time = cputime(0); real_time_start = clock::now(); } // Performance-o-meter performance_gb_time += time; const auto performance_now = clock::now(); const auto performance_real_time = performance_now - performance_start; if (performance_real_time > seconds(10)) { const auto accuracy = duration_cast<milliseconds>(performance_gb_time - performance_real_time).count(); const double speed = static_cast<double>(duration_cast<nanoseconds>(performance_gb_time).count()) / static_cast<double>(duration_cast<nanoseconds>(performance_real_time - performance_sleep_time).count()) * 100.0; debug("PERF: simulation drift in the last 10 s was ", accuracy, " ms"); debug("PERF: simulation speed in the last 10 s was ", speed, " % of required speed"); if (speed < 110.0) { debug("PERF WARNING: simulation speed is too low (< 110 %)"); } performance_sleep_time = seconds(0); performance_gb_time = cputime(0); performance_start = performance_now; } } } catch (const stop_exception &) { // this might be ugly but it works well :) } }
Java
# Verified-BPF Initial tinkering with a BPF metalanguage and implementation formally verified in Coq.
Java
//M*////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ /****************************************************************************************\ * Very fast SAD-based (Sum-of-Absolute-Diffrences) stereo correspondence algorithm. * * Contributed by Kurt Konolige * \****************************************************************************************/ #include "precomp.hpp" #include <stdio.h> #include <limits> #include "opencl_kernels_calib3d.hpp" namespace cv { struct StereoBMParams { StereoBMParams(int _numDisparities=64, int _SADWindowSize=21) { preFilterType = StereoBM::PREFILTER_XSOBEL; preFilterSize = 9; preFilterCap = 31; SADWindowSize = _SADWindowSize; minDisparity = 0; numDisparities = _numDisparities > 0 ? _numDisparities : 64; textureThreshold = 10; uniquenessRatio = 15; speckleRange = speckleWindowSize = 0; roi1 = roi2 = Rect(0,0,0,0); disp12MaxDiff = -1; dispType = CV_16S; } int preFilterType; int preFilterSize; int preFilterCap; int SADWindowSize; int minDisparity; int numDisparities; int textureThreshold; int uniquenessRatio; int speckleRange; int speckleWindowSize; Rect roi1, roi2; int disp12MaxDiff; int dispType; }; static bool ocl_prefilter_norm(InputArray _input, OutputArray _output, int winsize, int prefilterCap) { ocl::Kernel k("prefilter_norm", ocl::calib3d::stereobm_oclsrc, cv::format("-D WSZ=%d", winsize)); if(k.empty()) return false; int scale_g = winsize*winsize/8, scale_s = (1024 + scale_g)/(scale_g*2); scale_g *= scale_s; UMat input = _input.getUMat(), output; _output.create(input.size(), input.type()); output = _output.getUMat(); size_t globalThreads[3] = { input.cols, input.rows, 1 }; k.args(ocl::KernelArg::PtrReadOnly(input), ocl::KernelArg::PtrWriteOnly(output), input.rows, input.cols, prefilterCap, scale_g, scale_s); return k.run(2, globalThreads, NULL, false); } static void prefilterNorm( const Mat& src, Mat& dst, int winsize, int ftzero, uchar* buf ) { int x, y, wsz2 = winsize/2; int* vsum = (int*)alignPtr(buf + (wsz2 + 1)*sizeof(vsum[0]), 32); int scale_g = winsize*winsize/8, scale_s = (1024 + scale_g)/(scale_g*2); const int OFS = 256*5, TABSZ = OFS*2 + 256; uchar tab[TABSZ]; const uchar* sptr = src.ptr(); int srcstep = (int)src.step; Size size = src.size(); scale_g *= scale_s; for( x = 0; x < TABSZ; x++ ) tab[x] = (uchar)(x - OFS < -ftzero ? 0 : x - OFS > ftzero ? ftzero*2 : x - OFS + ftzero); for( x = 0; x < size.width; x++ ) vsum[x] = (ushort)(sptr[x]*(wsz2 + 2)); for( y = 1; y < wsz2; y++ ) { for( x = 0; x < size.width; x++ ) vsum[x] = (ushort)(vsum[x] + sptr[srcstep*y + x]); } for( y = 0; y < size.height; y++ ) { const uchar* top = sptr + srcstep*MAX(y-wsz2-1,0); const uchar* bottom = sptr + srcstep*MIN(y+wsz2,size.height-1); const uchar* prev = sptr + srcstep*MAX(y-1,0); const uchar* curr = sptr + srcstep*y; const uchar* next = sptr + srcstep*MIN(y+1,size.height-1); uchar* dptr = dst.ptr<uchar>(y); for( x = 0; x < size.width; x++ ) vsum[x] = (ushort)(vsum[x] + bottom[x] - top[x]); for( x = 0; x <= wsz2; x++ ) { vsum[-x-1] = vsum[0]; vsum[size.width+x] = vsum[size.width-1]; } int sum = vsum[0]*(wsz2 + 1); for( x = 1; x <= wsz2; x++ ) sum += vsum[x]; int val = ((curr[0]*5 + curr[1] + prev[0] + next[0])*scale_g - sum*scale_s) >> 10; dptr[0] = tab[val + OFS]; for( x = 1; x < size.width-1; x++ ) { sum += vsum[x+wsz2] - vsum[x-wsz2-1]; val = ((curr[x]*4 + curr[x-1] + curr[x+1] + prev[x] + next[x])*scale_g - sum*scale_s) >> 10; dptr[x] = tab[val + OFS]; } sum += vsum[x+wsz2] - vsum[x-wsz2-1]; val = ((curr[x]*5 + curr[x-1] + prev[x] + next[x])*scale_g - sum*scale_s) >> 10; dptr[x] = tab[val + OFS]; } } static bool ocl_prefilter_xsobel(InputArray _input, OutputArray _output, int prefilterCap) { ocl::Kernel k("prefilter_xsobel", ocl::calib3d::stereobm_oclsrc); if(k.empty()) return false; UMat input = _input.getUMat(), output; _output.create(input.size(), input.type()); output = _output.getUMat(); size_t globalThreads[3] = { input.cols, input.rows, 1 }; k.args(ocl::KernelArg::PtrReadOnly(input), ocl::KernelArg::PtrWriteOnly(output), input.rows, input.cols, prefilterCap); return k.run(2, globalThreads, NULL, false); } static void prefilterXSobel( const Mat& src, Mat& dst, int ftzero ) { int x, y; const int OFS = 256*4, TABSZ = OFS*2 + 256; uchar tab[TABSZ]; Size size = src.size(); for( x = 0; x < TABSZ; x++ ) tab[x] = (uchar)(x - OFS < -ftzero ? 0 : x - OFS > ftzero ? ftzero*2 : x - OFS + ftzero); uchar val0 = tab[0 + OFS]; #if CV_SSE2 volatile bool useSIMD = checkHardwareSupport(CV_CPU_SSE2); #endif for( y = 0; y < size.height-1; y += 2 ) { const uchar* srow1 = src.ptr<uchar>(y); const uchar* srow0 = y > 0 ? srow1 - src.step : size.height > 1 ? srow1 + src.step : srow1; const uchar* srow2 = y < size.height-1 ? srow1 + src.step : size.height > 1 ? srow1 - src.step : srow1; const uchar* srow3 = y < size.height-2 ? srow1 + src.step*2 : srow1; uchar* dptr0 = dst.ptr<uchar>(y); uchar* dptr1 = dptr0 + dst.step; dptr0[0] = dptr0[size.width-1] = dptr1[0] = dptr1[size.width-1] = val0; x = 1; #if CV_SSE2 if( useSIMD ) { __m128i z = _mm_setzero_si128(), ftz = _mm_set1_epi16((short)ftzero), ftz2 = _mm_set1_epi8(cv::saturate_cast<uchar>(ftzero*2)); for( ; x <= size.width-9; x += 8 ) { __m128i c0 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow0 + x - 1)), z); __m128i c1 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow1 + x - 1)), z); __m128i d0 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow0 + x + 1)), z); __m128i d1 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow1 + x + 1)), z); d0 = _mm_sub_epi16(d0, c0); d1 = _mm_sub_epi16(d1, c1); __m128i c2 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow2 + x - 1)), z); __m128i c3 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow3 + x - 1)), z); __m128i d2 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow2 + x + 1)), z); __m128i d3 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow3 + x + 1)), z); d2 = _mm_sub_epi16(d2, c2); d3 = _mm_sub_epi16(d3, c3); __m128i v0 = _mm_add_epi16(d0, _mm_add_epi16(d2, _mm_add_epi16(d1, d1))); __m128i v1 = _mm_add_epi16(d1, _mm_add_epi16(d3, _mm_add_epi16(d2, d2))); v0 = _mm_packus_epi16(_mm_add_epi16(v0, ftz), _mm_add_epi16(v1, ftz)); v0 = _mm_min_epu8(v0, ftz2); _mm_storel_epi64((__m128i*)(dptr0 + x), v0); _mm_storel_epi64((__m128i*)(dptr1 + x), _mm_unpackhi_epi64(v0, v0)); } } #endif for( ; x < size.width-1; x++ ) { int d0 = srow0[x+1] - srow0[x-1], d1 = srow1[x+1] - srow1[x-1], d2 = srow2[x+1] - srow2[x-1], d3 = srow3[x+1] - srow3[x-1]; int v0 = tab[d0 + d1*2 + d2 + OFS]; int v1 = tab[d1 + d2*2 + d3 + OFS]; dptr0[x] = (uchar)v0; dptr1[x] = (uchar)v1; } } for( ; y < size.height; y++ ) { uchar* dptr = dst.ptr<uchar>(y); for( x = 0; x < size.width; x++ ) dptr[x] = val0; } } static const int DISPARITY_SHIFT = 4; #if CV_SSE2 static void findStereoCorrespondenceBM_SSE2( const Mat& left, const Mat& right, Mat& disp, Mat& cost, StereoBMParams& state, uchar* buf, int _dy0, int _dy1 ) { const int ALIGN = 16; int x, y, d; int wsz = state.SADWindowSize, wsz2 = wsz/2; int dy0 = MIN(_dy0, wsz2+1), dy1 = MIN(_dy1, wsz2+1); int ndisp = state.numDisparities; int mindisp = state.minDisparity; int lofs = MAX(ndisp - 1 + mindisp, 0); int rofs = -MIN(ndisp - 1 + mindisp, 0); int width = left.cols, height = left.rows; int width1 = width - rofs - ndisp + 1; int ftzero = state.preFilterCap; int textureThreshold = state.textureThreshold; int uniquenessRatio = state.uniquenessRatio; short FILTERED = (short)((mindisp - 1) << DISPARITY_SHIFT); ushort *sad, *hsad0, *hsad, *hsad_sub; int *htext; uchar *cbuf0, *cbuf; const uchar* lptr0 = left.ptr() + lofs; const uchar* rptr0 = right.ptr() + rofs; const uchar *lptr, *lptr_sub, *rptr; short* dptr = disp.ptr<short>(); int sstep = (int)left.step; int dstep = (int)(disp.step/sizeof(dptr[0])); int cstep = (height + dy0 + dy1)*ndisp; short costbuf = 0; int coststep = cost.data ? (int)(cost.step/sizeof(costbuf)) : 0; const int TABSZ = 256; uchar tab[TABSZ]; const __m128i d0_8 = _mm_setr_epi16(0,1,2,3,4,5,6,7), dd_8 = _mm_set1_epi16(8); sad = (ushort*)alignPtr(buf + sizeof(sad[0]), ALIGN); hsad0 = (ushort*)alignPtr(sad + ndisp + 1 + dy0*ndisp, ALIGN); htext = (int*)alignPtr((int*)(hsad0 + (height+dy1)*ndisp) + wsz2 + 2, ALIGN); cbuf0 = (uchar*)alignPtr((uchar*)(htext + height + wsz2 + 2) + dy0*ndisp, ALIGN); for( x = 0; x < TABSZ; x++ ) tab[x] = (uchar)std::abs(x - ftzero); // initialize buffers memset( hsad0 - dy0*ndisp, 0, (height + dy0 + dy1)*ndisp*sizeof(hsad0[0]) ); memset( htext - wsz2 - 1, 0, (height + wsz + 1)*sizeof(htext[0]) ); for( x = -wsz2-1; x < wsz2; x++ ) { hsad = hsad0 - dy0*ndisp; cbuf = cbuf0 + (x + wsz2 + 1)*cstep - dy0*ndisp; lptr = lptr0 + MIN(MAX(x, -lofs), width-lofs-1) - dy0*sstep; rptr = rptr0 + MIN(MAX(x, -rofs), width-rofs-1) - dy0*sstep; for( y = -dy0; y < height + dy1; y++, hsad += ndisp, cbuf += ndisp, lptr += sstep, rptr += sstep ) { int lval = lptr[0]; __m128i lv = _mm_set1_epi8((char)lval), z = _mm_setzero_si128(); for( d = 0; d < ndisp; d += 16 ) { __m128i rv = _mm_loadu_si128((const __m128i*)(rptr + d)); __m128i hsad_l = _mm_load_si128((__m128i*)(hsad + d)); __m128i hsad_h = _mm_load_si128((__m128i*)(hsad + d + 8)); __m128i diff = _mm_adds_epu8(_mm_subs_epu8(lv, rv), _mm_subs_epu8(rv, lv)); _mm_store_si128((__m128i*)(cbuf + d), diff); hsad_l = _mm_add_epi16(hsad_l, _mm_unpacklo_epi8(diff,z)); hsad_h = _mm_add_epi16(hsad_h, _mm_unpackhi_epi8(diff,z)); _mm_store_si128((__m128i*)(hsad + d), hsad_l); _mm_store_si128((__m128i*)(hsad + d + 8), hsad_h); } htext[y] += tab[lval]; } } // initialize the left and right borders of the disparity map for( y = 0; y < height; y++ ) { for( x = 0; x < lofs; x++ ) dptr[y*dstep + x] = FILTERED; for( x = lofs + width1; x < width; x++ ) dptr[y*dstep + x] = FILTERED; } dptr += lofs; for( x = 0; x < width1; x++, dptr++ ) { short* costptr = cost.data ? cost.ptr<short>() + lofs + x : &costbuf; int x0 = x - wsz2 - 1, x1 = x + wsz2; const uchar* cbuf_sub = cbuf0 + ((x0 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp; cbuf = cbuf0 + ((x1 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp; hsad = hsad0 - dy0*ndisp; lptr_sub = lptr0 + MIN(MAX(x0, -lofs), width-1-lofs) - dy0*sstep; lptr = lptr0 + MIN(MAX(x1, -lofs), width-1-lofs) - dy0*sstep; rptr = rptr0 + MIN(MAX(x1, -rofs), width-1-rofs) - dy0*sstep; for( y = -dy0; y < height + dy1; y++, cbuf += ndisp, cbuf_sub += ndisp, hsad += ndisp, lptr += sstep, lptr_sub += sstep, rptr += sstep ) { int lval = lptr[0]; __m128i lv = _mm_set1_epi8((char)lval), z = _mm_setzero_si128(); for( d = 0; d < ndisp; d += 16 ) { __m128i rv = _mm_loadu_si128((const __m128i*)(rptr + d)); __m128i hsad_l = _mm_load_si128((__m128i*)(hsad + d)); __m128i hsad_h = _mm_load_si128((__m128i*)(hsad + d + 8)); __m128i cbs = _mm_load_si128((const __m128i*)(cbuf_sub + d)); __m128i diff = _mm_adds_epu8(_mm_subs_epu8(lv, rv), _mm_subs_epu8(rv, lv)); __m128i diff_h = _mm_sub_epi16(_mm_unpackhi_epi8(diff, z), _mm_unpackhi_epi8(cbs, z)); _mm_store_si128((__m128i*)(cbuf + d), diff); diff = _mm_sub_epi16(_mm_unpacklo_epi8(diff, z), _mm_unpacklo_epi8(cbs, z)); hsad_h = _mm_add_epi16(hsad_h, diff_h); hsad_l = _mm_add_epi16(hsad_l, diff); _mm_store_si128((__m128i*)(hsad + d), hsad_l); _mm_store_si128((__m128i*)(hsad + d + 8), hsad_h); } htext[y] += tab[lval] - tab[lptr_sub[0]]; } // fill borders for( y = dy1; y <= wsz2; y++ ) htext[height+y] = htext[height+dy1-1]; for( y = -wsz2-1; y < -dy0; y++ ) htext[y] = htext[-dy0]; // initialize sums for( d = 0; d < ndisp; d++ ) sad[d] = (ushort)(hsad0[d-ndisp*dy0]*(wsz2 + 2 - dy0)); hsad = hsad0 + (1 - dy0)*ndisp; for( y = 1 - dy0; y < wsz2; y++, hsad += ndisp ) for( d = 0; d < ndisp; d += 16 ) { __m128i s0 = _mm_load_si128((__m128i*)(sad + d)); __m128i s1 = _mm_load_si128((__m128i*)(sad + d + 8)); __m128i t0 = _mm_load_si128((__m128i*)(hsad + d)); __m128i t1 = _mm_load_si128((__m128i*)(hsad + d + 8)); s0 = _mm_add_epi16(s0, t0); s1 = _mm_add_epi16(s1, t1); _mm_store_si128((__m128i*)(sad + d), s0); _mm_store_si128((__m128i*)(sad + d + 8), s1); } int tsum = 0; for( y = -wsz2-1; y < wsz2; y++ ) tsum += htext[y]; // finally, start the real processing for( y = 0; y < height; y++ ) { int minsad = INT_MAX, mind = -1; hsad = hsad0 + MIN(y + wsz2, height+dy1-1)*ndisp; hsad_sub = hsad0 + MAX(y - wsz2 - 1, -dy0)*ndisp; __m128i minsad8 = _mm_set1_epi16(SHRT_MAX); __m128i mind8 = _mm_set1_epi16(0), d8 = d0_8, mask; for( d = 0; d < ndisp; d += 16 ) { __m128i u0 = _mm_load_si128((__m128i*)(hsad_sub + d)); __m128i u1 = _mm_load_si128((__m128i*)(hsad + d)); __m128i v0 = _mm_load_si128((__m128i*)(hsad_sub + d + 8)); __m128i v1 = _mm_load_si128((__m128i*)(hsad + d + 8)); __m128i usad8 = _mm_load_si128((__m128i*)(sad + d)); __m128i vsad8 = _mm_load_si128((__m128i*)(sad + d + 8)); u1 = _mm_sub_epi16(u1, u0); v1 = _mm_sub_epi16(v1, v0); usad8 = _mm_add_epi16(usad8, u1); vsad8 = _mm_add_epi16(vsad8, v1); mask = _mm_cmpgt_epi16(minsad8, usad8); minsad8 = _mm_min_epi16(minsad8, usad8); mind8 = _mm_max_epi16(mind8, _mm_and_si128(mask, d8)); _mm_store_si128((__m128i*)(sad + d), usad8); _mm_store_si128((__m128i*)(sad + d + 8), vsad8); mask = _mm_cmpgt_epi16(minsad8, vsad8); minsad8 = _mm_min_epi16(minsad8, vsad8); d8 = _mm_add_epi16(d8, dd_8); mind8 = _mm_max_epi16(mind8, _mm_and_si128(mask, d8)); d8 = _mm_add_epi16(d8, dd_8); } tsum += htext[y + wsz2] - htext[y - wsz2 - 1]; if( tsum < textureThreshold ) { dptr[y*dstep] = FILTERED; continue; } ushort CV_DECL_ALIGNED(16) minsad_buf[8], mind_buf[8]; _mm_store_si128((__m128i*)minsad_buf, minsad8); _mm_store_si128((__m128i*)mind_buf, mind8); for( d = 0; d < 8; d++ ) if(minsad > (int)minsad_buf[d] || (minsad == (int)minsad_buf[d] && mind > mind_buf[d])) { minsad = minsad_buf[d]; mind = mind_buf[d]; } if( uniquenessRatio > 0 ) { int thresh = minsad + (minsad * uniquenessRatio/100); __m128i thresh8 = _mm_set1_epi16((short)(thresh + 1)); __m128i d1 = _mm_set1_epi16((short)(mind-1)), d2 = _mm_set1_epi16((short)(mind+1)); __m128i dd_16 = _mm_add_epi16(dd_8, dd_8); d8 = _mm_sub_epi16(d0_8, dd_16); for( d = 0; d < ndisp; d += 16 ) { __m128i usad8 = _mm_load_si128((__m128i*)(sad + d)); __m128i vsad8 = _mm_load_si128((__m128i*)(sad + d + 8)); mask = _mm_cmpgt_epi16( thresh8, _mm_min_epi16(usad8,vsad8)); d8 = _mm_add_epi16(d8, dd_16); if( !_mm_movemask_epi8(mask) ) continue; mask = _mm_cmpgt_epi16( thresh8, usad8); mask = _mm_and_si128(mask, _mm_or_si128(_mm_cmpgt_epi16(d1,d8), _mm_cmpgt_epi16(d8,d2))); if( _mm_movemask_epi8(mask) ) break; __m128i t8 = _mm_add_epi16(d8, dd_8); mask = _mm_cmpgt_epi16( thresh8, vsad8); mask = _mm_and_si128(mask, _mm_or_si128(_mm_cmpgt_epi16(d1,t8), _mm_cmpgt_epi16(t8,d2))); if( _mm_movemask_epi8(mask) ) break; } if( d < ndisp ) { dptr[y*dstep] = FILTERED; continue; } } if( 0 < mind && mind < ndisp - 1 ) { int p = sad[mind+1], n = sad[mind-1]; d = p + n - 2*sad[mind] + std::abs(p - n); dptr[y*dstep] = (short)(((ndisp - mind - 1 + mindisp)*256 + (d != 0 ? (p-n)*256/d : 0) + 15) >> 4); } else dptr[y*dstep] = (short)((ndisp - mind - 1 + mindisp)*16); costptr[y*coststep] = sad[mind]; } } } #endif static void findStereoCorrespondenceBM( const Mat& left, const Mat& right, Mat& disp, Mat& cost, const StereoBMParams& state, uchar* buf, int _dy0, int _dy1 ) { const int ALIGN = 16; int x, y, d; int wsz = state.SADWindowSize, wsz2 = wsz/2; int dy0 = MIN(_dy0, wsz2+1), dy1 = MIN(_dy1, wsz2+1); int ndisp = state.numDisparities; int mindisp = state.minDisparity; int lofs = MAX(ndisp - 1 + mindisp, 0); int rofs = -MIN(ndisp - 1 + mindisp, 0); int width = left.cols, height = left.rows; int width1 = width - rofs - ndisp + 1; int ftzero = state.preFilterCap; int textureThreshold = state.textureThreshold; int uniquenessRatio = state.uniquenessRatio; short FILTERED = (short)((mindisp - 1) << DISPARITY_SHIFT); int *sad, *hsad0, *hsad, *hsad_sub, *htext; uchar *cbuf0, *cbuf; const uchar* lptr0 = left.ptr() + lofs; const uchar* rptr0 = right.ptr() + rofs; const uchar *lptr, *lptr_sub, *rptr; short* dptr = disp.ptr<short>(); int sstep = (int)left.step; int dstep = (int)(disp.step/sizeof(dptr[0])); int cstep = (height+dy0+dy1)*ndisp; int costbuf = 0; int coststep = cost.data ? (int)(cost.step/sizeof(costbuf)) : 0; const int TABSZ = 256; uchar tab[TABSZ]; sad = (int*)alignPtr(buf + sizeof(sad[0]), ALIGN); hsad0 = (int*)alignPtr(sad + ndisp + 1 + dy0*ndisp, ALIGN); htext = (int*)alignPtr((int*)(hsad0 + (height+dy1)*ndisp) + wsz2 + 2, ALIGN); cbuf0 = (uchar*)alignPtr((uchar*)(htext + height + wsz2 + 2) + dy0*ndisp, ALIGN); for( x = 0; x < TABSZ; x++ ) tab[x] = (uchar)std::abs(x - ftzero); // initialize buffers memset( hsad0 - dy0*ndisp, 0, (height + dy0 + dy1)*ndisp*sizeof(hsad0[0]) ); memset( htext - wsz2 - 1, 0, (height + wsz + 1)*sizeof(htext[0]) ); for( x = -wsz2-1; x < wsz2; x++ ) { hsad = hsad0 - dy0*ndisp; cbuf = cbuf0 + (x + wsz2 + 1)*cstep - dy0*ndisp; lptr = lptr0 + std::min(std::max(x, -lofs), width-lofs-1) - dy0*sstep; rptr = rptr0 + std::min(std::max(x, -rofs), width-rofs-1) - dy0*sstep; for( y = -dy0; y < height + dy1; y++, hsad += ndisp, cbuf += ndisp, lptr += sstep, rptr += sstep ) { int lval = lptr[0]; for( d = 0; d < ndisp; d++ ) { int diff = std::abs(lval - rptr[d]); cbuf[d] = (uchar)diff; hsad[d] = (int)(hsad[d] + diff); } htext[y] += tab[lval]; } } // initialize the left and right borders of the disparity map for( y = 0; y < height; y++ ) { for( x = 0; x < lofs; x++ ) dptr[y*dstep + x] = FILTERED; for( x = lofs + width1; x < width; x++ ) dptr[y*dstep + x] = FILTERED; } dptr += lofs; for( x = 0; x < width1; x++, dptr++ ) { int* costptr = cost.data ? cost.ptr<int>() + lofs + x : &costbuf; int x0 = x - wsz2 - 1, x1 = x + wsz2; const uchar* cbuf_sub = cbuf0 + ((x0 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp; cbuf = cbuf0 + ((x1 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp; hsad = hsad0 - dy0*ndisp; lptr_sub = lptr0 + MIN(MAX(x0, -lofs), width-1-lofs) - dy0*sstep; lptr = lptr0 + MIN(MAX(x1, -lofs), width-1-lofs) - dy0*sstep; rptr = rptr0 + MIN(MAX(x1, -rofs), width-1-rofs) - dy0*sstep; for( y = -dy0; y < height + dy1; y++, cbuf += ndisp, cbuf_sub += ndisp, hsad += ndisp, lptr += sstep, lptr_sub += sstep, rptr += sstep ) { int lval = lptr[0]; for( d = 0; d < ndisp; d++ ) { int diff = std::abs(lval - rptr[d]); cbuf[d] = (uchar)diff; hsad[d] = hsad[d] + diff - cbuf_sub[d]; } htext[y] += tab[lval] - tab[lptr_sub[0]]; } // fill borders for( y = dy1; y <= wsz2; y++ ) htext[height+y] = htext[height+dy1-1]; for( y = -wsz2-1; y < -dy0; y++ ) htext[y] = htext[-dy0]; // initialize sums for( d = 0; d < ndisp; d++ ) sad[d] = (int)(hsad0[d-ndisp*dy0]*(wsz2 + 2 - dy0)); hsad = hsad0 + (1 - dy0)*ndisp; for( y = 1 - dy0; y < wsz2; y++, hsad += ndisp ) for( d = 0; d < ndisp; d++ ) sad[d] = (int)(sad[d] + hsad[d]); int tsum = 0; for( y = -wsz2-1; y < wsz2; y++ ) tsum += htext[y]; // finally, start the real processing for( y = 0; y < height; y++ ) { int minsad = INT_MAX, mind = -1; hsad = hsad0 + MIN(y + wsz2, height+dy1-1)*ndisp; hsad_sub = hsad0 + MAX(y - wsz2 - 1, -dy0)*ndisp; for( d = 0; d < ndisp; d++ ) { int currsad = sad[d] + hsad[d] - hsad_sub[d]; sad[d] = currsad; if( currsad < minsad ) { minsad = currsad; mind = d; } } tsum += htext[y + wsz2] - htext[y - wsz2 - 1]; if( tsum < textureThreshold ) { dptr[y*dstep] = FILTERED; continue; } if( uniquenessRatio > 0 ) { int thresh = minsad + (minsad * uniquenessRatio/100); for( d = 0; d < ndisp; d++ ) { if( (d < mind-1 || d > mind+1) && sad[d] <= thresh) break; } if( d < ndisp ) { dptr[y*dstep] = FILTERED; continue; } } { sad[-1] = sad[1]; sad[ndisp] = sad[ndisp-2]; int p = sad[mind+1], n = sad[mind-1]; d = p + n - 2*sad[mind] + std::abs(p - n); dptr[y*dstep] = (short)(((ndisp - mind - 1 + mindisp)*256 + (d != 0 ? (p-n)*256/d : 0) + 15) >> 4); costptr[y*coststep] = sad[mind]; } } } } static bool ocl_prefiltering(InputArray left0, InputArray right0, OutputArray left, OutputArray right, StereoBMParams* state) { if( state->preFilterType == StereoBM::PREFILTER_NORMALIZED_RESPONSE ) { if(!ocl_prefilter_norm( left0, left, state->preFilterSize, state->preFilterCap)) return false; if(!ocl_prefilter_norm( right0, right, state->preFilterSize, state->preFilterCap)) return false; } else { if(!ocl_prefilter_xsobel( left0, left, state->preFilterCap )) return false; if(!ocl_prefilter_xsobel( right0, right, state->preFilterCap)) return false; } return true; } struct PrefilterInvoker : public ParallelLoopBody { PrefilterInvoker(const Mat& left0, const Mat& right0, Mat& left, Mat& right, uchar* buf0, uchar* buf1, StereoBMParams* _state) { imgs0[0] = &left0; imgs0[1] = &right0; imgs[0] = &left; imgs[1] = &right; buf[0] = buf0; buf[1] = buf1; state = _state; } void operator()( const Range& range ) const { for( int i = range.start; i < range.end; i++ ) { if( state->preFilterType == StereoBM::PREFILTER_NORMALIZED_RESPONSE ) prefilterNorm( *imgs0[i], *imgs[i], state->preFilterSize, state->preFilterCap, buf[i] ); else prefilterXSobel( *imgs0[i], *imgs[i], state->preFilterCap ); } } const Mat* imgs0[2]; Mat* imgs[2]; uchar* buf[2]; StereoBMParams* state; }; static bool ocl_stereobm( InputArray _left, InputArray _right, OutputArray _disp, StereoBMParams* state) { int ndisp = state->numDisparities; int mindisp = state->minDisparity; int wsz = state->SADWindowSize; int wsz2 = wsz/2; ocl::Device devDef = ocl::Device::getDefault(); int sizeX = devDef.isIntel() ? 32 : std::max(11, 27 - devDef.maxComputeUnits()), sizeY = sizeX - 1, N = ndisp * 2; cv::String opt = cv::format("-D DEFINE_KERNEL_STEREOBM -D MIN_DISP=%d -D NUM_DISP=%d" " -D BLOCK_SIZE_X=%d -D BLOCK_SIZE_Y=%d -D WSZ=%d", mindisp, ndisp, sizeX, sizeY, wsz); ocl::Kernel k("stereoBM", ocl::calib3d::stereobm_oclsrc, opt); if(k.empty()) return false; UMat left = _left.getUMat(), right = _right.getUMat(); int cols = left.cols, rows = left.rows; _disp.create(_left.size(), CV_16S); _disp.setTo((mindisp - 1) << 4); Rect roi = Rect(Point(wsz2 + mindisp + ndisp - 1, wsz2), Point(cols-wsz2-mindisp, rows-wsz2) ); UMat disp = (_disp.getUMat())(roi); int globalX = (disp.cols + sizeX - 1) / sizeX, globalY = (disp.rows + sizeY - 1) / sizeY; size_t globalThreads[3] = {N, globalX, globalY}; size_t localThreads[3] = {N, 1, 1}; int idx = 0; idx = k.set(idx, ocl::KernelArg::PtrReadOnly(left)); idx = k.set(idx, ocl::KernelArg::PtrReadOnly(right)); idx = k.set(idx, ocl::KernelArg::WriteOnlyNoSize(disp)); idx = k.set(idx, rows); idx = k.set(idx, cols); idx = k.set(idx, state->textureThreshold); idx = k.set(idx, state->uniquenessRatio); return k.run(3, globalThreads, localThreads, false); } struct FindStereoCorrespInvoker : public ParallelLoopBody { FindStereoCorrespInvoker( const Mat& _left, const Mat& _right, Mat& _disp, StereoBMParams* _state, int _nstripes, size_t _stripeBufSize, bool _useShorts, Rect _validDisparityRect, Mat& _slidingSumBuf, Mat& _cost ) { left = &_left; right = &_right; disp = &_disp; state = _state; nstripes = _nstripes; stripeBufSize = _stripeBufSize; useShorts = _useShorts; validDisparityRect = _validDisparityRect; slidingSumBuf = &_slidingSumBuf; cost = &_cost; } void operator()( const Range& range ) const { int cols = left->cols, rows = left->rows; int _row0 = std::min(cvRound(range.start * rows / nstripes), rows); int _row1 = std::min(cvRound(range.end * rows / nstripes), rows); uchar *ptr = slidingSumBuf->ptr() + range.start * stripeBufSize; int FILTERED = (state->minDisparity - 1)*16; Rect roi = validDisparityRect & Rect(0, _row0, cols, _row1 - _row0); if( roi.height == 0 ) return; int row0 = roi.y; int row1 = roi.y + roi.height; Mat part; if( row0 > _row0 ) { part = disp->rowRange(_row0, row0); part = Scalar::all(FILTERED); } if( _row1 > row1 ) { part = disp->rowRange(row1, _row1); part = Scalar::all(FILTERED); } Mat left_i = left->rowRange(row0, row1); Mat right_i = right->rowRange(row0, row1); Mat disp_i = disp->rowRange(row0, row1); Mat cost_i = state->disp12MaxDiff >= 0 ? cost->rowRange(row0, row1) : Mat(); #if CV_SSE2 if( useShorts ) findStereoCorrespondenceBM_SSE2( left_i, right_i, disp_i, cost_i, *state, ptr, row0, rows - row1 ); else #endif findStereoCorrespondenceBM( left_i, right_i, disp_i, cost_i, *state, ptr, row0, rows - row1 ); if( state->disp12MaxDiff >= 0 ) validateDisparity( disp_i, cost_i, state->minDisparity, state->numDisparities, state->disp12MaxDiff ); if( roi.x > 0 ) { part = disp_i.colRange(0, roi.x); part = Scalar::all(FILTERED); } if( roi.x + roi.width < cols ) { part = disp_i.colRange(roi.x + roi.width, cols); part = Scalar::all(FILTERED); } } protected: const Mat *left, *right; Mat* disp, *slidingSumBuf, *cost; StereoBMParams *state; int nstripes; size_t stripeBufSize; bool useShorts; Rect validDisparityRect; }; class StereoBMImpl : public StereoBM { public: StereoBMImpl() { params = StereoBMParams(); } StereoBMImpl( int _numDisparities, int _SADWindowSize ) { params = StereoBMParams(_numDisparities, _SADWindowSize); } void compute( InputArray leftarr, InputArray rightarr, OutputArray disparr ) { int dtype = disparr.fixedType() ? disparr.type() : params.dispType; Size leftsize = leftarr.size(); if (leftarr.size() != rightarr.size()) CV_Error( Error::StsUnmatchedSizes, "All the images must have the same size" ); if (leftarr.type() != CV_8UC1 || rightarr.type() != CV_8UC1) CV_Error( Error::StsUnsupportedFormat, "Both input images must have CV_8UC1" ); if (dtype != CV_16SC1 && dtype != CV_32FC1) CV_Error( Error::StsUnsupportedFormat, "Disparity image must have CV_16SC1 or CV_32FC1 format" ); if( params.preFilterType != PREFILTER_NORMALIZED_RESPONSE && params.preFilterType != PREFILTER_XSOBEL ) CV_Error( Error::StsOutOfRange, "preFilterType must be = CV_STEREO_BM_NORMALIZED_RESPONSE" ); if( params.preFilterSize < 5 || params.preFilterSize > 255 || params.preFilterSize % 2 == 0 ) CV_Error( Error::StsOutOfRange, "preFilterSize must be odd and be within 5..255" ); if( params.preFilterCap < 1 || params.preFilterCap > 63 ) CV_Error( Error::StsOutOfRange, "preFilterCap must be within 1..63" ); if( params.SADWindowSize < 5 || params.SADWindowSize > 255 || params.SADWindowSize % 2 == 0 || params.SADWindowSize >= std::min(leftsize.width, leftsize.height) ) CV_Error( Error::StsOutOfRange, "SADWindowSize must be odd, be within 5..255 and be not larger than image width or height" ); if( params.numDisparities <= 0 || params.numDisparities % 16 != 0 ) CV_Error( Error::StsOutOfRange, "numDisparities must be positive and divisble by 16" ); if( params.textureThreshold < 0 ) CV_Error( Error::StsOutOfRange, "texture threshold must be non-negative" ); if( params.uniquenessRatio < 0 ) CV_Error( Error::StsOutOfRange, "uniqueness ratio must be non-negative" ); int FILTERED = (params.minDisparity - 1) << DISPARITY_SHIFT; if(ocl::useOpenCL() && disparr.isUMat() && params.textureThreshold == 0) { UMat left, right; if(ocl_prefiltering(leftarr, rightarr, left, right, &params)) { if(ocl_stereobm(left, right, disparr, &params)) { if( params.speckleRange >= 0 && params.speckleWindowSize > 0 ) filterSpeckles(disparr.getMat(), FILTERED, params.speckleWindowSize, params.speckleRange, slidingSumBuf); if (dtype == CV_32F) disparr.getUMat().convertTo(disparr, CV_32FC1, 1./(1 << DISPARITY_SHIFT), 0); CV_IMPL_ADD(CV_IMPL_OCL); return; } } } Mat left0 = leftarr.getMat(), right0 = rightarr.getMat(); disparr.create(left0.size(), dtype); Mat disp0 = disparr.getMat(); preFilteredImg0.create( left0.size(), CV_8U ); preFilteredImg1.create( left0.size(), CV_8U ); cost.create( left0.size(), CV_16S ); Mat left = preFilteredImg0, right = preFilteredImg1; int mindisp = params.minDisparity; int ndisp = params.numDisparities; int width = left0.cols; int height = left0.rows; int lofs = std::max(ndisp - 1 + mindisp, 0); int rofs = -std::min(ndisp - 1 + mindisp, 0); int width1 = width - rofs - ndisp + 1; if( lofs >= width || rofs >= width || width1 < 1 ) { disp0 = Scalar::all( FILTERED * ( disp0.type() < CV_32F ? 1 : 1./(1 << DISPARITY_SHIFT) ) ); return; } Mat disp = disp0; if( dtype == CV_32F ) { dispbuf.create(disp0.size(), CV_16S); disp = dispbuf; } int wsz = params.SADWindowSize; int bufSize0 = (int)((ndisp + 2)*sizeof(int)); bufSize0 += (int)((height+wsz+2)*ndisp*sizeof(int)); bufSize0 += (int)((height + wsz + 2)*sizeof(int)); bufSize0 += (int)((height+wsz+2)*ndisp*(wsz+2)*sizeof(uchar) + 256); int bufSize1 = (int)((width + params.preFilterSize + 2) * sizeof(int) + 256); int bufSize2 = 0; if( params.speckleRange >= 0 && params.speckleWindowSize > 0 ) bufSize2 = width*height*(sizeof(Point_<short>) + sizeof(int) + sizeof(uchar)); #if CV_SSE2 bool useShorts = params.preFilterCap <= 31 && params.SADWindowSize <= 21 && checkHardwareSupport(CV_CPU_SSE2); #else const bool useShorts = false; #endif const double SAD_overhead_coeff = 10.0; double N0 = 8000000 / (useShorts ? 1 : 4); // approx tbb's min number instructions reasonable for one thread double maxStripeSize = std::min(std::max(N0 / (width * ndisp), (wsz-1) * SAD_overhead_coeff), (double)height); int nstripes = cvCeil(height / maxStripeSize); int bufSize = std::max(bufSize0 * nstripes, std::max(bufSize1 * 2, bufSize2)); if( slidingSumBuf.cols < bufSize ) slidingSumBuf.create( 1, bufSize, CV_8U ); uchar *_buf = slidingSumBuf.ptr(); parallel_for_(Range(0, 2), PrefilterInvoker(left0, right0, left, right, _buf, _buf + bufSize1, &params), 1); Rect validDisparityRect(0, 0, width, height), R1 = params.roi1, R2 = params.roi2; validDisparityRect = getValidDisparityROI(R1.area() > 0 ? Rect(0, 0, width, height) : validDisparityRect, R2.area() > 0 ? Rect(0, 0, width, height) : validDisparityRect, params.minDisparity, params.numDisparities, params.SADWindowSize); parallel_for_(Range(0, nstripes), FindStereoCorrespInvoker(left, right, disp, &params, nstripes, bufSize0, useShorts, validDisparityRect, slidingSumBuf, cost)); if( params.speckleRange >= 0 && params.speckleWindowSize > 0 ) filterSpeckles(disp, FILTERED, params.speckleWindowSize, params.speckleRange, slidingSumBuf); if (disp0.data != disp.data) disp.convertTo(disp0, disp0.type(), 1./(1 << DISPARITY_SHIFT), 0); } AlgorithmInfo* info() const { return 0; } int getMinDisparity() const { return params.minDisparity; } void setMinDisparity(int minDisparity) { params.minDisparity = minDisparity; } int getNumDisparities() const { return params.numDisparities; } void setNumDisparities(int numDisparities) { params.numDisparities = numDisparities; } int getBlockSize() const { return params.SADWindowSize; } void setBlockSize(int blockSize) { params.SADWindowSize = blockSize; } int getSpeckleWindowSize() const { return params.speckleWindowSize; } void setSpeckleWindowSize(int speckleWindowSize) { params.speckleWindowSize = speckleWindowSize; } int getSpeckleRange() const { return params.speckleRange; } void setSpeckleRange(int speckleRange) { params.speckleRange = speckleRange; } int getDisp12MaxDiff() const { return params.disp12MaxDiff; } void setDisp12MaxDiff(int disp12MaxDiff) { params.disp12MaxDiff = disp12MaxDiff; } int getPreFilterType() const { return params.preFilterType; } void setPreFilterType(int preFilterType) { params.preFilterType = preFilterType; } int getPreFilterSize() const { return params.preFilterSize; } void setPreFilterSize(int preFilterSize) { params.preFilterSize = preFilterSize; } int getPreFilterCap() const { return params.preFilterCap; } void setPreFilterCap(int preFilterCap) { params.preFilterCap = preFilterCap; } int getTextureThreshold() const { return params.textureThreshold; } void setTextureThreshold(int textureThreshold) { params.textureThreshold = textureThreshold; } int getUniquenessRatio() const { return params.uniquenessRatio; } void setUniquenessRatio(int uniquenessRatio) { params.uniquenessRatio = uniquenessRatio; } int getSmallerBlockSize() const { return 0; } void setSmallerBlockSize(int) {} Rect getROI1() const { return params.roi1; } void setROI1(Rect roi1) { params.roi1 = roi1; } Rect getROI2() const { return params.roi2; } void setROI2(Rect roi2) { params.roi2 = roi2; } void write(FileStorage& fs) const { fs << "name" << name_ << "minDisparity" << params.minDisparity << "numDisparities" << params.numDisparities << "blockSize" << params.SADWindowSize << "speckleWindowSize" << params.speckleWindowSize << "speckleRange" << params.speckleRange << "disp12MaxDiff" << params.disp12MaxDiff << "preFilterType" << params.preFilterType << "preFilterSize" << params.preFilterSize << "preFilterCap" << params.preFilterCap << "textureThreshold" << params.textureThreshold << "uniquenessRatio" << params.uniquenessRatio; } void read(const FileNode& fn) { FileNode n = fn["name"]; CV_Assert( n.isString() && String(n) == name_ ); params.minDisparity = (int)fn["minDisparity"]; params.numDisparities = (int)fn["numDisparities"]; params.SADWindowSize = (int)fn["blockSize"]; params.speckleWindowSize = (int)fn["speckleWindowSize"]; params.speckleRange = (int)fn["speckleRange"]; params.disp12MaxDiff = (int)fn["disp12MaxDiff"]; params.preFilterType = (int)fn["preFilterType"]; params.preFilterSize = (int)fn["preFilterSize"]; params.preFilterCap = (int)fn["preFilterCap"]; params.textureThreshold = (int)fn["textureThreshold"]; params.uniquenessRatio = (int)fn["uniquenessRatio"]; params.roi1 = params.roi2 = Rect(); } StereoBMParams params; Mat preFilteredImg0, preFilteredImg1, cost, dispbuf; Mat slidingSumBuf; static const char* name_; }; const char* StereoBMImpl::name_ = "StereoMatcher.BM"; Ptr<StereoBM> StereoBM::create(int _numDisparities, int _SADWindowSize) { return makePtr<StereoBMImpl>(_numDisparities, _SADWindowSize); } } /* End of file. */
Java
"use strict"; var mapnik = require('../'); var assert = require('assert'); var path = require('path'); mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'geojson.input')); describe('mapnik.Geometry ', function() { it('should throw with invalid usage', function() { // geometry cannot be created directly for now assert.throws(function() { mapnik.Geometry(); }); }); it('should access a geometry from a feature', function() { var feature = new mapnik.Feature(1); var point = { "type": "MultiPoint", "coordinates": [[0,0],[1,1]] }; var input = { type: "Feature", properties: {}, geometry: point }; var f = new mapnik.Feature.fromJSON(JSON.stringify(input)); var geom = f.geometry(); assert.equal(geom.type(),mapnik.Geometry.MultiPoint); assert.deepEqual(JSON.parse(geom.toJSONSync()),point); var expected_wkb = new Buffer('0104000000020000000101000000000000000000000000000000000000000101000000000000000000f03f000000000000f03f', 'hex'); assert.deepEqual(geom.toWKB(),expected_wkb); }); it('should fail on toJSON due to bad parameters', function() { var feature = new mapnik.Feature(1); var point = { "type": "MultiPoint", "coordinates": [[0,0],[1,1]] }; var input = { type: "Feature", properties: {}, geometry: point }; var f = new mapnik.Feature.fromJSON(JSON.stringify(input)); var geom = f.geometry(); assert.equal(geom.type(),mapnik.Geometry.MultiPoint); assert.throws(function() { geom.toJSONSync(null); }); assert.throws(function() { geom.toJSONSync({transform:null}); }); assert.throws(function() { geom.toJSONSync({transform:{}}); }); assert.throws(function() { geom.toJSON(null, function(err,json) {}); }); assert.throws(function() { geom.toJSON({transform:null}, function(err, json) {}); }); assert.throws(function() { geom.toJSON({transform:{}}, function(err, json) {}); }); }); it('should throw if we attempt to create a Feature from a geojson geometry (rather than geojson feature)', function() { var geometry = { type: 'Point', coordinates: [ 7.415119300000001, 43.730364300000005 ] }; // starts throwing, as expected, at Mapnik v3.0.9 (https://github.com/mapnik/node-mapnik/issues/560) if (mapnik.versions.mapnik_number >= 300009) { assert.throws(function() { var transformed = mapnik.Feature.fromJSON(JSON.stringify(geometry)); }); } }); it('should throw from empty geometry from toWKB', function() { var s = new mapnik.Feature(1); assert.throws(function() { var geom = s.geometry().toWKB(); }); }); });
Java
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model frontend\models\ManagerTrain */ $this->title = $model->id; $this->params['breadcrumbs'][] = ['label' => 'Manager Trains', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="manager-train-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a('Delete', ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'rangkaian_fasiliti_awam', 'cat_id', 'location', 'state_id', 'district_id', 'mukim_id', 'sub_base_id', 'cluster_id', 'kampung_id', 'alamat', 'poskod', 'nama_pengurus', 'ic', 'jantina', 'no_fon', 'date_enter', 'enter_by', ], ]) ?> </div>
Java
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2012-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: correspondence_estimation_backprojection.hpp 7230 2012-09-21 06:31:19Z rusu $ * */ #ifndef PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_ #define PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_ #include <pcl/registration/correspondence_estimation_normal_shooting.h> /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> bool pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::initCompute () { if (!source_normals_ || !target_normals_) { PCL_WARN ("[pcl::registration::%s::initCompute] Datasets containing normals for source/target have not been given!\n", getClassName ().c_str ()); return (false); } return (CorrespondenceEstimationBase<PointSource, PointTarget, Scalar>::initCompute ()); } /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::rotatePointCloudNormals ( const pcl::PointCloud<NormalT> &cloud_in, pcl::PointCloud<NormalT> &cloud_out, const Eigen::Matrix<Scalar, 4, 4> &transform) { if (&cloud_in != &cloud_out) { // Note: could be replaced by cloud_out = cloud_in cloud_out.header = cloud_in.header; cloud_out.width = cloud_in.width; cloud_out.height = cloud_in.height; cloud_out.is_dense = cloud_in.is_dense; cloud_out.points.reserve (cloud_out.points.size ()); cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ()); } for (size_t i = 0; i < cloud_out.points.size (); ++i) { // Rotate normals (WARNING: transform.rotation () uses SVD internally!) Eigen::Matrix<Scalar, 3, 1> nt (cloud_in[i].normal_x, cloud_in[i].normal_y, cloud_in[i].normal_z); cloud_out[i].normal_x = static_cast<float> (transform (0, 0) * nt.coeffRef (0) + transform (0, 1) * nt.coeffRef (1) + transform (0, 2) * nt.coeffRef (2)); cloud_out[i].normal_y = static_cast<float> (transform (1, 0) * nt.coeffRef (0) + transform (1, 1) * nt.coeffRef (1) + transform (1, 2) * nt.coeffRef (2)); cloud_out[i].normal_z = static_cast<float> (transform (2, 0) * nt.coeffRef (0) + transform (2, 1) * nt.coeffRef (1) + transform (2, 2) * nt.coeffRef (2)); } } /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::determineCorrespondences ( pcl::Correspondences &correspondences, double max_distance) { if (!initCompute ()) return; typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget; correspondences.resize (indices_->size ()); std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); float min_dist = std::numeric_limits<float>::max (); int min_index = 0; pcl::Correspondence corr; unsigned int nr_valid_correspondences = 0; // Check if the template types are the same. If true, avoid a copy. // Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro! if (isSamePointType<PointSource, PointTarget> ()) { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } else { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { PointSource pt_src; // Copy the source data to a target PointTarget format so we can search in the tree pcl::for_each_type <FieldListTarget> (pcl::NdConcatenateFunctor <PointSource, PointTarget> ( input_->points[*idx_i], pt_src)); float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } correspondences.resize (nr_valid_correspondences); deinitCompute (); } /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::determineReciprocalCorrespondences ( pcl::Correspondences &correspondences, double max_distance) { if (!initCompute ()) return; typedef typename pcl::traits::fieldList<PointSource>::type FieldListSource; typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget; typedef typename pcl::intersect<FieldListSource, FieldListTarget>::type FieldList; // setup tree for reciprocal search pcl::KdTreeFLANN<PointSource> tree_reciprocal; // Set the internal point representation of choice if (point_representation_) tree_reciprocal.setPointRepresentation (point_representation_); tree_reciprocal.setInputCloud (input_, indices_); correspondences.resize (indices_->size ()); std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); std::vector<int> index_reciprocal (1); std::vector<float> distance_reciprocal (1); float min_dist = std::numeric_limits<float>::max (); int min_index = 0; pcl::Correspondence corr; unsigned int nr_valid_correspondences = 0; int target_idx = 0; // Check if the template types are the same. If true, avoid a copy. // Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro! if (isSamePointType<PointSource, PointTarget> ()) { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; // Check if the correspondence is reciprocal target_idx = nn_indices[min_index]; tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal); if (*idx_i != index_reciprocal[0]) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } else { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { PointSource pt_src; // Copy the source data to a target PointTarget format so we can search in the tree pcl::for_each_type <FieldListTarget> (pcl::NdConcatenateFunctor <PointSource, PointTarget> ( input_->points[*idx_i], pt_src)); float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; // Check if the correspondence is reciprocal target_idx = nn_indices[min_index]; tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal); if (*idx_i != index_reciprocal[0]) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } correspondences.resize (nr_valid_correspondences); deinitCompute (); } #endif // PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_
Java
package xcordion.impl.command; import junit.framework.TestCase; import junit.framework.Assert; import org.junit.Test; import org.junit.Ignore; public class ForEachCommandTest { @Test @Ignore public void testPlaceholder() { Assert.fail("WRITE ME"); } }
Java
/*========================================================================= Program: Visualization Toolkit Module: vtkDataSetEdgeSubdivisionCriterion.h Language: C++ Copyright 2003 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive license for use of this work by or on behalf of the U.S. Government. Redistribution and use in source and binary forms, with or without modification, are permitted provided that this Notice and any statement of authorship are reproduced on all copies. =========================================================================*/ #ifndef vtkDataSetEdgeSubdivisionCriterion_h #define vtkDataSetEdgeSubdivisionCriterion_h // .NAME vtkDataSetEdgeSubdivisionCriterion - a subclass of vtkEdgeSubdivisionCriterion for vtkDataSet objects. // // .SECTION Description // This is a subclass of vtkEdgeSubdivisionCriterion that is used for // tessellating cells of a vtkDataSet, particularly nonlinear // cells. // // It provides functions for setting the current cell being tessellated and a // convenience routine, \a EvaluateFields() to evaluate field values at a // point. You should call \a EvaluateFields() from inside \a EvaluateEdge() // whenever the result of \a EvaluateEdge() will be true. Otherwise, do // not call \a EvaluateFields() as the midpoint is about to be discarded. // (<i>Implementor's note</i>: This isn't true if UGLY_ASPECT_RATIO_HACK // has been defined. But in that case, we don't want the exact field values; // we need the linearly interpolated ones at the midpoint for continuity.) // // .SECTION See Also // vtkEdgeSubdivisionCriterion #include "vtkFiltersCoreModule.h" // For export macro #include "vtkEdgeSubdivisionCriterion.h" class vtkCell; class vtkDataSet; class VTKFILTERSCORE_EXPORT vtkDataSetEdgeSubdivisionCriterion : public vtkEdgeSubdivisionCriterion { public: vtkTypeMacro(vtkDataSetEdgeSubdivisionCriterion,vtkEdgeSubdivisionCriterion); static vtkDataSetEdgeSubdivisionCriterion* New(); virtual void PrintSelf( ostream& os, vtkIndent indent ); virtual void SetMesh( vtkDataSet* ); vtkDataSet* GetMesh(); //BTX const vtkDataSet* GetMesh() const; //ETX virtual void SetCellId( vtkIdType cell ); vtkIdType GetCellId() const; //BTX vtkIdType& GetCellId(); //ETX vtkCell* GetCell(); //BTX const vtkCell* GetCell() const; //ETX virtual bool EvaluateEdge( const double* p0, double* midpt, const double* p1, int field_start ); // Description: // Evaluate all of the fields that should be output with the // given \a vertex and store them just past the parametric coordinates // of \a vertex, at the offsets given by // \p vtkEdgeSubdivisionCriterion::GetFieldOffsets() plus \a field_start. // \a field_start contains the number of world-space coordinates (always 3) // plus the embedding dimension (the size of the parameter-space in which // the cell is embedded). It will range between 3 and 6, inclusive. // // You must have called SetCellId() before calling this routine or there // will not be a mesh over which to evaluate the fields. // // You must have called \p vtkEdgeSubdivisionCriterion::PassDefaultFields() // or \p vtkEdgeSubdivisionCriterion::PassField() or there will be no fields // defined for the output vertex. // // This routine is public and returns its input argument so that it // may be used as an argument to // \p vtkStreamingTessellator::AdaptivelySamplekFacet(): // @verbatim // vtkStreamingTessellator* t = vtkStreamingTessellator::New(); // vtkEdgeSubdivisionCriterion* s; // ... // t->AdaptivelySample1Facet( s->EvaluateFields( p0 ), s->EvaluateFields( p1 ) ); // ... // @endverbatim // Although this will work, using \p EvaluateFields() in this manner // should be avoided. It's much more efficient to fetch the corner values // for each attribute and copy them into \a p0, \a p1, ... as opposed to // performing shape function evaluations. The only case where you wouldn't // want to do this is when the field you are interpolating is discontinuous // at cell borders, such as with a discontinuous galerkin method or when // all the Gauss points for quadrature are interior to the cell. // // The final argument, \a weights, is the array of weights to apply to each // point's data when interpolating the field. This is returned by // \a vtkCell::EvaluateLocation() when evaluating the geometry. double* EvaluateFields( double* vertex, double* weights, int field_start ); // Description: // Evaluate either a cell or nodal field. // This exists because of the funky way that Exodus data will be handled. // Sure, it's a hack, but what are ya gonna do? void EvaluatePointDataField( double* result, double* weights, int field ); void EvaluateCellDataField( double* result, double* weights, int field ); // Description: // Get/Set the square of the allowable chord error at any edge's midpoint. // This value is used by EvaluateEdge. vtkSetMacro(ChordError2,double); vtkGetMacro(ChordError2,double); // Description: // Get/Set the square of the allowable error magnitude for the // scalar field \a s at any edge's midpoint. // A value less than or equal to 0 indicates that the field // should not be used as a criterion for subdivision. virtual void SetFieldError2( int s, double err ); double GetFieldError2( int s ) const; // Description: // Tell the subdivider not to use any field values as subdivision criteria. // Effectively calls SetFieldError2( a, -1. ) for all fields. virtual void ResetFieldError2(); // Description: // Return a bitfield specifying which FieldError2 criteria are positive (i.e., actively // used to decide edge subdivisions). // This is stored as separate state to make subdivisions go faster. vtkGetMacro(ActiveFieldCriteria,int); int GetActiveFieldCriteria() const { return this->ActiveFieldCriteria; } protected: vtkDataSetEdgeSubdivisionCriterion(); virtual ~vtkDataSetEdgeSubdivisionCriterion(); vtkDataSet* CurrentMesh; vtkIdType CurrentCellId; vtkCell* CurrentCellData; double ChordError2; double* FieldError2; int FieldError2Length; int FieldError2Capacity; int ActiveFieldCriteria; private: vtkDataSetEdgeSubdivisionCriterion( const vtkDataSetEdgeSubdivisionCriterion& ); // Not implemented. void operator = ( const vtkDataSetEdgeSubdivisionCriterion& ); // Not implemented. }; //BTX inline vtkIdType& vtkDataSetEdgeSubdivisionCriterion::GetCellId() { return this->CurrentCellId; } inline vtkIdType vtkDataSetEdgeSubdivisionCriterion::GetCellId() const { return this->CurrentCellId; } inline vtkDataSet* vtkDataSetEdgeSubdivisionCriterion::GetMesh() { return this->CurrentMesh; } inline const vtkDataSet* vtkDataSetEdgeSubdivisionCriterion::GetMesh() const { return this->CurrentMesh; } inline vtkCell* vtkDataSetEdgeSubdivisionCriterion::GetCell() { return this->CurrentCellData; } inline const vtkCell* vtkDataSetEdgeSubdivisionCriterion::GetCell() const { return this->CurrentCellData; } //ETX #endif // vtkDataSetEdgeSubdivisionCriterion_h
Java
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package asm import ( "bufio" "bytes" "fmt" "io/ioutil" "os" "path/filepath" "regexp" "sort" "strconv" "strings" "testing" "cmd/asm/internal/lex" "cmd/internal/obj" "cmd/internal/objabi" ) // An end-to-end test for the assembler: Do we print what we parse? // Output is generated by, in effect, turning on -S and comparing the // result against a golden file. func testEndToEnd(t *testing.T, goarch, file string) { input := filepath.Join("testdata", file+".s") architecture, ctxt := setArch(goarch) architecture.Init(ctxt) lexer := lex.NewLexer(input) parser := NewParser(ctxt, architecture, lexer) pList := new(obj.Plist) var ok bool testOut = new(bytes.Buffer) // The assembler writes test output to this buffer. ctxt.Bso = bufio.NewWriter(os.Stdout) defer ctxt.Bso.Flush() failed := false ctxt.DiagFunc = func(format string, args ...interface{}) { failed = true t.Errorf(format, args...) } pList.Firstpc, ok = parser.Parse() if !ok || failed { t.Errorf("asm: %s assembly failed", goarch) return } output := strings.Split(testOut.String(), "\n") // Reconstruct expected output by independently "parsing" the input. data, err := ioutil.ReadFile(input) if err != nil { t.Error(err) return } lineno := 0 seq := 0 hexByLine := map[string]string{} lines := strings.SplitAfter(string(data), "\n") Diff: for _, line := range lines { lineno++ // Ignore include of textflag.h. if strings.HasPrefix(line, "#include ") { continue } // The general form of a test input line is: // // comment // INST args [// printed form] [// hex encoding] parts := strings.Split(line, "//") printed := strings.TrimSpace(parts[0]) if printed == "" || strings.HasSuffix(printed, ":") { // empty or label continue } seq++ var hexes string switch len(parts) { default: t.Errorf("%s:%d: unable to understand comments: %s", input, lineno, line) case 1: // no comment case 2: // might be printed form or hex note := strings.TrimSpace(parts[1]) if isHexes(note) { hexes = note } else { printed = note } case 3: // printed form, then hex printed = strings.TrimSpace(parts[1]) hexes = strings.TrimSpace(parts[2]) if !isHexes(hexes) { t.Errorf("%s:%d: malformed hex instruction encoding: %s", input, lineno, line) } } if hexes != "" { hexByLine[fmt.Sprintf("%s:%d", input, lineno)] = hexes } // Canonicalize spacing in printed form. // First field is opcode, then tab, then arguments separated by spaces. // Canonicalize spaces after commas first. // Comma to separate argument gets a space; comma within does not. var buf []byte nest := 0 for i := 0; i < len(printed); i++ { c := printed[i] switch c { case '{', '[': nest++ case '}', ']': nest-- case ',': buf = append(buf, ',') if nest == 0 { buf = append(buf, ' ') } for i+1 < len(printed) && (printed[i+1] == ' ' || printed[i+1] == '\t') { i++ } continue } buf = append(buf, c) } f := strings.Fields(string(buf)) // Turn relative (PC) into absolute (PC) automatically, // so that most branch instructions don't need comments // giving the absolute form. if len(f) > 0 && strings.HasSuffix(printed, "(PC)") { last := f[len(f)-1] n, err := strconv.Atoi(last[:len(last)-len("(PC)")]) if err == nil { f[len(f)-1] = fmt.Sprintf("%d(PC)", seq+n) } } if len(f) == 1 { printed = f[0] } else { printed = f[0] + "\t" + strings.Join(f[1:], " ") } want := fmt.Sprintf("%05d (%s:%d)\t%s", seq, input, lineno, printed) for len(output) > 0 && (output[0] < want || output[0] != want && len(output[0]) >= 5 && output[0][:5] == want[:5]) { if len(output[0]) >= 5 && output[0][:5] == want[:5] { t.Errorf("mismatched output:\nhave %s\nwant %s", output[0], want) output = output[1:] continue Diff } t.Errorf("unexpected output: %q", output[0]) output = output[1:] } if len(output) > 0 && output[0] == want { output = output[1:] } else { t.Errorf("missing output: %q", want) } } for len(output) > 0 { if output[0] == "" { // spurious blank caused by Split on "\n" output = output[1:] continue } t.Errorf("unexpected output: %q", output[0]) output = output[1:] } // Checked printing. // Now check machine code layout. top := pList.Firstpc var text *obj.LSym ok = true ctxt.DiagFunc = func(format string, args ...interface{}) { t.Errorf(format, args...) ok = false } obj.Flushplist(ctxt, pList, nil, "") for p := top; p != nil; p = p.Link { if p.As == obj.ATEXT { text = p.From.Sym } hexes := hexByLine[p.Line()] if hexes == "" { continue } delete(hexByLine, p.Line()) if text == nil { t.Errorf("%s: instruction outside TEXT", p) } size := int64(len(text.P)) - p.Pc if p.Link != nil { size = p.Link.Pc - p.Pc } else if p.Isize != 0 { size = int64(p.Isize) } var code []byte if p.Pc < int64(len(text.P)) { code = text.P[p.Pc:] if size < int64(len(code)) { code = code[:size] } } codeHex := fmt.Sprintf("%x", code) if codeHex == "" { codeHex = "empty" } ok := false for _, hex := range strings.Split(hexes, " or ") { if codeHex == hex { ok = true break } } if !ok { t.Errorf("%s: have encoding %s, want %s", p, codeHex, hexes) } } if len(hexByLine) > 0 { var missing []string for key := range hexByLine { missing = append(missing, key) } sort.Strings(missing) for _, line := range missing { t.Errorf("%s: did not find instruction encoding", line) } } } func isHexes(s string) bool { if s == "" { return false } if s == "empty" { return true } for _, f := range strings.Split(s, " or ") { if f == "" || len(f)%2 != 0 || strings.TrimLeft(f, "0123456789abcdef") != "" { return false } } return true } // It would be nice if the error messages began with // the standard file:line: prefix, // but that's not where we are today. // It might be at the beginning but it might be in the middle of the printed instruction. var fileLineRE = regexp.MustCompile(`(?:^|\()(testdata[/\\][0-9a-z]+\.s:[0-9]+)(?:$|\))`) // Same as in test/run.go var ( errRE = regexp.MustCompile(`// ERROR ?(.*)`) errQuotesRE = regexp.MustCompile(`"([^"]*)"`) ) func testErrors(t *testing.T, goarch, file string) { input := filepath.Join("testdata", file+".s") architecture, ctxt := setArch(goarch) lexer := lex.NewLexer(input) parser := NewParser(ctxt, architecture, lexer) pList := new(obj.Plist) var ok bool testOut = new(bytes.Buffer) // The assembler writes test output to this buffer. ctxt.Bso = bufio.NewWriter(os.Stdout) defer ctxt.Bso.Flush() failed := false var errBuf bytes.Buffer ctxt.DiagFunc = func(format string, args ...interface{}) { failed = true s := fmt.Sprintf(format, args...) if !strings.HasSuffix(s, "\n") { s += "\n" } errBuf.WriteString(s) } pList.Firstpc, ok = parser.Parse() obj.Flushplist(ctxt, pList, nil, "") if ok && !failed { t.Errorf("asm: %s had no errors", goarch) } errors := map[string]string{} for _, line := range strings.Split(errBuf.String(), "\n") { if line == "" || strings.HasPrefix(line, "\t") { continue } m := fileLineRE.FindStringSubmatch(line) if m == nil { t.Errorf("unexpected error: %v", line) continue } fileline := m[1] if errors[fileline] != "" && errors[fileline] != line { t.Errorf("multiple errors on %s:\n\t%s\n\t%s", fileline, errors[fileline], line) continue } errors[fileline] = line } // Reconstruct expected errors by independently "parsing" the input. data, err := ioutil.ReadFile(input) if err != nil { t.Error(err) return } lineno := 0 lines := strings.Split(string(data), "\n") for _, line := range lines { lineno++ fileline := fmt.Sprintf("%s:%d", input, lineno) if m := errRE.FindStringSubmatch(line); m != nil { all := m[1] mm := errQuotesRE.FindAllStringSubmatch(all, -1) if len(mm) != 1 { t.Errorf("%s: invalid errorcheck line:\n%s", fileline, line) } else if err := errors[fileline]; err == "" { t.Errorf("%s: missing error, want %s", fileline, all) } else if !strings.Contains(err, mm[0][1]) { t.Errorf("%s: wrong error for %s:\n%s", fileline, all, err) } } else { if errors[fileline] != "" { t.Errorf("unexpected error on %s: %v", fileline, errors[fileline]) } } delete(errors, fileline) } var extra []string for key := range errors { extra = append(extra, key) } sort.Strings(extra) for _, fileline := range extra { t.Errorf("unexpected error on %s: %v", fileline, errors[fileline]) } } func Test386EndToEnd(t *testing.T) { defer func(old string) { objabi.GO386 = old }(objabi.GO386) for _, go386 := range []string{"387", "sse2"} { t.Logf("GO386=%v", go386) objabi.GO386 = go386 testEndToEnd(t, "386", "386") } } func TestARMEndToEnd(t *testing.T) { defer func(old int) { objabi.GOARM = old }(objabi.GOARM) for _, goarm := range []int{5, 6, 7} { t.Logf("GOARM=%d", goarm) objabi.GOARM = goarm testEndToEnd(t, "arm", "arm") if goarm == 6 { testEndToEnd(t, "arm", "armv6") } } } func TestARMErrors(t *testing.T) { testErrors(t, "arm", "armerror") } func TestARM64EndToEnd(t *testing.T) { testEndToEnd(t, "arm64", "arm64") } func TestARM64Encoder(t *testing.T) { testEndToEnd(t, "arm64", "arm64enc") } func TestARM64Errors(t *testing.T) { testErrors(t, "arm64", "arm64error") } func TestAMD64EndToEnd(t *testing.T) { testEndToEnd(t, "amd64", "amd64") } func Test386Encoder(t *testing.T) { testEndToEnd(t, "386", "386enc") } func TestAMD64Encoder(t *testing.T) { testEndToEnd(t, "amd64", "amd64enc") testEndToEnd(t, "amd64", "amd64enc_extra") } func TestAMD64Errors(t *testing.T) { testErrors(t, "amd64", "amd64error") } func TestMIPSEndToEnd(t *testing.T) { testEndToEnd(t, "mips", "mips") testEndToEnd(t, "mips64", "mips64") } func TestPPC64EndToEnd(t *testing.T) { testEndToEnd(t, "ppc64", "ppc64") } func TestPPC64Encoder(t *testing.T) { testEndToEnd(t, "ppc64", "ppc64enc") } func TestS390XEndToEnd(t *testing.T) { testEndToEnd(t, "s390x", "s390x") }
Java
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/android/chrome_jni_onload.h" #include "chrome/app/android/chrome_android_initializer.h" #include "content/public/app/content_jni_onload.h" namespace android { bool OnJNIOnLoadInit() { if (!content::android::OnJNIOnLoadInit()) return false; return RunChrome(); } } // namespace android
Java
package ch.epfl.lamp.slick.direct import org.scalatest.FlatSpec import slick.driver.H2Driver.api._ class ProblemSpec extends FlatSpec with TestHelper { // TODO: WIP }
Java
/* * ctm-cvb * * CollapsedBayesEngine */ #ifndef COLLAPSED_BAYES_ENGINE_H #define COLLAPSED_BAYES_ENGINE_H #include "InferenceEngine.h" #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> namespace ctm { class CollapsedBayesEngine : public InferenceEngine { /*** * Model hyperparameters learnt by maximisation */ struct Model { gsl_vector* mu; gsl_matrix* cov; gsl_matrix* inv_cov; gsl_matrix* log_beta; double gamma; double log_det_inv_cov; Model( int D, int K, int V ); ~Model(); }; /*** * Data collected in the 'expectation' step, to be used in the * maximisation step. */ struct CollectedData { // Expected counts gsl_matrix* n_ij; gsl_matrix* n_jk; double ndata; CollectedData( int D, int K, int V ); ~CollectedData(); }; /*** * Variational parameters to be optimised in the expectation step */ struct Parameters { // Stores \phi_{*kj} gsl_matrix* phi; gsl_matrix* log_phi; // Likelihood saved for optimisation purposes double lhood; Parameters( int K, int V ); ~Parameters(); }; public: CollapsedBayesEngine(InferenceOptions& options); // Load/Store in a file virtual void init( string filename ); virtual void save( string filename ); // Parse a single file virtual double infer( Corpus& data ); virtual double infer( Corpus& data, CollectedData* cd ); virtual void estimate( Corpus& data ); protected: Model* model; }; }; #endif // COLLAPSED_BAYES_ENGINE_H
Java
isPrime :: Integral a => a -> Bool isPrime 2 = True isPrime 3 = True isPrime n = all (\ x -> x /= 0) [n `mod` x | x <- [2..(truncate $ sqrt (fromIntegral n) + 1)]] goldbach :: (Integral t, Integral t1) => t1 -> (t, t1) goldbach n = goldbach' 3 (n - 3) where goldbach' a b | isPrime a && isPrime b = (a, b) | otherwise = goldbach' (a + 2) (b - 2)
Java
/** * Copyright (c) 2013, Yahoo! Inc. All rights reserved. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms */ package visualoozie.api; public class WorkflowNode { public enum NodeType{ START , KILL , DECISION , FORK , JOIN , END , ACTION } private String name; private NodeType type; private String[] to; public String getName() { return name; } public void setName(String name) { this.name = name; } public NodeType getType() { return type; } public void setType(NodeType type) { this.type = type; } public String[] getTo() { return to; } public void setTo(String[] to) { this.to = to; } }
Java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__char_file_execl_43.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-43.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: file Read input from a file * GoodSource: Fixed string * Sinks: execl * BadSink : execute command with execl * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT "cmd.exe" #define COMMAND_ARG1 "/c" #define COMMAND_ARG2 "dir " #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH "/bin/sh" #define COMMAND_INT "sh" #define COMMAND_ARG1 "-c" #define COMMAND_ARG2 "ls " #define COMMAND_ARG3 data #endif #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #ifdef _WIN32 #include <process.h> #define EXECL _execl #else /* NOT _WIN32 */ #define EXECL execl #endif namespace CWE78_OS_Command_Injection__char_file_execl_43 { #ifndef OMITBAD static void badSource(char * &data) { { /* Read input from a file */ size_t dataLen = strlen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (100-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL) { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } fclose(pFile); } } } } void bad() { char * data; char dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; badSource(data); /* execl - specify the path where the command is located */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSource(char * &data) { /* FIX: Append a fixed string to data (not user / external input) */ strcat(data, "*.*"); } static void goodG2B() { char * data; char dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; goodG2BSource(data); /* execl - specify the path where the command is located */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE78_OS_Command_Injection__char_file_execl_43; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
Java
INSTALL_DIR=usr/local/lib DEPS="coreutils" "sudo" REBARPROFILE ?= default include ../../config.mk include ../../_build/${REBARPROFILE}/lib/fifo_utils/priv/pkgng.mk .PHONY: prepare prepare: -rm -r $(STAGE_DIR)/$(INSTALL_DIR)/$(COMPONENT_INTERNAL) -rm $(STAGE_DIR)/+* -rm $(STAGE_DIR)/plist mkdir -p $(STAGE_DIR)/$(INSTALL_DIR) cp -r ../../_build/${REBARPROFILE}/rel/$(COMPONENT_INTERNAL) $(STAGE_DIR)/$(INSTALL_DIR)/$(COMPONENT_INTERNAL)
Java
/*- * Copyright (c) 1996-1999 * Kazutaka YOKOTA (yokota@zodiac.mech.utsunomiya-u.ac.jp) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $Id: atkbdc.c,v 1.1 1999/01/09 02:44:50 yokota Exp $ * from kbdio.c,v 1.13 1998/09/25 11:55:46 yokota Exp */ #include "atkbdc.h" #include "opt_kbd.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/malloc.h> #include <sys/syslog.h> #include <machine/clock.h> #include <dev/kbd/atkbdcreg.h> #ifndef __i386__ #include <isa/isareg.h> #else #include <i386/isa/isa.h> #endif /* constants */ #define MAXKBDC MAX(NATKBDC, 1) /* macros */ #ifndef MAX #define MAX(x, y) ((x) > (y) ? (x) : (y)) #endif #define kbdcp(p) ((atkbdc_softc_t *)(p)) #define nextq(i) (((i) + 1) % KBDQ_BUFSIZE) #define availq(q) ((q)->head != (q)->tail) #if KBDIO_DEBUG >= 2 #define emptyq(q) ((q)->tail = (q)->head = (q)->qcount = 0) #else #define emptyq(q) ((q)->tail = (q)->head = 0) #endif /* local variables */ /* * We always need at least one copy of the kbdc_softc struct for the * low-level console. As the low-level console accesses the keyboard * controller before kbdc, and all other devices, is probed, we * statically allocate one entry. XXX */ static atkbdc_softc_t default_kbdc; static atkbdc_softc_t *atkbdc_softc[MAXKBDC] = { &default_kbdc }; static int verbose = KBDIO_DEBUG; /* function prototypes */ static int atkbdc_setup(atkbdc_softc_t *sc, int port); static int addq(kqueue *q, int c); static int removeq(kqueue *q); static int wait_while_controller_busy(atkbdc_softc_t *kbdc); static int wait_for_data(atkbdc_softc_t *kbdc); static int wait_for_kbd_data(atkbdc_softc_t *kbdc); static int wait_for_kbd_ack(atkbdc_softc_t *kbdc); static int wait_for_aux_data(atkbdc_softc_t *kbdc); static int wait_for_aux_ack(atkbdc_softc_t *kbdc); #if NATKBDC > 0 atkbdc_softc_t *atkbdc_get_softc(int unit) { atkbdc_softc_t *sc; if (unit >= sizeof(atkbdc_softc)/sizeof(atkbdc_softc[0])) return NULL; sc = atkbdc_softc[unit]; if (sc == NULL) { sc = atkbdc_softc[unit] = malloc(sizeof(*sc), M_DEVBUF, M_NOWAIT); if (sc == NULL) return NULL; bzero(sc, sizeof(*sc)); sc->port = -1; /* XXX */ } return sc; } int atkbdc_probe_unit(atkbdc_softc_t *sc, int unit, int port) { return atkbdc_setup(sc, port); } #endif /* NATKBDC > 0 */ /* the backdoor to the keyboard controller! XXX */ int atkbdc_configure(void) { return atkbdc_setup(atkbdc_softc[0], -1); } static int atkbdc_setup(atkbdc_softc_t *sc, int port) { if (port <= 0) port = IO_KBD; if (sc->port <= 0) { sc->command_byte = -1; sc->command_mask = 0; sc->lock = FALSE; sc->kbd.head = sc->kbd.tail = 0; sc->aux.head = sc->aux.tail = 0; #if KBDIO_DEBUG >= 2 sc->kbd.call_count = 0; sc->kbd.qcount = sc->kbd.max_qcount = 0; sc->aux.call_count = 0; sc->aux.qcount = sc->aux.max_qcount = 0; #endif } sc->port = port; /* may override the previous value */ return 0; } /* associate a port number with a KBDC */ KBDC kbdc_open(int port) { int s; int i; if (port <= 0) port = IO_KBD; s = spltty(); for (i = 0; i < sizeof(atkbdc_softc)/sizeof(atkbdc_softc[0]); ++i) { if (atkbdc_softc[i] == NULL) continue; if (atkbdc_softc[i]->port == port) { splx(s); return (KBDC)atkbdc_softc[i]; } if (atkbdc_softc[i]->port <= 0) { if (atkbdc_setup(atkbdc_softc[i], port)) break; splx(s); return (KBDC)atkbdc_softc[i]; } } splx(s); return NULL; } /* * I/O access arbitration in `kbdio' * * The `kbdio' module uses a simplistic convention to arbitrate * I/O access to the controller/keyboard/mouse. The convention requires * close cooperation of the calling device driver. * * The device driver which utilizes the `kbdio' module are assumed to * have the following set of routines. * a. An interrupt handler (the bottom half of the driver). * b. Timeout routines which may briefly polls the keyboard controller. * c. Routines outside interrupt context (the top half of the driver). * They should follow the rules below: * 1. The interrupt handler may assume that it always has full access * to the controller/keyboard/mouse. * 2. The other routines must issue `spltty()' if they wish to * prevent the interrupt handler from accessing * the controller/keyboard/mouse. * 3. The timeout routines and the top half routines of the device driver * arbitrate I/O access by observing the lock flag in `kbdio'. * The flag is manipulated via `kbdc_lock()'; when one wants to * perform I/O, call `kbdc_lock(kbdc, TRUE)' and proceed only if * the call returns with TRUE. Otherwise the caller must back off. * Call `kbdc_lock(kbdc, FALSE)' when necessary I/O operaion * is finished. This mechanism does not prevent the interrupt * handler from being invoked at any time and carrying out I/O. * Therefore, `spltty()' must be strategically placed in the device * driver code. Also note that the timeout routine may interrupt * `kbdc_lock()' called by the top half of the driver, but this * interruption is OK so long as the timeout routine observes the * the rule 4 below. * 4. The interrupt and timeout routines should not extend I/O operation * across more than one interrupt or timeout; they must complete * necessary I/O operation within one invokation of the routine. * This measns that if the timeout routine acquires the lock flag, * it must reset the flag to FALSE before it returns. */ /* set/reset polling lock */ int kbdc_lock(KBDC p, int lock) { int prevlock; prevlock = kbdcp(p)->lock; kbdcp(p)->lock = lock; return (prevlock != lock); } /* check if any data is waiting to be processed */ int kbdc_data_ready(KBDC p) { return (availq(&kbdcp(p)->kbd) || availq(&kbdcp(p)->aux) || (inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_ANY_BUFFER_FULL)); } /* queuing functions */ static int addq(kqueue *q, int c) { if (nextq(q->tail) != q->head) { q->q[q->tail] = c; q->tail = nextq(q->tail); #if KBDIO_DEBUG >= 2 ++q->call_count; ++q->qcount; if (q->qcount > q->max_qcount) q->max_qcount = q->qcount; #endif return TRUE; } return FALSE; } static int removeq(kqueue *q) { int c; if (q->tail != q->head) { c = q->q[q->head]; q->head = nextq(q->head); #if KBDIO_DEBUG >= 2 --q->qcount; #endif return c; } return -1; } /* * device I/O routines */ static int wait_while_controller_busy(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 100msec at most */ int retry = 5000; int port = kbdc->port; int f; while ((f = inb(port + KBD_STATUS_PORT)) & KBDS_INPUT_BUFFER_FULL) { if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdc->kbd, inb(port + KBD_DATA_PORT)); } else if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdc->aux, inb(port + KBD_DATA_PORT)); } DELAY(KBDC_DELAYTIME); if (--retry < 0) return FALSE; } return TRUE; } /* * wait for any data; whether it's from the controller, * the keyboard, or the aux device. */ static int wait_for_data(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 200msec at most */ int retry = 10000; int port = kbdc->port; int f; while ((f = inb(port + KBD_STATUS_PORT) & KBDS_ANY_BUFFER_FULL) == 0) { DELAY(KBDC_DELAYTIME); if (--retry < 0) return 0; } DELAY(KBDD_DELAYTIME); return f; } /* wait for data from the keyboard */ static int wait_for_kbd_data(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 200msec at most */ int retry = 10000; int port = kbdc->port; int f; while ((f = inb(port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL) != KBDS_KBD_BUFFER_FULL) { if (f == KBDS_AUX_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdc->aux, inb(port + KBD_DATA_PORT)); } DELAY(KBDC_DELAYTIME); if (--retry < 0) return 0; } DELAY(KBDD_DELAYTIME); return f; } /* * wait for an ACK(FAh), RESEND(FEh), or RESET_FAIL(FCh) from the keyboard. * queue anything else. */ static int wait_for_kbd_ack(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 200msec at most */ int retry = 10000; int port = kbdc->port; int f; int b; while (retry-- > 0) { if ((f = inb(port + KBD_STATUS_PORT)) & KBDS_ANY_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); b = inb(port + KBD_DATA_PORT); if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) { if ((b == KBD_ACK) || (b == KBD_RESEND) || (b == KBD_RESET_FAIL)) return b; addq(&kbdc->kbd, b); } else if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) { addq(&kbdc->aux, b); } } DELAY(KBDC_DELAYTIME); } return -1; } /* wait for data from the aux device */ static int wait_for_aux_data(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 200msec at most */ int retry = 10000; int port = kbdc->port; int f; while ((f = inb(port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL) != KBDS_AUX_BUFFER_FULL) { if (f == KBDS_KBD_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdc->kbd, inb(port + KBD_DATA_PORT)); } DELAY(KBDC_DELAYTIME); if (--retry < 0) return 0; } DELAY(KBDD_DELAYTIME); return f; } /* * wait for an ACK(FAh), RESEND(FEh), or RESET_FAIL(FCh) from the aux device. * queue anything else. */ static int wait_for_aux_ack(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 200msec at most */ int retry = 10000; int port = kbdc->port; int f; int b; while (retry-- > 0) { if ((f = inb(port + KBD_STATUS_PORT)) & KBDS_ANY_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); b = inb(port + KBD_DATA_PORT); if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) { if ((b == PSM_ACK) || (b == PSM_RESEND) || (b == PSM_RESET_FAIL)) return b; addq(&kbdc->aux, b); } else if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) { addq(&kbdc->kbd, b); } } DELAY(KBDC_DELAYTIME); } return -1; } /* write a one byte command to the controller */ int write_controller_command(KBDC p, int c) { if (!wait_while_controller_busy(kbdcp(p))) return FALSE; outb(kbdcp(p)->port + KBD_COMMAND_PORT, c); return TRUE; } /* write a one byte data to the controller */ int write_controller_data(KBDC p, int c) { if (!wait_while_controller_busy(kbdcp(p))) return FALSE; outb(kbdcp(p)->port + KBD_DATA_PORT, c); return TRUE; } /* write a one byte keyboard command */ int write_kbd_command(KBDC p, int c) { if (!wait_while_controller_busy(kbdcp(p))) return FALSE; outb(kbdcp(p)->port + KBD_DATA_PORT, c); return TRUE; } /* write a one byte auxiliary device command */ int write_aux_command(KBDC p, int c) { if (!write_controller_command(p, KBDC_WRITE_TO_AUX)) return FALSE; return write_controller_data(p, c); } /* send a command to the keyboard and wait for ACK */ int send_kbd_command(KBDC p, int c) { int retry = KBD_MAXRETRY; int res = -1; while (retry-- > 0) { if (!write_kbd_command(p, c)) continue; res = wait_for_kbd_ack(kbdcp(p)); if (res == KBD_ACK) break; } return res; } /* send a command to the auxiliary device and wait for ACK */ int send_aux_command(KBDC p, int c) { int retry = KBD_MAXRETRY; int res = -1; while (retry-- > 0) { if (!write_aux_command(p, c)) continue; /* * FIXME: XXX * The aux device may have already sent one or two bytes of * status data, when a command is received. It will immediately * stop data transmission, thus, leaving an incomplete data * packet in our buffer. We have to discard any unprocessed * data in order to remove such packets. Well, we may remove * unprocessed, but necessary data byte as well... */ emptyq(&kbdcp(p)->aux); res = wait_for_aux_ack(kbdcp(p)); if (res == PSM_ACK) break; } return res; } /* send a command and a data to the keyboard, wait for ACKs */ int send_kbd_command_and_data(KBDC p, int c, int d) { int retry; int res = -1; for (retry = KBD_MAXRETRY; retry > 0; --retry) { if (!write_kbd_command(p, c)) continue; res = wait_for_kbd_ack(kbdcp(p)); if (res == KBD_ACK) break; else if (res != KBD_RESEND) return res; } if (retry <= 0) return res; for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) { if (!write_kbd_command(p, d)) continue; res = wait_for_kbd_ack(kbdcp(p)); if (res != KBD_RESEND) break; } return res; } /* send a command and a data to the auxiliary device, wait for ACKs */ int send_aux_command_and_data(KBDC p, int c, int d) { int retry; int res = -1; for (retry = KBD_MAXRETRY; retry > 0; --retry) { if (!write_aux_command(p, c)) continue; emptyq(&kbdcp(p)->aux); res = wait_for_aux_ack(kbdcp(p)); if (res == PSM_ACK) break; else if (res != PSM_RESEND) return res; } if (retry <= 0) return res; for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) { if (!write_aux_command(p, d)) continue; res = wait_for_aux_ack(kbdcp(p)); if (res != PSM_RESEND) break; } return res; } /* * read one byte from any source; whether from the controller, * the keyboard, or the aux device */ int read_controller_data(KBDC p) { if (availq(&kbdcp(p)->kbd)) return removeq(&kbdcp(p)->kbd); if (availq(&kbdcp(p)->aux)) return removeq(&kbdcp(p)->aux); if (!wait_for_data(kbdcp(p))) return -1; /* timeout */ return inb(kbdcp(p)->port + KBD_DATA_PORT); } #if KBDIO_DEBUG >= 2 static int call = 0; #endif /* read one byte from the keyboard */ int read_kbd_data(KBDC p) { #if KBDIO_DEBUG >= 2 if (++call > 2000) { call = 0; log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, " "aux q: %d calls, max %d chars\n", kbdcp(p)->kbd.call_count, kbdcp(p)->kbd.max_qcount, kbdcp(p)->aux.call_count, kbdcp(p)->aux.max_qcount); } #endif if (availq(&kbdcp(p)->kbd)) return removeq(&kbdcp(p)->kbd); if (!wait_for_kbd_data(kbdcp(p))) return -1; /* timeout */ return inb(kbdcp(p)->port + KBD_DATA_PORT); } /* read one byte from the keyboard, but return immediately if * no data is waiting */ int read_kbd_data_no_wait(KBDC p) { int f; #if KBDIO_DEBUG >= 2 if (++call > 2000) { call = 0; log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, " "aux q: %d calls, max %d chars\n", kbdcp(p)->kbd.call_count, kbdcp(p)->kbd.max_qcount, kbdcp(p)->aux.call_count, kbdcp(p)->aux.max_qcount); } #endif if (availq(&kbdcp(p)->kbd)) return removeq(&kbdcp(p)->kbd); f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL; if (f == KBDS_AUX_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdcp(p)->aux, inb(kbdcp(p)->port + KBD_DATA_PORT)); f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL; } if (f == KBDS_KBD_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); return inb(kbdcp(p)->port + KBD_DATA_PORT); } return -1; /* no data */ } /* read one byte from the aux device */ int read_aux_data(KBDC p) { if (availq(&kbdcp(p)->aux)) return removeq(&kbdcp(p)->aux); if (!wait_for_aux_data(kbdcp(p))) return -1; /* timeout */ return inb(kbdcp(p)->port + KBD_DATA_PORT); } /* read one byte from the aux device, but return immediately if * no data is waiting */ int read_aux_data_no_wait(KBDC p) { int f; if (availq(&kbdcp(p)->aux)) return removeq(&kbdcp(p)->aux); f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL; if (f == KBDS_KBD_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdcp(p)->kbd, inb(kbdcp(p)->port + KBD_DATA_PORT)); f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL; } if (f == KBDS_AUX_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); return inb(kbdcp(p)->port + KBD_DATA_PORT); } return -1; /* no data */ } /* discard data from the keyboard */ void empty_kbd_buffer(KBDC p, int wait) { int t; int b; int f; #if KBDIO_DEBUG >= 2 int c1 = 0; int c2 = 0; #endif int delta = 2; for (t = wait; t > 0; ) { if ((f = inb(kbdcp(p)->port + KBD_STATUS_PORT)) & KBDS_ANY_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); b = inb(kbdcp(p)->port + KBD_DATA_PORT); if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) { addq(&kbdcp(p)->aux, b); #if KBDIO_DEBUG >= 2 ++c2; } else { ++c1; #endif } t = wait; } else { t -= delta; } DELAY(delta*1000); } #if KBDIO_DEBUG >= 2 if ((c1 > 0) || (c2 > 0)) log(LOG_DEBUG, "kbdc: %d:%d char read (empty_kbd_buffer)\n", c1, c2); #endif emptyq(&kbdcp(p)->kbd); } /* discard data from the aux device */ void empty_aux_buffer(KBDC p, int wait) { int t; int b; int f; #if KBDIO_DEBUG >= 2 int c1 = 0; int c2 = 0; #endif int delta = 2; for (t = wait; t > 0; ) { if ((f = inb(kbdcp(p)->port + KBD_STATUS_PORT)) & KBDS_ANY_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); b = inb(kbdcp(p)->port + KBD_DATA_PORT); if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) { addq(&kbdcp(p)->kbd, b); #if KBDIO_DEBUG >= 2 ++c1; } else { ++c2; #endif } t = wait; } else { t -= delta; } DELAY(delta*1000); } #if KBDIO_DEBUG >= 2 if ((c1 > 0) || (c2 > 0)) log(LOG_DEBUG, "kbdc: %d:%d char read (empty_aux_buffer)\n", c1, c2); #endif emptyq(&kbdcp(p)->aux); } /* discard any data from the keyboard or the aux device */ void empty_both_buffers(KBDC p, int wait) { int t; int f; #if KBDIO_DEBUG >= 2 int c1 = 0; int c2 = 0; #endif int delta = 2; for (t = wait; t > 0; ) { if ((f = inb(kbdcp(p)->port + KBD_STATUS_PORT)) & KBDS_ANY_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); (void)inb(kbdcp(p)->port + KBD_DATA_PORT); #if KBDIO_DEBUG >= 2 if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) ++c1; else ++c2; #endif t = wait; } else { t -= delta; } DELAY(delta*1000); } #if KBDIO_DEBUG >= 2 if ((c1 > 0) || (c2 > 0)) log(LOG_DEBUG, "kbdc: %d:%d char read (empty_both_buffers)\n", c1, c2); #endif emptyq(&kbdcp(p)->kbd); emptyq(&kbdcp(p)->aux); } /* keyboard and mouse device control */ /* NOTE: enable the keyboard port but disable the keyboard * interrupt before calling "reset_kbd()". */ int reset_kbd(KBDC p) { int retry = KBD_MAXRETRY; int again = KBD_MAXWAIT; int c = KBD_RESEND; /* keep the compiler happy */ while (retry-- > 0) { empty_both_buffers(p, 10); if (!write_kbd_command(p, KBDC_RESET_KBD)) continue; emptyq(&kbdcp(p)->kbd); c = read_controller_data(p); if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: RESET_KBD return code:%04x\n", c); if (c == KBD_ACK) /* keyboard has agreed to reset itself... */ break; } if (retry < 0) return FALSE; while (again-- > 0) { /* wait awhile, well, in fact we must wait quite loooooooooooong */ DELAY(KBD_RESETDELAY*1000); c = read_controller_data(p); /* RESET_DONE/RESET_FAIL */ if (c != -1) /* wait again if the controller is not ready */ break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: RESET_KBD status:%04x\n", c); if (c != KBD_RESET_DONE) return FALSE; return TRUE; } /* NOTE: enable the aux port but disable the aux interrupt * before calling `reset_aux_dev()'. */ int reset_aux_dev(KBDC p) { int retry = KBD_MAXRETRY; int again = KBD_MAXWAIT; int c = PSM_RESEND; /* keep the compiler happy */ while (retry-- > 0) { empty_both_buffers(p, 10); if (!write_aux_command(p, PSMC_RESET_DEV)) continue; emptyq(&kbdcp(p)->aux); /* NOTE: Compaq Armada laptops require extra delay here. XXX */ for (again = KBD_MAXWAIT; again > 0; --again) { DELAY(KBD_RESETDELAY*1000); c = read_aux_data_no_wait(p); if (c != -1) break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: RESET_AUX return code:%04x\n", c); if (c == PSM_ACK) /* aux dev is about to reset... */ break; } if (retry < 0) return FALSE; for (again = KBD_MAXWAIT; again > 0; --again) { /* wait awhile, well, quite looooooooooooong */ DELAY(KBD_RESETDELAY*1000); c = read_aux_data_no_wait(p); /* RESET_DONE/RESET_FAIL */ if (c != -1) /* wait again if the controller is not ready */ break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: RESET_AUX status:%04x\n", c); if (c != PSM_RESET_DONE) /* reset status */ return FALSE; c = read_aux_data(p); /* device ID */ if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: RESET_AUX ID:%04x\n", c); /* NOTE: we could check the device ID now, but leave it later... */ return TRUE; } /* controller diagnostics and setup */ int test_controller(KBDC p) { int retry = KBD_MAXRETRY; int again = KBD_MAXWAIT; int c = KBD_DIAG_FAIL; while (retry-- > 0) { empty_both_buffers(p, 10); if (write_controller_command(p, KBDC_DIAGNOSE)) break; } if (retry < 0) return FALSE; emptyq(&kbdcp(p)->kbd); while (again-- > 0) { /* wait awhile */ DELAY(KBD_RESETDELAY*1000); c = read_controller_data(p); /* DIAG_DONE/DIAG_FAIL */ if (c != -1) /* wait again if the controller is not ready */ break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: DIAGNOSE status:%04x\n", c); return (c == KBD_DIAG_DONE); } int test_kbd_port(KBDC p) { int retry = KBD_MAXRETRY; int again = KBD_MAXWAIT; int c = -1; while (retry-- > 0) { empty_both_buffers(p, 10); if (write_controller_command(p, KBDC_TEST_KBD_PORT)) break; } if (retry < 0) return FALSE; emptyq(&kbdcp(p)->kbd); while (again-- > 0) { c = read_controller_data(p); if (c != -1) /* try again if the controller is not ready */ break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: TEST_KBD_PORT status:%04x\n", c); return c; } int test_aux_port(KBDC p) { int retry = KBD_MAXRETRY; int again = KBD_MAXWAIT; int c = -1; while (retry-- > 0) { empty_both_buffers(p, 10); if (write_controller_command(p, KBDC_TEST_AUX_PORT)) break; } if (retry < 0) return FALSE; emptyq(&kbdcp(p)->kbd); while (again-- > 0) { c = read_controller_data(p); if (c != -1) /* try again if the controller is not ready */ break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: TEST_AUX_PORT status:%04x\n", c); return c; } int kbdc_get_device_mask(KBDC p) { return kbdcp(p)->command_mask; } void kbdc_set_device_mask(KBDC p, int mask) { kbdcp(p)->command_mask = mask & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS); } int get_controller_command_byte(KBDC p) { if (kbdcp(p)->command_byte != -1) return kbdcp(p)->command_byte; if (!write_controller_command(p, KBDC_GET_COMMAND_BYTE)) return -1; emptyq(&kbdcp(p)->kbd); kbdcp(p)->command_byte = read_controller_data(p); return kbdcp(p)->command_byte; } int set_controller_command_byte(KBDC p, int mask, int command) { if (get_controller_command_byte(p) == -1) return FALSE; command = (kbdcp(p)->command_byte & ~mask) | (command & mask); if (command & KBD_DISABLE_KBD_PORT) { if (!write_controller_command(p, KBDC_DISABLE_KBD_PORT)) return FALSE; } if (!write_controller_command(p, KBDC_SET_COMMAND_BYTE)) return FALSE; if (!write_controller_data(p, command)) return FALSE; kbdcp(p)->command_byte = command; if (verbose) log(LOG_DEBUG, "kbdc: new command byte:%04x (set_controller...)\n", command); return TRUE; }
Java
call this commnad yii migrate --migrationPath=@yii/rbac/migrations In case of yii2-app-base template, from which I have created my application, there is a config/console.php configuration file where the authManager needs to be declared. It is not sufficient to have it in the config/web.php declared only. 'authManager' => [ 'class' => 'yii\rbac\DbManager', 'defaultRoles' => ['guest'], ], ALTER TABLE `auth_assignment` CHANGE `created_at` `created_at` VARCHAR(50) NULL DEFAULT NULL; --------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------OR Directly--------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------- drop table if exists `auth_assignment`; drop table if exists `auth_item_child`; drop table if exists `auth_item`; drop table if exists `auth_rule`; create table `auth_rule` ( `name` varchar(64) not null, `data` text, `created_at` VARCHAR(50) NULL DEFAULT NULL, `updated_at` VARCHAR(50) NULL DEFAULT NULL, primary key (`name`) ) engine InnoDB; create table `auth_item` ( `name` varchar(64) not null, `type` integer not null, `description` text, `rule_name` varchar(64), `data` text, `created_at` VARCHAR(50) NULL DEFAULT NULL, `updated_at` VARCHAR(50) NULL DEFAULT NULL, primary key (`name`), foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade, key `type` (`type`) ) engine InnoDB; create table `auth_item_child` ( `parent` varchar(64) not null, `child` varchar(64) not null, primary key (`parent`, `child`), foreign key (`parent`) references `auth_item` (`name`) on delete cascade on update cascade, foreign key (`child`) references `auth_item` (`name`) on delete cascade on update cascade ) engine InnoDB; create table `auth_assignment` ( `item_name` varchar(64) not null, `user_id` varchar(64) not null, `created_at` VARCHAR(50) NULL DEFAULT NULL, primary key (`item_name`, `user_id`), foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade ) engine InnoDB;
Java
// +build l476xx // Peripheral: CAN_TxMailBox_Periph Controller Area Network TxMailBox. // Instances: // Registers: // 0x00 32 TIR CAN TX mailbox identifier register. // 0x04 32 TDTR CAN mailbox data length control and time stamp register. // 0x08 32 TDLR CAN mailbox data low register. // 0x0C 32 TDHR CAN mailbox data high register. // Import: // stm32/o/l476xx/mmap package can // DO NOT EDIT THIS FILE. GENERATED BY stm32xgen.
Java
""" Vision-specific analysis functions. $Id: featureresponses.py 7714 2008-01-24 16:42:21Z antolikjan $ """ __version__='$Revision: 7714 $' from math import fmod,floor,pi,sin,cos,sqrt import numpy from numpy.oldnumeric import Float from numpy import zeros, array, size, empty, object_ #import scipy try: import pylab except ImportError: print "Warning: Could not import matplotlib; pylab plots will not work." import param import topo from topo.base.cf import CFSheet from topo.base.sheetview import SheetView from topo.misc.filepath import normalize_path from topo.misc.numbergenerator import UniformRandom from topo.plotting.plotgroup import create_plotgroup, plotgroups from topo.command.analysis import measure_sine_pref max_value = 0 global_index = () def _complexity_rec(x,y,index,depth,fm): """ Recurrent helper function for complexity() """ global max_value global global_index if depth<size(fm.features): for i in range(size(fm.features[depth].values)): _complexity_rec(x,y,index + (i,),depth+1,fm) else: if max_value < fm.full_matrix[index][x][y]: global_index = index max_value = fm.full_matrix[index][x][y] def complexity(full_matrix): global global_index global max_value """This function expects as an input a object of type FullMatrix which contains responses of all neurons in a sheet to stimuly with different varying parameter values. One of these parameters (features) has to be phase. In such case it computes the classic modulation ratio (see Hawken et al. for definition) for each neuron and returns them as a matrix. """ rows,cols = full_matrix.matrix_shape complexity = zeros(full_matrix.matrix_shape) complex_matrix = zeros(full_matrix.matrix_shape,object_) fftmeasure = zeros(full_matrix.matrix_shape,Float) i = 0 for f in full_matrix.features: if f.name == "phase": phase_index = i break i=i+1 sum = 0.0 res = 0.0 average = 0.0 for x in range(rows): for y in range(cols): complex_matrix[x,y] = []# max_value=-0.01 global_index = () _complexity_rec(x,y,(),0,full_matrix) #compute the sum of the responses over phases given the found index of highest response iindex = array(global_index) sum = 0.0 for i in range(size(full_matrix.features[phase_index].values)): iindex[phase_index] = i sum = sum + full_matrix.full_matrix[tuple(iindex.tolist())][x][y] #average average = sum / float(size(full_matrix.features[phase_index].values)) res = 0.0 #compute the sum of absolute values of the responses minus average for i in range(size(full_matrix.features[phase_index].values)): iindex[phase_index] = i res = res + abs(full_matrix.full_matrix[tuple(iindex.tolist())][x][y] - average) complex_matrix[x,y] = complex_matrix[x,y] + [full_matrix.full_matrix[tuple(iindex.tolist())][x][y]] #this is taking away the DC component #complex_matrix[x,y] -= numpy.min(complex_matrix[x,y]) if x==15 and y==15: pylab.figure() pylab.plot(complex_matrix[x,y]) if x==26 and y==26: pylab.figure() pylab.plot(complex_matrix[x,y]) #complexity[x,y] = res / (2*sum) fft = numpy.fft.fft(complex_matrix[x,y]+complex_matrix[x,y]+complex_matrix[x,y]+complex_matrix[x,y],2048) first_har = 2048/len(complex_matrix[0,0]) if abs(fft[0]) != 0: fftmeasure[x,y] = 2 *abs(fft[first_har]) /abs(fft[0]) else: fftmeasure[x,y] = 0 return fftmeasure def compute_ACDC_orientation_tuning_curves(full_matrix,curve_label,sheet): """ This function allows and alternative computation of orientation tuning curve where for each given orientation the response is computed as a maximum of AC or DC component across the phases instead of the maximum used as a standard in Topographica""" # this method assumes that only single frequency has been used i = 0 for f in full_matrix.features: if f.name == "phase": phase_index = i if f.name == "orientation": orientation_index = i if f.name == "frequency": frequency_index = i i=i+1 print sheet.curve_dict if not sheet.curve_dict.has_key("orientationACDC"): sheet.curve_dict["orientationACDC"]={} sheet.curve_dict["orientationACDC"][curve_label]={} rows,cols = full_matrix.matrix_shape for o in xrange(size(full_matrix.features[orientation_index].values)): s_w = zeros(full_matrix.matrix_shape) for x in range(rows): for y in range(cols): or_response=[] for p in xrange(size(full_matrix.features[phase_index].values)): index = [0,0,0] index[phase_index] = p index[orientation_index] = o index[frequency_index] = 0 or_response.append(full_matrix.full_matrix[tuple(index)][x][y]) fft = numpy.fft.fft(or_response+or_response+or_response+or_response,2048) first_har = 2048/len(or_response) s_w[x][y] = numpy.maximum(2 *abs(fft[first_har]),abs(fft[0])) s = SheetView((s_w,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence) sheet.curve_dict["orientationACDC"][curve_label].update({full_matrix.features[orientation_index].values[o]:s}) def phase_preference_scatter_plot(sheet_name,diameter=0.39): r = UniformRandom(seed=1023) preference_map = topo.sim[sheet_name].sheet_views['PhasePreference'] offset_magnitude = 0.03 datax = [] datay = [] (v,bb) = preference_map.view() for z in zeros(66): x = (r() - 0.5)*2*diameter y = (r() - 0.5)*2*diameter rand = r() xoff = sin(rand*2*pi)*offset_magnitude yoff = cos(rand*2*pi)*offset_magnitude xx = max(min(x+xoff,diameter),-diameter) yy = max(min(y+yoff,diameter),-diameter) x = max(min(x,diameter),-diameter) y = max(min(y,diameter),-diameter) [xc1,yc1] = topo.sim[sheet_name].sheet2matrixidx(xx,yy) [xc2,yc2] = topo.sim[sheet_name].sheet2matrixidx(x,y) if((xc1==xc2) & (yc1==yc2)): continue datax = datax + [v[xc1,yc1]] datay = datay + [v[xc2,yc2]] for i in range(0,len(datax)): datax[i] = datax[i] * 360 datay[i] = datay[i] * 360 if(datay[i] > datax[i] + 180): datay[i]= datay[i]- 360 if((datax[i] > 180) & (datay[i]> 180)): datax[i] = datax[i] - 360; datay[i] = datay[i] - 360 if((datax[i] > 180) & (datay[i] < (datax[i]-180))): datax[i] = datax[i] - 360; #datay[i] = datay[i] - 360 f = pylab.figure() ax = f.add_subplot(111, aspect='equal') pylab.plot(datax,datay,'ro') pylab.plot([0,360],[-180,180]) pylab.plot([-180,180],[0,360]) pylab.plot([-180,-180],[360,360]) ax.axis([-180,360,-180,360]) pylab.xticks([-180,0,180,360], [-180,0,180,360]) pylab.yticks([-180,0,180,360], [-180,0,180,360]) pylab.grid() pylab.savefig(normalize_path(str(topo.sim.timestr()) + sheet_name + "_scatter.png")) ############################################################################### # JABALERT: Should we move this plot and command to analysis.py or # pylabplots.py, where all the rest are? # # In any case, it requires generalization; it should not be hardcoded # to any particular map name, and should just do the right thing for # most networks for which it makes sense. E.g. it already measures # the ComplexSelectivity for all measured_sheets, but then # plot_modulation_ratio only accepts two with specific names. # plot_modulation_ratio should just plot whatever it is given, and # then analyze_complexity can simply pass in whatever was measured, # with the user controlling what is measured using the measure_map # attribute of each Sheet. That way the complexity of any sheet could # be measured, which is what we want. # # Specific changes needed: # - Make plot_modulation_ratio accept a list of sheets and # plot their individual modulation ratios and combined ratio. # - Remove complex_sheet_name argument, which is no longer needed # - Make sure it still works fine even if V1Simple doesn't exist; # as this is just for an optional scatter plot, it's fine to skip # it. # - Preferably remove the filename argument by default, so that # plots will show up in the GUI def analyze_complexity(full_matrix,simple_sheet_name,complex_sheet_name,filename=None): """ Compute modulation ratio for each neuron, to distinguish complex from simple cells. Uses full_matrix data obtained from measure_or_pref(). If there is a sheet named as specified in simple_sheet_name, also plots its phase preference as a scatter plot. """ import topo measured_sheets = [s for s in topo.sim.objects(CFSheet).values() if hasattr(s,'measure_maps') and s.measure_maps] for sheet in measured_sheets: # Divide by two to get into 0-1 scale - that means simple/complex boundry is now at 0.5 complx = array(complexity(full_matrix[sheet]))/2.0 # Should this be renamed to ModulationRatio? sheet.sheet_views['ComplexSelectivity']=SheetView((complx,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence) import topo.command.pylabplots topo.command.pylabplots.plot_modulation_ratio(full_matrix,simple_sheet_name=simple_sheet_name,complex_sheet_name=complex_sheet_name,filename=filename) # Avoid error if no simple sheet exists try: phase_preference_scatter_plot(simple_sheet_name,diameter=0.24999) except AttributeError: print "Skipping phase preference scatter plot; could not analyze region %s." \ % simple_sheet_name class measure_and_analyze_complexity(measure_sine_pref): """Macro for measuring orientation preference and then analyzing its complexity.""" def __call__(self,**params): fm = super(measure_and_analyze_complexity,self).__call__(**params) #from topo.command.analysis import measure_or_pref #fm = measure_or_pref() analyze_complexity(fm,simple_sheet_name="V1Simple",complex_sheet_name="V1Complex",filename="ModulationRatio") pg= create_plotgroup(name='Orientation Preference and Complexity',category="Preference Maps", doc='Measure preference for sine grating orientation.', pre_plot_hooks=[measure_and_analyze_complexity.instance()]) pg.add_plot('Orientation Preference',[('Hue','OrientationPreference')]) pg.add_plot('Orientation Preference&Selectivity',[('Hue','OrientationPreference'), ('Confidence','OrientationSelectivity')]) pg.add_plot('Orientation Selectivity',[('Strength','OrientationSelectivity')]) pg.add_plot('Modulation Ratio',[('Strength','ComplexSelectivity')]) pg.add_plot('Phase Preference',[('Hue','PhasePreference')]) pg.add_static_image('Color Key','command/or_key_white_vert_small.png')
Java
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model common\models\Offer */ $this->title = $model->id; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Offers'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="offer-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'), 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'code', 'text:ntext', 'created_at', 'updated_at', ], ]) ?> </div>
Java
/* $OpenBSD: isp_sbus.c,v 1.7 1999/03/25 22:58:37 mjacob Exp $ */ /* release_03_25_99 */ /* * SBus specific probe and attach routines for Qlogic ISP SCSI adapters. * * Copyright (c) 1997 by Matthew Jacob * NASA AMES Research Center * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice immediately at the beginning of the file, without modification, * this list of conditions, and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include <sys/param.h> #include <sys/systm.h> #include <sys/device.h> #include <sys/kernel.h> #include <sys/malloc.h> #include <sys/queue.h> #include <machine/autoconf.h> #include <machine/cpu.h> #include <machine/param.h> #include <machine/vmparam.h> #include <sparc/sparc/cpuvar.h> #include <dev/ic/isp_openbsd.h> #include <dev/microcode/isp/asm_sbus.h> static u_int16_t isp_sbus_rd_reg __P((struct ispsoftc *, int)); static void isp_sbus_wr_reg __P((struct ispsoftc *, int, u_int16_t)); static int isp_sbus_mbxdma __P((struct ispsoftc *)); static int isp_sbus_dmasetup __P((struct ispsoftc *, struct scsi_xfer *, ispreq_t *, u_int8_t *, u_int8_t)); static void isp_sbus_dmateardown __P((struct ispsoftc *, struct scsi_xfer *, u_int32_t)); static struct ispmdvec mdvec = { isp_sbus_rd_reg, isp_sbus_wr_reg, isp_sbus_mbxdma, isp_sbus_dmasetup, isp_sbus_dmateardown, NULL, NULL, NULL, ISP_RISC_CODE, ISP_CODE_LENGTH, ISP_CODE_ORG, ISP_CODE_VERSION, BIU_BURST_ENABLE, 0 }; struct isp_sbussoftc { struct ispsoftc sbus_isp; sdparam sbus_dev; struct intrhand sbus_ih; volatile u_char *sbus_reg; int sbus_node; int sbus_pri; struct ispmdvec sbus_mdvec; vm_offset_t sbus_kdma_allocs[MAXISPREQUEST]; int16_t sbus_poff[_NREG_BLKS]; }; static int isp_match __P((struct device *, void *, void *)); static void isp_sbus_attach __P((struct device *, struct device *, void *)); struct cfattach isp_sbus_ca = { sizeof (struct isp_sbussoftc), isp_match, isp_sbus_attach }; static int isp_match(parent, cfarg, aux) struct device *parent; void *cfarg; void *aux; { int rv; struct cfdata *cf = cfarg; #ifdef DEBUG static int oneshot = 1; #endif struct confargs *ca = aux; register struct romaux *ra = &ca->ca_ra; rv = (strcmp(cf->cf_driver->cd_name, ra->ra_name) == 0 || strcmp("PTI,ptisp", ra->ra_name) == 0 || strcmp("ptisp", ra->ra_name) == 0 || strcmp("SUNW,isp", ra->ra_name) == 0 || strcmp("QLGC,isp", ra->ra_name) == 0); if (rv == 0) return (rv); #ifdef DEBUG if (rv && oneshot) { oneshot = 0; printf("Qlogic ISP Driver, NetBSD (sbus) Platform Version " "%d.%d Core Version %d.%d\n", ISP_PLATFORM_VERSION_MAJOR, ISP_PLATFORM_VERSION_MINOR, ISP_CORE_VERSION_MAJOR, ISP_CORE_VERSION_MINOR); } #endif if (ca->ca_bustype == BUS_SBUS) return (1); ra->ra_len = NBPG; return (probeget(ra->ra_vaddr, 1) != -1); } static void isp_sbus_attach(parent, self, aux) struct device *parent, *self; void *aux; { int freq; struct confargs *ca = aux; struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) self; struct ispsoftc *isp = &sbc->sbus_isp; ISP_LOCKVAL_DECL; if (ca->ca_ra.ra_nintr != 1) { printf(": expected 1 interrupt, got %d\n", ca->ca_ra.ra_nintr); return; } printf("\n"); sbc->sbus_pri = ca->ca_ra.ra_intr[0].int_pri; sbc->sbus_mdvec = mdvec; if (ca->ca_ra.ra_vaddr) { sbc->sbus_reg = (volatile u_char *) ca->ca_ra.ra_vaddr; } else { sbc->sbus_reg = (volatile u_char *) mapiodev(ca->ca_ra.ra_reg, 0, ca->ca_ra.ra_len); } sbc->sbus_node = ca->ca_ra.ra_node; freq = getpropint(ca->ca_ra.ra_node, "clock-frequency", 0); if (freq) { /* * Convert from HZ to MHz, rounding up. */ freq = (freq + 500000)/1000000; #if 0 printf("%s: %d MHz\n", self->dv_xname, freq); #endif } sbc->sbus_mdvec.dv_clock = freq; /* * XXX: Now figure out what the proper burst sizes, etc., to use. */ sbc->sbus_mdvec.dv_conf1 |= BIU_SBUS_CONF1_FIFO_8; /* * Some early versions of the PTI SBus adapter * would fail in trying to download (via poking) * FW. We give up on them. */ if (strcmp("PTI,ptisp", ca->ca_ra.ra_name) == 0 || strcmp("ptisp", ca->ca_ra.ra_name) == 0) { sbc->sbus_mdvec.dv_fwlen = 0; } isp->isp_mdvec = &sbc->sbus_mdvec; isp->isp_bustype = ISP_BT_SBUS; isp->isp_type = ISP_HA_SCSI_UNKNOWN; isp->isp_param = &sbc->sbus_dev; bzero(isp->isp_param, sizeof (sdparam)); sbc->sbus_poff[BIU_BLOCK >> _BLK_REG_SHFT] = BIU_REGS_OFF; sbc->sbus_poff[MBOX_BLOCK >> _BLK_REG_SHFT] = SBUS_MBOX_REGS_OFF; sbc->sbus_poff[SXP_BLOCK >> _BLK_REG_SHFT] = SBUS_SXP_REGS_OFF; sbc->sbus_poff[RISC_BLOCK >> _BLK_REG_SHFT] = SBUS_RISC_REGS_OFF; sbc->sbus_poff[DMA_BLOCK >> _BLK_REG_SHFT] = DMA_REGS_OFF; /* Establish interrupt channel */ sbc->sbus_ih.ih_fun = (void *) isp_intr; sbc->sbus_ih.ih_arg = sbc; intr_establish(sbc->sbus_pri, &sbc->sbus_ih); ISP_LOCK(isp); isp_reset(isp); if (isp->isp_state != ISP_RESETSTATE) { ISP_UNLOCK(isp); return; } isp_init(isp); if (isp->isp_state != ISP_INITSTATE) { isp_uninit(isp); ISP_UNLOCK(isp); return; } /* * do generic attach. */ isp_attach(isp); if (isp->isp_state != ISP_RUNSTATE) { isp_uninit(isp); } ISP_UNLOCK(isp); } static u_int16_t isp_sbus_rd_reg(isp, regoff) struct ispsoftc *isp; int regoff; { struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp; int offset = sbc->sbus_poff[(regoff & _BLK_REG_MASK) >> _BLK_REG_SHFT]; offset += (regoff & 0xff); return (*((u_int16_t *) &sbc->sbus_reg[offset])); } static void isp_sbus_wr_reg (isp, regoff, val) struct ispsoftc *isp; int regoff; u_int16_t val; { struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp; int offset = sbc->sbus_poff[(regoff & _BLK_REG_MASK) >> _BLK_REG_SHFT]; offset += (regoff & 0xff); *((u_int16_t *) &sbc->sbus_reg[offset]) = val; } static int isp_sbus_mbxdma(isp) struct ispsoftc *isp; { size_t len; /* * NOTE: Since most Sun machines aren't I/O coherent, * map the mailboxes through kdvma space to force them * to be uncached. */ /* * Allocate and map the request queue. */ len = ISP_QUEUE_SIZE(RQUEST_QUEUE_LEN); isp->isp_rquest = (volatile caddr_t)malloc(len, M_DEVBUF, M_NOWAIT); if (isp->isp_rquest == 0) return (1); isp->isp_rquest_dma = (u_int32_t)kdvma_mapin((caddr_t)isp->isp_rquest, len, 0); if (isp->isp_rquest_dma == 0) return (1); /* * Allocate and map the result queue. */ len = ISP_QUEUE_SIZE(RESULT_QUEUE_LEN); isp->isp_result = (volatile caddr_t)malloc(len, M_DEVBUF, M_NOWAIT); if (isp->isp_result == 0) return (1); isp->isp_result_dma = (u_int32_t)kdvma_mapin((caddr_t)isp->isp_result, len, 0); if (isp->isp_result_dma == 0) return (1); return (0); } /* * TODO: If kdvma_mapin fails, try using multiple smaller chunks.. */ static int isp_sbus_dmasetup(isp, xs, rq, iptrp, optr) struct ispsoftc *isp; struct scsi_xfer *xs; ispreq_t *rq; u_int8_t *iptrp; u_int8_t optr; { struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp; vm_offset_t kdvma; int dosleep = (xs->flags & SCSI_NOSLEEP) != 0; if (xs->datalen == 0) { rq->req_seg_count = 1; return (CMD_QUEUED); } if (rq->req_handle > RQUEST_QUEUE_LEN || rq->req_handle < 1) { panic("%s: bad handle (%d) in isp_sbus_dmasetup\n", isp->isp_name, rq->req_handle); /* NOTREACHED */ } if (CPU_ISSUN4M) { kdvma = (vm_offset_t) kdvma_mapin((caddr_t)xs->data, xs->datalen, dosleep); if (kdvma == (vm_offset_t) 0) { XS_SETERR(xs, HBA_BOTCH); return (CMD_COMPLETE); } } else { kdvma = (vm_offset_t) xs->data; } if (sbc->sbus_kdma_allocs[rq->req_handle - 1] != (vm_offset_t) 0) { panic("%s: kdma handle already allocated\n", isp->isp_name); /* NOTREACHED */ } sbc->sbus_kdma_allocs[rq->req_handle - 1] = kdvma; if (xs->flags & SCSI_DATA_IN) { rq->req_flags |= REQFLAG_DATA_IN; } else { rq->req_flags |= REQFLAG_DATA_OUT; } rq->req_dataseg[0].ds_count = xs->datalen; rq->req_dataseg[0].ds_base = (u_int32_t) kdvma; rq->req_seg_count = 1; return (CMD_QUEUED); } static void isp_sbus_dmateardown(isp, xs, handle) struct ispsoftc *isp; struct scsi_xfer *xs; u_int32_t handle; { struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp; vm_offset_t kdvma; if (xs->flags & SCSI_DATA_IN) { cpuinfo.cache_flush(xs->data, xs->datalen - xs->resid); } if (handle >= RQUEST_QUEUE_LEN) { panic("%s: bad handle (%d) in isp_sbus_dmateardown\n", isp->isp_name, handle); /* NOTREACHED */ } if (sbc->sbus_kdma_allocs[handle] == (vm_offset_t) 0) { panic("%s: kdma handle not already allocated\n", isp->isp_name); /* NOTREACHED */ } kdvma = sbc->sbus_kdma_allocs[handle]; sbc->sbus_kdma_allocs[handle] = (vm_offset_t) 0; if (CPU_ISSUN4M) { dvma_mapout(kdvma, (vm_offset_t) xs->data, xs->datalen); } }
Java
/* * Copyright (C) 2001 Peter Kelly (pmk@post.com) * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de) * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com) * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "sky/engine/config.h" #include "sky/engine/core/events/UIEvent.h" namespace blink { UIEventInit::UIEventInit() : view(nullptr) , detail(0) { } UIEvent::UIEvent() : m_detail(0) { } UIEvent::UIEvent(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg) : Event(eventType, canBubbleArg, cancelableArg) , m_view(viewArg) , m_detail(detailArg) { } UIEvent::UIEvent(const AtomicString& eventType, const UIEventInit& initializer) : Event(eventType, initializer) , m_view(initializer.view) , m_detail(initializer.detail) { } UIEvent::~UIEvent() { } void UIEvent::initUIEvent(const AtomicString& typeArg, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg) { if (dispatched()) return; initEvent(typeArg, canBubbleArg, cancelableArg); m_view = viewArg; m_detail = detailArg; } bool UIEvent::isUIEvent() const { return true; } const AtomicString& UIEvent::interfaceName() const { return EventNames::UIEvent; } int UIEvent::keyCode() const { return 0; } int UIEvent::charCode() const { return 0; } int UIEvent::layerX() { return 0; } int UIEvent::layerY() { return 0; } int UIEvent::pageX() const { return 0; } int UIEvent::pageY() const { return 0; } int UIEvent::which() const { return 0; } } // namespace blink
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_45) on Tue Apr 17 08:41:58 IDT 2018 --> <title>DNXConstants.PRESERVATIONLEVEL</title> <meta name="date" content="2018-04-17"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DNXConstants.PRESERVATIONLEVEL"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRODUCER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html" target="_top">Frames</a></li> <li><a href="DNXConstants.PRESERVATIONLEVEL.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.exlibris.digitool.common.dnx</div> <h2 title="Interface DNXConstants.PRESERVATIONLEVEL" class="title">Interface DNXConstants.PRESERVATIONLEVEL</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants</a></dd> </dl> <hr> <br> <pre>public static interface <span class="typeNameLabel">DNXConstants.PRESERVATIONLEVEL</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#PRESERVATIONLEVELDATEASSIGNED">PRESERVATIONLEVELDATEASSIGNED</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#PRESERVATIONLEVELRATIONALE">PRESERVATIONLEVELRATIONALE</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#PRESERVATIONLEVELROLE">PRESERVATIONLEVELROLE</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#PRESERVATIONLEVELVALUE">PRESERVATIONLEVELVALUE</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#sectionId">sectionId</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="sectionId"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sectionId</h4> <pre>static final&nbsp;java.lang.String sectionId</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DNXConstants.PRESERVATIONLEVEL.sectionId">Constant Field Values</a></dd> </dl> </li> </ul> <a name="PRESERVATIONLEVELVALUE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PRESERVATIONLEVELVALUE</h4> <pre>static final&nbsp;<a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> PRESERVATIONLEVELVALUE</pre> </li> </ul> <a name="PRESERVATIONLEVELROLE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PRESERVATIONLEVELROLE</h4> <pre>static final&nbsp;<a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> PRESERVATIONLEVELROLE</pre> </li> </ul> <a name="PRESERVATIONLEVELRATIONALE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PRESERVATIONLEVELRATIONALE</h4> <pre>static final&nbsp;<a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> PRESERVATIONLEVELRATIONALE</pre> </li> </ul> <a name="PRESERVATIONLEVELDATEASSIGNED"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>PRESERVATIONLEVELDATEASSIGNED</h4> <pre>static final&nbsp;<a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> PRESERVATIONLEVELDATEASSIGNED</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRODUCER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html" target="_top">Frames</a></li> <li><a href="DNXConstants.PRESERVATIONLEVEL.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
import { takeLatest, call, put } from 'redux-saga/effects'; import { gql } from 'react-apollo'; import { push } from 'react-router-redux'; import jwtDecode from 'jwt-decode'; import { setJwtToken } from '../../utils/auth'; import { bootstrap } from '../../utils/sagas'; import { registerError, registerSuccess } from './actions'; import { REGISTER } from './constants'; import { loginSuccess } from '../Login/actions'; import { client } from '../../graphql'; import { homePage } from '../../local-urls'; const RegisterMutation = gql` mutation RegisterMutation($nick: String!, $password: String!, $name: String!, $email: String!){ register(nick: $nick, password: $password, name: $name, email: $email) } `; function sendRegister(user) { return client.mutate({ mutation: RegisterMutation, variables: user }); } function* register({ user }) { try { const response = yield call(sendRegister, user); const token = response.data.register; const userInfo = jwtDecode(token); setJwtToken(token); yield put(registerSuccess()); yield put(loginSuccess(userInfo)); yield put(push(homePage())); } catch (e) { yield put(registerError()); } } function* registerSaga() { yield takeLatest(REGISTER, register); } export default bootstrap([ registerSaga, ]);
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>statsmodels.tsa.vector_ar.var_model.VARResults.pvalues &#8212; statsmodels 0.9.0 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt" href="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt.html" /> <link rel="prev" title="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim" href="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt.html" title="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim.html" title="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../tsa.html" >Time Series analysis <code class="docutils literal notranslate"><span class="pre">tsa</span></code></a> |</li> <li class="nav-item nav-item-2"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.html" accesskey="U">statsmodels.tsa.vector_ar.var_model.VARResults</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-tsa-vector-ar-var-model-varresults-pvalues"> <h1>statsmodels.tsa.vector_ar.var_model.VARResults.pvalues<a class="headerlink" href="#statsmodels-tsa-vector-ar-var-model-varresults-pvalues" title="Permalink to this headline">¶</a></h1> <dl class="method"> <dt id="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues"> <code class="descclassname">VARResults.</code><code class="descname">pvalues</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.pvalues"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.tsa.vector_ar.var_model.VARResults.pvalues" title="Permalink to this definition">¶</a></dt> <dd><p>Two-sided p-values for model coefficients from Student t-distribution</p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim.html" title="previous chapter">statsmodels.tsa.vector_ar.var_model.VARResults.plotsim</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt.html" title="next chapter">statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.tsa.vector_ar.var_model.VARResults.pvalues.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.7.4. </div> </body> </html>
Java
<!doctype html> <html> <head> <title>LazyLoad Test</title> <style type="text/css"> fieldset { border: 1px solid #afafaf; margin-bottom: 1em; } .log { font: 10pt Consolas, Monaco, fixed; width: 100%; } #css-status { background-color: #fff; height: 30px; margin: 10px auto; width: 100px; } #n1,#n2,#n3,#n4,#n5 { width: 0; } </style> </head> <body> <h1>LazyLoad Test</h1> <form action="" method="get"> <fieldset> <legend>JavaScript</legend> <p> <input type="button" id="btnLoadJS" value="Load JS (sequential calls)" /> <input type="button" id="btnLoadJSSingle" value="Load JS (single call)" /> </p> <p> <textarea id="jslog" class="log" rows="15" cols="50"></textarea> </p> </fieldset> <fieldset> <legend>CSS</legend> <p> <input type="button" id="btnLoadCSS" value="Load CSS (sequential calls)" /> <input type="button" id="btnLoadCSSSingle" value="Load CSS (single call)" /> </p> <p> <textarea id="csslog" class="log" rows="15" cols="50"></textarea> </p> <div id="css-status"></div> <div id="n1"></div> <div id="n2"></div> <div id="n3"></div> <div id="n4"></div> <div id="n5"></div> </fieldset> </form> <script src="../lazyload.js"></script> <script type="text/javascript"> var btnLoadCSS = document.getElementById('btnLoadCSS'), btnLoadCSSSingle = document.getElementById('btnLoadCSSSingle'), btnLoadJS = document.getElementById('btnLoadJS'), btnLoadJSSingle = document.getElementById('btnLoadJSSingle'), cssLogEl = document.getElementById('csslog'), jsLogEl = document.getElementById('jslog'), n1 = document.getElementById('n1'), n2 = document.getElementById('n2'), n3 = document.getElementById('n3'), n4 = document.getElementById('n4'), n5 = document.getElementById('n5'), cssInterval = null, css = [ 'http://pieisgood.org/test/lazyload/../lazyload/css.php?num=1', 'http://pieisgood.org/test/lazyload/css.php?num=2', 'http://pieisgood.org/test/lazyload/css.php?num=3', 'http://pieisgood.org/test/lazyload/css.php?num=4', 'http://pieisgood.org/test/lazyload/css.php?num=5' ], js = [ 'http://pieisgood.org/test/lazyload/js.php?num=1', 'http://pieisgood.org/test/lazyload/js.php?num=2', 'http://pieisgood.org/test/lazyload/js.php?num=3', 'http://pieisgood.org/test/lazyload/js.php?num=4', 'http://pieisgood.org/test/lazyload/js.php?num=5' ]; function cssComplete() { csslog('callback'); } function csslog(message) { cssLogEl.value += "[" + (new Date()).toTimeString() + "] " + message + "\r\n"; } function cssPollStart() { var check = [n1, n2, n3, n4, n5], i, item; cssPollStop(); var links = document.getElementsByTagName('link'); cssInterval = setInterval(function () { for (i = 0; i < check.length; ++i) { item = check[i]; if (item.offsetWidth > 0) { check.splice(i, 1); i -= 1; csslog('stylesheet ' + item.id.substr(1) + ' applied'); } } if (!check.length) { cssPollStop(); } }, 15); } function cssPollStop() { clearInterval(cssInterval); } function jsComplete() { jslog('callback'); } function jslog(message) { jsLogEl.value += "[" + (new Date()).toTimeString() + "] " + message + "\r\n"; } btnLoadCSS.onclick = function () { cssPollStart(); csslog('loading (sequential calls)'); for (var i = 0; i < css.length; i += 1) { LazyLoad.css(css[i], cssComplete); } } btnLoadCSSSingle.onclick = function () { cssPollStart(); csslog('loading (single call)'); LazyLoad.css(css, cssComplete); } btnLoadJS.onclick = function () { jslog('loading (sequential calls)'); for (var i = 0; i < js.length; i += 1) { LazyLoad.js(js[i], jsComplete); } } btnLoadJSSingle.onclick = function () { jslog('loading (single call)'); LazyLoad.js(js, jsComplete); } </script> </body> </html>
Java
$(function () { var colors = Highcharts.getOptions().colors, categories = ['已关闭', 'NEW', '已解决'], name = 'Browser brands', data = [{ y: 290, color: colors[0], drilldown: { name: 'close bug version', categories: ['当前版本', '历史版本'], data: [20,270], color: colors[0] } }, { y: 64, color: colors[1], drilldown: { name: 'fix bug version', categories: ['当前版本', '历史版本'], data: [8,56], color: colors[1] } }, { y: 82, color: colors[2], drilldown: { name: 'NEW bug versions', categories: ['当前版本', '历史版本'], data: [5,77], color: colors[2] } }]; // Build the data arrays var browserData = []; var versionsData = []; for (var i = 0; i < data.length; i++) { // add browser data browserData.push({ name: categories[i], y: data[i].y, color: data[i].color }); // add version data for (var j = 0; j < data[i].drilldown.data.length; j++) { var brightness = 0.2 - (j / data[i].drilldown.data.length) / 5 ; versionsData.push({ name: data[i].drilldown.categories[j], y: data[i].drilldown.data[j], color: Highcharts.Color(data[i].color).brighten(brightness).get() }); } } // Create the chart $('#container11').highcharts({ chart: { type: 'pie' }, title: { text: '当前版本在历史版本总和占比' }, yAxis: { title: { text: 'Total percent market share' } }, plotOptions: { pie: { shadow: false, center: ['50%', '50%'] } }, tooltip: { valueSuffix: '' //这里更改tooltip显示的单位 }, series: [{ name: 'Browsers', data: browserData, size: '80%', dataLabels: { formatter: function() { return this.y > 5 ? this.point.name : null; }, color: 'white', distance: -30 } }, { name: 'Versions', data: versionsData, size: '100%', innerSize: '80%', dataLabels: { formatter: function() { // display only if larger than 1 return this.y > 0 ? '<b>'+ this.point.name +':</b> '+ this.y+'个' : null; } } }] }); });
Java
/* * This file is part of the MIAMI framework. For copyright information, see * the LICENSE file in the MIAMI root folder. */ /* * File: TemplateExecutionUnit.h * Author: Gabriel Marin, mgabi99@gmail.com * * Defines data structure to hold information about the use pattern of an * execution unit type as part of an instruction execution template. */ #ifndef _TEMPLATE_EXECUTION_UNIT_H_ #define _TEMPLATE_EXECUTION_UNIT_H_ #include <stdio.h> #include <stdlib.h> #include "BitSet.h" #include <list> namespace MIAMI { #define EXACT_MATCH_ALLOCATE 0 class TemplateExecutionUnit { public: TemplateExecutionUnit (int _unit, BitSet* _umask, int _count); ~TemplateExecutionUnit () { if (unit_mask) delete unit_mask; } inline BitSet* UnitsMask () const { return (unit_mask); } inline int Count () const { return (count); } int index; int count; BitSet *unit_mask; }; typedef std::list<TemplateExecutionUnit*> TEUList; } /* namespace MIAMI */ #endif
Java
# # product import logging from django.contrib import messages from django.contrib.auth.decorators import user_passes_test from django.urls import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from dojo.utils import add_breadcrumb from dojo.forms import ToolTypeForm from dojo.models import Tool_Type logger = logging.getLogger(__name__) @user_passes_test(lambda u: u.is_staff) def new_tool_type(request): if request.method == 'POST': tform = ToolTypeForm(request.POST, instance=Tool_Type()) if tform.is_valid(): tform.save() messages.add_message(request, messages.SUCCESS, 'Tool Type Configuration Successfully Created.', extra_tags='alert-success') return HttpResponseRedirect(reverse('tool_type', )) else: tform = ToolTypeForm() add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request) return render(request, 'dojo/new_tool_type.html', {'tform': tform}) @user_passes_test(lambda u: u.is_staff) def edit_tool_type(request, ttid): tool_type = Tool_Type.objects.get(pk=ttid) if request.method == 'POST': tform = ToolTypeForm(request.POST, instance=tool_type) if tform.is_valid(): tform.save() messages.add_message(request, messages.SUCCESS, 'Tool Type Configuration Successfully Updated.', extra_tags='alert-success') return HttpResponseRedirect(reverse('tool_type', )) else: tform = ToolTypeForm(instance=tool_type) add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request) return render(request, 'dojo/edit_tool_type.html', { 'tform': tform, }) @user_passes_test(lambda u: u.is_staff) def tool_type(request): confs = Tool_Type.objects.all().order_by('name') add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request) return render(request, 'dojo/tool_type.html', {'confs': confs, })
Java
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <stdint.h> #include "base/bind.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "media/base/media_log.h" #include "media/base/mock_filters.h" #include "media/base/test_helpers.h" #include "media/blink/buffered_data_source.h" #include "media/blink/mock_webframeclient.h" #include "media/blink/mock_weburlloader.h" #include "media/blink/multibuffer_data_source.h" #include "media/blink/multibuffer_reader.h" #include "media/blink/resource_multibuffer_data_provider.h" #include "media/blink/test_response_generator.h" #include "third_party/WebKit/public/platform/WebURLResponse.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebView.h" using ::testing::_; using ::testing::Assign; using ::testing::DoAll; using ::testing::Invoke; using ::testing::InvokeWithoutArgs; using ::testing::InSequence; using ::testing::NiceMock; using ::testing::StrictMock; using blink::WebLocalFrame; using blink::WebString; using blink::WebURLLoader; using blink::WebURLResponse; using blink::WebView; namespace media { class TestResourceMultiBuffer; class TestMultiBufferDataProvider; std::set<TestMultiBufferDataProvider*> test_data_providers; class TestMultiBufferDataProvider : public ResourceMultiBufferDataProvider { public: TestMultiBufferDataProvider(UrlData* url_data, MultiBuffer::BlockId pos) : ResourceMultiBufferDataProvider(url_data, pos), loading_(false) { CHECK(test_data_providers.insert(this).second); } ~TestMultiBufferDataProvider() override { CHECK_EQ(static_cast<size_t>(1), test_data_providers.erase(this)); } void Start() override { // Create a mock active loader. // Keep track of active loading state via loadAsynchronously() and cancel(). NiceMock<MockWebURLLoader>* url_loader = new NiceMock<MockWebURLLoader>(); ON_CALL(*url_loader, cancel()) .WillByDefault(Invoke([this]() { // Check that we have not been destroyed first. if (test_data_providers.find(this) != test_data_providers.end()) { this->loading_ = false; } })); loading_ = true; active_loader_.reset( new ActiveLoader(std::unique_ptr<WebURLLoader>(url_loader))); if (!on_start_.is_null()) { on_start_.Run(); } } bool loading() const { return loading_; } void RunOnStart(base::Closure cb) { on_start_ = cb; } private: bool loading_; base::Closure on_start_; }; class TestUrlData; class TestResourceMultiBuffer : public ResourceMultiBuffer { public: explicit TestResourceMultiBuffer(UrlData* url_data, int shift) : ResourceMultiBuffer(url_data, shift) {} std::unique_ptr<MultiBuffer::DataProvider> CreateWriter( const BlockId& pos) override { TestMultiBufferDataProvider* ret = new TestMultiBufferDataProvider(url_data_, pos); ret->Start(); return std::unique_ptr<MultiBuffer::DataProvider>(ret); } // TODO: Make these global TestMultiBufferDataProvider* GetProvider() { EXPECT_EQ(test_data_providers.size(), 1U); if (test_data_providers.size() != 1) return nullptr; return *test_data_providers.begin(); } TestMultiBufferDataProvider* GetProvider_allownull() { EXPECT_LE(test_data_providers.size(), 1U); if (test_data_providers.size() != 1U) return nullptr; return *test_data_providers.begin(); } bool HasProvider() const { return test_data_providers.size() == 1U; } bool loading() { if (test_data_providers.empty()) return false; return GetProvider()->loading(); } }; class TestUrlData : public UrlData { public: TestUrlData(const GURL& url, CORSMode cors_mode, const base::WeakPtr<UrlIndex>& url_index) : UrlData(url, cors_mode, url_index), block_shift_(url_index->block_shift()) {} ResourceMultiBuffer* multibuffer() override { if (!test_multibuffer_.get()) { test_multibuffer_.reset(new TestResourceMultiBuffer(this, block_shift_)); } return test_multibuffer_.get(); } TestResourceMultiBuffer* test_multibuffer() { if (!test_multibuffer_.get()) { test_multibuffer_.reset(new TestResourceMultiBuffer(this, block_shift_)); } return test_multibuffer_.get(); } protected: ~TestUrlData() override {} const int block_shift_; std::unique_ptr<TestResourceMultiBuffer> test_multibuffer_; }; class TestUrlIndex : public UrlIndex { public: explicit TestUrlIndex(blink::WebFrame* frame) : UrlIndex(frame) {} scoped_refptr<UrlData> NewUrlData(const GURL& url, UrlData::CORSMode cors_mode) override { last_url_data_ = new TestUrlData(url, cors_mode, weak_factory_.GetWeakPtr()); return last_url_data_; } scoped_refptr<TestUrlData> last_url_data() { EXPECT_TRUE(last_url_data_); return last_url_data_; } private: scoped_refptr<TestUrlData> last_url_data_; }; class MockBufferedDataSourceHost : public BufferedDataSourceHost { public: MockBufferedDataSourceHost() {} virtual ~MockBufferedDataSourceHost() {} MOCK_METHOD1(SetTotalBytes, void(int64_t total_bytes)); MOCK_METHOD2(AddBufferedByteRange, void(int64_t start, int64_t end)); private: DISALLOW_COPY_AND_ASSIGN(MockBufferedDataSourceHost); }; class MockMultibufferDataSource : public MultibufferDataSource { public: MockMultibufferDataSource( const GURL& url, UrlData::CORSMode cors_mode, const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, linked_ptr<UrlIndex> url_index, WebLocalFrame* frame, BufferedDataSourceHost* host) : MultibufferDataSource( url, cors_mode, task_runner, url_index, frame, new media::MediaLog(), host, base::Bind(&MockMultibufferDataSource::set_downloading, base::Unretained(this))), downloading_(false) {} bool downloading() { return downloading_; } void set_downloading(bool downloading) { downloading_ = downloading; } bool range_supported() { return url_data_->range_supported(); } private: // Whether the resource is downloading or deferred. bool downloading_; DISALLOW_COPY_AND_ASSIGN(MockMultibufferDataSource); }; static const int64_t kFileSize = 5000000; static const int64_t kFarReadPosition = 3997696; static const int kDataSize = 32 << 10; static const char kHttpUrl[] = "http://localhost/foo.webm"; static const char kFileUrl[] = "file:///tmp/bar.webm"; static const char kHttpDifferentPathUrl[] = "http://localhost/bar.webm"; static const char kHttpDifferentOriginUrl[] = "http://127.0.0.1/foo.webm"; class MultibufferDataSourceTest : public testing::Test { public: MultibufferDataSourceTest() : view_(WebView::create(nullptr, blink::WebPageVisibilityStateVisible)), frame_( WebLocalFrame::create(blink::WebTreeScopeType::Document, &client_)), preload_(MultibufferDataSource::AUTO), url_index_(make_linked_ptr(new TestUrlIndex(frame_))) { view_->setMainFrame(frame_); } virtual ~MultibufferDataSourceTest() { view_->close(); frame_->close(); } MOCK_METHOD1(OnInitialize, void(bool)); void InitializeWithCORS(const char* url, bool expected, UrlData::CORSMode cors_mode) { GURL gurl(url); data_source_.reset(new MockMultibufferDataSource( gurl, cors_mode, message_loop_.task_runner(), url_index_, view_->mainFrame()->toWebLocalFrame(), &host_)); data_source_->SetPreload(preload_); response_generator_.reset(new TestResponseGenerator(gurl, kFileSize)); EXPECT_CALL(*this, OnInitialize(expected)); data_source_->Initialize(base::Bind( &MultibufferDataSourceTest::OnInitialize, base::Unretained(this))); base::RunLoop().RunUntilIdle(); // Not really loading until after OnInitialize is called. EXPECT_EQ(data_source_->downloading(), false); } void Initialize(const char* url, bool expected) { InitializeWithCORS(url, expected, UrlData::CORS_UNSPECIFIED); } // Helper to initialize tests with a valid 200 response. void InitializeWith200Response() { Initialize(kHttpUrl, true); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate200()); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); } // Helper to initialize tests with a valid 206 response. void InitializeWith206Response() { Initialize(kHttpUrl, true); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate206(0)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); } // Helper to initialize tests with a valid file:// response. void InitializeWithFileResponse() { Initialize(kFileUrl, true); EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kFileSize)); Respond(response_generator_->GenerateFileResponse(0)); ReceiveData(kDataSize); } // Stops any active loaders and shuts down the data source. // // This typically happens when the page is closed and for our purposes is // appropriate to do when tearing down a test. void Stop() { if (loading()) { data_provider()->didFail(url_loader(), response_generator_->GenerateError()); base::RunLoop().RunUntilIdle(); } data_source_->Stop(); base::RunLoop().RunUntilIdle(); } void Respond(const WebURLResponse& response) { EXPECT_TRUE(url_loader()); if (!active_loader()) return; data_provider()->didReceiveResponse(url_loader(), response); base::RunLoop().RunUntilIdle(); } void ReceiveData(int size) { EXPECT_TRUE(url_loader()); if (!url_loader()) return; std::unique_ptr<char[]> data(new char[size]); memset(data.get(), 0xA5, size); // Arbitrary non-zero value. data_provider()->didReceiveData(url_loader(), data.get(), size, size, size); base::RunLoop().RunUntilIdle(); } void FinishLoading() { EXPECT_TRUE(url_loader()); if (!url_loader()) return; data_provider()->didFinishLoading(url_loader(), 0, -1); base::RunLoop().RunUntilIdle(); } void FailLoading() { data_provider()->didFail(url_loader(), response_generator_->GenerateError()); base::RunLoop().RunUntilIdle(); } void Restart() { EXPECT_TRUE(data_provider()); EXPECT_FALSE(active_loader_allownull()); if (!data_provider()) return; data_provider()->Start(); } MOCK_METHOD1(ReadCallback, void(int size)); void ReadAt(int64_t position, int64_t howmuch = kDataSize) { data_source_->Read(position, howmuch, buffer_, base::Bind(&MultibufferDataSourceTest::ReadCallback, base::Unretained(this))); base::RunLoop().RunUntilIdle(); } void ExecuteMixedResponseSuccessTest(const WebURLResponse& response1, const WebURLResponse& response2) { EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)).Times(2); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); FinishLoading(); Restart(); ReadAt(kDataSize); Respond(response2); ReceiveData(kDataSize); FinishLoading(); Stop(); } void ExecuteMixedResponseFailureTest(const WebURLResponse& response1, const WebURLResponse& response2) { EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)); // Stop() will also cause the readback to be called with kReadError, but // we want to make sure it was called before Stop(). bool failed_ = false; EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)) .WillOnce(Assign(&failed_, true)); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); FinishLoading(); Restart(); ReadAt(kDataSize); Respond(response2); EXPECT_TRUE(failed_); Stop(); } void CheckCapacityDefer() { EXPECT_EQ(2 << 20, preload_low()); EXPECT_EQ(3 << 20, preload_high()); } void CheckReadThenDefer() { EXPECT_EQ(0, preload_low()); EXPECT_EQ(0, preload_high()); } void CheckNeverDefer() { EXPECT_EQ(1LL << 40, preload_low()); EXPECT_EQ(1LL << 40, preload_high()); } // Accessors for private variables on |data_source_|. MultiBufferReader* loader() { return data_source_->reader_.get(); } TestResourceMultiBuffer* multibuffer() { return url_index_->last_url_data()->test_multibuffer(); } TestMultiBufferDataProvider* data_provider() { return multibuffer()->GetProvider(); } ActiveLoader* active_loader() { EXPECT_TRUE(data_provider()); if (!data_provider()) return nullptr; return data_provider()->active_loader_.get(); } ActiveLoader* active_loader_allownull() { TestMultiBufferDataProvider* data_provider = multibuffer()->GetProvider_allownull(); if (!data_provider) return nullptr; return data_provider->active_loader_.get(); } WebURLLoader* url_loader() { EXPECT_TRUE(active_loader()); if (!active_loader()) return nullptr; return active_loader()->loader_.get(); } bool loading() { return multibuffer()->loading(); } MultibufferDataSource::Preload preload() { return data_source_->preload_; } void set_preload(MultibufferDataSource::Preload preload) { preload_ = preload; } int64_t preload_high() { CHECK(loader()); return loader()->preload_high(); } int64_t preload_low() { CHECK(loader()); return loader()->preload_low(); } int data_source_bitrate() { return data_source_->bitrate_; } double data_source_playback_rate() { return data_source_->playback_rate_; } bool is_local_source() { return data_source_->assume_fully_buffered(); } void set_might_be_reused_from_cache_in_future(bool value) { data_source_->url_data_->set_cacheable(value); } protected: MockWebFrameClient client_; WebView* view_; WebLocalFrame* frame_; MultibufferDataSource::Preload preload_; base::MessageLoop message_loop_; linked_ptr<TestUrlIndex> url_index_; std::unique_ptr<MockMultibufferDataSource> data_source_; std::unique_ptr<TestResponseGenerator> response_generator_; StrictMock<MockBufferedDataSourceHost> host_; // Used for calling MultibufferDataSource::Read(). uint8_t buffer_[kDataSize * 2]; DISALLOW_COPY_AND_ASSIGN(MultibufferDataSourceTest); }; TEST_F(MultibufferDataSourceTest, Range_Supported) { InitializeWith206Response(); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_InstanceSizeUnknown) { Initialize(kHttpUrl, true); Respond(response_generator_->Generate206( 0, TestResponseGenerator::kNoContentRangeInstanceSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); EXPECT_TRUE(loading()); EXPECT_TRUE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_NotFound) { Initialize(kHttpUrl, false); Respond(response_generator_->Generate404()); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_NotSupported) { InitializeWith200Response(); EXPECT_TRUE(loading()); EXPECT_TRUE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_NotSatisfiable) { Initialize(kHttpUrl, true); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); Respond(response_generator_->GenerateResponse(416)); EXPECT_FALSE(loading()); Stop(); } // Special carve-out for Apache versions that choose to return a 200 for // Range:0- ("because it's more efficient" than a 206) TEST_F(MultibufferDataSourceTest, Range_SupportedButReturned200) { Initialize(kHttpUrl, true); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); WebURLResponse response = response_generator_->Generate200(); response.setHTTPHeaderField(WebString::fromUTF8("Accept-Ranges"), WebString::fromUTF8("bytes")); Respond(response); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_MissingContentRange) { Initialize(kHttpUrl, false); Respond(response_generator_->Generate206( 0, TestResponseGenerator::kNoContentRange)); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_MissingContentLength) { Initialize(kHttpUrl, true); // It'll manage without a Content-Length response. EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate206( 0, TestResponseGenerator::kNoContentLength)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_WrongContentRange) { Initialize(kHttpUrl, false); // Now it's done and will fail. Respond(response_generator_->Generate206(1337)); EXPECT_FALSE(loading()); Stop(); } // Test the case where the initial response from the server indicates that // Range requests are supported, but a later request prove otherwise. TEST_F(MultibufferDataSourceTest, Range_ServerLied) { InitializeWith206Response(); // Read causing a new request to be made -- we'll expect it to error. ReadAt(kFarReadPosition); // Return a 200 in response to a range request. EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)); Respond(response_generator_->Generate200()); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_AbortWhileReading) { InitializeWith206Response(); // Make sure there's a pending read -- we'll expect it to error. ReadAt(kFileSize); // Abort!!! EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)); data_source_->Abort(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_AbortWhileReading) { InitializeWithFileResponse(); // Make sure there's a pending read -- we'll expect it to error. ReadAt(kFileSize); // Abort!!! EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)); data_source_->Abort(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_Retry) { InitializeWith206Response(); // Read to advance our position. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); // Issue a pending read but terminate the connection to force a retry. ReadAt(kDataSize); FinishLoading(); Restart(); Respond(response_generator_->Generate206(kDataSize)); // Complete the read. EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize); EXPECT_TRUE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_RetryOnError) { InitializeWith206Response(); // Read to advance our position. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); // Issue a pending read but trigger an error to force a retry. EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReadAt(kDataSize); base::RunLoop run_loop; data_provider()->didFail(url_loader(), response_generator_->GenerateError()); data_provider()->RunOnStart(run_loop.QuitClosure()); run_loop.Run(); Respond(response_generator_->Generate206(kDataSize)); ReceiveData(kDataSize); FinishLoading(); EXPECT_FALSE(loading()); Stop(); } // Make sure that we prefetch across partial responses. (crbug.com/516589) TEST_F(MultibufferDataSourceTest, Http_PartialResponsePrefetch) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 3 - 1); EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); FinishLoading(); Restart(); Respond(response2); ReceiveData(kDataSize); ReceiveData(kDataSize); FinishLoading(); Stop(); } TEST_F(MultibufferDataSourceTest, Http_PartialResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // The origin URL of response1 and response2 are same. So no error should // occur. ExecuteMixedResponseSuccessTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_RedirectedToDifferentPathResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); response2.setURL(GURL(kHttpDifferentPathUrl)); // The origin URL of response1 and response2 are same. So no error should // occur. ExecuteMixedResponseSuccessTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_RedirectedToDifferentOriginResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); response2.setURL(GURL(kHttpDifferentOriginUrl)); // The origin URL of response1 and response2 are different. So an error should // occur. ExecuteMixedResponseFailureTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_ServiceWorkerGeneratedResponseAndNormalResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.setWasFetchedViaServiceWorker(true); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // response1 is generated in a Service Worker but response2 is from a native // server. So an error should occur. ExecuteMixedResponseFailureTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_ServiceWorkerProxiedAndSameURLResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.setWasFetchedViaServiceWorker(true); response1.setOriginalURLViaServiceWorker(GURL(kHttpUrl)); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // The origin URL of response1 and response2 are same. So no error should // occur. ExecuteMixedResponseSuccessTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_ServiceWorkerProxiedAndDifferentPathResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.setWasFetchedViaServiceWorker(true); response1.setOriginalURLViaServiceWorker(GURL(kHttpDifferentPathUrl)); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // The origin URL of response1 and response2 are same. So no error should // occur. ExecuteMixedResponseSuccessTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_ServiceWorkerProxiedAndDifferentOriginResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.setWasFetchedViaServiceWorker(true); response1.setOriginalURLViaServiceWorker(GURL(kHttpDifferentOriginUrl)); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // The origin URL of response1 and response2 are different. So an error should // occur. ExecuteMixedResponseFailureTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_ServiceWorkerProxiedAndDifferentOriginResponseCORS) { InitializeWithCORS(kHttpUrl, true, UrlData::CORS_ANONYMOUS); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.setWasFetchedViaServiceWorker(true); response1.setOriginalURLViaServiceWorker(GURL(kHttpDifferentOriginUrl)); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // The origin URL of response1 and response2 are different, but a CORS check // has been passed for each request, so expect success. ExecuteMixedResponseSuccessTest(response1, response2); } TEST_F(MultibufferDataSourceTest, File_Retry) { InitializeWithFileResponse(); // Read to advance our position. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); // Issue a pending read but terminate the connection to force a retry. ReadAt(kDataSize); FinishLoading(); Restart(); Respond(response_generator_->GenerateFileResponse(kDataSize)); // Complete the read. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReceiveData(kDataSize); EXPECT_TRUE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_TooManyRetries) { InitializeWith206Response(); // Make sure there's a pending read -- we'll expect it to error. ReadAt(kDataSize); for (int i = 0; i < ResourceMultiBufferDataProvider::kMaxRetries; i++) { FailLoading(); data_provider()->Start(); Respond(response_generator_->Generate206(kDataSize)); } // Stop() will also cause the readback to be called with kReadError, but // we want to make sure it was called during FailLoading(). bool failed_ = false; EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)) .WillOnce(Assign(&failed_, true)); FailLoading(); EXPECT_TRUE(failed_); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_TooManyRetries) { InitializeWithFileResponse(); // Make sure there's a pending read -- we'll expect it to error. ReadAt(kDataSize); for (int i = 0; i < ResourceMultiBufferDataProvider::kMaxRetries; i++) { FailLoading(); data_provider()->Start(); Respond(response_generator_->Generate206(kDataSize)); } // Stop() will also cause the readback to be called with kReadError, but // we want to make sure it was called during FailLoading(). bool failed_ = false; EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)) .WillOnce(Assign(&failed_, true)); FailLoading(); EXPECT_TRUE(failed_); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_InstanceSizeUnknown) { Initialize(kFileUrl, false); Respond( response_generator_->GenerateFileResponse(media::DataSource::kReadError)); ReceiveData(kDataSize); EXPECT_FALSE(data_source_->downloading()); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_Successful) { InitializeWithFileResponse(); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, StopDuringRead) { InitializeWith206Response(); uint8_t buffer[256]; data_source_->Read(0, arraysize(buffer), buffer, base::Bind(&MultibufferDataSourceTest::ReadCallback, base::Unretained(this))); // The outstanding read should fail before the stop callback runs. { InSequence s; EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)); data_source_->Stop(); } base::RunLoop().RunUntilIdle(); } TEST_F(MultibufferDataSourceTest, DefaultValues) { InitializeWith206Response(); // Ensure we have sane values for default loading scenario. EXPECT_EQ(MultibufferDataSource::AUTO, preload()); EXPECT_EQ(2 << 20, preload_low()); EXPECT_EQ(3 << 20, preload_high()); EXPECT_EQ(0, data_source_bitrate()); EXPECT_EQ(0.0, data_source_playback_rate()); EXPECT_TRUE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, SetBitrate) { InitializeWith206Response(); data_source_->SetBitrate(1234); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1234, data_source_bitrate()); // Read so far ahead to cause the loader to get recreated. TestMultiBufferDataProvider* old_loader = data_provider(); ReadAt(kFarReadPosition); Respond(response_generator_->Generate206(kFarReadPosition)); // Verify loader changed but still has same bitrate. EXPECT_NE(old_loader, data_provider()); EXPECT_TRUE(loading()); EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)); Stop(); } TEST_F(MultibufferDataSourceTest, MediaPlaybackRateChanged) { InitializeWith206Response(); data_source_->MediaPlaybackRateChanged(2.0); base::RunLoop().RunUntilIdle(); EXPECT_EQ(2.0, data_source_playback_rate()); // Read so far ahead to cause the loader to get recreated. TestMultiBufferDataProvider* old_loader = data_provider(); ReadAt(kFarReadPosition); Respond(response_generator_->Generate206(kFarReadPosition)); // Verify loader changed but still has same playback rate. EXPECT_NE(old_loader, data_provider()); EXPECT_TRUE(loading()); EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)); Stop(); } TEST_F(MultibufferDataSourceTest, Http_Read) { InitializeWith206Response(); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0, kDataSize * 2); ReadAt(kDataSize, kDataSize); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + kDataSize / 2)); ReceiveData(kDataSize / 2); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize / 2); EXPECT_TRUE(data_source_->downloading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_ShareData) { InitializeWith206Response(); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0, kDataSize * 2); ReadAt(kDataSize, kDataSize); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + kDataSize / 2)); ReceiveData(kDataSize / 2); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize / 2); EXPECT_TRUE(data_source_->downloading()); StrictMock<MockBufferedDataSourceHost> host2; MockMultibufferDataSource source2( GURL(kHttpUrl), UrlData::CORS_UNSPECIFIED, message_loop_.task_runner(), url_index_, view_->mainFrame()->toWebLocalFrame(), &host2); source2.SetPreload(preload_); EXPECT_CALL(*this, OnInitialize(true)); // This call would not be expected if we were not sharing data. EXPECT_CALL(host2, SetTotalBytes(response_generator_->content_length())); source2.Initialize(base::Bind(&MultibufferDataSourceTest::OnInitialize, base::Unretained(this))); base::RunLoop().RunUntilIdle(); // Always loading after initialize. EXPECT_EQ(source2.downloading(), true); Stop(); } TEST_F(MultibufferDataSourceTest, Http_Read_Seek) { InitializeWith206Response(); // Read a bit from the beginning. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); // Simulate a seek by reading a bit beyond kDataSize. ReadAt(kDataSize * 2); // We receive data leading up to but not including our read. // No notification will happen, since it's progress outside // of our current range. ReceiveData(kDataSize); // We now receive the rest of the data for our read. EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); ReceiveData(kDataSize); EXPECT_TRUE(data_source_->downloading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_Read) { InitializeWithFileResponse(); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0, kDataSize * 2); ReadAt(kDataSize, kDataSize); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReceiveData(kDataSize); Stop(); } TEST_F(MultibufferDataSourceTest, Http_FinishLoading) { InitializeWith206Response(); EXPECT_TRUE(data_source_->downloading()); // premature didFinishLoading() will cause a retry. FinishLoading(); EXPECT_TRUE(data_source_->downloading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_FinishLoading) { InitializeWithFileResponse(); ReceiveData(kDataSize); EXPECT_FALSE(data_source_->downloading()); // premature didFinishLoading() will cause a retry. FinishLoading(); EXPECT_FALSE(data_source_->downloading()); Stop(); } TEST_F(MultibufferDataSourceTest, LocalResource_DeferStrategy) { InitializeWithFileResponse(); EXPECT_EQ(MultibufferDataSource::AUTO, preload()); EXPECT_TRUE(is_local_source()); CheckCapacityDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); data_source_->SetBufferingStrategy( BufferedDataSourceInterface::BUFFERING_STRATEGY_AGGRESSIVE); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, LocalResource_PreloadMetadata_DeferStrategy) { set_preload(MultibufferDataSource::METADATA); InitializeWithFileResponse(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_TRUE(is_local_source()); CheckReadThenDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); data_source_->SetBufferingStrategy( BufferedDataSourceInterface::BUFFERING_STRATEGY_AGGRESSIVE); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Reponse200_DeferStrategy) { InitializeWith200Response(); EXPECT_EQ(MultibufferDataSource::AUTO, preload()); EXPECT_FALSE(is_local_source()); EXPECT_FALSE(data_source_->range_supported()); CheckCapacityDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); data_source_->SetBufferingStrategy( BufferedDataSourceInterface::BUFFERING_STRATEGY_AGGRESSIVE); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Response200_PreloadMetadata_DeferStrategy) { set_preload(MultibufferDataSource::METADATA); InitializeWith200Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_FALSE(data_source_->range_supported()); CheckReadThenDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); data_source_->SetBufferingStrategy( BufferedDataSourceInterface::BUFFERING_STRATEGY_AGGRESSIVE); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Reponse206_DeferStrategy) { InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::AUTO, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckCapacityDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); set_might_be_reused_from_cache_in_future(true); data_source_->SetBufferingStrategy( BufferedDataSourceInterface::BUFFERING_STRATEGY_AGGRESSIVE); CheckNeverDefer(); data_source_->SetBufferingStrategy( BufferedDataSourceInterface::BUFFERING_STRATEGY_NORMAL); data_source_->MediaIsPlaying(); CheckCapacityDefer(); set_might_be_reused_from_cache_in_future(false); data_source_->SetBufferingStrategy( BufferedDataSourceInterface::BUFFERING_STRATEGY_AGGRESSIVE); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_PreloadMetadata_DeferStrategy) { set_preload(MultibufferDataSource::METADATA); InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckReadThenDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); set_might_be_reused_from_cache_in_future(true); data_source_->SetBufferingStrategy( BufferedDataSourceInterface::BUFFERING_STRATEGY_AGGRESSIVE); CheckNeverDefer(); data_source_->SetBufferingStrategy( BufferedDataSourceInterface::BUFFERING_STRATEGY_NORMAL); data_source_->MediaIsPlaying(); CheckCapacityDefer(); set_might_be_reused_from_cache_in_future(false); data_source_->SetBufferingStrategy( BufferedDataSourceInterface::BUFFERING_STRATEGY_AGGRESSIVE); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_VerifyDefer) { set_preload(MultibufferDataSource::METADATA); InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckReadThenDefer(); // Read a bit from the beginning. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); ASSERT_TRUE(active_loader()); EXPECT_TRUE(active_loader()->deferred()); } TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_CancelAfterDefer) { set_preload(MultibufferDataSource::METADATA); InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckReadThenDefer(); ReadAt(kDataSize); data_source_->OnBufferingHaveEnough(false); ASSERT_TRUE(active_loader()); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize); EXPECT_FALSE(active_loader_allownull()); } TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_CancelAfterPlay) { set_preload(BufferedDataSource::METADATA); InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckReadThenDefer(); ReadAt(kDataSize); // Marking the media as playing should prevent deferral. It also tells the // data source to start buffering beyond the initial load. data_source_->MediaIsPlaying(); data_source_->OnBufferingHaveEnough(false); CheckCapacityDefer(); ASSERT_TRUE(active_loader()); // Read a bit from the beginning and ensure deferral hasn't happened yet. EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize); ASSERT_TRUE(active_loader()); data_source_->OnBufferingHaveEnough(true); ASSERT_TRUE(active_loader()); ASSERT_FALSE(active_loader()->deferred()); // Deliver data until capacity is reached and verify deferral. int bytes_received = 0; EXPECT_CALL(host_, AddBufferedByteRange(_, _)).Times(testing::AtLeast(1)); while (active_loader_allownull() && !active_loader()->deferred()) { ReceiveData(kDataSize); bytes_received += kDataSize; } EXPECT_GT(bytes_received, 0); EXPECT_LT(bytes_received + kDataSize, kFileSize); EXPECT_FALSE(active_loader_allownull()); } TEST_F(MultibufferDataSourceTest, SeekPastEOF) { GURL gurl(kHttpUrl); data_source_.reset(new MockMultibufferDataSource( gurl, UrlData::CORS_UNSPECIFIED, message_loop_.task_runner(), url_index_, view_->mainFrame()->toWebLocalFrame(), &host_)); data_source_->SetPreload(preload_); response_generator_.reset(new TestResponseGenerator(gurl, kDataSize + 1)); EXPECT_CALL(*this, OnInitialize(true)); data_source_->Initialize(base::Bind(&MultibufferDataSourceTest::OnInitialize, base::Unretained(this))); base::RunLoop().RunUntilIdle(); // Not really loading until after OnInitialize is called. EXPECT_EQ(data_source_->downloading(), false); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate206(0)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); // Read a bit from the beginning. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + 1)); ReceiveData(1); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); FinishLoading(); EXPECT_CALL(*this, ReadCallback(0)); ReadAt(kDataSize + 5, kDataSize * 2); Stop(); } TEST_F(MultibufferDataSourceTest, Http_RetryThenRedirect) { InitializeWith206Response(); // Read to advance our position. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); // Issue a pending read but trigger an error to force a retry. EXPECT_CALL(*this, ReadCallback(kDataSize - 10)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReadAt(kDataSize + 10, kDataSize - 10); base::RunLoop run_loop; data_provider()->didFail(url_loader(), response_generator_->GenerateError()); data_provider()->RunOnStart(run_loop.QuitClosure()); run_loop.Run(); // Server responds with a redirect. blink::WebURLRequest request((GURL(kHttpDifferentPathUrl))); blink::WebURLResponse response((GURL(kHttpUrl))); response.setHTTPStatusCode(307); data_provider()->willFollowRedirect(url_loader(), request, response, 0); Respond(response_generator_->Generate206(kDataSize)); ReceiveData(kDataSize); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); FinishLoading(); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_NotStreamingAfterRedirect) { Initialize(kHttpUrl, true); // Server responds with a redirect. blink::WebURLRequest request((GURL(kHttpDifferentPathUrl))); blink::WebURLResponse response((GURL(kHttpUrl))); response.setHTTPStatusCode(307); data_provider()->willFollowRedirect(url_loader(), request, response, 0); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate206(0)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); EXPECT_FALSE(data_source_->IsStreaming()); FinishLoading(); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_RangeNotSatisfiableAfterRedirect) { Initialize(kHttpUrl, true); // Server responds with a redirect. blink::WebURLRequest request((GURL(kHttpDifferentPathUrl))); blink::WebURLResponse response((GURL(kHttpUrl))); response.setHTTPStatusCode(307); data_provider()->willFollowRedirect(url_loader(), request, response, 0); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); Respond(response_generator_->GenerateResponse(416)); Stop(); } TEST_F(MultibufferDataSourceTest, LengthKnownAtEOF) { Initialize(kHttpUrl, true); // Server responds without content-length. WebURLResponse response = response_generator_->Generate200(); response.clearHTTPHeaderField(WebString::fromUTF8("Content-Length")); response.setExpectedContentLength(kPositionNotSpecified); Respond(response); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); int64_t len; EXPECT_FALSE(data_source_->GetSize(&len)); EXPECT_TRUE(data_source_->IsStreaming()); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); ReadAt(kDataSize); EXPECT_CALL(host_, SetTotalBytes(kDataSize)); EXPECT_CALL(*this, ReadCallback(0)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); FinishLoading(); // Done loading, now we should know the length. EXPECT_TRUE(data_source_->GetSize(&len)); EXPECT_EQ(kDataSize, len); Stop(); } TEST_F(MultibufferDataSourceTest, FileSizeLessThanBlockSize) { Initialize(kHttpUrl, true); GURL gurl(kHttpUrl); blink::WebURLResponse response(gurl); response.setHTTPStatusCode(200); response.setHTTPHeaderField( WebString::fromUTF8("Content-Length"), WebString::fromUTF8(base::Int64ToString(kDataSize / 2))); response.setExpectedContentLength(kDataSize / 2); Respond(response); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize / 2)); EXPECT_CALL(host_, SetTotalBytes(kDataSize / 2)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize / 2); FinishLoading(); int64_t len = 0; EXPECT_TRUE(data_source_->GetSize(&len)); EXPECT_EQ(kDataSize / 2, len); Stop(); } } // namespace media
Java
<?php namespace BackEnd\Form; use Zend\Form\Form; use Zend\InputFilter\Factory as InputFactory; use Zend\InputFilter\InputFilter; class LoginForm extends Form { protected $inputFilter; public function __construct(){ parent::__construct('login-form'); $this->setAttribute('method', 'post'); $this->add(array( 'name' => 'username', 'options' => array( 'label' => '用户名' ), )); $this->add(array( 'name' => 'password', 'options' => array( 'label' => '密码' ), )); $this->add(array( 'name' => 'submit', 'attributes' => array( 'value' => 'Login', 'type' => 'submit', ), )); $this->setInputFilter($this->getInputFilter()); } public function getInputFilter(){ if(!$this->inputFilter){ $inputFilter = new InputFilter(); $factory = new InputFactory(); $inputFilter->add($factory->createInput(array( 'name' => 'username', 'required' => true, 'validators' => array( array('name' => 'StringLength' , 'options' => array('min' => 3 , 'max' => 20)), ), ))); $inputFilter->add($factory->createInput(array( 'name' => 'password', 'required' => true, 'validators' => array( array('name' => 'Alnum'), ), ))); $this->inputFilter = $inputFilter; } return $this->inputFilter; } }
Java
module UI.Widget.List ( listWidget ) where import Reactive.Banana import Reactive.Banana.Extra import Reactive.Banana.Frameworks import UI.TclTk import UI.TclTk.AST import UI.TclTk.Builder import UI.Widget -- | List widget listWidget :: Frameworks t => Event t [a] -> GUI t p (TkName, Event t (Int,a)) listWidget eList = do frame [Fill FillX] $ withPack PackLeft $ do let toEvt x (_,e) = x <$ e -- Buttons spacer e1 <- toEvt ToBegin <$> button [Text "<|" ] [] e2 <- toEvt (MoveBack 10) <$> button [Text "<<<"] [] e3 <- toEvt (MoveBack 1 ) <$> button [Text "<" ] [] -- Central area spacer Widget _ eN finiN <- entryInt [] [] _ <- label [ Text " / " ] [] labN <- label [] [] actimateTcl (length <$> eList) $ do configure labN $ LamOpt $ Text . show spacer -- More buttons e4 <- toEvt (MoveFwd 1 ) <$> button [Text ">" ] [] e5 <- toEvt (MoveFwd 10) <$> button [Text ">>>"] [] e6 <- toEvt ToEnd <$> button [Text "|>" ] [] spacer -- OOPS let events = listEvents eList (unions [JumpTo <$> eN, e1, e2, e3, e4, e5, e6]) finiN $ Bhv 0 $ fst <$> events return events -- Commands for a list data ListCmd = MoveFwd Int | MoveBack Int | JumpTo Int | ToBegin | ToEnd deriving (Show) -- Cursor for list of values data Cursor a = Cursor Int [a] Int -- Length × list × position | Invalid listEvents :: Event t [a] -> Event t ListCmd -> Event t (Int,a) listEvents listEvt command = filterJust $ fmap fini $ scanE acc Invalid $ listEvt `joinE` command where -- fini (Cursor _ xs i) = Just (i, xs !! i) fini Invalid = Nothing -- Accumulate data acc Invalid (Left []) = Invalid acc Invalid (Left xs) = Cursor (length xs) xs 0 acc Invalid _ = Invalid acc (Cursor _ _ n) (Left xs) = Cursor len xs $ clip len n where len = length xs acc (Cursor len xs n) (Right c) = case c of MoveFwd d -> go $ n + d MoveBack d -> go $ n - d JumpTo d -> go d ToBegin -> go 0 ToEnd -> go $ len - 1 where go = Cursor len xs . clip len -- Clip out of range indices clip len i | i < 0 = 0 | i >= len = len -1 | otherwise = i
Java
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_VIDEO_SUPPORTED_VIDEO_DECODER_CONFIG_H_ #define MEDIA_VIDEO_SUPPORTED_VIDEO_DECODER_CONFIG_H_ #include <vector> #include "base/containers/flat_map.h" #include "base/macros.h" #include "media/base/media_export.h" #include "media/base/video_codecs.h" #include "media/base/video_decoder_config.h" #include "ui/gfx/geometry/size.h" namespace media { // Specification of a range of configurations that are supported by a video // decoder. Also provides the ability to check if a VideoDecoderConfig matches // the supported range. struct MEDIA_EXPORT SupportedVideoDecoderConfig { SupportedVideoDecoderConfig(); SupportedVideoDecoderConfig(VideoCodecProfile profile_min, VideoCodecProfile profile_max, const gfx::Size& coded_size_min, const gfx::Size& coded_size_max, bool allow_encrypted, bool require_encrypted); ~SupportedVideoDecoderConfig(); // Returns true if and only if |config| is a supported config. bool Matches(const VideoDecoderConfig& config) const; // Range of VideoCodecProfiles to match, inclusive. VideoCodecProfile profile_min = VIDEO_CODEC_PROFILE_UNKNOWN; VideoCodecProfile profile_max = VIDEO_CODEC_PROFILE_UNKNOWN; // Coded size range, inclusive. gfx::Size coded_size_min; gfx::Size coded_size_max; // TODO(liberato): consider switching these to "allow_clear" and // "allow_encrypted", so that they're orthogonal. // If true, then this will match encrypted configs. bool allow_encrypted = true; // If true, then unencrypted configs will not match. bool require_encrypted = false; // Allow copy and assignment. }; // Enumeration of possible implementations for (Mojo)VideoDecoders. enum class VideoDecoderImplementation { kDefault = 0, kAlternate = 1, kMaxValue = kAlternate }; using SupportedVideoDecoderConfigs = std::vector<SupportedVideoDecoderConfig>; // Map of mojo VideoDecoder implementations to the vector of configs that they // (probably) support. using SupportedVideoDecoderConfigMap = base::flat_map<VideoDecoderImplementation, SupportedVideoDecoderConfigs>; // Helper method to determine if |config| is supported by |supported_configs|. MEDIA_EXPORT bool IsVideoDecoderConfigSupported( const SupportedVideoDecoderConfigs& supported_configs, const VideoDecoderConfig& config); } // namespace media #endif // MEDIA_VIDEO_SUPPORTED_VIDEO_DECODER_CONFIG_H_
Java
/* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <proxygen/lib/http/codec/experimental/HTTP2Framer.h> #include <cstdint> using namespace folly::io; using namespace folly; namespace proxygen { namespace http2 { const uint8_t kMaxFrameType = static_cast<uint8_t>(FrameType::ALTSVC); const boost::optional<uint8_t> kNoPadding; const PriorityUpdate DefaultPriority{0, false, 15}; namespace { const uint32_t kLengthMask = 0x00ffffff; const uint32_t kUint31Mask = 0x7fffffff; static const uint64_t kZeroPad[32] = {0}; static const bool kStrictPadding = true; static_assert(sizeof(kZeroPad) == 256, "bad zero padding"); void writePriorityBody(IOBufQueue& queue, uint32_t streamDependency, bool exclusive, uint8_t weight) { DCHECK_EQ(0, ~kUint31Mask & streamDependency); if (exclusive) { streamDependency |= ~kUint31Mask; } QueueAppender appender(&queue, 8); appender.writeBE<uint32_t>(streamDependency); appender.writeBE<uint8_t>(weight); } void writePadding(IOBufQueue& queue, boost::optional<uint8_t> size) { if (size && size.get() > 0) { auto out = queue.preallocate(size.get(), size.get()); memset(out.first, 0, size.get()); queue.postallocate(size.get()); } } /** * Generate just the common frame header. This includes the padding length * bits that sometimes come right after the frame header. Returns the * length field written to the common frame header. */ size_t writeFrameHeader(IOBufQueue& queue, uint32_t length, FrameType type, uint8_t flags, uint32_t stream, boost::optional<uint8_t> padding, boost::optional<PriorityUpdate> priority, std::unique_ptr<IOBuf> payload) noexcept { size_t headerSize = kFrameHeaderSize; // the acceptable length is now conditional based on state :( DCHECK_EQ(0, ~kLengthMask & length); DCHECK_EQ(0, ~kUint31Mask & stream); // Adjust length if we will emit a priority section if (flags & PRIORITY) { DCHECK(FrameType::HEADERS == type); length += kFramePrioritySize; headerSize += kFramePrioritySize; DCHECK_EQ(0, ~kLengthMask & length); } // Add or remove padding flags if (padding) { flags |= PADDED; length += padding.get() + 1; headerSize += 1; } else { flags &= ~PADDED; } if (priority) { headerSize += kFramePrioritySize; } DCHECK_EQ(0, ~kLengthMask & length); DCHECK_GE(kMaxFrameType, static_cast<uint8_t>(type)); uint32_t lengthAndType = ((kLengthMask & length) << 8) | static_cast<uint8_t>(type); uint64_t payloadLength = 0; if (payload && !payload->isSharedOne() && payload->headroom() >= headerSize && queue.tailroom() < headerSize) { // Use the headroom in payload for the frame header. // Make it appear that the payload IOBuf is empty and retreat so // appender can access the headroom payloadLength = payload->length(); payload->trimEnd(payloadLength); payload->retreat(headerSize); auto tail = payload->pop(); queue.append(std::move(payload)); payload = std::move(tail); } QueueAppender appender(&queue, kFrameHeaderSize); appender.writeBE<uint32_t>(lengthAndType); appender.writeBE<uint8_t>(flags); appender.writeBE<uint32_t>(kUint31Mask & stream); if (padding) { appender.writeBE<uint8_t>(padding.get()); } if (priority) { DCHECK_NE(priority->streamDependency, stream) << "Circular dependecy"; writePriorityBody(queue, priority->streamDependency, priority->exclusive, priority->weight); } if (payloadLength) { queue.postallocate(payloadLength); } queue.append(std::move(payload)); return length; } uint32_t parseUint31(Cursor& cursor) { // MUST ignore the 1 bit before the stream-id return kUint31Mask & cursor.readBE<uint32_t>(); } ErrorCode parseErrorCode(Cursor& cursor, ErrorCode& outCode) { auto code = cursor.readBE<uint32_t>(); if (code > kMaxErrorCode) { return ErrorCode::PROTOCOL_ERROR; } outCode = ErrorCode(code); return ErrorCode::NO_ERROR; } PriorityUpdate parsePriorityCommon(Cursor& cursor) { PriorityUpdate priority; uint32_t streamAndExclusive = cursor.readBE<uint32_t>(); priority.weight = cursor.readBE<uint8_t>(); priority.exclusive = ~kUint31Mask & streamAndExclusive; priority.streamDependency = kUint31Mask & streamAndExclusive; return priority; } /** * Given the flags for a frame and the cursor pointing at the top of the * frame-specific section (after the common header), return the number of * bytes to skip at the end of the frame. Caller must ensure there is at * least 1 bytes in the cursor. * * @param cursor The cursor to pull data from * @param header The frame header for the frame being parsed. The length * field may be modified based on the number of optional * padding length fields were read. * @param padding The out parameter that will return the number of padding * bytes at the end of the frame. * @return Nothing if success. The connection error code if failure. */ ErrorCode parsePadding(Cursor& cursor, FrameHeader& header, uint8_t& padding) noexcept { if (frameHasPadding(header)) { if (header.length < 1) { return ErrorCode::FRAME_SIZE_ERROR; } header.length -= 1; padding = cursor.readBE<uint8_t>(); } else { padding = 0; } return ErrorCode::NO_ERROR; } ErrorCode skipPadding(Cursor& cursor, uint8_t length, bool verify) { if (verify) { while (length > 0) { auto cur = cursor.peek(); uint8_t toCmp = std::min<size_t>(cur.second, length); if (memcmp(cur.first, kZeroPad, toCmp)) { return ErrorCode::PROTOCOL_ERROR; } cursor.skip(toCmp); length -= toCmp; } } else { cursor.skip(length); } return ErrorCode::NO_ERROR; } } // anonymous namespace bool frameAffectsCompression(FrameType t) { return t == FrameType::HEADERS || t == FrameType::PUSH_PROMISE || t == FrameType::CONTINUATION; } bool frameHasPadding(const FrameHeader& header) { return header.flags & PADDED; } //// Parsing //// ErrorCode parseFrameHeader(Cursor& cursor, FrameHeader& header) noexcept { DCHECK_LE(kFrameHeaderSize, cursor.totalLength()); // MUST ignore the 2 bits before the length uint32_t lengthAndType = cursor.readBE<uint32_t>(); header.length = kLengthMask & (lengthAndType >> 8); uint8_t type = lengthAndType & 0xff; header.type = FrameType(type); header.flags = cursor.readBE<uint8_t>(); header.stream = parseUint31(cursor); return ErrorCode::NO_ERROR; } ErrorCode parseData(Cursor& cursor, FrameHeader header, std::unique_ptr<IOBuf>& outBuf, uint16_t& outPadding) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; const auto err = parsePadding(cursor, header, padding); RETURN_IF_ERROR(err); if (header.length < padding) { return ErrorCode::PROTOCOL_ERROR; } // outPadding is the total number of flow-controlled pad bytes, which // includes the length byte, if present. outPadding = padding + ((frameHasPadding(header)) ? 1 : 0); cursor.clone(outBuf, header.length - padding); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parseDataBegin(Cursor& cursor, FrameHeader header, size_t& parsed, uint16_t& outPadding) noexcept { uint8_t padding = 0; const auto err = http2::parsePadding(cursor, header, padding); RETURN_IF_ERROR(err); if (header.length < padding) { return ErrorCode::PROTOCOL_ERROR; } // outPadding is the total number of flow-controlled pad bytes, which // includes the length byte, if present. outPadding = padding + ((frameHasPadding(header)) ? 1 : 0); return ErrorCode::NO_ERROR; } ErrorCode parseDataEnd(Cursor& cursor, const size_t bufLen, const size_t pendingDataFramePaddingBytes, size_t& toSkip) noexcept { toSkip = std::min(pendingDataFramePaddingBytes, bufLen); return skipPadding(cursor, toSkip, kStrictPadding); } ErrorCode parseHeaders(Cursor& cursor, FrameHeader header, boost::optional<PriorityUpdate>& outPriority, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; auto err = parsePadding(cursor, header, padding); RETURN_IF_ERROR(err); if (header.flags & PRIORITY) { if (header.length < kFramePrioritySize) { return ErrorCode::FRAME_SIZE_ERROR; } outPriority = parsePriorityCommon(cursor); header.length -= kFramePrioritySize; } else { outPriority = boost::none; } if (header.length < padding) { return ErrorCode::PROTOCOL_ERROR; } cursor.clone(outBuf, header.length - padding); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parsePriority(Cursor& cursor, FrameHeader header, PriorityUpdate& outPriority) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFramePrioritySize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } outPriority = parsePriorityCommon(cursor); return ErrorCode::NO_ERROR; } ErrorCode parseRstStream(Cursor& cursor, FrameHeader header, ErrorCode& outCode) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFrameRstStreamSize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } return parseErrorCode(cursor, outCode); } ErrorCode parseSettings(Cursor& cursor, FrameHeader header, std::deque<SettingPair>& settings) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } if (header.flags & ACK) { if (header.length != 0) { return ErrorCode::FRAME_SIZE_ERROR; } return ErrorCode::NO_ERROR; } if (header.length % 6 != 0) { return ErrorCode::FRAME_SIZE_ERROR; } for (; header.length > 0; header.length -= 6) { uint16_t id = cursor.readBE<uint16_t>(); uint32_t val = cursor.readBE<uint32_t>(); settings.push_back(std::make_pair(SettingsId(id), val)); } return ErrorCode::NO_ERROR; } ErrorCode parsePushPromise(Cursor& cursor, FrameHeader header, uint32_t& outPromisedStream, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; auto err = parsePadding(cursor, header, padding); RETURN_IF_ERROR(err); if (header.length < kFramePushPromiseSize) { return ErrorCode::FRAME_SIZE_ERROR; } header.length -= kFramePushPromiseSize; outPromisedStream = parseUint31(cursor); if (outPromisedStream == 0 || outPromisedStream & 0x1) { // client MUST reserve an even stream id greater than 0 return ErrorCode::PROTOCOL_ERROR; } if (header.length < padding) { return ErrorCode::PROTOCOL_ERROR; } cursor.clone(outBuf, header.length - padding); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parsePing(Cursor& cursor, FrameHeader header, uint64_t& outOpaqueData) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFramePingSize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } cursor.pull(&outOpaqueData, sizeof(outOpaqueData)); return ErrorCode::NO_ERROR; } ErrorCode parseGoaway(Cursor& cursor, FrameHeader header, uint32_t& outLastStreamID, ErrorCode& outCode, std::unique_ptr<IOBuf>& outDebugData) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length < kFrameGoawaySize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } outLastStreamID = parseUint31(cursor); auto err = parseErrorCode(cursor, outCode); RETURN_IF_ERROR(err); header.length -= kFrameGoawaySize; if (header.length > 0) { cursor.clone(outDebugData, header.length); } return ErrorCode::NO_ERROR; } ErrorCode parseWindowUpdate(Cursor& cursor, FrameHeader header, uint32_t& outAmount) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFrameWindowUpdateSize) { return ErrorCode::FRAME_SIZE_ERROR; } outAmount = parseUint31(cursor); return ErrorCode::NO_ERROR; } ErrorCode parseContinuation(Cursor& cursor, FrameHeader header, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK(header.type == FrameType::CONTINUATION); DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; auto err = parsePadding(cursor, header, padding); RETURN_IF_ERROR(err); if (header.length < padding) { return ErrorCode::PROTOCOL_ERROR; } cursor.clone(outBuf, header.length - padding); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parseAltSvc(Cursor& cursor, FrameHeader header, uint32_t& outMaxAge, uint32_t& outPort, std::string& outProtocol, std::string& outHost, std::string& outOrigin) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length < kFrameAltSvcSizeBase) { return ErrorCode::FRAME_SIZE_ERROR; } std::unique_ptr<IOBuf> tmpBuf; outMaxAge = cursor.readBE<uint32_t>(); outPort = cursor.readBE<uint16_t>(); const auto protoLen = cursor.readBE<uint8_t>(); if (header.length < kFrameAltSvcSizeBase + protoLen) { return ErrorCode::FRAME_SIZE_ERROR; } outProtocol = cursor.readFixedString(protoLen); const auto hostLen = cursor.readBE<uint8_t>(); if (header.length < kFrameAltSvcSizeBase + protoLen + hostLen) { return ErrorCode::FRAME_SIZE_ERROR; } outHost = cursor.readFixedString(hostLen); const auto originLen = (header.length - kFrameAltSvcSizeBase - protoLen - hostLen); outOrigin = cursor.readFixedString(originLen); return ErrorCode::NO_ERROR; } //// Egress //// size_t writeData(IOBufQueue& queue, std::unique_ptr<IOBuf> data, uint32_t stream, boost::optional<uint8_t> padding, bool endStream) noexcept { DCHECK_NE(0, stream); uint8_t flags = 0; if (endStream) { flags |= END_STREAM; } const uint64_t dataLen = data ? data->computeChainDataLength() : 0; // Caller must not exceed peer setting for MAX_FRAME_SIZE // TODO: look into using headroom from data to hold the frame header const auto frameLen = writeFrameHeader(queue, dataLen, FrameType::DATA, flags, stream, padding, boost::none, std::move(data)); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writeHeaders(IOBufQueue& queue, std::unique_ptr<IOBuf> headers, uint32_t stream, boost::optional<PriorityUpdate> priority, boost::optional<uint8_t> padding, bool endStream, bool endHeaders) noexcept { DCHECK_NE(0, stream); const auto dataLen = (headers) ? headers->computeChainDataLength() : 0; uint32_t flags = 0; if (priority) { flags |= PRIORITY; } if (endStream) { flags |= END_STREAM; } if (endHeaders) { flags |= END_HEADERS; } // padding flags handled directly inside writeFrameHeader() const auto frameLen = writeFrameHeader(queue, dataLen, FrameType::HEADERS, flags, stream, padding, priority, std::move(headers)); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writePriority(IOBufQueue& queue, uint32_t stream, PriorityUpdate priority) noexcept { DCHECK_NE(0, stream); const auto frameLen = writeFrameHeader(queue, kFramePrioritySize, FrameType::PRIORITY, 0, stream, kNoPadding, priority, nullptr); return kFrameHeaderSize + frameLen; } size_t writeRstStream(IOBufQueue& queue, uint32_t stream, ErrorCode errorCode) noexcept { DCHECK_NE(0, stream); const auto frameLen = writeFrameHeader(queue, kFrameRstStreamSize, FrameType::RST_STREAM, 0, stream, kNoPadding, boost::none, nullptr); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(static_cast<uint32_t>(errorCode)); return kFrameHeaderSize + frameLen; } size_t writeSettings(IOBufQueue& queue, const std::deque<SettingPair>& settings) { const auto settingsSize = settings.size() * 6; const auto frameLen = writeFrameHeader(queue, settingsSize, FrameType::SETTINGS, 0, 0, kNoPadding, boost::none, nullptr); QueueAppender appender(&queue, settingsSize); for (const auto& setting: settings) { DCHECK_LE(static_cast<uint32_t>(setting.first), std::numeric_limits<uint16_t>::max()); appender.writeBE<uint16_t>(static_cast<uint16_t>(setting.first)); appender.writeBE<uint32_t>(setting.second); } return kFrameHeaderSize + frameLen; } size_t writeSettingsAck(IOBufQueue& queue) { writeFrameHeader(queue, 0, FrameType::SETTINGS, ACK, 0, kNoPadding, boost::none, nullptr); return kFrameHeaderSize; } size_t writePushPromise(IOBufQueue& queue, uint32_t associatedStream, uint32_t promisedStream, std::unique_ptr<IOBuf> headers, boost::optional<uint8_t> padding, bool endHeaders) noexcept { DCHECK_NE(0, promisedStream); DCHECK_NE(0, associatedStream); DCHECK_EQ(0, 0x1 & promisedStream); DCHECK_EQ(1, 0x1 & associatedStream); DCHECK_EQ(0, ~kUint31Mask & promisedStream); const auto dataLen = headers->computeChainDataLength(); const auto frameLen = writeFrameHeader(queue, dataLen + kFramePushPromiseSize, FrameType::PUSH_PROMISE, endHeaders ? END_HEADERS : 0, associatedStream, padding, boost::none, nullptr); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(promisedStream); queue.append(std::move(headers)); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writePing(IOBufQueue& queue, uint64_t opaqueData, bool ack) noexcept { const auto frameLen = writeFrameHeader(queue, kFramePingSize, FrameType::PING, ack ? ACK : 0, 0, kNoPadding, boost::none, nullptr); queue.append(&opaqueData, sizeof(opaqueData)); return kFrameHeaderSize + frameLen; } size_t writeGoaway(IOBufQueue& queue, uint32_t lastStreamID, ErrorCode errorCode, std::unique_ptr<IOBuf> debugData) noexcept { uint32_t debugLen = debugData ? debugData->computeChainDataLength() : 0; DCHECK_EQ(0, ~kLengthMask & debugLen); const auto frameLen = writeFrameHeader(queue, kFrameGoawaySize + debugLen, FrameType::GOAWAY, 0, 0, kNoPadding, boost::none, nullptr); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(lastStreamID); appender.writeBE<uint32_t>(static_cast<uint32_t>(errorCode)); queue.append(std::move(debugData)); return kFrameHeaderSize + frameLen; } size_t writeWindowUpdate(IOBufQueue& queue, uint32_t stream, uint32_t amount) noexcept { const auto frameLen = writeFrameHeader(queue, kFrameWindowUpdateSize, FrameType::WINDOW_UPDATE, 0, stream, kNoPadding, boost::none, nullptr); DCHECK_EQ(0, ~kUint31Mask & amount); DCHECK_LT(0, amount); QueueAppender appender(&queue, kFrameWindowUpdateSize); appender.writeBE<uint32_t>(amount); return kFrameHeaderSize + frameLen; } size_t writeContinuation(IOBufQueue& queue, uint32_t stream, bool endHeaders, std::unique_ptr<IOBuf> headers, boost::optional<uint8_t> padding) noexcept { DCHECK_NE(0, stream); const auto dataLen = headers->computeChainDataLength(); const auto frameLen = writeFrameHeader(queue, dataLen, FrameType::CONTINUATION, endHeaders ? END_HEADERS : 0, stream, padding, boost::none, std::move(headers)); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writeAltSvc(IOBufQueue& queue, uint32_t stream, uint32_t maxAge, uint16_t port, StringPiece protocol, StringPiece host, StringPiece origin) noexcept { const auto protoLen = protocol.size(); const auto hostLen = host.size(); const auto originLen = origin.size(); const auto frameLen = protoLen + hostLen + originLen + kFrameAltSvcSizeBase; writeFrameHeader(queue, frameLen, FrameType::ALTSVC, 0, stream, kNoPadding, boost::none, nullptr); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(maxAge); appender.writeBE<uint16_t>(port); appender.writeBE<uint8_t>(protoLen); appender.push(reinterpret_cast<const uint8_t*>(protocol.data()), protoLen); appender.writeBE<uint8_t>(hostLen); appender.push(reinterpret_cast<const uint8_t*>(host.data()), hostLen); appender.push(reinterpret_cast<const uint8_t*>(origin.data()), originLen); return kFrameHeaderSize + frameLen; } const char* getFrameTypeString(FrameType type) { switch (type) { case FrameType::DATA: return "DATA"; case FrameType::HEADERS: return "HEADERS"; case FrameType::PRIORITY: return "PRIORITY"; case FrameType::RST_STREAM: return "RST_STREAM"; case FrameType::SETTINGS: return "SETTINGS"; case FrameType::PUSH_PROMISE: return "PUSH_PROMISE"; case FrameType::PING: return "PING"; case FrameType::GOAWAY: return "GOAWAY"; case FrameType::WINDOW_UPDATE: return "WINDOW_UPDATE"; case FrameType::CONTINUATION: return "CONTINUATION"; case FrameType::ALTSVC: return "ALTSVC"; default: // can happen when type was cast from uint8_t return "Unknown"; } LOG(FATAL) << "Unreachable"; return ""; } }}
Java
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Fichier contenant le paramètre 'voir' de la commande 'chemin'.""" from primaires.format.fonctions import oui_ou_non from primaires.interpreteur.masque.parametre import Parametre from primaires.pnj.chemin import FLAGS class PrmVoir(Parametre): """Commande 'chemin voir'. """ def __init__(self): """Constructeur du paramètre""" Parametre.__init__(self, "voir", "view") self.schema = "<cle>" self.aide_courte = "affiche le détail d'un chemin" self.aide_longue = \ "Cette commande permet d'obtenir plus d'informations sur " \ "un chemin (ses flags actifs, ses salles et sorties...)." def ajouter(self): """Méthode appelée lors de l'ajout de la commande à l'interpréteur""" cle = self.noeud.get_masque("cle") cle.proprietes["regex"] = r"'[a-z0-9_:]{3,}'" def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" cle = dic_masques["cle"].cle if cle not in importeur.pnj.chemins: personnage << "|err|Ce chemin n'existe pas.|ff|" return chemin = importeur.pnj.chemins[cle] msg = "Détail sur le chemin {} :".format(chemin.cle) msg += "\n Flags :" for nom_flag in FLAGS.keys(): msg += "\n {}".format(nom_flag.capitalize()) msg += " : " + oui_ou_non(chemin.a_flag(nom_flag)) msg += "\n Salles du chemin :" if len(chemin.salles) == 0: msg += "\n Aucune" else: for salle, direction in chemin.salles.items(): msg += "\n " + salle.ident.ljust(20) + " " msg += direction.ljust(10) if salle in chemin.salles_retour and \ chemin.salles_retour[salle]: msg += " (retour " + chemin.salles_retour[salle] + ")" personnage << msg
Java
#This is where the tests go.
Java
import FontAwesome from '@expo/vector-icons/build/FontAwesome'; import MaterialIcons from '@expo/vector-icons/build/MaterialIcons'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { useFocusEffect } from '@react-navigation/native'; import { StackNavigationProp } from '@react-navigation/stack'; import * as Location from 'expo-location'; import * as TaskManager from 'expo-task-manager'; import { EventEmitter, EventSubscription } from 'fbemitter'; import * as React from 'react'; import { Modal, Platform, StyleSheet, Text, View } from 'react-native'; import MapView from 'react-native-maps'; import Button from '../../components/Button'; import Colors from '../../constants/Colors'; import usePermissions from '../../utilities/usePermissions'; const STORAGE_KEY = 'expo-home-locations'; const LOCATION_UPDATES_TASK = 'location-updates'; const locationEventsEmitter = new EventEmitter(); const locationAccuracyStates: { [key in Location.Accuracy]: Location.Accuracy } = { [Location.Accuracy.Lowest]: Location.Accuracy.Low, [Location.Accuracy.Low]: Location.Accuracy.Balanced, [Location.Accuracy.Balanced]: Location.Accuracy.High, [Location.Accuracy.High]: Location.Accuracy.Highest, [Location.Accuracy.Highest]: Location.Accuracy.BestForNavigation, [Location.Accuracy.BestForNavigation]: Location.Accuracy.Lowest, }; const locationActivityTypes: { [key in Location.ActivityType]: Location.ActivityType | undefined; } = { [Location.ActivityType.Other]: Location.ActivityType.AutomotiveNavigation, [Location.ActivityType.AutomotiveNavigation]: Location.ActivityType.Fitness, [Location.ActivityType.Fitness]: Location.ActivityType.OtherNavigation, [Location.ActivityType.OtherNavigation]: Location.ActivityType.Airborne, [Location.ActivityType.Airborne]: undefined, }; interface Props { navigation: StackNavigationProp<any>; } type Region = { latitude: number; longitude: number; latitudeDelta: number; longitudeDelta: number; }; type State = Pick<Location.LocationTaskOptions, 'showsBackgroundLocationIndicator'> & { activityType: Location.ActivityType | null; accuracy: Location.Accuracy; isTracking: boolean; savedLocations: any[]; initialRegion: Region | null; }; const initialState: State = { isTracking: false, savedLocations: [], activityType: null, accuracy: Location.Accuracy.High, initialRegion: null, showsBackgroundLocationIndicator: false, }; function reducer(state: State, action: Partial<State>): State { return { ...state, ...action, }; } export default function BackgroundLocationMapScreen(props: Props) { const [permission] = usePermissions(Location.requestForegroundPermissionsAsync); React.useEffect(() => { (async () => { if (!(await Location.isBackgroundLocationAvailableAsync())) { alert('Background location is not available in this application.'); props.navigation.goBack(); } })(); }, [props.navigation]); if (!permission) { return ( <Text style={styles.errorText}> Location permissions are required in order to use this feature. You can manually enable them at any time in the "Location Services" section of the Settings app. </Text> ); } return <BackgroundLocationMapView />; } function BackgroundLocationMapView() { const mapViewRef = React.useRef<MapView>(null); const [state, dispatch] = React.useReducer(reducer, initialState); const onFocus = React.useCallback(() => { let subscription: EventSubscription | null = null; let isMounted = true; (async () => { if ((await Location.getBackgroundPermissionsAsync()).status !== 'granted') { console.log( 'Missing background location permissions. Make sure it is granted in the OS Settings.' ); return; } const { coords } = await Location.getCurrentPositionAsync(); const isTracking = await Location.hasStartedLocationUpdatesAsync(LOCATION_UPDATES_TASK); const task = (await TaskManager.getRegisteredTasksAsync()).find( ({ taskName }) => taskName === LOCATION_UPDATES_TASK ); const savedLocations = await getSavedLocations(); subscription = locationEventsEmitter.addListener('update', (savedLocations: any) => { if (isMounted) dispatch({ savedLocations }); }); if (!isTracking) { alert('Click `Start tracking` to start getting location updates.'); } if (!isMounted) return; dispatch({ isTracking, accuracy: task?.options.accuracy ?? state.accuracy, showsBackgroundLocationIndicator: task?.options.showsBackgroundLocationIndicator, activityType: task?.options.activityType ?? null, savedLocations, initialRegion: { latitude: coords.latitude, longitude: coords.longitude, latitudeDelta: 0.004, longitudeDelta: 0.002, }, }); })(); return () => { isMounted = false; if (subscription) { subscription.remove(); } }; }, [state.accuracy, state.isTracking]); useFocusEffect(onFocus); const startLocationUpdates = React.useCallback( async (acc = state.accuracy) => { if ((await Location.getBackgroundPermissionsAsync()).status !== 'granted') { console.log( 'Missing background location permissions. Make sure it is granted in the OS Settings.' ); return; } await Location.startLocationUpdatesAsync(LOCATION_UPDATES_TASK, { accuracy: acc, activityType: state.activityType ?? undefined, pausesUpdatesAutomatically: state.activityType != null, showsBackgroundLocationIndicator: state.showsBackgroundLocationIndicator, deferredUpdatesInterval: 60 * 1000, // 1 minute deferredUpdatesDistance: 100, // 100 meters foregroundService: { notificationTitle: 'expo-location-demo', notificationBody: 'Background location is running...', notificationColor: Colors.tintColor, }, }); if (!state.isTracking) { alert( // tslint:disable-next-line max-line-length 'Now you can send app to the background, go somewhere and come back here! You can even terminate the app and it will be woken up when the new significant location change comes out.' ); } dispatch({ isTracking: true, }); }, [state.isTracking, state.accuracy, state.activityType, state.showsBackgroundLocationIndicator] ); const stopLocationUpdates = React.useCallback(async () => { await Location.stopLocationUpdatesAsync(LOCATION_UPDATES_TASK); dispatch({ isTracking: false, }); }, []); const clearLocations = React.useCallback(async () => { await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify([])); dispatch({ savedLocations: [], }); }, []); const toggleTracking = React.useCallback(async () => { await AsyncStorage.removeItem(STORAGE_KEY); if (state.isTracking) { await stopLocationUpdates(); } else { await startLocationUpdates(); } dispatch({ savedLocations: [], }); }, [state.isTracking, startLocationUpdates, stopLocationUpdates]); const onAccuracyChange = React.useCallback(() => { const currentAccuracy = locationAccuracyStates[state.accuracy]; dispatch({ accuracy: currentAccuracy, }); if (state.isTracking) { // Restart background task with the new accuracy. startLocationUpdates(currentAccuracy); } }, [state.accuracy, state.isTracking, startLocationUpdates]); const toggleLocationIndicator = React.useCallback(() => { dispatch({ showsBackgroundLocationIndicator: !state.showsBackgroundLocationIndicator, }); if (state.isTracking) { startLocationUpdates(); } }, [state.showsBackgroundLocationIndicator, state.isTracking, startLocationUpdates]); const toggleActivityType = React.useCallback(() => { let nextActivityType: Location.ActivityType | null; if (state.activityType) { nextActivityType = locationActivityTypes[state.activityType] ?? null; } else { nextActivityType = Location.ActivityType.Other; } dispatch({ activityType: nextActivityType, }); if (state.isTracking) { // Restart background task with the new activity type startLocationUpdates(); } }, [state.activityType, state.isTracking, startLocationUpdates]); const onCenterMap = React.useCallback(async () => { const { coords } = await Location.getCurrentPositionAsync(); const mapView = mapViewRef.current; if (mapView) { mapView.animateToRegion({ latitude: coords.latitude, longitude: coords.longitude, latitudeDelta: 0.004, longitudeDelta: 0.002, }); } }, []); const renderPolyline = React.useCallback(() => { if (state.savedLocations.length === 0) { return null; } return ( // @ts-ignore <MapView.Polyline coordinates={state.savedLocations} strokeWidth={3} strokeColor={Colors.tintColor} /> ); }, [state.savedLocations]); return ( <View style={styles.screen}> <PermissionsModal /> <MapView ref={mapViewRef} style={styles.mapView} initialRegion={state.initialRegion ?? undefined} showsUserLocation> {renderPolyline()} </MapView> <View style={styles.buttons} pointerEvents="box-none"> <View style={styles.topButtons}> <View style={styles.buttonsColumn}> {Platform.OS === 'android' ? null : ( <Button style={styles.button} onPress={toggleLocationIndicator}> <View style={styles.buttonContentWrapper}> <Text style={styles.text}> {state.showsBackgroundLocationIndicator ? 'Hide' : 'Show'} </Text> <Text style={styles.text}> background </Text> <FontAwesome name="location-arrow" size={20} color="white" /> <Text style={styles.text}> indicator</Text> </View> </Button> )} {Platform.OS === 'android' ? null : ( <Button style={styles.button} onPress={toggleActivityType} title={ state.activityType ? `Activity type: ${Location.ActivityType[state.activityType]}` : 'No activity type' } /> )} <Button title={`Accuracy: ${Location.Accuracy[state.accuracy]}`} style={styles.button} onPress={onAccuracyChange} /> </View> <View style={styles.buttonsColumn}> <Button style={styles.button} onPress={onCenterMap}> <MaterialIcons name="my-location" size={20} color="white" /> </Button> </View> </View> <View style={styles.bottomButtons}> <Button title="Clear locations" style={styles.button} onPress={clearLocations} /> <Button title={state.isTracking ? 'Stop tracking' : 'Start tracking'} style={styles.button} onPress={toggleTracking} /> </View> </View> </View> ); } const PermissionsModal = () => { const [showPermissionsModal, setShowPermissionsModal] = React.useState(true); const [permission] = usePermissions(Location.getBackgroundPermissionsAsync); return ( <Modal animationType="slide" transparent={false} visible={!permission && showPermissionsModal} onRequestClose={() => { setShowPermissionsModal(!showPermissionsModal); }}> <View style={{ flex: 1, justifyContent: 'space-around', alignItems: 'center' }}> <View style={{ flex: 2, justifyContent: 'center', alignItems: 'center' }}> <Text style={styles.modalHeader}>Background location access</Text> <Text style={styles.modalText}> This app collects location data to enable updating the MapView in the background even when the app is closed or not in use. Otherwise, your location on the map will only be updated while the app is foregrounded. </Text> <Text style={styles.modalText}> This data is not used for anything other than updating the position on the map, and this data is never shared with anyone. </Text> </View> <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Button title="Request background location permission" style={styles.button} onPress={async () => { // Need both background and foreground permissions await Location.requestForegroundPermissionsAsync(); await Location.requestBackgroundPermissionsAsync(); setShowPermissionsModal(!showPermissionsModal); }} /> <Button title="Continue without background location permission" style={styles.button} onPress={() => setShowPermissionsModal(!showPermissionsModal)} /> </View> </View> </Modal> ); }; BackgroundLocationMapScreen.navigationOptions = { title: 'Background location', }; async function getSavedLocations() { try { const item = await AsyncStorage.getItem(STORAGE_KEY); return item ? JSON.parse(item) : []; } catch (e) { return []; } } TaskManager.defineTask(LOCATION_UPDATES_TASK, async ({ data: { locations } }: any) => { if (locations && locations.length > 0) { const savedLocations = await getSavedLocations(); const newLocations = locations.map(({ coords }: any) => ({ latitude: coords.latitude, longitude: coords.longitude, })); // tslint:disable-next-line no-console console.log(`Received new locations at ${new Date()}:`, locations); savedLocations.push(...newLocations); await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(savedLocations)); locationEventsEmitter.emit('update', savedLocations); } }); const styles = StyleSheet.create({ screen: { flex: 1, }, mapView: { flex: 1, }, buttons: { flex: 1, flexDirection: 'column', justifyContent: 'space-between', padding: 10, position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, }, topButtons: { flexDirection: 'row', justifyContent: 'space-between', }, bottomButtons: { flexDirection: 'column', alignItems: 'flex-end', }, buttonsColumn: { flexDirection: 'column', alignItems: 'flex-start', }, button: { paddingVertical: 5, paddingHorizontal: 10, marginVertical: 5, }, buttonContentWrapper: { flexDirection: 'row', }, text: { color: 'white', fontWeight: '700', }, errorText: { fontSize: 15, color: 'rgba(0,0,0,0.7)', margin: 20, }, modalHeader: { padding: 12, fontSize: 20, fontWeight: '800' }, modalText: { padding: 8, fontWeight: '600' }, });
Java
using System; namespace DistributedPrimeCalculatorApp { public class MessageTypes { public const int Terminate = 0; //tells the prime worker to stop public const int Start = 1; //initialize the prime workers public const int ReplyBatch = 2; //the main worker sends a batch of numbers public const int RequestBatch = 3; //the prime worker requests a new batch public const int Result = 4; //the prime worker sends the count back } }
Java
// // Use this file to import your target's public headers that you would like to expose to Swift. // #import "MockORKTask.h" #import "MockTrackedDataStore.h" #import "MockAppInfoDelegate.h" #import "MockKeychainWrapper.h" #import "BridgeSDKTestable.h"
Java
/*! * Bootstrap v2.3.2 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */ .clearfix { *zoom: 1; } .clearfix:before, .clearfix:after { display: table; content: ""; line-height: 0; } .clearfix:after { clear: both; } .hide-text { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .input-block-level { display: block; width: 100%; min-height: 30px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } article, aside, details, figcaption, figure, footer, header, hgroup, nav, section { display: block; } audio, canvas, video { display: inline-block; *display: inline; *zoom: 1; } audio:not([controls]) { display: none; } html { font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } a:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } a:hover, a:active { outline: 0; } sub, sup { position: relative; font-size: 75%; line-height: 0; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } img { /* Responsive images (ensure images don't scale beyond their parents) */ max-width: 100%; /* Part 1: Set a maxium relative to the parent */ width: auto\9; /* IE7-8 need help adjusting responsive images */ height: auto; /* Part 2: Scale the height according to the width, otherwise you get stretching */ vertical-align: middle; border: 0; -ms-interpolation-mode: bicubic; } #map_canvas img, .google-maps img { max-width: none; } button, input, select, textarea { margin: 0; font-size: 100%; vertical-align: middle; } button, input { *overflow: visible; line-height: normal; } button::-moz-focus-inner, input::-moz-focus-inner { padding: 0; border: 0; } button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; } label, select, button, input[type="button"], input[type="reset"], input[type="submit"], input[type="radio"], input[type="checkbox"] { cursor: pointer; } input[type="search"] { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; -webkit-appearance: textfield; } input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; } textarea { overflow: auto; vertical-align: top; } @media print { * { text-shadow: none !important; color: #000 !important; background: transparent !important; box-shadow: none !important; } a, a:visited { text-decoration: underline; } a[href]:after { content: " (" attr(href) ")"; } abbr[title]:after { content: " (" attr(title) ")"; } .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } tr, img { page-break-inside: avoid; } img { max-width: 100% !important; } @page { margin: 0.5cm; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } } body { margin: 0; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; line-height: 20px; color: #2a2a2a; background-color: #c5ad91; } a { color: #715458; text-decoration: none; } a:hover, a:focus { color: #ca3308; text-decoration: underline; } .img-rounded { -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .img-polaroid { padding: 4px; background-color: #fff; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.2); -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); } .img-circle { -webkit-border-radius: 500px; -moz-border-radius: 500px; border-radius: 500px; } .row { margin-left: -20px; *zoom: 1; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 20px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 940px; } .span12 { width: 940px; } .span11 { width: 860px; } .span10 { width: 780px; } .span9 { width: 700px; } .span8 { width: 620px; } .span7 { width: 540px; } .span6 { width: 460px; } .span5 { width: 380px; } .span4 { width: 300px; } .span3 { width: 220px; } .span2 { width: 140px; } .span1 { width: 60px; } .offset12 { margin-left: 980px; } .offset11 { margin-left: 900px; } .offset10 { margin-left: 820px; } .offset9 { margin-left: 740px; } .offset8 { margin-left: 660px; } .offset7 { margin-left: 580px; } .offset6 { margin-left: 500px; } .offset5 { margin-left: 420px; } .offset4 { margin-left: 340px; } .offset3 { margin-left: 260px; } .offset2 { margin-left: 180px; } .offset1 { margin-left: 100px; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; width: 100%; min-height: 30px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: left; margin-left: 2.127659574468085%; *margin-left: 2.074468085106383%; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.127659574468085%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.48936170212765%; *width: 91.43617021276594%; } .row-fluid .span10 { width: 82.97872340425532%; *width: 82.92553191489361%; } .row-fluid .span9 { width: 74.46808510638297%; *width: 74.41489361702126%; } .row-fluid .span8 { width: 65.95744680851064%; *width: 65.90425531914893%; } .row-fluid .span7 { width: 57.44680851063829%; *width: 57.39361702127659%; } .row-fluid .span6 { width: 48.93617021276595%; *width: 48.88297872340425%; } .row-fluid .span5 { width: 40.42553191489362%; *width: 40.37234042553192%; } .row-fluid .span4 { width: 31.914893617021278%; *width: 31.861702127659576%; } .row-fluid .span3 { width: 23.404255319148934%; *width: 23.351063829787233%; } .row-fluid .span2 { width: 14.893617021276595%; *width: 14.840425531914894%; } .row-fluid .span1 { width: 6.382978723404255%; *width: 6.329787234042553%; } .row-fluid .offset12 { margin-left: 104.25531914893617%; *margin-left: 104.14893617021275%; } .row-fluid .offset12:first-child { margin-left: 102.12765957446808%; *margin-left: 102.02127659574467%; } .row-fluid .offset11 { margin-left: 95.74468085106382%; *margin-left: 95.6382978723404%; } .row-fluid .offset11:first-child { margin-left: 93.61702127659574%; *margin-left: 93.51063829787232%; } .row-fluid .offset10 { margin-left: 87.23404255319149%; *margin-left: 87.12765957446807%; } .row-fluid .offset10:first-child { margin-left: 85.1063829787234%; *margin-left: 84.99999999999999%; } .row-fluid .offset9 { margin-left: 78.72340425531914%; *margin-left: 78.61702127659572%; } .row-fluid .offset9:first-child { margin-left: 76.59574468085106%; *margin-left: 76.48936170212764%; } .row-fluid .offset8 { margin-left: 70.2127659574468%; *margin-left: 70.10638297872339%; } .row-fluid .offset8:first-child { margin-left: 68.08510638297872%; *margin-left: 67.9787234042553%; } .row-fluid .offset7 { margin-left: 61.70212765957446%; *margin-left: 61.59574468085106%; } .row-fluid .offset7:first-child { margin-left: 59.574468085106375%; *margin-left: 59.46808510638297%; } .row-fluid .offset6 { margin-left: 53.191489361702125%; *margin-left: 53.085106382978715%; } .row-fluid .offset6:first-child { margin-left: 51.063829787234035%; *margin-left: 50.95744680851063%; } .row-fluid .offset5 { margin-left: 44.68085106382979%; *margin-left: 44.57446808510638%; } .row-fluid .offset5:first-child { margin-left: 42.5531914893617%; *margin-left: 42.4468085106383%; } .row-fluid .offset4 { margin-left: 36.170212765957444%; *margin-left: 36.06382978723405%; } .row-fluid .offset4:first-child { margin-left: 34.04255319148936%; *margin-left: 33.93617021276596%; } .row-fluid .offset3 { margin-left: 27.659574468085104%; *margin-left: 27.5531914893617%; } .row-fluid .offset3:first-child { margin-left: 25.53191489361702%; *margin-left: 25.425531914893618%; } .row-fluid .offset2 { margin-left: 19.148936170212764%; *margin-left: 19.04255319148936%; } .row-fluid .offset2:first-child { margin-left: 17.02127659574468%; *margin-left: 16.914893617021278%; } .row-fluid .offset1 { margin-left: 10.638297872340425%; *margin-left: 10.53191489361702%; } .row-fluid .offset1:first-child { margin-left: 8.51063829787234%; *margin-left: 8.404255319148938%; } [class*="span"].hide, .row-fluid [class*="span"].hide { display: none; } [class*="span"].pull-right, .row-fluid [class*="span"].pull-right { float: right; } .container { margin-right: auto; margin-left: auto; *zoom: 1; } .container:before, .container:after { display: table; content: ""; line-height: 0; } .container:after { clear: both; } .container-fluid { padding-right: 20px; padding-left: 20px; *zoom: 1; } .container-fluid:before, .container-fluid:after { display: table; content: ""; line-height: 0; } .container-fluid:after { clear: both; } p { margin: 0 0 10px; } .lead { margin-bottom: 20px; font-size: 21px; font-weight: 200; line-height: 30px; } small { font-size: 85%; } strong { font-weight: bold; } em { font-style: italic; } cite { font-style: normal; } .muted { color: #999999; } a.muted:hover, a.muted:focus { color: #808080; } .text-warning { color: #c09853; } a.text-warning:hover, a.text-warning:focus { color: #a47e3c; } .text-error { color: #b94a48; } a.text-error:hover, a.text-error:focus { color: #953b39; } .text-info { color: #3a87ad; } a.text-info:hover, a.text-info:focus { color: #2d6987; } .text-success { color: #468847; } a.text-success:hover, a.text-success:focus { color: #356635; } .text-left { text-align: left; } .text-right { text-align: right; } .text-center { text-align: center; } h1, h2, h3, h4, h5, h6 { margin: 10px 0; font-family: inherit; font-weight: bold; line-height: 20px; color: inherit; text-rendering: optimizelegibility; } h1 small, h2 small, h3 small, h4 small, h5 small, h6 small { font-weight: normal; line-height: 1; color: #999999; } h1, h2, h3 { line-height: 40px; } h1 { font-size: 38.5px; } h2 { font-size: 31.5px; } h3 { font-size: 24.5px; } h4 { font-size: 17.5px; } h5 { font-size: 14px; } h6 { font-size: 11.9px; } h1 small { font-size: 24.5px; } h2 small { font-size: 17.5px; } h3 small { font-size: 14px; } h4 small { font-size: 14px; } .page-header { padding-bottom: 9px; margin: 20px 0 30px; border-bottom: 1px solid #eeeeee; } ul, ol { padding: 0; margin: 0 0 10px 25px; } ul ul, ul ol, ol ol, ol ul { margin-bottom: 0; } li { line-height: 20px; } ul.unstyled, ol.unstyled { margin-left: 0; list-style: none; } ul.inline, ol.inline { margin-left: 0; list-style: none; } ul.inline > li, ol.inline > li { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; padding-left: 5px; padding-right: 5px; } dl { margin-bottom: 20px; } dt, dd { line-height: 20px; } dt { font-weight: bold; } dd { margin-left: 10px; } .dl-horizontal { *zoom: 1; } .dl-horizontal:before, .dl-horizontal:after { display: table; content: ""; line-height: 0; } .dl-horizontal:after { clear: both; } .dl-horizontal dt { float: left; width: 160px; clear: left; text-align: right; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .dl-horizontal dd { margin-left: 180px; } hr { margin: 20px 0; border: 0; border-top: 1px solid #eeeeee; border-bottom: 1px solid #ffffff; } abbr[title], abbr[data-original-title] { cursor: help; border-bottom: 1px dotted #999999; } abbr.initialism { font-size: 90%; text-transform: uppercase; } blockquote { padding: 0 0 0 15px; margin: 0 0 20px; border-left: 5px solid #eeeeee; } blockquote p { margin-bottom: 0; font-size: 17.5px; font-weight: 300; line-height: 1.25; } blockquote small { display: block; line-height: 20px; color: #999999; } blockquote small:before { content: '\2014 \00A0'; } blockquote.pull-right { float: right; padding-right: 15px; padding-left: 0; border-right: 5px solid #eeeeee; border-left: 0; } blockquote.pull-right p, blockquote.pull-right small { text-align: right; } blockquote.pull-right small:before { content: ''; } blockquote.pull-right small:after { content: '\00A0 \2014'; } q:before, q:after, blockquote:before, blockquote:after { content: ""; } address { display: block; margin-bottom: 20px; font-style: normal; line-height: 20px; } code, pre { padding: 0 3px 2px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: #333333; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } code { padding: 2px 4px; color: #d14; background-color: #f7f7f9; border: 1px solid #e1e1e8; white-space: nowrap; } pre { display: block; padding: 9.5px; margin: 0 0 10px; font-size: 13px; line-height: 20px; word-break: break-all; word-wrap: break-word; white-space: pre; white-space: pre-wrap; background-color: #f5f5f5; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.15); -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } pre.prettyprint { margin-bottom: 20px; } pre code { padding: 0; color: inherit; white-space: pre; white-space: pre-wrap; background-color: transparent; border: 0; } .pre-scrollable { max-height: 340px; overflow-y: scroll; } .label, .badge { display: inline-block; padding: 2px 4px; font-size: 11.844px; font-weight: bold; line-height: 14px; color: #ffffff; vertical-align: baseline; white-space: nowrap; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #999999; } .label { -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .badge { padding-left: 9px; padding-right: 9px; -webkit-border-radius: 9px; -moz-border-radius: 9px; border-radius: 9px; } .label:empty, .badge:empty { display: none; } a.label:hover, a.label:focus, a.badge:hover, a.badge:focus { color: #ffffff; text-decoration: none; cursor: pointer; } .label-important, .badge-important { background-color: #b94a48; } .label-important[href], .badge-important[href] { background-color: #953b39; } .label-warning, .badge-warning { background-color: #fc9f06; } .label-warning[href], .badge-warning[href] { background-color: #cd8002; } .label-success, .badge-success { background-color: #468847; } .label-success[href], .badge-success[href] { background-color: #356635; } .label-info, .badge-info { background-color: #3a87ad; } .label-info[href], .badge-info[href] { background-color: #2d6987; } .label-inverse, .badge-inverse { background-color: #333333; } .label-inverse[href], .badge-inverse[href] { background-color: #1a1a1a; } .btn .label, .btn .badge { position: relative; top: -1px; } .btn-mini .label, .btn-mini .badge { top: 0; } table { max-width: 100%; background-color: transparent; border-collapse: collapse; border-spacing: 0; } .table { width: 100%; margin-bottom: 20px; } .table th, .table td { padding: 8px; line-height: 20px; text-align: left; vertical-align: top; border-top: 1px solid #dddddd; } .table th { font-weight: bold; } .table thead th { vertical-align: bottom; } .table caption + thead tr:first-child th, .table caption + thead tr:first-child td, .table colgroup + thead tr:first-child th, .table colgroup + thead tr:first-child td, .table thead:first-child tr:first-child th, .table thead:first-child tr:first-child td { border-top: 0; } .table tbody + tbody { border-top: 2px solid #dddddd; } .table .table { background-color: #c5ad91; } .table-condensed th, .table-condensed td { padding: 4px 5px; } .table-bordered { border: 1px solid #dddddd; border-collapse: separate; *border-collapse: collapse; border-left: 0; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .table-bordered th, .table-bordered td { border-left: 1px solid #dddddd; } .table-bordered caption + thead tr:first-child th, .table-bordered caption + tbody tr:first-child th, .table-bordered caption + tbody tr:first-child td, .table-bordered colgroup + thead tr:first-child th, .table-bordered colgroup + tbody tr:first-child th, .table-bordered colgroup + tbody tr:first-child td, .table-bordered thead:first-child tr:first-child th, .table-bordered tbody:first-child tr:first-child th, .table-bordered tbody:first-child tr:first-child td { border-top: 0; } .table-bordered thead:first-child tr:first-child > th:first-child, .table-bordered tbody:first-child tr:first-child > td:first-child, .table-bordered tbody:first-child tr:first-child > th:first-child { -webkit-border-top-left-radius: 4px; -moz-border-radius-topleft: 4px; border-top-left-radius: 4px; } .table-bordered thead:first-child tr:first-child > th:last-child, .table-bordered tbody:first-child tr:first-child > td:last-child, .table-bordered tbody:first-child tr:first-child > th:last-child { -webkit-border-top-right-radius: 4px; -moz-border-radius-topright: 4px; border-top-right-radius: 4px; } .table-bordered thead:last-child tr:last-child > th:first-child, .table-bordered tbody:last-child tr:last-child > td:first-child, .table-bordered tbody:last-child tr:last-child > th:first-child, .table-bordered tfoot:last-child tr:last-child > td:first-child, .table-bordered tfoot:last-child tr:last-child > th:first-child { -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomleft: 4px; border-bottom-left-radius: 4px; } .table-bordered thead:last-child tr:last-child > th:last-child, .table-bordered tbody:last-child tr:last-child > td:last-child, .table-bordered tbody:last-child tr:last-child > th:last-child, .table-bordered tfoot:last-child tr:last-child > td:last-child, .table-bordered tfoot:last-child tr:last-child > th:last-child { -webkit-border-bottom-right-radius: 4px; -moz-border-radius-bottomright: 4px; border-bottom-right-radius: 4px; } .table-bordered tfoot + tbody:last-child tr:last-child td:first-child { -webkit-border-bottom-left-radius: 0; -moz-border-radius-bottomleft: 0; border-bottom-left-radius: 0; } .table-bordered tfoot + tbody:last-child tr:last-child td:last-child { -webkit-border-bottom-right-radius: 0; -moz-border-radius-bottomright: 0; border-bottom-right-radius: 0; } .table-bordered caption + thead tr:first-child th:first-child, .table-bordered caption + tbody tr:first-child td:first-child, .table-bordered colgroup + thead tr:first-child th:first-child, .table-bordered colgroup + tbody tr:first-child td:first-child { -webkit-border-top-left-radius: 4px; -moz-border-radius-topleft: 4px; border-top-left-radius: 4px; } .table-bordered caption + thead tr:first-child th:last-child, .table-bordered caption + tbody tr:first-child td:last-child, .table-bordered colgroup + thead tr:first-child th:last-child, .table-bordered colgroup + tbody tr:first-child td:last-child { -webkit-border-top-right-radius: 4px; -moz-border-radius-topright: 4px; border-top-right-radius: 4px; } .table-striped tbody > tr:nth-child(odd) > td, .table-striped tbody > tr:nth-child(odd) > th { background-color: #f9f9f9; } .table-hover tbody tr:hover > td, .table-hover tbody tr:hover > th { background-color: #f5f5f5; } table td[class*="span"], table th[class*="span"], .row-fluid table td[class*="span"], .row-fluid table th[class*="span"] { display: table-cell; float: none; margin-left: 0; } .table td.span1, .table th.span1 { float: none; width: 44px; margin-left: 0; } .table td.span2, .table th.span2 { float: none; width: 124px; margin-left: 0; } .table td.span3, .table th.span3 { float: none; width: 204px; margin-left: 0; } .table td.span4, .table th.span4 { float: none; width: 284px; margin-left: 0; } .table td.span5, .table th.span5 { float: none; width: 364px; margin-left: 0; } .table td.span6, .table th.span6 { float: none; width: 444px; margin-left: 0; } .table td.span7, .table th.span7 { float: none; width: 524px; margin-left: 0; } .table td.span8, .table th.span8 { float: none; width: 604px; margin-left: 0; } .table td.span9, .table th.span9 { float: none; width: 684px; margin-left: 0; } .table td.span10, .table th.span10 { float: none; width: 764px; margin-left: 0; } .table td.span11, .table th.span11 { float: none; width: 844px; margin-left: 0; } .table td.span12, .table th.span12 { float: none; width: 924px; margin-left: 0; } .table tbody tr.success > td { background-color: #dff0d8; } .table tbody tr.error > td { background-color: #f2dede; } .table tbody tr.warning > td { background-color: #fcf8e3; } .table tbody tr.info > td { background-color: #d9edf7; } .table-hover tbody tr.success:hover > td { background-color: #d0e9c6; } .table-hover tbody tr.error:hover > td { background-color: #ebcccc; } .table-hover tbody tr.warning:hover > td { background-color: #faf2cc; } .table-hover tbody tr.info:hover > td { background-color: #c4e3f3; } form { margin: 0 0 20px; } fieldset { padding: 0; margin: 0; border: 0; } legend { display: block; width: 100%; padding: 0; margin-bottom: 20px; font-size: 21px; line-height: 40px; color: #333333; border: 0; border-bottom: 1px solid #e5e5e5; } legend small { font-size: 15px; color: #999999; } label, input, button, select, textarea { font-size: 14px; font-weight: normal; line-height: 20px; } input, button, select, textarea { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } label { display: block; margin-bottom: 5px; } select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input { display: inline-block; height: 20px; padding: 4px 6px; margin-bottom: 10px; font-size: 14px; line-height: 20px; color: #555555; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; vertical-align: middle; } input, textarea, .uneditable-input { width: 206px; } textarea { height: auto; } textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input { background-color: #ffffff; border: 1px solid #cccccc; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border linear .2s, box-shadow linear .2s; -moz-transition: border linear .2s, box-shadow linear .2s; -o-transition: border linear .2s, box-shadow linear .2s; transition: border linear .2s, box-shadow linear .2s; } textarea:focus, input[type="text"]:focus, input[type="password"]:focus, input[type="datetime"]:focus, input[type="datetime-local"]:focus, input[type="date"]:focus, input[type="month"]:focus, input[type="time"]:focus, input[type="week"]:focus, input[type="number"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="search"]:focus, input[type="tel"]:focus, input[type="color"]:focus, .uneditable-input:focus { border-color: rgba(82, 168, 236, 0.8); outline: 0; outline: thin dotted \9; /* IE6-9 */ -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); } input[type="radio"], input[type="checkbox"] { margin: 4px 0 0; *margin-top: 0; /* IE7 */ margin-top: 1px \9; /* IE8-9 */ line-height: normal; } input[type="file"], input[type="image"], input[type="submit"], input[type="reset"], input[type="button"], input[type="radio"], input[type="checkbox"] { width: auto; } select, input[type="file"] { height: 30px; /* In IE7, the height of the select element cannot be changed by height, only font-size */ *margin-top: 4px; /* For IE7, add top margin to align select with labels */ line-height: 30px; } select { width: 220px; border: 1px solid #cccccc; background-color: #ffffff; } select[multiple], select[size] { height: auto; } select:focus, input[type="file"]:focus, input[type="radio"]:focus, input[type="checkbox"]:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } .uneditable-input, .uneditable-textarea { color: #999999; background-color: #fcfcfc; border-color: #cccccc; -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); cursor: not-allowed; } .uneditable-input { overflow: hidden; white-space: nowrap; } .uneditable-textarea { width: auto; height: auto; } input:-moz-placeholder, textarea:-moz-placeholder { color: #999999; } input:-ms-input-placeholder, textarea:-ms-input-placeholder { color: #999999; } input::-webkit-input-placeholder, textarea::-webkit-input-placeholder { color: #999999; } .radio, .checkbox { min-height: 20px; padding-left: 20px; } .radio input[type="radio"], .checkbox input[type="checkbox"] { float: left; margin-left: -20px; } .controls > .radio:first-child, .controls > .checkbox:first-child { padding-top: 5px; } .radio.inline, .checkbox.inline { display: inline-block; padding-top: 5px; margin-bottom: 0; vertical-align: middle; } .radio.inline + .radio.inline, .checkbox.inline + .checkbox.inline { margin-left: 10px; } .input-mini { width: 60px; } .input-small { width: 90px; } .input-medium { width: 150px; } .input-large { width: 210px; } .input-xlarge { width: 270px; } .input-xxlarge { width: 530px; } input[class*="span"], select[class*="span"], textarea[class*="span"], .uneditable-input[class*="span"], .row-fluid input[class*="span"], .row-fluid select[class*="span"], .row-fluid textarea[class*="span"], .row-fluid .uneditable-input[class*="span"] { float: none; margin-left: 0; } .input-append input[class*="span"], .input-append .uneditable-input[class*="span"], .input-prepend input[class*="span"], .input-prepend .uneditable-input[class*="span"], .row-fluid input[class*="span"], .row-fluid select[class*="span"], .row-fluid textarea[class*="span"], .row-fluid .uneditable-input[class*="span"], .row-fluid .input-prepend [class*="span"], .row-fluid .input-append [class*="span"] { display: inline-block; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 20px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 926px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 846px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 766px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 686px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 606px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 526px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 446px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 366px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 286px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 206px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 126px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 46px; } .controls-row { *zoom: 1; } .controls-row:before, .controls-row:after { display: table; content: ""; line-height: 0; } .controls-row:after { clear: both; } .controls-row [class*="span"], .row-fluid .controls-row [class*="span"] { float: left; } .controls-row .checkbox[class*="span"], .controls-row .radio[class*="span"] { padding-top: 5px; } input[disabled], select[disabled], textarea[disabled], input[readonly], select[readonly], textarea[readonly] { cursor: not-allowed; background-color: #eeeeee; } input[type="radio"][disabled], input[type="checkbox"][disabled], input[type="radio"][readonly], input[type="checkbox"][readonly] { background-color: transparent; } .control-group.warning .control-label, .control-group.warning .help-block, .control-group.warning .help-inline { color: #c09853; } .control-group.warning .checkbox, .control-group.warning .radio, .control-group.warning input, .control-group.warning select, .control-group.warning textarea { color: #c09853; } .control-group.warning input, .control-group.warning select, .control-group.warning textarea { border-color: #c09853; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.warning input:focus, .control-group.warning select:focus, .control-group.warning textarea:focus { border-color: #a47e3c; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; } .control-group.warning .input-prepend .add-on, .control-group.warning .input-append .add-on { color: #c09853; background-color: #fcf8e3; border-color: #c09853; } .control-group.error .control-label, .control-group.error .help-block, .control-group.error .help-inline { color: #b94a48; } .control-group.error .checkbox, .control-group.error .radio, .control-group.error input, .control-group.error select, .control-group.error textarea { color: #b94a48; } .control-group.error input, .control-group.error select, .control-group.error textarea { border-color: #b94a48; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.error input:focus, .control-group.error select:focus, .control-group.error textarea:focus { border-color: #953b39; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; } .control-group.error .input-prepend .add-on, .control-group.error .input-append .add-on { color: #b94a48; background-color: #f2dede; border-color: #b94a48; } .control-group.success .control-label, .control-group.success .help-block, .control-group.success .help-inline { color: #468847; } .control-group.success .checkbox, .control-group.success .radio, .control-group.success input, .control-group.success select, .control-group.success textarea { color: #468847; } .control-group.success input, .control-group.success select, .control-group.success textarea { border-color: #468847; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.success input:focus, .control-group.success select:focus, .control-group.success textarea:focus { border-color: #356635; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; } .control-group.success .input-prepend .add-on, .control-group.success .input-append .add-on { color: #468847; background-color: #dff0d8; border-color: #468847; } .control-group.info .control-label, .control-group.info .help-block, .control-group.info .help-inline { color: #3a87ad; } .control-group.info .checkbox, .control-group.info .radio, .control-group.info input, .control-group.info select, .control-group.info textarea { color: #3a87ad; } .control-group.info input, .control-group.info select, .control-group.info textarea { border-color: #3a87ad; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.info input:focus, .control-group.info select:focus, .control-group.info textarea:focus { border-color: #2d6987; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; } .control-group.info .input-prepend .add-on, .control-group.info .input-append .add-on { color: #3a87ad; background-color: #d9edf7; border-color: #3a87ad; } input:focus:invalid, textarea:focus:invalid, select:focus:invalid { color: #b94a48; border-color: #ee5f5b; } input:focus:invalid:focus, textarea:focus:invalid:focus, select:focus:invalid:focus { border-color: #e9322d; -webkit-box-shadow: 0 0 6px #f8b9b7; -moz-box-shadow: 0 0 6px #f8b9b7; box-shadow: 0 0 6px #f8b9b7; } .form-actions { padding: 19px 20px 20px; margin-top: 20px; margin-bottom: 20px; background-color: #f5f5f5; border-top: 1px solid #e5e5e5; *zoom: 1; } .form-actions:before, .form-actions:after { display: table; content: ""; line-height: 0; } .form-actions:after { clear: both; } .help-block, .help-inline { color: #505050; } .help-block { display: block; margin-bottom: 10px; } .help-inline { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; vertical-align: middle; padding-left: 5px; } .input-append, .input-prepend { display: inline-block; margin-bottom: 10px; vertical-align: middle; font-size: 0; white-space: nowrap; } .input-append input, .input-prepend input, .input-append select, .input-prepend select, .input-append .uneditable-input, .input-prepend .uneditable-input, .input-append .dropdown-menu, .input-prepend .dropdown-menu, .input-append .popover, .input-prepend .popover { font-size: 14px; } .input-append input, .input-prepend input, .input-append select, .input-prepend select, .input-append .uneditable-input, .input-prepend .uneditable-input { position: relative; margin-bottom: 0; *margin-left: 0; vertical-align: top; -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .input-append input:focus, .input-prepend input:focus, .input-append select:focus, .input-prepend select:focus, .input-append .uneditable-input:focus, .input-prepend .uneditable-input:focus { z-index: 2; } .input-append .add-on, .input-prepend .add-on { display: inline-block; width: auto; height: 20px; min-width: 16px; padding: 4px 5px; font-size: 14px; font-weight: normal; line-height: 20px; text-align: center; text-shadow: 0 1px 0 #ffffff; background-color: #eeeeee; border: 1px solid #ccc; } .input-append .add-on, .input-prepend .add-on, .input-append .btn, .input-prepend .btn, .input-append .btn-group > .dropdown-toggle, .input-prepend .btn-group > .dropdown-toggle { vertical-align: top; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .input-append .active, .input-prepend .active { background-color: #a9dba9; border-color: #46a546; } .input-prepend .add-on, .input-prepend .btn { margin-right: -1px; } .input-prepend .add-on:first-child, .input-prepend .btn:first-child { -webkit-border-radius: 4px 0 0 4px; -moz-border-radius: 4px 0 0 4px; border-radius: 4px 0 0 4px; } .input-append input, .input-append select, .input-append .uneditable-input { -webkit-border-radius: 4px 0 0 4px; -moz-border-radius: 4px 0 0 4px; border-radius: 4px 0 0 4px; } .input-append input + .btn-group .btn:last-child, .input-append select + .btn-group .btn:last-child, .input-append .uneditable-input + .btn-group .btn:last-child { -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .input-append .add-on, .input-append .btn, .input-append .btn-group { margin-left: -1px; } .input-append .add-on:last-child, .input-append .btn:last-child, .input-append .btn-group:last-child > .dropdown-toggle { -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .input-prepend.input-append input, .input-prepend.input-append select, .input-prepend.input-append .uneditable-input { -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .input-prepend.input-append input + .btn-group .btn, .input-prepend.input-append select + .btn-group .btn, .input-prepend.input-append .uneditable-input + .btn-group .btn { -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .input-prepend.input-append .add-on:first-child, .input-prepend.input-append .btn:first-child { margin-right: -1px; -webkit-border-radius: 4px 0 0 4px; -moz-border-radius: 4px 0 0 4px; border-radius: 4px 0 0 4px; } .input-prepend.input-append .add-on:last-child, .input-prepend.input-append .btn:last-child { margin-left: -1px; -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .input-prepend.input-append .btn-group:first-child { margin-left: 0; } input.search-query { padding-right: 14px; padding-right: 4px \9; padding-left: 14px; padding-left: 4px \9; /* IE7-8 doesn't have border-radius, so don't indent the padding */ margin-bottom: 0; -webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px; } /* Allow for input prepend/append in search forms */ .form-search .input-append .search-query, .form-search .input-prepend .search-query { -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .form-search .input-append .search-query { -webkit-border-radius: 14px 0 0 14px; -moz-border-radius: 14px 0 0 14px; border-radius: 14px 0 0 14px; } .form-search .input-append .btn { -webkit-border-radius: 0 14px 14px 0; -moz-border-radius: 0 14px 14px 0; border-radius: 0 14px 14px 0; } .form-search .input-prepend .search-query { -webkit-border-radius: 0 14px 14px 0; -moz-border-radius: 0 14px 14px 0; border-radius: 0 14px 14px 0; } .form-search .input-prepend .btn { -webkit-border-radius: 14px 0 0 14px; -moz-border-radius: 14px 0 0 14px; border-radius: 14px 0 0 14px; } .form-search input, .form-inline input, .form-horizontal input, .form-search textarea, .form-inline textarea, .form-horizontal textarea, .form-search select, .form-inline select, .form-horizontal select, .form-search .help-inline, .form-inline .help-inline, .form-horizontal .help-inline, .form-search .uneditable-input, .form-inline .uneditable-input, .form-horizontal .uneditable-input, .form-search .input-prepend, .form-inline .input-prepend, .form-horizontal .input-prepend, .form-search .input-append, .form-inline .input-append, .form-horizontal .input-append { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; margin-bottom: 0; vertical-align: middle; } .form-search .hide, .form-inline .hide, .form-horizontal .hide { display: none; } .form-search label, .form-inline label, .form-search .btn-group, .form-inline .btn-group { display: inline-block; } .form-search .input-append, .form-inline .input-append, .form-search .input-prepend, .form-inline .input-prepend { margin-bottom: 0; } .form-search .radio, .form-search .checkbox, .form-inline .radio, .form-inline .checkbox { padding-left: 0; margin-bottom: 0; vertical-align: middle; } .form-search .radio input[type="radio"], .form-search .checkbox input[type="checkbox"], .form-inline .radio input[type="radio"], .form-inline .checkbox input[type="checkbox"] { float: left; margin-right: 3px; margin-left: 0; } .control-group { margin-bottom: 10px; } legend + .control-group { margin-top: 20px; -webkit-margin-top-collapse: separate; } .form-horizontal .control-group { margin-bottom: 20px; *zoom: 1; } .form-horizontal .control-group:before, .form-horizontal .control-group:after { display: table; content: ""; line-height: 0; } .form-horizontal .control-group:after { clear: both; } .form-horizontal .control-label { float: left; width: 160px; padding-top: 5px; text-align: right; } .form-horizontal .controls { *display: inline-block; *padding-left: 20px; margin-left: 180px; *margin-left: 0; } .form-horizontal .controls:first-child { *padding-left: 180px; } .form-horizontal .help-block { margin-bottom: 0; } .form-horizontal input + .help-block, .form-horizontal select + .help-block, .form-horizontal textarea + .help-block, .form-horizontal .uneditable-input + .help-block, .form-horizontal .input-prepend + .help-block, .form-horizontal .input-append + .help-block { margin-top: 10px; } .form-horizontal .form-actions { padding-left: 180px; } .btn { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; padding: 4px 12px; margin-bottom: 0; font-size: 14px; line-height: 20px; text-align: center; vertical-align: middle; cursor: pointer; color: #333333; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); background-color: #f5f5f5; background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); background-image: linear-gradient(to bottom, #ffffff, #e6e6e6); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0); border-color: #e6e6e6 #e6e6e6 #bfbfbf; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #e6e6e6; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); border: 1px solid #cccccc; *border: 0; border-bottom-color: #b3b3b3; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; *margin-left: .3em; -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); } .btn:hover, .btn:focus, .btn:active, .btn.active, .btn.disabled, .btn[disabled] { color: #333333; background-color: #e6e6e6; *background-color: #d9d9d9; } .btn:active, .btn.active { background-color: #cccccc \9; } .btn:first-child { *margin-left: 0; } .btn:hover, .btn:focus { color: #333333; text-decoration: none; background-position: 0 -15px; -webkit-transition: background-position 0.1s linear; -moz-transition: background-position 0.1s linear; -o-transition: background-position 0.1s linear; transition: background-position 0.1s linear; } .btn:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } .btn.active, .btn:active { background-image: none; outline: 0; -webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); } .btn.disabled, .btn[disabled] { cursor: default; background-image: none; opacity: 0.65; filter: alpha(opacity=65); -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .btn-large { padding: 11px 19px; font-size: 17.5px; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .btn-large [class^="icon-"], .btn-large [class*=" icon-"] { margin-top: 4px; } .btn-small { padding: 2px 10px; font-size: 11.9px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .btn-small [class^="icon-"], .btn-small [class*=" icon-"] { margin-top: 0; } .btn-mini [class^="icon-"], .btn-mini [class*=" icon-"] { margin-top: -1px; } .btn-mini { padding: 0 6px; font-size: 10.5px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .btn-block { display: block; width: 100%; padding-left: 0; padding-right: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .btn-block + .btn-block { margin-top: 5px; } input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="button"].btn-block { width: 100%; } .btn-primary.active, .btn-warning.active, .btn-danger.active, .btn-success.active, .btn-info.active, .btn-inverse.active { color: rgba(255, 255, 255, 0.75); } .btn-primary { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #816266; background-image: -moz-linear-gradient(top, #715458, #9a777c); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#715458), to(#9a777c)); background-image: -webkit-linear-gradient(top, #715458, #9a777c); background-image: -o-linear-gradient(top, #715458, #9a777c); background-image: linear-gradient(to bottom, #715458, #9a777c); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff715458', endColorstr='#ff9a777c', GradientType=0); border-color: #9a777c #9a777c #715458; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #9a777c; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .btn-primary.disabled, .btn-primary[disabled] { color: #ffffff; background-color: #9a777c; *background-color: #8e6a6f; } .btn-primary:active, .btn-primary.active { background-color: #805f63 \9; } .btn-warning { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #fdb033; background-image: -moz-linear-gradient(top, #fdbc52, #fc9f06); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fdbc52), to(#fc9f06)); background-image: -webkit-linear-gradient(top, #fdbc52, #fc9f06); background-image: -o-linear-gradient(top, #fdbc52, #fc9f06); background-image: linear-gradient(to bottom, #fdbc52, #fc9f06); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffdbc52', endColorstr='#fffc9f06', GradientType=0); border-color: #fc9f06 #fc9f06 #b37002; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #fc9f06; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-warning:hover, .btn-warning:focus, .btn-warning:active, .btn-warning.active, .btn-warning.disabled, .btn-warning[disabled] { color: #ffffff; background-color: #fc9f06; *background-color: #e69003; } .btn-warning:active, .btn-warning.active { background-color: #cd8002 \9; } .btn-danger { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #da4f49; background-image: -moz-linear-gradient(top, #ee5f5b, #bd362f); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f)); background-image: -webkit-linear-gradient(top, #ee5f5b, #bd362f); background-image: -o-linear-gradient(top, #ee5f5b, #bd362f); background-image: linear-gradient(to bottom, #ee5f5b, #bd362f); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0); border-color: #bd362f #bd362f #802420; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #bd362f; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-danger:hover, .btn-danger:focus, .btn-danger:active, .btn-danger.active, .btn-danger.disabled, .btn-danger[disabled] { color: #ffffff; background-color: #bd362f; *background-color: #a9302a; } .btn-danger:active, .btn-danger.active { background-color: #942a25 \9; } .btn-success { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #5bb75b; background-image: -moz-linear-gradient(top, #62c462, #51a351); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351)); background-image: -webkit-linear-gradient(top, #62c462, #51a351); background-image: -o-linear-gradient(top, #62c462, #51a351); background-image: linear-gradient(to bottom, #62c462, #51a351); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0); border-color: #51a351 #51a351 #387038; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #51a351; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-success:hover, .btn-success:focus, .btn-success:active, .btn-success.active, .btn-success.disabled, .btn-success[disabled] { color: #ffffff; background-color: #51a351; *background-color: #499249; } .btn-success:active, .btn-success.active { background-color: #408140 \9; } .btn-info { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #49afcd; background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); background-image: linear-gradient(to bottom, #5bc0de, #2f96b4); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0); border-color: #2f96b4 #2f96b4 #1f6377; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #2f96b4; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-info:hover, .btn-info:focus, .btn-info:active, .btn-info.active, .btn-info.disabled, .btn-info[disabled] { color: #ffffff; background-color: #2f96b4; *background-color: #2a85a0; } .btn-info:active, .btn-info.active { background-color: #24748c \9; } .btn-inverse { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #363636; background-image: -moz-linear-gradient(top, #444444, #222222); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222)); background-image: -webkit-linear-gradient(top, #444444, #222222); background-image: -o-linear-gradient(top, #444444, #222222); background-image: linear-gradient(to bottom, #444444, #222222); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0); border-color: #222222 #222222 #000000; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #222222; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-inverse:hover, .btn-inverse:focus, .btn-inverse:active, .btn-inverse.active, .btn-inverse.disabled, .btn-inverse[disabled] { color: #ffffff; background-color: #222222; *background-color: #151515; } .btn-inverse:active, .btn-inverse.active { background-color: #080808 \9; } button.btn, input[type="submit"].btn { *padding-top: 3px; *padding-bottom: 3px; } button.btn::-moz-focus-inner, input[type="submit"].btn::-moz-focus-inner { padding: 0; border: 0; } button.btn.btn-large, input[type="submit"].btn.btn-large { *padding-top: 7px; *padding-bottom: 7px; } button.btn.btn-small, input[type="submit"].btn.btn-small { *padding-top: 3px; *padding-bottom: 3px; } button.btn.btn-mini, input[type="submit"].btn.btn-mini { *padding-top: 1px; *padding-bottom: 1px; } .btn-link, .btn-link:active, .btn-link[disabled] { background-color: transparent; background-image: none; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .btn-link { border-color: transparent; cursor: pointer; color: #715458; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .btn-link:hover, .btn-link:focus { color: #ca3308; text-decoration: underline; background-color: transparent; } .btn-link[disabled]:hover, .btn-link[disabled]:focus { color: #333333; text-decoration: none; } [class^="icon-"], [class*=" icon-"] { display: inline-block; width: 14px; height: 14px; *margin-right: .3em; line-height: 14px; vertical-align: text-top; background-image: url("../img/glyphicons-halflings.png"); background-position: 14px 14px; background-repeat: no-repeat; margin-top: 1px; } /* White icons with optional class, or on hover/focus/active states of certain elements */ .icon-white, .nav-pills > .active > a > [class^="icon-"], .nav-pills > .active > a > [class*=" icon-"], .nav-list > .active > a > [class^="icon-"], .nav-list > .active > a > [class*=" icon-"], .navbar-inverse .nav > .active > a > [class^="icon-"], .navbar-inverse .nav > .active > a > [class*=" icon-"], .dropdown-menu > li > a:hover > [class^="icon-"], .dropdown-menu > li > a:focus > [class^="icon-"], .dropdown-menu > li > a:hover > [class*=" icon-"], .dropdown-menu > li > a:focus > [class*=" icon-"], .dropdown-menu > .active > a > [class^="icon-"], .dropdown-menu > .active > a > [class*=" icon-"], .dropdown-submenu:hover > a > [class^="icon-"], .dropdown-submenu:focus > a > [class^="icon-"], .dropdown-submenu:hover > a > [class*=" icon-"], .dropdown-submenu:focus > a > [class*=" icon-"] { background-image: url("../img/glyphicons-halflings-white.png"); } .icon-glass { background-position: 0 0; } .icon-music { background-position: -24px 0; } .icon-search { background-position: -48px 0; } .icon-envelope { background-position: -72px 0; } .icon-heart { background-position: -96px 0; } .icon-star { background-position: -120px 0; } .icon-star-empty { background-position: -144px 0; } .icon-user { background-position: -168px 0; } .icon-film { background-position: -192px 0; } .icon-th-large { background-position: -216px 0; } .icon-th { background-position: -240px 0; } .icon-th-list { background-position: -264px 0; } .icon-ok { background-position: -288px 0; } .icon-remove { background-position: -312px 0; } .icon-zoom-in { background-position: -336px 0; } .icon-zoom-out { background-position: -360px 0; } .icon-off { background-position: -384px 0; } .icon-signal { background-position: -408px 0; } .icon-cog { background-position: -432px 0; } .icon-trash { background-position: -456px 0; } .icon-home { background-position: 0 -24px; } .icon-file { background-position: -24px -24px; } .icon-time { background-position: -48px -24px; } .icon-road { background-position: -72px -24px; } .icon-download-alt { background-position: -96px -24px; } .icon-download { background-position: -120px -24px; } .icon-upload { background-position: -144px -24px; } .icon-inbox { background-position: -168px -24px; } .icon-play-circle { background-position: -192px -24px; } .icon-repeat { background-position: -216px -24px; } .icon-refresh { background-position: -240px -24px; } .icon-list-alt { background-position: -264px -24px; } .icon-lock { background-position: -287px -24px; } .icon-flag { background-position: -312px -24px; } .icon-headphones { background-position: -336px -24px; } .icon-volume-off { background-position: -360px -24px; } .icon-volume-down { background-position: -384px -24px; } .icon-volume-up { background-position: -408px -24px; } .icon-qrcode { background-position: -432px -24px; } .icon-barcode { background-position: -456px -24px; } .icon-tag { background-position: 0 -48px; } .icon-tags { background-position: -25px -48px; } .icon-book { background-position: -48px -48px; } .icon-bookmark { background-position: -72px -48px; } .icon-print { background-position: -96px -48px; } .icon-camera { background-position: -120px -48px; } .icon-font { background-position: -144px -48px; } .icon-bold { background-position: -167px -48px; } .icon-italic { background-position: -192px -48px; } .icon-text-height { background-position: -216px -48px; } .icon-text-width { background-position: -240px -48px; } .icon-align-left { background-position: -264px -48px; } .icon-align-center { background-position: -288px -48px; } .icon-align-right { background-position: -312px -48px; } .icon-align-justify { background-position: -336px -48px; } .icon-list { background-position: -360px -48px; } .icon-indent-left { background-position: -384px -48px; } .icon-indent-right { background-position: -408px -48px; } .icon-facetime-video { background-position: -432px -48px; } .icon-picture { background-position: -456px -48px; } .icon-pencil { background-position: 0 -72px; } .icon-map-marker { background-position: -24px -72px; } .icon-adjust { background-position: -48px -72px; } .icon-tint { background-position: -72px -72px; } .icon-edit { background-position: -96px -72px; } .icon-share { background-position: -120px -72px; } .icon-check { background-position: -144px -72px; } .icon-move { background-position: -168px -72px; } .icon-step-backward { background-position: -192px -72px; } .icon-fast-backward { background-position: -216px -72px; } .icon-backward { background-position: -240px -72px; } .icon-play { background-position: -264px -72px; } .icon-pause { background-position: -288px -72px; } .icon-stop { background-position: -312px -72px; } .icon-forward { background-position: -336px -72px; } .icon-fast-forward { background-position: -360px -72px; } .icon-step-forward { background-position: -384px -72px; } .icon-eject { background-position: -408px -72px; } .icon-chevron-left { background-position: -432px -72px; } .icon-chevron-right { background-position: -456px -72px; } .icon-plus-sign { background-position: 0 -96px; } .icon-minus-sign { background-position: -24px -96px; } .icon-remove-sign { background-position: -48px -96px; } .icon-ok-sign { background-position: -72px -96px; } .icon-question-sign { background-position: -96px -96px; } .icon-info-sign { background-position: -120px -96px; } .icon-screenshot { background-position: -144px -96px; } .icon-remove-circle { background-position: -168px -96px; } .icon-ok-circle { background-position: -192px -96px; } .icon-ban-circle { background-position: -216px -96px; } .icon-arrow-left { background-position: -240px -96px; } .icon-arrow-right { background-position: -264px -96px; } .icon-arrow-up { background-position: -289px -96px; } .icon-arrow-down { background-position: -312px -96px; } .icon-share-alt { background-position: -336px -96px; } .icon-resize-full { background-position: -360px -96px; } .icon-resize-small { background-position: -384px -96px; } .icon-plus { background-position: -408px -96px; } .icon-minus { background-position: -433px -96px; } .icon-asterisk { background-position: -456px -96px; } .icon-exclamation-sign { background-position: 0 -120px; } .icon-gift { background-position: -24px -120px; } .icon-leaf { background-position: -48px -120px; } .icon-fire { background-position: -72px -120px; } .icon-eye-open { background-position: -96px -120px; } .icon-eye-close { background-position: -120px -120px; } .icon-warning-sign { background-position: -144px -120px; } .icon-plane { background-position: -168px -120px; } .icon-calendar { background-position: -192px -120px; } .icon-random { background-position: -216px -120px; width: 16px; } .icon-comment { background-position: -240px -120px; } .icon-magnet { background-position: -264px -120px; } .icon-chevron-up { background-position: -288px -120px; } .icon-chevron-down { background-position: -313px -119px; } .icon-retweet { background-position: -336px -120px; } .icon-shopping-cart { background-position: -360px -120px; } .icon-folder-close { background-position: -384px -120px; width: 16px; } .icon-folder-open { background-position: -408px -120px; width: 16px; } .icon-resize-vertical { background-position: -432px -119px; } .icon-resize-horizontal { background-position: -456px -118px; } .icon-hdd { background-position: 0 -144px; } .icon-bullhorn { background-position: -24px -144px; } .icon-bell { background-position: -48px -144px; } .icon-certificate { background-position: -72px -144px; } .icon-thumbs-up { background-position: -96px -144px; } .icon-thumbs-down { background-position: -120px -144px; } .icon-hand-right { background-position: -144px -144px; } .icon-hand-left { background-position: -168px -144px; } .icon-hand-up { background-position: -192px -144px; } .icon-hand-down { background-position: -216px -144px; } .icon-circle-arrow-right { background-position: -240px -144px; } .icon-circle-arrow-left { background-position: -264px -144px; } .icon-circle-arrow-up { background-position: -288px -144px; } .icon-circle-arrow-down { background-position: -312px -144px; } .icon-globe { background-position: -336px -144px; } .icon-wrench { background-position: -360px -144px; } .icon-tasks { background-position: -384px -144px; } .icon-filter { background-position: -408px -144px; } .icon-briefcase { background-position: -432px -144px; } .icon-fullscreen { background-position: -456px -144px; } .btn-group { position: relative; display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; font-size: 0; vertical-align: middle; white-space: nowrap; *margin-left: .3em; } .btn-group:first-child { *margin-left: 0; } .btn-group + .btn-group { margin-left: 5px; } .btn-toolbar { font-size: 0; margin-top: 10px; margin-bottom: 10px; } .btn-toolbar > .btn + .btn, .btn-toolbar > .btn-group + .btn, .btn-toolbar > .btn + .btn-group { margin-left: 5px; } .btn-group > .btn { position: relative; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .btn-group > .btn + .btn { margin-left: -1px; } .btn-group > .btn, .btn-group > .dropdown-menu, .btn-group > .popover { font-size: 14px; } .btn-group > .btn-mini { font-size: 10.5px; } .btn-group > .btn-small { font-size: 11.9px; } .btn-group > .btn-large { font-size: 17.5px; } .btn-group > .btn:first-child { margin-left: 0; -webkit-border-top-left-radius: 4px; -moz-border-radius-topleft: 4px; border-top-left-radius: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomleft: 4px; border-bottom-left-radius: 4px; } .btn-group > .btn:last-child, .btn-group > .dropdown-toggle { -webkit-border-top-right-radius: 4px; -moz-border-radius-topright: 4px; border-top-right-radius: 4px; -webkit-border-bottom-right-radius: 4px; -moz-border-radius-bottomright: 4px; border-bottom-right-radius: 4px; } .btn-group > .btn.large:first-child { margin-left: 0; -webkit-border-top-left-radius: 6px; -moz-border-radius-topleft: 6px; border-top-left-radius: 6px; -webkit-border-bottom-left-radius: 6px; -moz-border-radius-bottomleft: 6px; border-bottom-left-radius: 6px; } .btn-group > .btn.large:last-child, .btn-group > .large.dropdown-toggle { -webkit-border-top-right-radius: 6px; -moz-border-radius-topright: 6px; border-top-right-radius: 6px; -webkit-border-bottom-right-radius: 6px; -moz-border-radius-bottomright: 6px; border-bottom-right-radius: 6px; } .btn-group > .btn:hover, .btn-group > .btn:focus, .btn-group > .btn:active, .btn-group > .btn.active { z-index: 2; } .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; } .btn-group > .btn + .dropdown-toggle { padding-left: 8px; padding-right: 8px; -webkit-box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); *padding-top: 5px; *padding-bottom: 5px; } .btn-group > .btn-mini + .dropdown-toggle { padding-left: 5px; padding-right: 5px; *padding-top: 2px; *padding-bottom: 2px; } .btn-group > .btn-small + .dropdown-toggle { *padding-top: 5px; *padding-bottom: 4px; } .btn-group > .btn-large + .dropdown-toggle { padding-left: 12px; padding-right: 12px; *padding-top: 7px; *padding-bottom: 7px; } .btn-group.open .dropdown-toggle { background-image: none; -webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); } .btn-group.open .btn.dropdown-toggle { background-color: #e6e6e6; } .btn-group.open .btn-primary.dropdown-toggle { background-color: #9a777c; } .btn-group.open .btn-warning.dropdown-toggle { background-color: #fc9f06; } .btn-group.open .btn-danger.dropdown-toggle { background-color: #bd362f; } .btn-group.open .btn-success.dropdown-toggle { background-color: #51a351; } .btn-group.open .btn-info.dropdown-toggle { background-color: #2f96b4; } .btn-group.open .btn-inverse.dropdown-toggle { background-color: #222222; } .btn .caret { margin-top: 8px; margin-left: 0; } .btn-large .caret { margin-top: 6px; } .btn-large .caret { border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; } .btn-mini .caret, .btn-small .caret { margin-top: 8px; } .dropup .btn-large .caret { border-bottom-width: 5px; } .btn-primary .caret, .btn-warning .caret, .btn-danger .caret, .btn-info .caret, .btn-success .caret, .btn-inverse .caret { border-top-color: #ffffff; border-bottom-color: #ffffff; } .btn-group-vertical { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; } .btn-group-vertical > .btn { display: block; float: none; max-width: 100%; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .btn-group-vertical > .btn + .btn { margin-left: 0; margin-top: -1px; } .btn-group-vertical > .btn:first-child { -webkit-border-radius: 4px 4px 0 0; -moz-border-radius: 4px 4px 0 0; border-radius: 4px 4px 0 0; } .btn-group-vertical > .btn:last-child { -webkit-border-radius: 0 0 4px 4px; -moz-border-radius: 0 0 4px 4px; border-radius: 0 0 4px 4px; } .btn-group-vertical > .btn-large:first-child { -webkit-border-radius: 6px 6px 0 0; -moz-border-radius: 6px 6px 0 0; border-radius: 6px 6px 0 0; } .btn-group-vertical > .btn-large:last-child { -webkit-border-radius: 0 0 6px 6px; -moz-border-radius: 0 0 6px 6px; border-radius: 0 0 6px 6px; } .nav { margin-left: 0; margin-bottom: 20px; list-style: none; } .nav > li > a { display: block; } .nav > li > a:hover, .nav > li > a:focus { text-decoration: none; background-color: #eeeeee; } .nav > li > a > img { max-width: none; } .nav > .pull-right { float: right; } .nav-header { display: block; padding: 3px 15px; font-size: 11px; font-weight: bold; line-height: 20px; color: #999999; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); text-transform: uppercase; } .nav li + .nav-header { margin-top: 9px; } .nav-list { padding-left: 15px; padding-right: 15px; margin-bottom: 0; } .nav-list > li > a, .nav-list .nav-header { margin-left: -15px; margin-right: -15px; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); } .nav-list > li > a { padding: 3px 15px; } .nav-list > .active > a, .nav-list > .active > a:hover, .nav-list > .active > a:focus { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); background-color: #715458; } .nav-list [class^="icon-"], .nav-list [class*=" icon-"] { margin-right: 2px; } .nav-list .divider { *width: 100%; height: 1px; margin: 9px 1px; *margin: -5px 0 5px; overflow: hidden; background-color: #e5e5e5; border-bottom: 1px solid #ffffff; } .nav-tabs, .nav-pills { *zoom: 1; } .nav-tabs:before, .nav-pills:before, .nav-tabs:after, .nav-pills:after { display: table; content: ""; line-height: 0; } .nav-tabs:after, .nav-pills:after { clear: both; } .nav-tabs > li, .nav-pills > li { float: left; } .nav-tabs > li > a, .nav-pills > li > a { padding-right: 12px; padding-left: 12px; margin-right: 2px; line-height: 14px; } .nav-tabs { border-bottom: 1px solid #ddd; } .nav-tabs > li { margin-bottom: -1px; } .nav-tabs > li > a { padding-top: 8px; padding-bottom: 8px; line-height: 20px; border: 1px solid transparent; -webkit-border-radius: 4px 4px 0 0; -moz-border-radius: 4px 4px 0 0; border-radius: 4px 4px 0 0; } .nav-tabs > li > a:hover, .nav-tabs > li > a:focus { border-color: #eeeeee #eeeeee #dddddd; } .nav-tabs > .active > a, .nav-tabs > .active > a:hover, .nav-tabs > .active > a:focus { color: #555555; background-color: #c5ad91; border: 1px solid #ddd; border-bottom-color: transparent; cursor: default; } .nav-pills > li > a { padding-top: 8px; padding-bottom: 8px; margin-top: 2px; margin-bottom: 2px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } .nav-pills > .active > a, .nav-pills > .active > a:hover, .nav-pills > .active > a:focus { color: #ffffff; background-color: #715458; } .nav-stacked > li { float: none; } .nav-stacked > li > a { margin-right: 0; } .nav-tabs.nav-stacked { border-bottom: 0; } .nav-tabs.nav-stacked > li > a { border: 1px solid #ddd; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .nav-tabs.nav-stacked > li:first-child > a { -webkit-border-top-right-radius: 4px; -moz-border-radius-topright: 4px; border-top-right-radius: 4px; -webkit-border-top-left-radius: 4px; -moz-border-radius-topleft: 4px; border-top-left-radius: 4px; } .nav-tabs.nav-stacked > li:last-child > a { -webkit-border-bottom-right-radius: 4px; -moz-border-radius-bottomright: 4px; border-bottom-right-radius: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomleft: 4px; border-bottom-left-radius: 4px; } .nav-tabs.nav-stacked > li > a:hover, .nav-tabs.nav-stacked > li > a:focus { border-color: #ddd; z-index: 2; } .nav-pills.nav-stacked > li > a { margin-bottom: 3px; } .nav-pills.nav-stacked > li:last-child > a { margin-bottom: 1px; } .nav-tabs .dropdown-menu { -webkit-border-radius: 0 0 6px 6px; -moz-border-radius: 0 0 6px 6px; border-radius: 0 0 6px 6px; } .nav-pills .dropdown-menu { -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .nav .dropdown-toggle .caret { border-top-color: #715458; border-bottom-color: #715458; margin-top: 6px; } .nav .dropdown-toggle:hover .caret, .nav .dropdown-toggle:focus .caret { border-top-color: #ca3308; border-bottom-color: #ca3308; } /* move down carets for tabs */ .nav-tabs .dropdown-toggle .caret { margin-top: 8px; } .nav .active .dropdown-toggle .caret { border-top-color: #fff; border-bottom-color: #fff; } .nav-tabs .active .dropdown-toggle .caret { border-top-color: #555555; border-bottom-color: #555555; } .nav > .dropdown.active > a:hover, .nav > .dropdown.active > a:focus { cursor: pointer; } .nav-tabs .open .dropdown-toggle, .nav-pills .open .dropdown-toggle, .nav > li.dropdown.open.active > a:hover, .nav > li.dropdown.open.active > a:focus { color: #ffffff; background-color: #999999; border-color: #999999; } .nav li.dropdown.open .caret, .nav li.dropdown.open.active .caret, .nav li.dropdown.open a:hover .caret, .nav li.dropdown.open a:focus .caret { border-top-color: #ffffff; border-bottom-color: #ffffff; opacity: 1; filter: alpha(opacity=100); } .tabs-stacked .open > a:hover, .tabs-stacked .open > a:focus { border-color: #999999; } .tabbable { *zoom: 1; } .tabbable:before, .tabbable:after { display: table; content: ""; line-height: 0; } .tabbable:after { clear: both; } .tab-content { overflow: auto; } .tabs-below > .nav-tabs, .tabs-right > .nav-tabs, .tabs-left > .nav-tabs { border-bottom: 0; } .tab-content > .tab-pane, .pill-content > .pill-pane { display: none; } .tab-content > .active, .pill-content > .active { display: block; } .tabs-below > .nav-tabs { border-top: 1px solid #ddd; } .tabs-below > .nav-tabs > li { margin-top: -1px; margin-bottom: 0; } .tabs-below > .nav-tabs > li > a { -webkit-border-radius: 0 0 4px 4px; -moz-border-radius: 0 0 4px 4px; border-radius: 0 0 4px 4px; } .tabs-below > .nav-tabs > li > a:hover, .tabs-below > .nav-tabs > li > a:focus { border-bottom-color: transparent; border-top-color: #ddd; } .tabs-below > .nav-tabs > .active > a, .tabs-below > .nav-tabs > .active > a:hover, .tabs-below > .nav-tabs > .active > a:focus { border-color: transparent #ddd #ddd #ddd; } .tabs-left > .nav-tabs > li, .tabs-right > .nav-tabs > li { float: none; } .tabs-left > .nav-tabs > li > a, .tabs-right > .nav-tabs > li > a { min-width: 74px; margin-right: 0; margin-bottom: 3px; } .tabs-left > .nav-tabs { float: left; margin-right: 19px; border-right: 1px solid #ddd; } .tabs-left > .nav-tabs > li > a { margin-right: -1px; -webkit-border-radius: 4px 0 0 4px; -moz-border-radius: 4px 0 0 4px; border-radius: 4px 0 0 4px; } .tabs-left > .nav-tabs > li > a:hover, .tabs-left > .nav-tabs > li > a:focus { border-color: #eeeeee #dddddd #eeeeee #eeeeee; } .tabs-left > .nav-tabs .active > a, .tabs-left > .nav-tabs .active > a:hover, .tabs-left > .nav-tabs .active > a:focus { border-color: #ddd transparent #ddd #ddd; *border-right-color: #ffffff; } .tabs-right > .nav-tabs { float: right; margin-left: 19px; border-left: 1px solid #ddd; } .tabs-right > .nav-tabs > li > a { margin-left: -1px; -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .tabs-right > .nav-tabs > li > a:hover, .tabs-right > .nav-tabs > li > a:focus { border-color: #eeeeee #eeeeee #eeeeee #dddddd; } .tabs-right > .nav-tabs .active > a, .tabs-right > .nav-tabs .active > a:hover, .tabs-right > .nav-tabs .active > a:focus { border-color: #ddd #ddd #ddd transparent; *border-left-color: #ffffff; } .nav > .disabled > a { color: #999999; } .nav > .disabled > a:hover, .nav > .disabled > a:focus { text-decoration: none; background-color: transparent; cursor: default; } .navbar { overflow: visible; margin-bottom: 20px; *position: relative; *z-index: 2; } .navbar-inner { min-height: 40px; padding-left: 20px; padding-right: 20px; background-color: #160902; background-image: -moz-linear-gradient(top, #000000, #371605); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#000000), to(#371605)); background-image: -webkit-linear-gradient(top, #000000, #371605); background-image: -o-linear-gradient(top, #000000, #371605); background-image: linear-gradient(to bottom, #000000, #371605); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff000000', endColorstr='#ff371605', GradientType=0); border: 1px solid #000000; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); *zoom: 1; } .navbar-inner:before, .navbar-inner:after { display: table; content: ""; line-height: 0; } .navbar-inner:after { clear: both; } .navbar .container { width: auto; } .nav-collapse.collapse { height: auto; overflow: visible; } .navbar .brand { float: left; display: block; padding: 10px 20px 10px; margin-left: -20px; font-size: 20px; font-weight: 200; color: #bb844e; text-shadow: 0 1px 0 #000000; } .navbar .brand:hover, .navbar .brand:focus { text-decoration: none; } .navbar-text { margin-bottom: 0; line-height: 40px; color: #bb844e; } .navbar-link { color: #bb844e; } .navbar-link:hover, .navbar-link:focus { color: #c5ad91; } .navbar .divider-vertical { height: 40px; margin: 0 9px; border-left: 1px solid #371605; border-right: 1px solid #000000; } .navbar .btn, .navbar .btn-group { margin-top: 5px; } .navbar .btn-group .btn, .navbar .input-prepend .btn, .navbar .input-append .btn, .navbar .input-prepend .btn-group, .navbar .input-append .btn-group { margin-top: 0; } .navbar-form { margin-bottom: 0; *zoom: 1; } .navbar-form:before, .navbar-form:after { display: table; content: ""; line-height: 0; } .navbar-form:after { clear: both; } .navbar-form input, .navbar-form select, .navbar-form .radio, .navbar-form .checkbox { margin-top: 5px; } .navbar-form input, .navbar-form select, .navbar-form .btn { display: inline-block; margin-bottom: 0; } .navbar-form input[type="image"], .navbar-form input[type="checkbox"], .navbar-form input[type="radio"] { margin-top: 3px; } .navbar-form .input-append, .navbar-form .input-prepend { margin-top: 5px; white-space: nowrap; } .navbar-form .input-append input, .navbar-form .input-prepend input { margin-top: 0; } .navbar-search { position: relative; float: left; margin-top: 5px; margin-bottom: 0; } .navbar-search .search-query { margin-bottom: 0; padding: 4px 14px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 13px; font-weight: normal; line-height: 1; -webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px; } .navbar-static-top { position: static; margin-bottom: 0; } .navbar-static-top .navbar-inner { -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .navbar-fixed-top, .navbar-fixed-bottom { position: fixed; right: 0; left: 0; z-index: 1030; margin-bottom: 0; } .navbar-fixed-top .navbar-inner, .navbar-static-top .navbar-inner { border-width: 0 0 1px; } .navbar-fixed-bottom .navbar-inner { border-width: 1px 0 0; } .navbar-fixed-top .navbar-inner, .navbar-fixed-bottom .navbar-inner { padding-left: 0; padding-right: 0; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 940px; } .navbar-fixed-top { top: 0; } .navbar-fixed-top .navbar-inner, .navbar-static-top .navbar-inner { -webkit-box-shadow: 0 1px 10px rgba(0,0,0,.1); -moz-box-shadow: 0 1px 10px rgba(0,0,0,.1); box-shadow: 0 1px 10px rgba(0,0,0,.1); } .navbar-fixed-bottom { bottom: 0; } .navbar-fixed-bottom .navbar-inner { -webkit-box-shadow: 0 -1px 10px rgba(0,0,0,.1); -moz-box-shadow: 0 -1px 10px rgba(0,0,0,.1); box-shadow: 0 -1px 10px rgba(0,0,0,.1); } .navbar .nav { position: relative; left: 0; display: block; float: left; margin: 0 10px 0 0; } .navbar .nav.pull-right { float: right; margin-right: 0; } .navbar .nav > li { float: left; } .navbar .nav > li > a { float: none; padding: 10px 15px 10px; color: #bb844e; text-decoration: none; text-shadow: 0 1px 0 #000000; } .navbar .nav .dropdown-toggle .caret { margin-top: 8px; } .navbar .nav > li > a:focus, .navbar .nav > li > a:hover { background-color: transparent; color: #c5ad91; text-decoration: none; } .navbar .nav > .active > a, .navbar .nav > .active > a:hover, .navbar .nav > .active > a:focus { color: #371605; text-decoration: none; background-color: #bb844e; -webkit-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); -moz-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); } .navbar .btn-navbar { display: none; float: right; padding: 7px 10px; margin-left: 5px; margin-right: 5px; color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #0d0501; background-image: -moz-linear-gradient(top, #000000, #200d03); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#000000), to(#200d03)); background-image: -webkit-linear-gradient(top, #000000, #200d03); background-image: -o-linear-gradient(top, #000000, #200d03); background-image: linear-gradient(to bottom, #000000, #200d03); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff000000', endColorstr='#ff200d03', GradientType=0); border-color: #200d03 #200d03 #000000; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #200d03; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); } .navbar .btn-navbar:hover, .navbar .btn-navbar:focus, .navbar .btn-navbar:active, .navbar .btn-navbar.active, .navbar .btn-navbar.disabled, .navbar .btn-navbar[disabled] { color: #ffffff; background-color: #200d03; *background-color: #080301; } .navbar .btn-navbar:active, .navbar .btn-navbar.active { background-color: #000000 \9; } .navbar .btn-navbar .icon-bar { display: block; width: 18px; height: 2px; background-color: #f5f5f5; -webkit-border-radius: 1px; -moz-border-radius: 1px; border-radius: 1px; -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); } .btn-navbar .icon-bar + .icon-bar { margin-top: 3px; } .navbar .nav > li > .dropdown-menu:before { content: ''; display: inline-block; border-left: 7px solid transparent; border-right: 7px solid transparent; border-bottom: 7px solid #ccc; border-bottom-color: rgba(0, 0, 0, 0.2); position: absolute; top: -7px; left: 9px; } .navbar .nav > li > .dropdown-menu:after { content: ''; display: inline-block; border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 6px solid #c5ad91; position: absolute; top: -6px; left: 10px; } .navbar-fixed-bottom .nav > li > .dropdown-menu:before { border-top: 7px solid #ccc; border-top-color: rgba(0, 0, 0, 0.2); border-bottom: 0; bottom: -7px; top: auto; } .navbar-fixed-bottom .nav > li > .dropdown-menu:after { border-top: 6px solid #c5ad91; border-bottom: 0; bottom: -6px; top: auto; } .navbar .nav li.dropdown > a:hover .caret, .navbar .nav li.dropdown > a:focus .caret { border-top-color: #c5ad91; border-bottom-color: #c5ad91; } .navbar .nav li.dropdown.open > .dropdown-toggle, .navbar .nav li.dropdown.active > .dropdown-toggle, .navbar .nav li.dropdown.open.active > .dropdown-toggle { background-color: #bb844e; color: #371605; } .navbar .nav li.dropdown > .dropdown-toggle .caret { border-top-color: #bb844e; border-bottom-color: #bb844e; } .navbar .nav li.dropdown.open > .dropdown-toggle .caret, .navbar .nav li.dropdown.active > .dropdown-toggle .caret, .navbar .nav li.dropdown.open.active > .dropdown-toggle .caret { border-top-color: #371605; border-bottom-color: #371605; } .navbar .pull-right > li > .dropdown-menu, .navbar .nav > li > .dropdown-menu.pull-right { left: auto; right: 0; } .navbar .pull-right > li > .dropdown-menu:before, .navbar .nav > li > .dropdown-menu.pull-right:before { left: auto; right: 12px; } .navbar .pull-right > li > .dropdown-menu:after, .navbar .nav > li > .dropdown-menu.pull-right:after { left: auto; right: 13px; } .navbar .pull-right > li > .dropdown-menu .dropdown-menu, .navbar .nav > li > .dropdown-menu.pull-right .dropdown-menu { left: auto; right: 100%; margin-left: 0; margin-right: -1px; -webkit-border-radius: 6px 0 6px 6px; -moz-border-radius: 6px 0 6px 6px; border-radius: 6px 0 6px 6px; } .navbar-inverse .navbar-inner { background-color: #1b1b1b; background-image: -moz-linear-gradient(top, #222222, #111111); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111)); background-image: -webkit-linear-gradient(top, #222222, #111111); background-image: -o-linear-gradient(top, #222222, #111111); background-image: linear-gradient(to bottom, #222222, #111111); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0); border-color: #252525; } .navbar-inverse .brand, .navbar-inverse .nav > li > a { color: #999999; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .navbar-inverse .brand:hover, .navbar-inverse .nav > li > a:hover, .navbar-inverse .brand:focus, .navbar-inverse .nav > li > a:focus { color: #ffffff; } .navbar-inverse .brand { color: #999999; } .navbar-inverse .navbar-text { color: #999999; } .navbar-inverse .nav > li > a:focus, .navbar-inverse .nav > li > a:hover { background-color: transparent; color: #ffffff; } .navbar-inverse .nav .active > a, .navbar-inverse .nav .active > a:hover, .navbar-inverse .nav .active > a:focus { color: #ffffff; background-color: #111111; } .navbar-inverse .navbar-link { color: #999999; } .navbar-inverse .navbar-link:hover, .navbar-inverse .navbar-link:focus { color: #ffffff; } .navbar-inverse .divider-vertical { border-left-color: #111111; border-right-color: #222222; } .navbar-inverse .nav li.dropdown.open > .dropdown-toggle, .navbar-inverse .nav li.dropdown.active > .dropdown-toggle, .navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle { background-color: #111111; color: #ffffff; } .navbar-inverse .nav li.dropdown > a:hover .caret, .navbar-inverse .nav li.dropdown > a:focus .caret { border-top-color: #ffffff; border-bottom-color: #ffffff; } .navbar-inverse .nav li.dropdown > .dropdown-toggle .caret { border-top-color: #999999; border-bottom-color: #999999; } .navbar-inverse .nav li.dropdown.open > .dropdown-toggle .caret, .navbar-inverse .nav li.dropdown.active > .dropdown-toggle .caret, .navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle .caret { border-top-color: #ffffff; border-bottom-color: #ffffff; } .navbar-inverse .navbar-search .search-query { color: #ffffff; background-color: #515151; border-color: #111111; -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); -moz-box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); -webkit-transition: none; -moz-transition: none; -o-transition: none; transition: none; } .navbar-inverse .navbar-search .search-query:-moz-placeholder { color: #cccccc; } .navbar-inverse .navbar-search .search-query:-ms-input-placeholder { color: #cccccc; } .navbar-inverse .navbar-search .search-query::-webkit-input-placeholder { color: #cccccc; } .navbar-inverse .navbar-search .search-query:focus, .navbar-inverse .navbar-search .search-query.focused { padding: 5px 15px; color: #333333; text-shadow: 0 1px 0 #ffffff; background-color: #ffffff; border: 0; -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); outline: 0; } .navbar-inverse .btn-navbar { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #0e0e0e; background-image: -moz-linear-gradient(top, #151515, #040404); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404)); background-image: -webkit-linear-gradient(top, #151515, #040404); background-image: -o-linear-gradient(top, #151515, #040404); background-image: linear-gradient(to bottom, #151515, #040404); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0); border-color: #040404 #040404 #000000; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #040404; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .navbar-inverse .btn-navbar:hover, .navbar-inverse .btn-navbar:focus, .navbar-inverse .btn-navbar:active, .navbar-inverse .btn-navbar.active, .navbar-inverse .btn-navbar.disabled, .navbar-inverse .btn-navbar[disabled] { color: #ffffff; background-color: #040404; *background-color: #000000; } .navbar-inverse .btn-navbar:active, .navbar-inverse .btn-navbar.active { background-color: #000000 \9; } .breadcrumb { padding: 8px 15px; margin: 0 0 20px; list-style: none; background-color: #f5f5f5; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .breadcrumb > li { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; text-shadow: 0 1px 0 #ffffff; } .breadcrumb > li > .divider { padding: 0 5px; color: #ccc; } .breadcrumb > .active { color: #999999; } .pagination { margin: 20px 0; } .pagination ul { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; margin-left: 0; margin-bottom: 0; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .pagination ul > li { display: inline; } .pagination ul > li > a, .pagination ul > li > span { float: left; padding: 4px 12px; line-height: 20px; text-decoration: none; background-color: #ffffff; border: 1px solid #dddddd; border-left-width: 0; } .pagination ul > li > a:hover, .pagination ul > li > a:focus, .pagination ul > .active > a, .pagination ul > .active > span { background-color: #f5f5f5; } .pagination ul > .active > a, .pagination ul > .active > span { color: #999999; cursor: default; } .pagination ul > .disabled > span, .pagination ul > .disabled > a, .pagination ul > .disabled > a:hover, .pagination ul > .disabled > a:focus { color: #999999; background-color: transparent; cursor: default; } .pagination ul > li:first-child > a, .pagination ul > li:first-child > span { border-left-width: 1px; -webkit-border-top-left-radius: 4px; -moz-border-radius-topleft: 4px; border-top-left-radius: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomleft: 4px; border-bottom-left-radius: 4px; } .pagination ul > li:last-child > a, .pagination ul > li:last-child > span { -webkit-border-top-right-radius: 4px; -moz-border-radius-topright: 4px; border-top-right-radius: 4px; -webkit-border-bottom-right-radius: 4px; -moz-border-radius-bottomright: 4px; border-bottom-right-radius: 4px; } .pagination-centered { text-align: center; } .pagination-right { text-align: right; } .pagination-large ul > li > a, .pagination-large ul > li > span { padding: 11px 19px; font-size: 17.5px; } .pagination-large ul > li:first-child > a, .pagination-large ul > li:first-child > span { -webkit-border-top-left-radius: 6px; -moz-border-radius-topleft: 6px; border-top-left-radius: 6px; -webkit-border-bottom-left-radius: 6px; -moz-border-radius-bottomleft: 6px; border-bottom-left-radius: 6px; } .pagination-large ul > li:last-child > a, .pagination-large ul > li:last-child > span { -webkit-border-top-right-radius: 6px; -moz-border-radius-topright: 6px; border-top-right-radius: 6px; -webkit-border-bottom-right-radius: 6px; -moz-border-radius-bottomright: 6px; border-bottom-right-radius: 6px; } .pagination-mini ul > li:first-child > a, .pagination-small ul > li:first-child > a, .pagination-mini ul > li:first-child > span, .pagination-small ul > li:first-child > span { -webkit-border-top-left-radius: 3px; -moz-border-radius-topleft: 3px; border-top-left-radius: 3px; -webkit-border-bottom-left-radius: 3px; -moz-border-radius-bottomleft: 3px; border-bottom-left-radius: 3px; } .pagination-mini ul > li:last-child > a, .pagination-small ul > li:last-child > a, .pagination-mini ul > li:last-child > span, .pagination-small ul > li:last-child > span { -webkit-border-top-right-radius: 3px; -moz-border-radius-topright: 3px; border-top-right-radius: 3px; -webkit-border-bottom-right-radius: 3px; -moz-border-radius-bottomright: 3px; border-bottom-right-radius: 3px; } .pagination-small ul > li > a, .pagination-small ul > li > span { padding: 2px 10px; font-size: 11.9px; } .pagination-mini ul > li > a, .pagination-mini ul > li > span { padding: 0 6px; font-size: 10.5px; } .pager { margin: 20px 0; list-style: none; text-align: center; *zoom: 1; } .pager:before, .pager:after { display: table; content: ""; line-height: 0; } .pager:after { clear: both; } .pager li { display: inline; } .pager li > a, .pager li > span { display: inline-block; padding: 5px 14px; background-color: #fff; border: 1px solid #ddd; -webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px; } .pager li > a:hover, .pager li > a:focus { text-decoration: none; background-color: #f5f5f5; } .pager .next > a, .pager .next > span { float: right; } .pager .previous > a, .pager .previous > span { float: left; } .pager .disabled > a, .pager .disabled > a:hover, .pager .disabled > a:focus, .pager .disabled > span { color: #999999; background-color: #fff; cursor: default; } .thumbnails { margin-left: -20px; list-style: none; *zoom: 1; } .thumbnails:before, .thumbnails:after { display: table; content: ""; line-height: 0; } .thumbnails:after { clear: both; } .row-fluid .thumbnails { margin-left: 0; } .thumbnails > li { float: left; margin-bottom: 20px; margin-left: 20px; } .thumbnail { display: block; padding: 4px; line-height: 20px; border: 1px solid #ddd; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } a.thumbnail:hover, a.thumbnail:focus { border-color: #715458; -webkit-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); -moz-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); } .thumbnail > img { display: block; max-width: 100%; margin-left: auto; margin-right: auto; } .thumbnail .caption { padding: 9px; color: #555555; } .alert { padding: 8px 35px 8px 14px; margin-bottom: 20px; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); background-color: #fcf8e3; border: 1px solid #fbeed5; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .alert, .alert h4 { color: #c09853; } .alert h4 { margin: 0; } .alert .close { position: relative; top: -2px; right: -21px; line-height: 20px; } .alert-success { background-color: #dff0d8; border-color: #d6e9c6; color: #468847; } .alert-success h4 { color: #468847; } .alert-danger, .alert-error { background-color: #f2dede; border-color: #eed3d7; color: #b94a48; } .alert-danger h4, .alert-error h4 { color: #b94a48; } .alert-info { background-color: #d9edf7; border-color: #bce8f1; color: #3a87ad; } .alert-info h4 { color: #3a87ad; } .alert-block { padding-top: 14px; padding-bottom: 14px; } .alert-block > p, .alert-block > ul { margin-bottom: 0; } .alert-block p + p { margin-top: 5px; } @-webkit-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @-moz-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @-ms-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @-o-keyframes progress-bar-stripes { from { background-position: 0 0; } to { background-position: 40px 0; } } @keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } .progress { overflow: hidden; height: 20px; margin-bottom: 20px; background-color: #f7f7f7; background-image: -moz-linear-gradient(top, #f5f5f5, #f9f9f9); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9)); background-image: -webkit-linear-gradient(top, #f5f5f5, #f9f9f9); background-image: -o-linear-gradient(top, #f5f5f5, #f9f9f9); background-image: linear-gradient(to bottom, #f5f5f5, #f9f9f9); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0); -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .progress .bar { width: 0%; height: 100%; color: #ffffff; float: left; font-size: 12px; text-align: center; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #0e90d2; background-image: -moz-linear-gradient(top, #149bdf, #0480be); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be)); background-image: -webkit-linear-gradient(top, #149bdf, #0480be); background-image: -o-linear-gradient(top, #149bdf, #0480be); background-image: linear-gradient(to bottom, #149bdf, #0480be); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0); -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; -webkit-transition: width 0.6s ease; -moz-transition: width 0.6s ease; -o-transition: width 0.6s ease; transition: width 0.6s ease; } .progress .bar + .bar { -webkit-box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); -moz-box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); } .progress-striped .bar { background-color: #149bdf; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -webkit-background-size: 40px 40px; -moz-background-size: 40px 40px; -o-background-size: 40px 40px; background-size: 40px 40px; } .progress.active .bar { -webkit-animation: progress-bar-stripes 2s linear infinite; -moz-animation: progress-bar-stripes 2s linear infinite; -ms-animation: progress-bar-stripes 2s linear infinite; -o-animation: progress-bar-stripes 2s linear infinite; animation: progress-bar-stripes 2s linear infinite; } .progress-danger .bar, .progress .bar-danger { background-color: #dd514c; background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35)); background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35); background-image: -o-linear-gradient(top, #ee5f5b, #c43c35); background-image: linear-gradient(to bottom, #ee5f5b, #c43c35); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0); } .progress-danger.progress-striped .bar, .progress-striped .bar-danger { background-color: #ee5f5b; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-success .bar, .progress .bar-success { background-color: #5eb95e; background-image: -moz-linear-gradient(top, #62c462, #57a957); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957)); background-image: -webkit-linear-gradient(top, #62c462, #57a957); background-image: -o-linear-gradient(top, #62c462, #57a957); background-image: linear-gradient(to bottom, #62c462, #57a957); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0); } .progress-success.progress-striped .bar, .progress-striped .bar-success { background-color: #62c462; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-info .bar, .progress .bar-info { background-color: #4bb1cf; background-image: -moz-linear-gradient(top, #5bc0de, #339bb9); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9)); background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9); background-image: -o-linear-gradient(top, #5bc0de, #339bb9); background-image: linear-gradient(to bottom, #5bc0de, #339bb9); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0); } .progress-info.progress-striped .bar, .progress-striped .bar-info { background-color: #5bc0de; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-warning .bar, .progress .bar-warning { background-color: #fdb033; background-image: -moz-linear-gradient(top, #fdbc52, #fc9f06); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fdbc52), to(#fc9f06)); background-image: -webkit-linear-gradient(top, #fdbc52, #fc9f06); background-image: -o-linear-gradient(top, #fdbc52, #fc9f06); background-image: linear-gradient(to bottom, #fdbc52, #fc9f06); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffdbc52', endColorstr='#fffc9f06', GradientType=0); } .progress-warning.progress-striped .bar, .progress-striped .bar-warning { background-color: #fdbc52; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .hero-unit { padding: 60px; margin-bottom: 30px; font-size: 18px; font-weight: 200; line-height: 30px; color: inherit; background-color: #bb844e; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .hero-unit h1 { margin-bottom: 0; font-size: 60px; line-height: 1; color: inherit; letter-spacing: -1px; } .hero-unit li { line-height: 30px; } .media, .media-body { overflow: hidden; *overflow: visible; zoom: 1; } .media, .media .media { margin-top: 15px; } .media:first-child { margin-top: 0; } .media-object { display: block; } .media-heading { margin: 0 0 5px; } .media > .pull-left { margin-right: 10px; } .media > .pull-right { margin-left: 10px; } .media-list { margin-left: 0; list-style: none; } .tooltip { position: absolute; z-index: 1030; display: block; visibility: visible; font-size: 11px; line-height: 1.4; opacity: 0; filter: alpha(opacity=0); } .tooltip.in { opacity: 0.8; filter: alpha(opacity=80); } .tooltip.top { margin-top: -3px; padding: 5px 0; } .tooltip.right { margin-left: 3px; padding: 0 5px; } .tooltip.bottom { margin-top: 3px; padding: 5px 0; } .tooltip.left { margin-left: -3px; padding: 0 5px; } .tooltip-inner { max-width: 200px; padding: 8px; color: #ffffff; text-align: center; text-decoration: none; background-color: #000000; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .tooltip-arrow { position: absolute; width: 0; height: 0; border-color: transparent; border-style: solid; } .tooltip.top .tooltip-arrow { bottom: 0; left: 50%; margin-left: -5px; border-width: 5px 5px 0; border-top-color: #000000; } .tooltip.right .tooltip-arrow { top: 50%; left: 0; margin-top: -5px; border-width: 5px 5px 5px 0; border-right-color: #000000; } .tooltip.left .tooltip-arrow { top: 50%; right: 0; margin-top: -5px; border-width: 5px 0 5px 5px; border-left-color: #000000; } .tooltip.bottom .tooltip-arrow { top: 0; left: 50%; margin-left: -5px; border-width: 0 5px 5px; border-bottom-color: #000000; } .popover { position: absolute; top: 0; left: 0; z-index: 1010; display: none; max-width: 276px; padding: 1px; text-align: left; background-color: #ffffff; -webkit-background-clip: padding-box; -moz-background-clip: padding; background-clip: padding-box; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.2); -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); white-space: normal; } .popover.top { margin-top: -10px; } .popover.right { margin-left: 10px; } .popover.bottom { margin-top: 10px; } .popover.left { margin-left: -10px; } .popover-title { margin: 0; padding: 8px 14px; font-size: 14px; font-weight: normal; line-height: 18px; background-color: #f7f7f7; border-bottom: 1px solid #ebebeb; -webkit-border-radius: 5px 5px 0 0; -moz-border-radius: 5px 5px 0 0; border-radius: 5px 5px 0 0; } .popover-title:empty { display: none; } .popover-content { padding: 9px 14px; } .popover .arrow, .popover .arrow:after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover .arrow { border-width: 11px; } .popover .arrow:after { border-width: 10px; content: ""; } .popover.top .arrow { left: 50%; margin-left: -11px; border-bottom-width: 0; border-top-color: #999; border-top-color: rgba(0, 0, 0, 0.25); bottom: -11px; } .popover.top .arrow:after { bottom: 1px; margin-left: -10px; border-bottom-width: 0; border-top-color: #ffffff; } .popover.right .arrow { top: 50%; left: -11px; margin-top: -11px; border-left-width: 0; border-right-color: #999; border-right-color: rgba(0, 0, 0, 0.25); } .popover.right .arrow:after { left: 1px; bottom: -10px; border-left-width: 0; border-right-color: #ffffff; } .popover.bottom .arrow { left: 50%; margin-left: -11px; border-top-width: 0; border-bottom-color: #999; border-bottom-color: rgba(0, 0, 0, 0.25); top: -11px; } .popover.bottom .arrow:after { top: 1px; margin-left: -10px; border-top-width: 0; border-bottom-color: #ffffff; } .popover.left .arrow { top: 50%; right: -11px; margin-top: -11px; border-right-width: 0; border-left-color: #999; border-left-color: rgba(0, 0, 0, 0.25); } .popover.left .arrow:after { right: 1px; border-right-width: 0; border-left-color: #ffffff; bottom: -10px; } .modal-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; background-color: #000000; } .modal-backdrop.fade { opacity: 0; } .modal-backdrop, .modal-backdrop.fade.in { opacity: 0.8; filter: alpha(opacity=80); } .modal { position: fixed; top: 10%; left: 50%; z-index: 1050; width: 560px; margin-left: -280px; background-color: #ffffff; border: 1px solid #999; border: 1px solid rgba(0, 0, 0, 0.3); *border: 1px solid #999; /* IE6-7 */ -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); -webkit-background-clip: padding-box; -moz-background-clip: padding-box; background-clip: padding-box; outline: none; } .modal.fade { -webkit-transition: opacity .3s linear, top .3s ease-out; -moz-transition: opacity .3s linear, top .3s ease-out; -o-transition: opacity .3s linear, top .3s ease-out; transition: opacity .3s linear, top .3s ease-out; top: -25%; } .modal.fade.in { top: 10%; } .modal-header { padding: 9px 15px; border-bottom: 1px solid #eee; } .modal-header .close { margin-top: 2px; } .modal-header h3 { margin: 0; line-height: 30px; } .modal-body { position: relative; overflow-y: auto; max-height: 400px; padding: 15px; } .modal-form { margin-bottom: 0; } .modal-footer { padding: 14px 15px 15px; margin-bottom: 0; text-align: right; background-color: #f5f5f5; border-top: 1px solid #ddd; -webkit-border-radius: 0 0 6px 6px; -moz-border-radius: 0 0 6px 6px; border-radius: 0 0 6px 6px; -webkit-box-shadow: inset 0 1px 0 #ffffff; -moz-box-shadow: inset 0 1px 0 #ffffff; box-shadow: inset 0 1px 0 #ffffff; *zoom: 1; } .modal-footer:before, .modal-footer:after { display: table; content: ""; line-height: 0; } .modal-footer:after { clear: both; } .modal-footer .btn + .btn { margin-left: 5px; margin-bottom: 0; } .modal-footer .btn-group .btn + .btn { margin-left: -1px; } .modal-footer .btn-block + .btn-block { margin-left: 0; } .dropup, .dropdown { position: relative; } .dropdown-toggle { *margin-bottom: -3px; } .dropdown-toggle:active, .open .dropdown-toggle { outline: 0; } .caret { display: inline-block; width: 0; height: 0; vertical-align: top; border-top: 4px solid #000000; border-right: 4px solid transparent; border-left: 4px solid transparent; content: ""; } .dropdown .caret { margin-top: 8px; margin-left: 2px; } .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; float: left; min-width: 160px; padding: 5px 0; margin: 2px 0 0; list-style: none; background-color: #c5ad91; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.2); *border-right-width: 2px; *border-bottom-width: 2px; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -webkit-background-clip: padding-box; -moz-background-clip: padding; background-clip: padding-box; } .dropdown-menu.pull-right { right: 0; left: auto; } .dropdown-menu .divider { *width: 100%; height: 1px; margin: 9px 1px; *margin: -5px 0 5px; overflow: hidden; background-color: #e5e5e5; border-bottom: 1px solid #ffffff; } .dropdown-menu > li > a { display: block; padding: 3px 20px; clear: both; font-weight: normal; line-height: 20px; color: #715458; white-space: nowrap; } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus, .dropdown-submenu:hover > a, .dropdown-submenu:focus > a { text-decoration: none; color: #c5ad91; background-color: #6b5053; background-image: -moz-linear-gradient(top, #715458, #62494d); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#715458), to(#62494d)); background-image: -webkit-linear-gradient(top, #715458, #62494d); background-image: -o-linear-gradient(top, #715458, #62494d); background-image: linear-gradient(to bottom, #715458, #62494d); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff715458', endColorstr='#ff62494d', GradientType=0); } .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { color: #ffffff; text-decoration: none; outline: 0; background-color: #6b5053; background-image: -moz-linear-gradient(top, #715458, #62494d); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#715458), to(#62494d)); background-image: -webkit-linear-gradient(top, #715458, #62494d); background-image: -o-linear-gradient(top, #715458, #62494d); background-image: linear-gradient(to bottom, #715458, #62494d); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff715458', endColorstr='#ff62494d', GradientType=0); } .dropdown-menu > .disabled > a, .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { color: #999999; } .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { text-decoration: none; background-color: transparent; background-image: none; filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); cursor: default; } .open { *z-index: 1000; } .open > .dropdown-menu { display: block; } .dropdown-backdrop { position: fixed; left: 0; right: 0; bottom: 0; top: 0; z-index: 990; } .pull-right > .dropdown-menu { right: 0; left: auto; } .dropup .caret, .navbar-fixed-bottom .dropdown .caret { border-top: 0; border-bottom: 4px solid #000000; content: ""; } .dropup .dropdown-menu, .navbar-fixed-bottom .dropdown .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 1px; } .dropdown-submenu { position: relative; } .dropdown-submenu > .dropdown-menu { top: 0; left: 100%; margin-top: -6px; margin-left: -1px; -webkit-border-radius: 0 6px 6px 6px; -moz-border-radius: 0 6px 6px 6px; border-radius: 0 6px 6px 6px; } .dropdown-submenu:hover > .dropdown-menu { display: block; } .dropup .dropdown-submenu > .dropdown-menu { top: auto; bottom: 0; margin-top: 0; margin-bottom: -2px; -webkit-border-radius: 5px 5px 5px 0; -moz-border-radius: 5px 5px 5px 0; border-radius: 5px 5px 5px 0; } .dropdown-submenu > a:after { display: block; content: " "; float: right; width: 0; height: 0; border-color: transparent; border-style: solid; border-width: 5px 0 5px 5px; border-left-color: #9d7b53; margin-top: 5px; margin-right: -10px; } .dropdown-submenu:hover > a:after { border-left-color: #c5ad91; } .dropdown-submenu.pull-left { float: none; } .dropdown-submenu.pull-left > .dropdown-menu { left: -100%; margin-left: 10px; -webkit-border-radius: 6px 0 6px 6px; -moz-border-radius: 6px 0 6px 6px; border-radius: 6px 0 6px 6px; } .dropdown .dropdown-menu .nav-header { padding-left: 20px; padding-right: 20px; } .typeahead { z-index: 1051; margin-top: 2px; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .accordion { margin-bottom: 20px; } .accordion-group { margin-bottom: 2px; border: 1px solid #e5e5e5; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .accordion-heading { border-bottom: 0; } .accordion-heading .accordion-toggle { display: block; padding: 8px 15px; } .accordion-toggle { cursor: pointer; } .accordion-inner { padding: 9px 15px; border-top: 1px solid #e5e5e5; } .carousel { position: relative; margin-bottom: 20px; line-height: 1; } .carousel-inner { overflow: hidden; width: 100%; position: relative; } .carousel-inner > .item { display: none; position: relative; -webkit-transition: 0.6s ease-in-out left; -moz-transition: 0.6s ease-in-out left; -o-transition: 0.6s ease-in-out left; transition: 0.6s ease-in-out left; } .carousel-inner > .item > img, .carousel-inner > .item > a > img { display: block; line-height: 1; } .carousel-inner > .active, .carousel-inner > .next, .carousel-inner > .prev { display: block; } .carousel-inner > .active { left: 0; } .carousel-inner > .next, .carousel-inner > .prev { position: absolute; top: 0; width: 100%; } .carousel-inner > .next { left: 100%; } .carousel-inner > .prev { left: -100%; } .carousel-inner > .next.left, .carousel-inner > .prev.right { left: 0; } .carousel-inner > .active.left { left: -100%; } .carousel-inner > .active.right { left: 100%; } .carousel-control { position: absolute; top: 40%; left: 15px; width: 40px; height: 40px; margin-top: -20px; font-size: 60px; font-weight: 100; line-height: 30px; color: #ffffff; text-align: center; background: #222222; border: 3px solid #ffffff; -webkit-border-radius: 23px; -moz-border-radius: 23px; border-radius: 23px; opacity: 0.5; filter: alpha(opacity=50); } .carousel-control.right { left: auto; right: 15px; } .carousel-control:hover, .carousel-control:focus { color: #ffffff; text-decoration: none; opacity: 0.9; filter: alpha(opacity=90); } .carousel-indicators { position: absolute; top: 15px; right: 15px; z-index: 5; margin: 0; list-style: none; } .carousel-indicators li { display: block; float: left; width: 10px; height: 10px; margin-left: 5px; text-indent: -999px; background-color: #ccc; background-color: rgba(255, 255, 255, 0.25); border-radius: 5px; } .carousel-indicators .active { background-color: #fff; } .carousel-caption { position: absolute; left: 0; right: 0; bottom: 0; padding: 15px; background: #333333; background: rgba(0, 0, 0, 0.75); } .carousel-caption h4, .carousel-caption p { color: #ffffff; line-height: 20px; } .carousel-caption h4 { margin: 0 0 5px; } .carousel-caption p { margin-bottom: 0; } .well { min-height: 20px; padding: 19px; margin-bottom: 20px; background-color: #f5f5f5; border: 1px solid #e3e3e3; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); } .well blockquote { border-color: #ddd; border-color: rgba(0, 0, 0, 0.15); } .well-large { padding: 24px; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .well-small { padding: 9px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .close { float: right; font-size: 20px; font-weight: bold; line-height: 20px; color: #000000; text-shadow: 0 1px 0 #ffffff; opacity: 0.2; filter: alpha(opacity=20); } .close:hover, .close:focus { color: #000000; text-decoration: none; cursor: pointer; opacity: 0.4; filter: alpha(opacity=40); } button.close { padding: 0; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; } .pull-right { float: right; } .pull-left { float: left; } .hide { display: none; } .show { display: block; } .invisible { visibility: hidden; } .affix { position: fixed; } .fade { opacity: 0; -webkit-transition: opacity 0.15s linear; -moz-transition: opacity 0.15s linear; -o-transition: opacity 0.15s linear; transition: opacity 0.15s linear; } .fade.in { opacity: 1; } .collapse { position: relative; height: 0; overflow: hidden; -webkit-transition: height 0.35s ease; -moz-transition: height 0.35s ease; -o-transition: height 0.35s ease; transition: height 0.35s ease; } .collapse.in { height: auto; } @-ms-viewport { width: device-width; } .hidden { display: none; visibility: hidden; } .visible-phone { display: none !important; } .visible-tablet { display: none !important; } .hidden-desktop { display: none !important; } .visible-desktop { display: inherit !important; } @media (min-width: 768px) and (max-width: 979px) { .hidden-desktop { display: inherit !important; } .visible-desktop { display: none !important ; } .visible-tablet { display: inherit !important; } .hidden-tablet { display: none !important; } } @media (max-width: 767px) { .hidden-desktop { display: inherit !important; } .visible-desktop { display: none !important; } .visible-phone { display: inherit !important; } .hidden-phone { display: none !important; } } .visible-print { display: none !important; } @media print { .visible-print { display: inherit !important; } .hidden-print { display: none !important; } } @media (max-width: 767px) { body { padding-left: 20px; padding-right: 20px; } .navbar-fixed-top, .navbar-fixed-bottom, .navbar-static-top { margin-left: -20px; margin-right: -20px; } .container-fluid { padding: 0; } .dl-horizontal dt { float: none; clear: none; width: auto; text-align: left; } .dl-horizontal dd { margin-left: 0; } .container { width: auto; } .row-fluid { width: 100%; } .row, .thumbnails { margin-left: 0; } .thumbnails > li { float: none; margin-left: 0; } [class*="span"], .uneditable-input[class*="span"], .row-fluid [class*="span"] { float: none; display: block; width: 100%; margin-left: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .span12, .row-fluid .span12 { width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .row-fluid [class*="offset"]:first-child { margin-left: 0; } .input-large, .input-xlarge, .input-xxlarge, input[class*="span"], select[class*="span"], textarea[class*="span"], .uneditable-input { display: block; width: 100%; min-height: 30px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .input-prepend input, .input-append input, .input-prepend input[class*="span"], .input-append input[class*="span"] { display: inline-block; width: auto; } .controls-row [class*="span"] + [class*="span"] { margin-left: 0; } .modal { position: fixed; top: 20px; left: 20px; right: 20px; width: auto; margin: 0; } .modal.fade { top: -100px; } .modal.fade.in { top: 20px; } } @media (max-width: 480px) { .nav-collapse { -webkit-transform: translate3d(0, 0, 0); } .page-header h1 small { display: block; line-height: 20px; } input[type="checkbox"], input[type="radio"] { border: 1px solid #ccc; } .form-horizontal .control-label { float: none; width: auto; padding-top: 0; text-align: left; } .form-horizontal .controls { margin-left: 0; } .form-horizontal .control-list { padding-top: 0; } .form-horizontal .form-actions { padding-left: 10px; padding-right: 10px; } .media .pull-left, .media .pull-right { float: none; display: block; margin-bottom: 10px; } .media-object { margin-right: 0; margin-left: 0; } .modal { top: 10px; left: 10px; right: 10px; } .modal-header .close { padding: 10px; margin: -10px; } .carousel-caption { position: static; } } @media (min-width: 768px) and (max-width: 979px) { .row { margin-left: -20px; *zoom: 1; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 20px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 724px; } .span12 { width: 724px; } .span11 { width: 662px; } .span10 { width: 600px; } .span9 { width: 538px; } .span8 { width: 476px; } .span7 { width: 414px; } .span6 { width: 352px; } .span5 { width: 290px; } .span4 { width: 228px; } .span3 { width: 166px; } .span2 { width: 104px; } .span1 { width: 42px; } .offset12 { margin-left: 764px; } .offset11 { margin-left: 702px; } .offset10 { margin-left: 640px; } .offset9 { margin-left: 578px; } .offset8 { margin-left: 516px; } .offset7 { margin-left: 454px; } .offset6 { margin-left: 392px; } .offset5 { margin-left: 330px; } .offset4 { margin-left: 268px; } .offset3 { margin-left: 206px; } .offset2 { margin-left: 144px; } .offset1 { margin-left: 82px; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; width: 100%; min-height: 30px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: left; margin-left: 2.7624309392265194%; *margin-left: 2.709239449864817%; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.7624309392265194%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.43646408839778%; *width: 91.38327259903608%; } .row-fluid .span10 { width: 82.87292817679558%; *width: 82.81973668743387%; } .row-fluid .span9 { width: 74.30939226519337%; *width: 74.25620077583166%; } .row-fluid .span8 { width: 65.74585635359117%; *width: 65.69266486422946%; } .row-fluid .span7 { width: 57.18232044198895%; *width: 57.12912895262725%; } .row-fluid .span6 { width: 48.61878453038674%; *width: 48.56559304102504%; } .row-fluid .span5 { width: 40.05524861878453%; *width: 40.00205712942283%; } .row-fluid .span4 { width: 31.491712707182323%; *width: 31.43852121782062%; } .row-fluid .span3 { width: 22.92817679558011%; *width: 22.87498530621841%; } .row-fluid .span2 { width: 14.3646408839779%; *width: 14.311449394616199%; } .row-fluid .span1 { width: 5.801104972375691%; *width: 5.747913483013988%; } .row-fluid .offset12 { margin-left: 105.52486187845304%; *margin-left: 105.41847889972962%; } .row-fluid .offset12:first-child { margin-left: 102.76243093922652%; *margin-left: 102.6560479605031%; } .row-fluid .offset11 { margin-left: 96.96132596685082%; *margin-left: 96.8549429881274%; } .row-fluid .offset11:first-child { margin-left: 94.1988950276243%; *margin-left: 94.09251204890089%; } .row-fluid .offset10 { margin-left: 88.39779005524862%; *margin-left: 88.2914070765252%; } .row-fluid .offset10:first-child { margin-left: 85.6353591160221%; *margin-left: 85.52897613729868%; } .row-fluid .offset9 { margin-left: 79.8342541436464%; *margin-left: 79.72787116492299%; } .row-fluid .offset9:first-child { margin-left: 77.07182320441989%; *margin-left: 76.96544022569647%; } .row-fluid .offset8 { margin-left: 71.2707182320442%; *margin-left: 71.16433525332079%; } .row-fluid .offset8:first-child { margin-left: 68.50828729281768%; *margin-left: 68.40190431409427%; } .row-fluid .offset7 { margin-left: 62.70718232044199%; *margin-left: 62.600799341718584%; } .row-fluid .offset7:first-child { margin-left: 59.94475138121547%; *margin-left: 59.838368402492065%; } .row-fluid .offset6 { margin-left: 54.14364640883978%; *margin-left: 54.037263430116376%; } .row-fluid .offset6:first-child { margin-left: 51.38121546961326%; *margin-left: 51.27483249088986%; } .row-fluid .offset5 { margin-left: 45.58011049723757%; *margin-left: 45.47372751851417%; } .row-fluid .offset5:first-child { margin-left: 42.81767955801105%; *margin-left: 42.71129657928765%; } .row-fluid .offset4 { margin-left: 37.01657458563536%; *margin-left: 36.91019160691196%; } .row-fluid .offset4:first-child { margin-left: 34.25414364640884%; *margin-left: 34.14776066768544%; } .row-fluid .offset3 { margin-left: 28.45303867403315%; *margin-left: 28.346655695309746%; } .row-fluid .offset3:first-child { margin-left: 25.69060773480663%; *margin-left: 25.584224756083227%; } .row-fluid .offset2 { margin-left: 19.88950276243094%; *margin-left: 19.783119783707537%; } .row-fluid .offset2:first-child { margin-left: 17.12707182320442%; *margin-left: 17.02068884448102%; } .row-fluid .offset1 { margin-left: 11.32596685082873%; *margin-left: 11.219583872105325%; } .row-fluid .offset1:first-child { margin-left: 8.56353591160221%; *margin-left: 8.457152932878806%; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 20px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 710px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 648px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 586px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 524px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 462px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 400px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 338px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 276px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 214px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 152px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 90px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 28px; } } @media (min-width: 1200px) { .row { margin-left: -30px; *zoom: 1; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 30px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 1170px; } .span12 { width: 1170px; } .span11 { width: 1070px; } .span10 { width: 970px; } .span9 { width: 870px; } .span8 { width: 770px; } .span7 { width: 670px; } .span6 { width: 570px; } .span5 { width: 470px; } .span4 { width: 370px; } .span3 { width: 270px; } .span2 { width: 170px; } .span1 { width: 70px; } .offset12 { margin-left: 1230px; } .offset11 { margin-left: 1130px; } .offset10 { margin-left: 1030px; } .offset9 { margin-left: 930px; } .offset8 { margin-left: 830px; } .offset7 { margin-left: 730px; } .offset6 { margin-left: 630px; } .offset5 { margin-left: 530px; } .offset4 { margin-left: 430px; } .offset3 { margin-left: 330px; } .offset2 { margin-left: 230px; } .offset1 { margin-left: 130px; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; width: 100%; min-height: 30px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: left; margin-left: 2.564102564102564%; *margin-left: 2.5109110747408616%; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.564102564102564%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.45299145299145%; *width: 91.39979996362975%; } .row-fluid .span10 { width: 82.90598290598291%; *width: 82.8527914166212%; } .row-fluid .span9 { width: 74.35897435897436%; *width: 74.30578286961266%; } .row-fluid .span8 { width: 65.81196581196582%; *width: 65.75877432260411%; } .row-fluid .span7 { width: 57.26495726495726%; *width: 57.21176577559556%; } .row-fluid .span6 { width: 48.717948717948715%; *width: 48.664757228587014%; } .row-fluid .span5 { width: 40.17094017094017%; *width: 40.11774868157847%; } .row-fluid .span4 { width: 31.623931623931625%; *width: 31.570740134569924%; } .row-fluid .span3 { width: 23.076923076923077%; *width: 23.023731587561375%; } .row-fluid .span2 { width: 14.52991452991453%; *width: 14.476723040552828%; } .row-fluid .span1 { width: 5.982905982905983%; *width: 5.929714493544281%; } .row-fluid .offset12 { margin-left: 105.12820512820512%; *margin-left: 105.02182214948171%; } .row-fluid .offset12:first-child { margin-left: 102.56410256410257%; *margin-left: 102.45771958537915%; } .row-fluid .offset11 { margin-left: 96.58119658119658%; *margin-left: 96.47481360247316%; } .row-fluid .offset11:first-child { margin-left: 94.01709401709402%; *margin-left: 93.91071103837061%; } .row-fluid .offset10 { margin-left: 88.03418803418803%; *margin-left: 87.92780505546462%; } .row-fluid .offset10:first-child { margin-left: 85.47008547008548%; *margin-left: 85.36370249136206%; } .row-fluid .offset9 { margin-left: 79.48717948717949%; *margin-left: 79.38079650845607%; } .row-fluid .offset9:first-child { margin-left: 76.92307692307693%; *margin-left: 76.81669394435352%; } .row-fluid .offset8 { margin-left: 70.94017094017094%; *margin-left: 70.83378796144753%; } .row-fluid .offset8:first-child { margin-left: 68.37606837606839%; *margin-left: 68.26968539734497%; } .row-fluid .offset7 { margin-left: 62.393162393162385%; *margin-left: 62.28677941443899%; } .row-fluid .offset7:first-child { margin-left: 59.82905982905982%; *margin-left: 59.72267685033642%; } .row-fluid .offset6 { margin-left: 53.84615384615384%; *margin-left: 53.739770867430444%; } .row-fluid .offset6:first-child { margin-left: 51.28205128205128%; *margin-left: 51.175668303327875%; } .row-fluid .offset5 { margin-left: 45.299145299145295%; *margin-left: 45.1927623204219%; } .row-fluid .offset5:first-child { margin-left: 42.73504273504273%; *margin-left: 42.62865975631933%; } .row-fluid .offset4 { margin-left: 36.75213675213675%; *margin-left: 36.645753773413354%; } .row-fluid .offset4:first-child { margin-left: 34.18803418803419%; *margin-left: 34.081651209310785%; } .row-fluid .offset3 { margin-left: 28.205128205128204%; *margin-left: 28.0987452264048%; } .row-fluid .offset3:first-child { margin-left: 25.641025641025642%; *margin-left: 25.53464266230224%; } .row-fluid .offset2 { margin-left: 19.65811965811966%; *margin-left: 19.551736679396257%; } .row-fluid .offset2:first-child { margin-left: 17.094017094017094%; *margin-left: 16.98763411529369%; } .row-fluid .offset1 { margin-left: 11.11111111111111%; *margin-left: 11.004728132387708%; } .row-fluid .offset1:first-child { margin-left: 8.547008547008547%; *margin-left: 8.440625568285142%; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 30px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 1156px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 1056px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 956px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 856px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 756px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 656px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 556px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 456px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 356px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 256px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 156px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 56px; } .thumbnails { margin-left: -30px; } .thumbnails > li { margin-left: 30px; } .row-fluid .thumbnails { margin-left: 0; } } @media (max-width: 979px) { body { padding-top: 0; } .navbar-fixed-top, .navbar-fixed-bottom { position: static; } .navbar-fixed-top { margin-bottom: 20px; } .navbar-fixed-bottom { margin-top: 20px; } .navbar-fixed-top .navbar-inner, .navbar-fixed-bottom .navbar-inner { padding: 5px; } .navbar .container { width: auto; padding: 0; } .navbar .brand { padding-left: 10px; padding-right: 10px; margin: 0 0 0 -5px; } .nav-collapse { clear: both; } .nav-collapse .nav { float: none; margin: 0 0 10px; } .nav-collapse .nav > li { float: none; } .nav-collapse .nav > li > a { margin-bottom: 2px; } .nav-collapse .nav > .divider-vertical { display: none; } .nav-collapse .nav .nav-header { color: #bb844e; text-shadow: none; } .nav-collapse .nav > li > a, .nav-collapse .dropdown-menu a { padding: 9px 15px; font-weight: bold; color: #bb844e; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .nav-collapse .btn { padding: 4px 10px 4px; font-weight: normal; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .nav-collapse .dropdown-menu li + li a { margin-bottom: 2px; } .nav-collapse .nav > li > a:hover, .nav-collapse .nav > li > a:focus, .nav-collapse .dropdown-menu a:hover, .nav-collapse .dropdown-menu a:focus { background-color: #371605; } .navbar-inverse .nav-collapse .nav > li > a, .navbar-inverse .nav-collapse .dropdown-menu a { color: #999999; } .navbar-inverse .nav-collapse .nav > li > a:hover, .navbar-inverse .nav-collapse .nav > li > a:focus, .navbar-inverse .nav-collapse .dropdown-menu a:hover, .navbar-inverse .nav-collapse .dropdown-menu a:focus { background-color: #111111; } .nav-collapse.in .btn-group { margin-top: 5px; padding: 0; } .nav-collapse .dropdown-menu { position: static; top: auto; left: auto; float: none; display: none; max-width: none; margin: 0 15px; padding: 0; background-color: transparent; border: none; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .nav-collapse .open > .dropdown-menu { display: block; } .nav-collapse .dropdown-menu:before, .nav-collapse .dropdown-menu:after { display: none; } .nav-collapse .dropdown-menu .divider { display: none; } .nav-collapse .nav > li > .dropdown-menu:before, .nav-collapse .nav > li > .dropdown-menu:after { display: none; } .nav-collapse .navbar-form, .nav-collapse .navbar-search { float: none; padding: 10px 15px; margin: 10px 0; border-top: 1px solid #371605; border-bottom: 1px solid #371605; -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); } .navbar-inverse .nav-collapse .navbar-form, .navbar-inverse .nav-collapse .navbar-search { border-top-color: #111111; border-bottom-color: #111111; } .navbar .nav-collapse .nav.pull-right { float: none; margin-left: 0; } .nav-collapse, .nav-collapse.collapse { overflow: hidden; height: 0; } .navbar .btn-navbar { display: block; } .navbar-static .navbar-inner { padding-left: 10px; padding-right: 10px; } } @media (min-width: 980px) { .nav-collapse.collapse { height: auto !important; overflow: visible !important; } }
Java
#ifndef ENTRY_H #define ENTRY_H #include "Object.h" #include "CompiledCode.h" #include "String.h" #define ENTRY_MAX_ARGS_SIZE 16 typedef struct { _Bool isHandle; union { Value value; Object *handle; }; } EntryArg; typedef struct { size_t size; EntryArg values[ENTRY_MAX_ARGS_SIZE]; } EntryArgs; Value invokeMethod(CompiledMethod *method, EntryArgs *args); Value invokeInititalize(Object *object); Value sendMessage(String *selector, EntryArgs *args); Value evalCode(char *source); _Bool parseFileAndInitialize(char *filename, Value *lastBlockResult); _Bool parseFile(char *filename, OrderedCollection *classes, OrderedCollection *blocks); static void entryArgsAddObject(EntryArgs *args, Object *object) { intptr_t index = args->size++; ASSERT(index <= ENTRY_MAX_ARGS_SIZE); args->values[index].isHandle = 1; args->values[index].handle = object; } static void entryArgsAdd(EntryArgs *args, Value value) { intptr_t index = args->size++; ASSERT(index <= ENTRY_MAX_ARGS_SIZE); args->values[index].isHandle = 0; args->values[index].value = value; } #endif
Java
// Copyright (c) 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef QUICHE_QUIC_QBONE_QBONE_CLIENT_INTERFACE_H_ #define QUICHE_QUIC_QBONE_QBONE_CLIENT_INTERFACE_H_ #include <cstdint> #include "absl/strings/string_view.h" namespace quic { // An interface that includes methods to interact with a QBONE client. class QboneClientInterface { public: virtual ~QboneClientInterface() {} // Accepts a given packet from the network and sends the packet down to the // QBONE connection. virtual void ProcessPacketFromNetwork(absl::string_view packet) = 0; }; } // namespace quic #endif // QUICHE_QUIC_QBONE_QBONE_CLIENT_INTERFACE_H_
Java
#ifndef SEQUENCE_INDEX_DATABASE_H_ #define SEQUENCE_INDEX_DATABASE_H_ #include <fstream> #include <iostream> #include <vector> #include <assert.h> #include <stdlib.h> #include <sstream> #include <algorithm> #include "Types.h" #include "DNASequence.h" #include "utils/StringUtils.h" using namespace std; #define SEQUENCE_INDEX_DATABASE_MAGIC 1233211233 template<typename TSeq> class SequenceIndexDatabase { public: vector<DNALength> growableSeqStartPos; vector<string> growableName; DNALength *seqStartPos; bool deleteSeqStartPos; char **names; bool deleteNames; int *nameLengths; bool deleteNameLengths; int nSeqPos; bool deleteStructures; // // This is stored after reading in the sequence. // vector<string> md5; SequenceIndexDatabase(int final=0) { nSeqPos = 0; if (!final) { growableSeqStartPos.push_back(0); } names = NULL; deleteNames = false; nameLengths = NULL; deleteNameLengths = false; seqStartPos = NULL; deleteSeqStartPos = false; deleteStructures = false; } DNALength GetLengthOfSeq(int seqIndex) { assert(seqIndex < nSeqPos-1); return seqStartPos[seqIndex+1] - seqStartPos[seqIndex] - 1; } void GetName(int seqIndex, string &name) { assert(seqIndex < nSeqPos-1); name = names[seqIndex]; } void MakeSAMSQString(string &sqString) { stringstream st; int i; for (i = 0; i < nSeqPos-1; i++) { st << "@SQ\tSN:" << names[i] << "\tLN:" << GetLengthOfSeq(i); if (md5.size() == nSeqPos-1) { st << "\tM5:" << md5[i]; } st << endl; } sqString = st.str(); } DNALength ChromosomePositionToGenome(int chrom, DNALength chromPos) { assert(chrom < nSeqPos); return seqStartPos[chrom] + chromPos; } int SearchForIndex(DNALength pos) { // The default behavior for the case // that there is just one genome. if (nSeqPos == 1) { return 0; } DNALength* seqPosIt = upper_bound(seqStartPos+1, seqStartPos + nSeqPos, pos); return seqPosIt - seqStartPos - 1; } string GetSpaceDelimitedName(unsigned int index) { int pos; assert(index < nSeqPos); string name; for (pos = 0; pos < nameLengths[index]; pos++) { if (names[index][pos] == ' ' or names[index][pos] == '\t' or names[index][pos] == '\0') { break; } } name.assign(names[index], pos); return name; } int SearchForStartBoundary(DNALength pos) { int index = SearchForIndex(pos); if (index != -1) { return seqStartPos[index]; } else { return -1; } } int SearchForEndBoundary(DNALength pos) { int index = SearchForIndex(pos); if (index != -1) { return seqStartPos[index + 1]; } else { return -1; } } DNALength SearchForStartAndEnd(DNALength pos, DNALength &start, DNALength &end) { int index = SearchForIndex(pos); if (index != -1) { start = seqStartPos[index]; end = seqStartPos[index+1]; return 1; } else { start = end = -1; return 0; } } void WriteDatabase(ofstream &out) { int mn = SEQUENCE_INDEX_DATABASE_MAGIC; out.write((char*) &mn, sizeof(int)); out.write((char*) &nSeqPos, sizeof(int)); out.write((char*) seqStartPos, sizeof(DNALength) * nSeqPos); int nSeq = nSeqPos - 1; out.write((char*) nameLengths, sizeof(int) * nSeq); int i; // // The number of sequences is 1 less than the number of positions // since the positions include 0 as a boundary. // char nullchar = '\0'; for (i = 0; i < nSeq; i++) { // // nameLengths has space for the null char, so the length of the // name = nameLengths[i]-1. Write a nullchar to disk so that it // may be read in later with no work. // out.write((char*) names[i], sizeof(char) * (nameLengths[i]-1)); out.write((char*) &nullchar, sizeof(char)); } } void ReadDatabase(ifstream &in) { int mn; // Make sure this is a read database, since the binary input // is not syntax checked. in.read((char*) &mn, sizeof(int)); if (mn != SEQUENCE_INDEX_DATABASE_MAGIC) { cout << "ERROR: Sequence index database is corrupt!" << endl; exit(0); } // // Read in the boundaries of each sequence. // deleteStructures = true; in.read((char*) &nSeqPos, sizeof(int)); seqStartPos = new DNALength[nSeqPos]; deleteSeqStartPos = true; in.read((char*) seqStartPos, sizeof(DNALength) * nSeqPos); int nSeq = nSeqPos - 1; // Get the lengths of the strings to read. nameLengths = new int[nSeq]; deleteNameLengths = true; in.read((char*)nameLengths, sizeof(int) * nSeq); // Get the titles of the sequences. names = new char*[nSeq]; deleteNames = true; char *namePtr; int i; for (i = 0; i < nSeq; i++) { namePtr = new char[nameLengths[i]]; if (nameLengths[i] > 0) { in.read(namePtr, nameLengths[i]); } namePtr[nameLengths[i]-1] = '\0'; names[i] = namePtr; } } void SequenceTitleLinesToNames() { int seqIndex; for (seqIndex = 0; seqIndex < nSeqPos-1; seqIndex++) { string tmpName; AssignUntilFirstSpace(names[seqIndex], nameLengths[seqIndex], tmpName); delete[] names[seqIndex]; names[seqIndex] = new char[tmpName.size()+1]; strcpy(names[seqIndex], tmpName.c_str()); names[seqIndex][tmpName.size()] = '\0'; nameLengths[seqIndex] = tmpName.size(); } } VectorIndex AddSequence(TSeq &sequence) { int endPos = growableSeqStartPos[growableSeqStartPos.size() - 1]; int growableSize = growableSeqStartPos.size(); growableSeqStartPos.push_back(endPos + sequence.length + 1); string fastaTitle; sequence.GetFASTATitle(fastaTitle); growableName.push_back(fastaTitle); return growableName.size(); } void Finalize() { deleteStructures = true; seqStartPos = &growableSeqStartPos[0]; nSeqPos = growableSeqStartPos.size(); int nSeq = nSeqPos - 1; names = new char*[nSeq]; deleteNames = true; unsigned int i; nameLengths = new int[nSeq]; deleteNameLengths = true; for (i = 0; i < nSeq; i++) { names[i] = new char[growableName[i].size() + 1]; memcpy((char*) names[i], (char*) growableName[i].c_str(), growableName[i].size()); names[i][growableName[i].size()] = '\0'; nameLengths[i] = growableName[i].size() + 1; } } void FreeDatabase() { int i; if (deleteStructures == false) { return; } if (names != NULL and deleteNames) { int nSeq = nSeqPos - 1; for (i = 0; i < nSeq; i++ ){ delete[] names[i]; } delete[] names; } if (nameLengths != NULL) { delete[] nameLengths; } if (seqStartPos != NULL and deleteSeqStartPos) { delete[] seqStartPos; } } }; template< typename TSeq > class SeqBoundaryFtr { public: SequenceIndexDatabase<TSeq> *seqDB; SeqBoundaryFtr(SequenceIndexDatabase<TSeq> *_seqDB) { seqDB = _seqDB; } int GetIndex(DNALength pos) { return seqDB->SearchForIndex(pos); } int GetStartPos(int index) { assert(index < seqDB->nSeqPos); return seqDB->seqStartPos[index]; } DNALength operator()(DNALength pos) { return seqDB->SearchForStartBoundary(pos); } // // This is misuse of a functor, but easier interface coding for now. DNALength Length(DNALength pos) { DNALength start, end; seqDB->SearchForStartAndEnd(pos, start, end); return end - start; } }; #endif
Java
/* Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #pragma once #include "ParticleSystemFwd.hpp" namespace KRE { namespace Particles { enum class EmitsType { VISUAL, EMITTER, AFFECTOR, TECHNIQUE, SYSTEM, }; class Emitter : public EmitObject { public: explicit Emitter(ParticleSystemContainer* parent, const variant& node); virtual ~Emitter(); Emitter(const Emitter&); int getEmittedParticleCountPerCycle(float t); color_vector getColor() const; Technique* getTechnique() { return technique_; } void setParentTechnique(Technique* tq) { technique_ = tq; } virtual Emitter* clone() = 0; static Emitter* factory(ParticleSystemContainer* parent, const variant& node); protected: virtual void internalCreate(Particle& p, float t) = 0; virtual bool durationExpired() { return can_be_deleted_; } private: virtual void handleEmitProcess(float t) override; virtual void handleDraw() const override; Technique* technique_; // These are generation parameters. ParameterPtr emission_rate_; ParameterPtr time_to_live_; ParameterPtr velocity_; ParameterPtr angle_; ParameterPtr mass_; // This is the duration that the emitter lives for ParameterPtr duration_; // this is the delay till the emitter repeats. ParameterPtr repeat_delay_; std::unique_ptr<std::pair<glm::quat, glm::quat>> orientation_range_; typedef std::pair<color_vector,color_vector> color_range; std::shared_ptr<color_range> color_range_; glm::vec4 color_; ParameterPtr particle_width_; ParameterPtr particle_height_; ParameterPtr particle_depth_; bool force_emission_; bool force_emission_processed_; bool can_be_deleted_; EmitsType emits_type_; std::string emits_name_; void initParticle(Particle& p, float t); void setParticleStartingValues(const std::vector<Particle>::iterator& start, const std::vector<Particle>::iterator& end); void createParticles(std::vector<Particle>& particles, std::vector<Particle>::iterator& start, std::vector<Particle>::iterator& end, float t); size_t calculateParticlesToEmit(float t, size_t quota, size_t current_size); float generateAngle() const; glm::vec3 getInitialDirection() const; //BoxOutlinePtr debug_draw_outline_; // working items // Any "left over" fractional count of emitted particles float emission_fraction_; // time till the emitter stops emitting. float duration_remaining_; // time remaining till a stopped emitter restarts. float repeat_delay_remaining_; Emitter(); }; } }
Java
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} module React.Flux.Mui.RadioButton.RadioButtonGroup where import Protolude import Data.Aeson import Data.Aeson.Casing import Data.String (String) import React.Flux import React.Flux.Mui.Types import React.Flux.Mui.Util data RadioButtonGroup = RadioButtonGroup { radioButtonGroupClassName :: !(Maybe Text) , radioButtonGroupLabelPosition :: !(Maybe (MuiSymbolEnum '[ "left", "right"])) , radioButtonGroupName :: !Text } deriving (Generic, Show) instance ToJSON RadioButtonGroup where toJSON = genericToJSON $ aesonDrop (length ("RadioButtonGroup" :: String)) camelCase defRadioButtonGroup :: Text -> RadioButtonGroup defRadioButtonGroup radioButtonGroupName_ = RadioButtonGroup { radioButtonGroupClassName = Nothing , radioButtonGroupLabelPosition = Nothing , radioButtonGroupName = radioButtonGroupName_ } radioButtonGroup_ :: RadioButtonGroup -> [PropertyOrHandler handler] -> ReactElementM handler () -> ReactElementM handler () radioButtonGroup_ args props = foreign_ "RadioButtonGroup" (fromMaybe [] (toProps args) ++ props)
Java
YUI.add('enc-utf16-test', function (Y) { var C = CryptoJS; Y.CryptoJSTestSuite.add(new Y.Test.Case({ name: 'Utf16', testStringify1: function () { Y.Assert.areEqual('z', C.enc.Utf16.stringify(C.lib.WordArray.create([0x007a0000], 2))); }, testStringify2: function () { Y.Assert.areEqual('水', C.enc.Utf16.stringify(C.lib.WordArray.create([0x6c340000], 2))); }, testStringify3: function () { Y.Assert.areEqual('𐀀', C.enc.Utf16.stringify(C.lib.WordArray.create([0xd800dc00], 4))); }, testStringify4: function () { Y.Assert.areEqual('𝄞', C.enc.Utf16.stringify(C.lib.WordArray.create([0xd834dd1e], 4))); }, testStringify5: function () { Y.Assert.areEqual('􏿽', C.enc.Utf16.stringify(C.lib.WordArray.create([0xdbffdffd], 4))); }, testStringifyLE: function () { Y.Assert.areEqual('􏿽', C.enc.Utf16LE.stringify(C.lib.WordArray.create([0xffdbfddf], 4))); }, testStringifyLEInputIntegrity: function () { var wordArray = C.lib.WordArray.create([0xffdbfddf], 4); Y.Assert.areEqual('􏿽', C.enc.Utf16LE.stringify(wordArray)); Y.Assert.areEqual('􏿽', C.enc.Utf16LE.stringify(wordArray)); }, testParse1: function () { Y.Assert.areEqual(C.lib.WordArray.create([0x007a0000], 2).toString(), C.enc.Utf16.parse('z').toString()); }, testParse2: function () { Y.Assert.areEqual(C.lib.WordArray.create([0x6c340000], 2).toString(), C.enc.Utf16.parse('水').toString()); }, testParse3: function () { Y.Assert.areEqual(C.lib.WordArray.create([0xd800dc00], 4).toString(), C.enc.Utf16.parse('𐀀').toString()); }, testParse4: function () { Y.Assert.areEqual(C.lib.WordArray.create([0xd834dd1e], 4).toString(), C.enc.Utf16.parse('𝄞').toString()); }, testParse5: function () { Y.Assert.areEqual(C.lib.WordArray.create([0xdbffdffd], 4).toString(), C.enc.Utf16.parse('􏿽').toString()); }, testParseLE: function () { Y.Assert.areEqual(C.lib.WordArray.create([0xffdbfddf], 4).toString(), C.enc.Utf16LE.parse('􏿽').toString()); } })); }, '$Rev$');
Java
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license (see the COPYING file). """ This package contains the qibuild actions. """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function
Java
package com.navisens.pojostick.navishare; import com.navisens.motiondnaapi.MotionDna; import com.navisens.pojostick.navisenscore.*; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Created by Joseph on 11/30/17. * <p> * NaviShare provides functionality for communicating with other devices * </p> */ @SuppressWarnings("unused") public class NaviShare implements NavisensPlugin { private static final long QUERY_INTERVAL = 500000000; private String host, port, room; private boolean changed; private boolean configured; private boolean connected; private NavisensCore core; private final Set<String> rooms; private final Set<NaviShareListener> listeners; private long roomsQueriedAt; @SuppressWarnings("unused") public NaviShare() { this.rooms = new HashSet<>(); this.listeners = new HashSet<>(); this.roomsQueriedAt = System.nanoTime(); } /** * Configure a server. This does not connect to it yet, but is required before calling connect. * * @param host server ip * @param port server port * @return a reference to this NaviShare */ @SuppressWarnings("unused") public NaviShare configure(String host, String port) { core.getSettings().overrideHost(null, null); this.host = host; this.port = port; this.changed = true; this.configured = true; return this; } /** * Connect to a room in the server. * * @param room The room to connect to * @return Whether this device connected to a server */ @SuppressWarnings("unused") public boolean connect(String room) { core.getSettings().overrideRoom(null); if (configured) { if (connected && !changed) { core.getMotionDna().setUDPRoom(room); } else { this.disconnect(); core.getMotionDna().startUDP(room, host, port); this.connected = true; } this.changed = false; return true; } return false; } /** * Disconnect from the server. */ @SuppressWarnings("unused") public void disconnect() { core.getMotionDna().stopUDP(); this.connected = false; } /** * Connect to a public test server. Don't use this for official release, as it is public * and can get filled up quickly. Each organization can claim one room, so if you need * multiple independent servers within your organization, you should test on a private * server instead, and use configure(host, port) to target that server instead. */ @SuppressWarnings("unused") public boolean testConnect() { if (!connected) { this.disconnect(); core.getMotionDna().startUDP(); return this.connected = true; } return false; } /** * Send a message to all other devices on the network * * @param msg A string to send, recommended web safe */ @SuppressWarnings("unused") public void sendMessage(String msg) { if (connected) { core.getMotionDna().sendUDPPacket(msg); } } /** * Add a listener to receive network events * * @param listener The listener to receive events * @return Whether the listener was added successfully */ @SuppressWarnings("unused") public boolean addListener(NaviShareListener listener) { return this.listeners.add(listener); } /** * Remove a listener to stop receiving events * * @param listener Ths listener to remove * @return Whether the listener was removed successfully */ @SuppressWarnings("unused") public boolean removeListener(NaviShareListener listener) { return this.listeners.remove(listener); } /** * Track a room so you can query its status. Call refreshRoomStatus to * receive a new roomStatus event * * @param room A room to track * @return Whether the room was added to be tracked or not */ @SuppressWarnings("unused") public boolean trackRoom(String room) { return this.rooms.add(room); } /** * Stop tracking a room. Call refreshRoomStatus to receive a new roomStatusEvent * * @param room A room to stop tracking * @return Whether the room was removed from tracking or not */ @SuppressWarnings("unused") public boolean untrackRoom(String room) { return this.rooms.remove(room); } /** * Refresh the status of any tracked rooms. Updates will be received from the * roomOccupancyChanged event * @return Whether a refresh request was sent or not */ @SuppressWarnings("unused") public boolean refreshRoomStatus() { final long now = System.nanoTime(); if (connected && now - roomsQueriedAt > QUERY_INTERVAL) { roomsQueriedAt = now; core.getMotionDna().sendUDPQueryRooms(rooms.toArray(new String[0])); return true; } return false; } @Override public boolean init(NavisensCore navisensCore, Object[] objects) { this.core = navisensCore; core.subscribe(this, NavisensCore.NETWORK_DATA); core.getSettings().requestNetworkRate(100); core.applySettings(); return true; } @Override public boolean stop() { this.disconnect(); core.remove(this); return true; } @Override public void receiveMotionDna(MotionDna motionDna) { } @Override public void receiveNetworkData(MotionDna motionDna) { } @Override public void receiveNetworkData(MotionDna.NetworkCode networkCode, Map<String, ?> map) { switch (networkCode) { case RAW_NETWORK_DATA: for (NaviShareListener listener : listeners) listener.messageReceived((String) map.get("ID"), (String) map.get("payload")); break; case ROOM_CAPACITY_STATUS: for (NaviShareListener listener : listeners) listener.roomOccupancyChanged((Map<String, Integer>) map.get("payload")); break; case EXCEEDED_SERVER_ROOM_CAPACITY: for (NaviShareListener listener : listeners) listener.serverCapacityExceeded(); this.disconnect(); break; case EXCEEDED_ROOM_CONNECTION_CAPACITY: for (NaviShareListener listener : listeners) listener.roomCapacityExceeded(); this.disconnect(); break; } } @Override public void receivePluginData(String id, int operator, Object... payload) { } @Override public void reportError(MotionDna.ErrorCode errorCode, String s) { } }
Java
# @desc makefile for Login # @author viticm<viticm.ti@gmail.com> # @date 2013-06-25 20:00:13 include ../../premake.mk CFLAGS = -I$(BASEDIR)/Login/Main -I$(BASEDIR)/Login/DB -I$(BASEDIR)/Login/Packets -I$(BASEDIR)/Login/Process -I$(BASEDIR)/Login/Player -I$(BASEDIR)/Login $(SERVER_BASE_INCLUDES) LDFLAGS = DIRS = OBJS = DBThread.o \ LoginDBManager.o \ DBThreadManager.o \ CharConfig.o \ DBLogicManager.o debug:$(OBJS) for dir in $(DIRS); do \ $(MAKE) debug -C $$dir; \ done release:$(OBJS) for dir in $(DIRS); do \ $(MAKE) release -C $$dir; \ done all:debug clean: $(RM) -f *.o
Java
# $FreeBSD$ PROG= juggle NO_MAN= WARNS?= 3 DPADD= ${LIBPTHREAD} LDADD= -lpthread .include <bsd.prog.mk>
Java
<?php // WARNING, this is a read only file created by import scripts // WARNING // WARNING, Changes made to this file will be clobbered // WARNING // WARNING, Please make changes on poeditor instead of here // // ?> subject: (opomnik) {if:transfer.files>1}Datoteke, pripravljene{else}Datoteka, pripravljena{endif} za prenos subject: (opomnik) {transfer.subject} {alternative:plain} Spoštovani, prejeli ste opomnik, da {if:transfer.files>1}so bile naložene datoteke{else}je bila naložena datoteka{endif} na {cfg:site_name} s strani {transfer.user_email}, Vam pa so bile dodeljene pravice za prenos {if:transfer.files>1}njihovih vsebin{else}njene vsebine{endif} : {if:transfer.files>1}{each:transfer.files as file} - {file.path} ({size:file.size}) {endeach}{else} {transfer.files.first().path} ({size:transfer.files.first().size}) {endif} Povezava za prenos: {recipient.download_link} Prenos je na voljo do {date:transfer.expires}. Po tem datumu bo avtomatsko izbrisan. {if:transfer.message || transfer.subject} Osebno sporočilo od {transfer.user_email}: {transfer.subject} {transfer.message} {endif} Lep pozdrav, {cfg:site_name} {alternative:html} <p> Spoštovani, </p> <p> prejeli ste opomnik, da {if:transfer.files>1}so bile naložene datoteke{else}je bila naložena datoteka{endif} na {cfg:site_name} s strani {transfer.user_email}, Vam pa so bile dodeljene pravice za prenos {if:transfer.files>1}njihovih vsebin{else}njene vsebine{endif}. </p> <table rules="rows"> <thead> <tr> <th colspan="2">Podrobnosti prenosa</th> </tr> </thead> <tbody> <tr> <td>{if:transfer.files>1}Datoteke{else}Datoteka{endif}</td> <td> {if:transfer.files>1} <ul> {each:transfer.files as file} <li>{file.path} ({size:file.size})</li> {endeach} </ul> {else} {transfer.files.first().path} ({size:transfer.files.first().size}) {endif} </td> </tr> {if:transfer.files>1} <tr> <td>Velikost prenosa</td> <td>{size:transfer.size}</td> </tr> {endif} <tr> <td>Rok veljavnosti</td> <td>{date:transfer.expires}</td> </tr> <tr> <td>Povezava do prenosa</td> <td><a href="{recipient.download_link}">{recipient.download_link}</a></td> </tr> </tbody> </table> {if:transfer.message} <p> Osebno sporočilo od {transfer.user_email}: </p> <p class="message"> <span class="subject">{transfer.subject}</span> {transfer.message} </p> {endif} <p> Lep pozdrav,<br /> {cfg:site_name} </p>
Java
-- | -- Module: Threshold -- Description: Time integrated threshold functions -- Copyright: (c) 2013 Tom Hawkins & Lee Pike -- -- Time integrated threshold functions typically used in condition monitoring. module Language.Atom.Common.Threshold ( boolThreshold , doubleThreshold ) where import Language.Atom.Expressions import Language.Atom.Language import Data.Int (Int32) -- | Boolean thresholding over time. Output is set when internal counter hits -- limit, and cleared when counter is 0. boolThreshold :: Name -> Int32 -> Bool -> E Bool -> Atom (E Bool) boolThreshold name_ num init_ input = atom name_ "" $ do --assert "positiveNumber" $ num >= 0 state <- bool "state" init_ count <- int32 "count" (if init_ then num else 0) atom "update" "" $ do cond $ value count >. Const 0 &&. value count <. Const num count <== value count + mux input (Const 1) (Const (-1)) atom "low" "" $ do cond $ value count ==. Const 0 state <== false atom "high" "" $ do cond $ value count ==. Const num state <== true return $ value state -- | Integrating threshold. Output is set with integral reaches limit, and -- cleared when integral reaches 0. doubleThreshold :: Name -> Double -> E Double -> Atom (E Bool) doubleThreshold name_ lim input = atom name_ "" $ do --assert "positiveLimit" $ lim >= 0 state <- bool "state" False sum_ <- double "sum" 0 -- TODO: Figure out what the below translates to in the newer library -- (high,low) <- priority atom "update" "" $ do sum_ <== value sum_ + input -- low atom "clear" "" $ do cond $ value sum_ <=. 0 state <== false sum_ <== 0 -- high atom "set" "" $ do cond $ value sum_ >=. Const lim state <== true sum_ <== Const lim -- high return $ value state
Java
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using NLog.Config; /// <summary> /// A XML Element /// </summary> [NLogConfigurationItem] public class XmlElement : XmlElementBase { private const string DefaultElementName = "item"; /// <inheritdoc/> public XmlElement() : this(DefaultElementName, null) { } /// <inheritdoc/> public XmlElement(string elementName, Layout elementValue) : base(elementName, elementValue) { } /// <summary> /// Name of the element /// </summary> /// <docgen category='Element Options' order='10' /> public string Name { get => base.ElementNameInternal; set => base.ElementNameInternal = value; } /// <summary> /// Value inside the element /// </summary> /// <docgen category='Element Options' order='10' /> public Layout Value { get => base.LayoutWrapper.Inner; set => base.LayoutWrapper.Inner = value; } /// <summary> /// Determines whether or not this attribute will be Xml encoded. /// </summary> /// <docgen category='Element Options' order='10' /> public bool Encode { get => base.LayoutWrapper.XmlEncode; set => base.LayoutWrapper.XmlEncode = value; } } }
Java
require "lita" Lita.load_locales Dir[File.expand_path( File.join("..", "..", "locales", "*.yml"), __FILE__ )] require 'lita/handlers/markov' # Lita::Handlers::Markov.template_root File.expand_path( # File.join("..", "..", "templates"), # __FILE__ # )
Java
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is configman # # The Initial Developer of the Original Code is # Mozilla Foundation # Portions created by the Initial Developer are Copyright (C) 2011 # the Initial Developer. All Rights Reserved. # # Contributor(s): # K Lars Lohn, lars@mozilla.com # Peter Bengtsson, peterbe@mozilla.com # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** import sys import re import datetime import types import inspect import collections import json from required_config import RequiredConfig from namespace import Namespace from .datetime_util import datetime_from_ISO_string as datetime_converter from .datetime_util import date_from_ISO_string as date_converter import datetime_util #------------------------------------------------------------------------------ def option_value_str(an_option): """return an instance of Option's value as a string. The option instance doesn't actually have to be from the Option class. All it requires is that the passed option instance has a ``value`` attribute. """ if an_option.value is None: return '' try: converter = to_string_converters[type(an_option.value)] s = converter(an_option.value) except KeyError: if not isinstance(an_option.value, basestring): s = unicode(an_option.value) else: s = an_option.value if an_option.from_string_converter in converters_requiring_quotes: s = "'''%s'''" % s return s #------------------------------------------------------------------------------ def str_dict_keys(a_dict): """return a modified dict where all the keys that are anything but str get converted to str. E.g. >>> result = str_dict_keys({u'name': u'Peter', u'age': 99, 1: 2}) >>> # can't compare whole dicts in doctests >>> result['name'] u'Peter' >>> result['age'] 99 >>> result[1] 2 The reason for this is that in Python <= 2.6.4 doing ``MyClass(**{u'name': u'Peter'})`` would raise a TypeError Note that only unicode types are converted to str types. The reason for that is you might have a class that looks like this:: class Option(object): def __init__(self, foo=None, bar=None, **kwargs): ... And it's being used like this:: Option(**{u'foo':1, u'bar':2, 3:4}) Then you don't want to change that {3:4} part which becomes part of `**kwargs` inside the __init__ method. Using integers as parameter keys is a silly example but the point is that due to the python 2.6.4 bug only unicode keys are converted to str. """ new_dict = {} for key in a_dict: if isinstance(key, unicode): new_dict[str(key)] = a_dict[key] else: new_dict[key] = a_dict[key] return new_dict #------------------------------------------------------------------------------ def io_converter(input_str): """ a conversion function for to select stdout, stderr or open a file for writing""" if type(input_str) is str: input_str_lower = input_str.lower() if input_str_lower == 'stdout': return sys.stdout if input_str_lower == 'stderr': return sys.stderr return open(input_str, "w") return input_str #------------------------------------------------------------------------------ def timedelta_converter(input_str): """a conversion function for time deltas""" if isinstance(input_str, basestring): days, hours, minutes, seconds = 0, 0, 0, 0 details = input_str.split(':') if len(details) >= 4: days = int(details[-4]) if len(details) >= 3: hours = int(details[-3]) if len(details) >= 2: minutes = int(details[-2]) if len(details) >= 1: seconds = int(details[-1]) return datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds) raise ValueError(input_str) #------------------------------------------------------------------------------ def boolean_converter(input_str): """ a conversion function for boolean """ return input_str.lower() in ("true", "t", "1", "y", "yes") #------------------------------------------------------------------------------ import __builtin__ _all_named_builtins = dir(__builtin__) def class_converter(input_str): """ a conversion that will import a module and class name """ if not input_str: return None if '.' not in input_str and input_str in _all_named_builtins: return eval(input_str) parts = [x.strip() for x in input_str.split('.') if x.strip()] try: # first try as a complete module package = __import__(input_str) except ImportError: # it must be a class from a module if len(parts) == 1: # since it has only one part, it must be a class from __main__ parts = ('__main__', input_str) package = __import__('.'.join(parts[:-1]), globals(), locals(), []) obj = package for name in parts[1:]: obj = getattr(obj, name) return obj #------------------------------------------------------------------------------ def classes_in_namespaces_converter(template_for_namespace="cls%d", name_of_class_option='cls', instantiate_classes=False): """take a comma delimited list of class names, convert each class name into an actual class as an option within a numbered namespace. This function creates a closure over a new function. That new function, in turn creates a class derived from RequiredConfig. The inner function, 'class_list_converter', populates the InnerClassList with a Namespace for each of the classes in the class list. In addition, it puts the each class itself into the subordinate Namespace. The requirement discovery mechanism of configman then reads the InnerClassList's requried config, pulling in the namespaces and associated classes within. For example, if we have a class list like this: "Alpha, Beta", then this converter will add the following Namespaces and options to the configuration: "cls0" - the subordinate Namespace for Alpha "cls0.cls" - the option containing the class Alpha itself "cls1" - the subordinate Namespace for Beta "cls1.cls" - the option containing the class Beta itself Optionally, the 'class_list_converter' inner function can embue the InnerClassList's subordinate namespaces with aggregates that will instantiate classes from the class list. This is a convenience to the programmer who would otherwise have to know ahead of time what the namespace names were so that the classes could be instantiated within the context of the correct namespace. Remember the user could completely change the list of classes at run time, so prediction could be difficult. "cls0" - the subordinate Namespace for Alpha "cls0.cls" - the option containing the class Alpha itself "cls0.cls_instance" - an instance of the class Alpha "cls1" - the subordinate Namespace for Beta "cls1.cls" - the option containing the class Beta itself "cls1.cls_instance" - an instance of the class Beta parameters: template_for_namespace - a template for the names of the namespaces that will contain the classes and their associated required config options. The namespaces will be numbered sequentially. By default, they will be "cls1", "cls2", etc. class_option_name - the name to be used for the class option within the nested namespace. By default, it will choose: "cls1.cls", "cls2.cls", etc. instantiate_classes - a boolean to determine if there should be an aggregator added to each namespace that instantiates each class. If True, then each Namespace will contain elements for the class, as well as an aggregator that will instantiate the class. """ #-------------------------------------------------------------------------- def class_list_converter(class_list_str): """This function becomes the actual converter used by configman to take a string and convert it into the nested sequence of Namespaces, one for each class in the list. It does this by creating a proxy class stuffed with its own 'required_config' that's dynamically generated.""" if isinstance(class_list_str, basestring): class_list = [x.strip() for x in class_list_str.split(',')] else: raise TypeError('must be derivative of a basestring') #====================================================================== class InnerClassList(RequiredConfig): """This nested class is a proxy list for the classes. It collects all the config requirements for the listed classes and places them each into their own Namespace. """ # we're dynamically creating a class here. The following block of # code is actually adding class level attributes to this new class required_config = Namespace() # 1st requirement for configman subordinate_namespace_names = [] # to help the programmer know # what Namespaces we added namespace_template = template_for_namespace # save the template # for future reference class_option_name = name_of_class_option # save the class's option # name for the future # for each class in the class list for namespace_index, a_class in enumerate(class_list): # figure out the Namespace name namespace_name = template_for_namespace % namespace_index subordinate_namespace_names.append(namespace_name) # create the new Namespace required_config[namespace_name] = Namespace() # add the option for the class itself required_config[namespace_name].add_option( name_of_class_option, #doc=a_class.__doc__ # not helpful if too verbose default=a_class, from_string_converter=class_converter ) if instantiate_classes: # add an aggregator to instantiate the class required_config[namespace_name].add_aggregation( "%s_instance" % name_of_class_option, lambda c, lc, a: lc[name_of_class_option](lc)) @classmethod def to_str(cls): """this method takes this inner class object and turns it back into the original string of classnames. This is used primarily as for the output of the 'help' option""" return ', '.join( py_obj_to_str(v[name_of_class_option].value) for v in cls.get_required_config().values() if isinstance(v, Namespace)) return InnerClassList # result of class_list_converter return class_list_converter # result of classes_in_namespaces_converter #------------------------------------------------------------------------------ def regex_converter(input_str): return re.compile(input_str) compiled_regexp_type = type(re.compile(r'x')) #------------------------------------------------------------------------------ from_string_converters = { int: int, float: float, str: str, unicode: unicode, bool: boolean_converter, dict: json.loads, datetime.datetime: datetime_converter, datetime.date: date_converter, datetime.timedelta: timedelta_converter, type: class_converter, types.FunctionType: class_converter, compiled_regexp_type: regex_converter, } #------------------------------------------------------------------------------ def py_obj_to_str(a_thing): if a_thing is None: return '' if inspect.ismodule(a_thing): return a_thing.__name__ if a_thing.__module__ == '__builtin__': return a_thing.__name__ if a_thing.__module__ == "__main__": return a_thing.__name__ if hasattr(a_thing, 'to_str'): return a_thing.to_str() return "%s.%s" % (a_thing.__module__, a_thing.__name__) #------------------------------------------------------------------------------ def list_to_str(a_list): return ', '.join(to_string_converters[type(x)](x) for x in a_list) #------------------------------------------------------------------------------ to_string_converters = { int: str, float: str, str: str, unicode: unicode, list: list_to_str, tuple: list_to_str, bool: lambda x: 'True' if x else 'False', dict: json.dumps, datetime.datetime: datetime_util.datetime_to_ISO_string, datetime.date: datetime_util.date_to_ISO_string, datetime.timedelta: datetime_util.timedelta_to_str, type: py_obj_to_str, types.ModuleType: py_obj_to_str, types.FunctionType: py_obj_to_str, compiled_regexp_type: lambda x: x.pattern, } #------------------------------------------------------------------------------ #converters_requiring_quotes = [eval, eval_to_regex_converter] converters_requiring_quotes = [eval, regex_converter]
Java
<?php //AJAX Poll System Hack Start - 5:03 PM 3/24/2007 $language['POLL_ID']='الرقم'; $language['LATEST_POLL']='آخر استفتاء'; $language['CAST_VOTE']='قدم صوتي'; $language['FETCHING_RESULTS']='جلب نتائج الاستفتاء الرجاء الانتظار'; $language['POLL_TITLE']='عنوان الاستفتاء'; $language['POLL_TITLE_MISSING']='عنوان الاستفتاء مفقود'; $language['POLLING_SYSTEM']='AJAX نظام استفتاء'; $language['CURRENT_POLLS']='الاستفتاءت الحالية'; $language['POLL_STARTED']='بدات في'; $language['POLL_ENDED']='انتهت في'; $language['POLL_LASTED']='استمرت'; $language['POLL_BY']='قدمها'; $language['POLL_VOTES']='الاصوات'; $language['POLL_STILL_ACTIVE']='فعالة'; $language['POLL_NEW']='جديد'; $language['POLL_START_NEW']='ابدى استفتاء جديد'; $language['POLL_ACTIVE']='فعال'; $language['POLL_ACTIVE_TRUE']='فعالة'; $language['POLL_ACTIVE_FALSE']='معطلة'; $language['POLL_OPTION']='خيار'; $language['POLL_OPTIONS']='خيارات'; $language['POLL_MOVE']='الى الاسفل'; $language['POLL_NEW_OPTIONS']='خيارات اخرى'; $language['POLL_SAVE']='حفظ'; $language['POLL_CANCEL']='الغاء'; $language['POLL_DELETE']='مسح'; $language['POLL_DEL_CONFIRM']='اكبس موافق لمسح الاستفتاء'; $language['POLL_VOTERS']='مصوتين الاستفتاء'; $language['POLL_IP_ADDRESS']='IP عناوين الـ'; $language['POLL_DATE']='اليوم'; $language['POLL_USER']='المستخدم'; $language['POLL_ACCOUNT_DEL']='<i>الحساب الغي</i>'; $language['POLL_BACK']='وراء'; $language['YEAR']='سنة'; $language['MONTH']='شهر'; $language['WEEK']='اسبوع'; $language['DAY']='يوم'; $language['HOUR']='ساعة'; $language['MINUTE']='دقيقة'; $language['SECOND']='ثانية'; $language['YEARS']='سنوات'; $language['MONTHS']='شهور'; $language['WEEKS']='اسابيع'; $language['DAYS']='ايام'; $language['HOURS']='سا عات'; $language['MINUTES']='دقائق'; $language['SECONDS']='ثواني'; //AJAX Poll System Hack Stop ?>
Java
package org.mafagafogigante.dungeon.stats; import org.mafagafogigante.dungeon.game.Id; import org.jetbrains.annotations.NotNull; import java.io.Serializable; /** * CauseOfDeath class that defines what kind of death happened and the ID of the related Item or Spell. */ public class CauseOfDeath implements Serializable { private static final CauseOfDeath UNARMED = new CauseOfDeath(TypeOfCauseOfDeath.UNARMED, new Id("UNARMED")); private final TypeOfCauseOfDeath type; private final Id id; /** * Constructs a CauseOfDeath with the specified TypeOfCauseOfDeath and ID. * * @param type a TypeOfCauseOfDeath * @param id an ID */ public CauseOfDeath(@NotNull TypeOfCauseOfDeath type, @NotNull Id id) { this.type = type; this.id = id; } /** * Convenience method that returns a CauseOfDeath that represents an unarmed kill. */ public static CauseOfDeath getUnarmedCauseOfDeath() { return UNARMED; } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } CauseOfDeath that = (CauseOfDeath) object; return id.equals(that.id) && type == that.type; } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + id.hashCode(); return result; } @Override public String toString() { return String.format("%s : %s", type, id); } }
Java
--- title: Towers of Hanoi id: 5951ed8945deab770972ae56 challengeType: 5 isHidden: false forumTopicId: 302341 --- ## Description <section id='description'> Solve the <a href="https://en.wikipedia.org/wiki/Towers_of_Hanoi" title="wp: Towers_of_Hanoi" target="_blank">Towers of Hanoi</a> problem.</p> Your solution should accept the number of discs as the first parameters, and three string used to identify each of the three stacks of discs, for example <code>towerOfHanoi(4, 'A', 'B', 'C')</code>. The function should return an array of arrays containing the list of moves, source -> destination. For example, the array <code>[['A', 'C'], ['B', 'A']]</code> indicates that the 1st move was to move a disc from stack A to C, and the 2nd move was to move a disc from stack B to A. </p> </section> ## Instructions <section id='instructions'> </section> ## Tests <section id='tests'> ```yml tests: - text: <code>towerOfHanoi</code> should be a function. testString: assert(typeof towerOfHanoi === 'function'); - text: <code>towerOfHanoi(3, ...)</code> should return 7 moves. testString: assert(res3.length === 7); - text: <code>towerOfHanoi(3, 'A', 'B', 'C')</code> should return <code>[['A','B'], ['A','C'], ['B','C'], ['A','B'], ['C','A'], ['C','B'], ['A','B']]</code>. testString: assert.deepEqual(towerOfHanoi(3, 'A', 'B', 'C'), res3Moves); - text: <code>towerOfHanoi(5, "X", "Y", "Z")</code> 10th move should be Y -> X. testString: assert.deepEqual(res5[9], ['Y', 'X']); - text: <code>towerOfHanoi(7, 'A', 'B', 'C')</code> first ten moves should be <code>[['A','B'], ['A','C'], ['B','C'], ['A','B'], ['C','A'], ['C','B'], ['A','B'], ['A','C'], ['B','C'], ['B','A']]</code> testString: assert.deepEqual(towerOfHanoi(7, 'A', 'B', 'C').slice(0, 10), res7First10Moves); ``` </section> ## Challenge Seed <section id='challengeSeed'> <div id='js-seed'> ```js function towerOfHanoi(n, a, b, c) { // Good luck! return [[]]; } ``` </div> ### After Test <div id='js-teardown'> ```js const res3 = towerOfHanoi(3, 'A', 'B', 'C'); const res3Moves = [['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B'], ['C', 'A'], ['C', 'B'], ['A', 'B']]; const res5 = towerOfHanoi(5, 'X', 'Y', 'Z'); const res7First10Moves = [['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B'], ['C', 'A'], ['C', 'B'], ['A', 'B'], ['A', 'C'], ['B', 'C'], ['B', 'A']]; ``` </div> </section> ## Solution <section id='solution'> ```js function towerOfHanoi(n, a, b, c) { const res = []; towerOfHanoiHelper(n, a, c, b, res); return res; } function towerOfHanoiHelper(n, a, b, c, res) { if (n > 0) { towerOfHanoiHelper(n - 1, a, c, b, res); res.push([a, c]); towerOfHanoiHelper(n - 1, b, a, c, res); } } ``` </section>
Java
// Benoit 2011-05-16 #include <ros/node_handle.h> #include <ros/subscriber.h> #include <ros/rate.h> #include <eu_nifti_env_msg_ros/RequestForUUIDs.h> #include "NIFTiROSUtil.h" #include "UUIDsManager.h" namespace eu { namespace nifti { namespace ocu { const char* UUIDsManager::TOPIC = "/eoi/RequestForUUIDs"; const u_int UUIDsManager::NUM_REQUESTED(10); UUIDsManager* UUIDsManager::instance = NULL; UUIDsManager* UUIDsManager::getInstance() { if (instance == NULL) { instance = new UUIDsManager(); } return instance; } UUIDsManager::UUIDsManager() : wxThread(wxTHREAD_JOINABLE) , condition(mutexForCondition) , keepManaging(true) { } void UUIDsManager::stopManaging() { //printf("IN UUIDsManager::stopManaging \n"); keepManaging = false; if (instance != NULL) { instance->condition.Signal(); // Will make it go out of the main loop and terminate } //printf("OUT UUIDsManager::stopManaging \n"); } void* UUIDsManager::Entry() { //printf("%s\n", "UUIDsManager::Entry()"); ::ros::ServiceClient client = NIFTiROSUtil::getNodeHandle()->serviceClient<eu_nifti_env_msg_ros::RequestForUUIDs > (TOPIC); eu_nifti_env_msg_ros::RequestForUUIDs srv; srv.request.numRequested = NUM_REQUESTED; mutexForCondition.Lock(); // This must be called before the first wait() while (keepManaging) { //ROS_INFO("In the loop (keepManaging)"); // This is a requirement from wxThread // http://docs.wxwidgets.org/2.8/wx_wxthread.html#wxthreadtestdestroy if (TestDestroy()) break; if (!client.call(srv)) { std::cerr << "Failed to call ROS service \"RequestForUUIDs\"" << std::endl; //return 0; // Removed this on 2012-03-02 so that it would re-check the service every time, since CAST is unstable } else { //ROS_INFO("Got UUIDs"); { wxMutexLocker lock(instance->mutexForQueue); // Adds all new UUIDs to the list for (u_int i = 0; i < srv.response.uuids.size(); i++) { availableUUIDs.push(srv.response.uuids.at(i)); //std::cout << "Added " << srv.response.uuids.at(i) << std::endl; } } } // Waits until more ids are needed (signal will be called on the condition) //ROS_INFO("Before waiting"); condition.Wait(); //ROS_INFO("After waiting"); } return 0; } int UUIDsManager::getUUID() { //ROS_INFO("int UUIDsManager::getUUID()"); int uuid; { wxMutexLocker lock(instance->mutexForQueue); //ROS_INFO("Num left: %i/%i", instance->availableUUIDs.size(), NUM_REQUESTED); //ROS_INFO("Enough? %i", instance->availableUUIDs.size() <= NUM_REQUESTED / 2); assert(instance != NULL); // Requests more id's when the list is half empty if (instance->availableUUIDs.size() <= NUM_REQUESTED / 2) { //ROS_INFO("Will try waking up the thread to request UUIDs"); instance->condition.Signal(); if (instance->availableUUIDs.size() == 0) { throw "No UUID available"; } } uuid = instance->availableUUIDs.front(); instance->availableUUIDs.pop(); } //ROS_INFO("int UUIDsManager::getUUID() returned %i. Num left: %i", uuid, instance->availableUUIDs.size()); return uuid; } } } }
Java
// Copyright (c) 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_RESERVATION_OFFSET_TABLE_H_ #define BASE_ALLOCATOR_PARTITION_ALLOCATOR_RESERVATION_OFFSET_TABLE_H_ #include <cstddef> #include <cstdint> #include <limits> #include <tuple> #include "base/allocator/buildflags.h" #include "base/allocator/partition_allocator/address_pool_manager.h" #include "base/allocator/partition_allocator/partition_address_space.h" #include "base/allocator/partition_allocator/partition_alloc_check.h" #include "base/allocator/partition_allocator/partition_alloc_constants.h" #include "base/compiler_specific.h" #include "build/build_config.h" namespace base { namespace internal { static constexpr uint16_t kOffsetTagNotAllocated = std::numeric_limits<uint16_t>::max(); static constexpr uint16_t kOffsetTagNormalBuckets = std::numeric_limits<uint16_t>::max() - 1; // The main purpose of the reservation offset table is to easily locate the // direct map reservation start address for any given address. There is one // entry in the table for each super page. // // When PartitionAlloc reserves an address region it is always aligned to // super page boundary. However, in 32-bit mode, the size may not be aligned // super-page-aligned, so it may look like this: // |<--------- actual reservation size --------->| // +----------+----------+-----+-----------+-----+ - - - + // |SuperPage0|SuperPage1| ... |SuperPage K|SuperPage K+1| // +----------+----------+-----+-----------+-----+ - - -.+ // |<-X->|<-Y*)->| // // The table entries for reserved super pages say how many pages away from the // reservation the super page is: // +----------+----------+-----+-----------+-------------+ // |Entry for |Entry for | ... |Entry for |Entry for | // |SuperPage0|SuperPage1| |SuperPage K|SuperPage K+1| // +----------+----------+-----+-----------+-------------+ // | 0 | 1 | ... | K | K + 1 | // +----------+----------+-----+-----------+-------------+ // // For an address Z, the reservation start can be found using this formula: // ((Z >> kSuperPageShift) - (the entry for Z)) << kSuperPageShift // // kOffsetTagNotAllocated is a special tag denoting that the super page isn't // allocated by PartitionAlloc and kOffsetTagNormalBuckets denotes that it is // used for a normal-bucket allocation, not for a direct-map allocation. // // *) In 32-bit mode, Y is not used by PartitionAlloc, and cannot be used // until X is unreserved, because PartitionAlloc always uses kSuperPageSize // alignment when reserving address spaces. One can use "GigaCage" to // further determine which part of the supe page is used by PartitionAlloc. // This isn't a problem in 64-bit mode, where allocation granularity is // kSuperPageSize. class BASE_EXPORT ReservationOffsetTable { public: #if defined(PA_HAS_64_BITS_POINTERS) // There is one reservation offset table per Pool in 64-bit mode. static constexpr size_t kReservationOffsetTableCoverage = kPoolMaxSize; static constexpr size_t kReservationOffsetTableLength = kReservationOffsetTableCoverage >> kSuperPageShift; #else // The size of the reservation offset table should cover the entire 32-bit // address space, one element per super page. static constexpr uint64_t kGiB = 1024 * 1024 * 1024ull; static constexpr size_t kReservationOffsetTableLength = 4 * kGiB / kSuperPageSize; #endif static_assert(kReservationOffsetTableLength < kOffsetTagNormalBuckets, "Offsets should be smaller than kOffsetTagNormalBuckets."); static struct _ReservationOffsetTable { // The number of table elements is less than MAX_UINT16, so the element type // can be uint16_t. static_assert( kReservationOffsetTableLength <= std::numeric_limits<uint16_t>::max(), "Length of the reservation offset table must be less than MAX_UINT16"); uint16_t offsets[kReservationOffsetTableLength] = {}; constexpr _ReservationOffsetTable() { for (uint16_t& offset : offsets) offset = kOffsetTagNotAllocated; } #if defined(PA_HAS_64_BITS_POINTERS) // One table per Pool. } reservation_offset_tables_[kNumPools]; #else // A single table for the entire 32-bit address space. } reservation_offset_table_; #endif }; #if defined(PA_HAS_64_BITS_POINTERS) ALWAYS_INLINE uint16_t* GetReservationOffsetTable(pool_handle handle) { PA_DCHECK(0 < handle && handle <= kNumPools); return ReservationOffsetTable::reservation_offset_tables_[handle - 1].offsets; } ALWAYS_INLINE const uint16_t* GetReservationOffsetTableEnd(pool_handle handle) { return GetReservationOffsetTable(handle) + ReservationOffsetTable::kReservationOffsetTableLength; } ALWAYS_INLINE uint16_t* GetReservationOffsetTable(uintptr_t address) { pool_handle handle = GetPool(address); return GetReservationOffsetTable(handle); } ALWAYS_INLINE const uint16_t* GetReservationOffsetTableEnd(uintptr_t address) { pool_handle handle = GetPool(address); return GetReservationOffsetTableEnd(handle); } ALWAYS_INLINE uint16_t* ReservationOffsetPointer(pool_handle pool, uintptr_t offset_in_pool) { size_t table_index = offset_in_pool >> kSuperPageShift; PA_DCHECK(table_index < ReservationOffsetTable::kReservationOffsetTableLength); return GetReservationOffsetTable(pool) + table_index; } #else ALWAYS_INLINE uint16_t* GetReservationOffsetTable(uintptr_t address) { return ReservationOffsetTable::reservation_offset_table_.offsets; } ALWAYS_INLINE const uint16_t* GetReservationOffsetTableEnd(uintptr_t address) { return ReservationOffsetTable::reservation_offset_table_.offsets + ReservationOffsetTable::kReservationOffsetTableLength; } #endif ALWAYS_INLINE uint16_t* ReservationOffsetPointer(uintptr_t address) { #if defined(PA_HAS_64_BITS_POINTERS) // In 64-bit mode, find the owning Pool and compute the offset from its base. pool_handle pool; address = memory::UnmaskPtr(address); uintptr_t offset; std::tie(pool, offset) = GetPoolAndOffset(address); return ReservationOffsetPointer(pool, offset); #else size_t table_index = address >> kSuperPageShift; PA_DCHECK(table_index < ReservationOffsetTable::kReservationOffsetTableLength); return GetReservationOffsetTable(address) + table_index; #endif } ALWAYS_INLINE uintptr_t ComputeReservationStart(uintptr_t address, uint16_t* offset_ptr) { return (address & kSuperPageBaseMask) - (static_cast<size_t>(*offset_ptr) << kSuperPageShift); } // If the given address doesn't point to direct-map allocated memory, // returns 0. ALWAYS_INLINE uintptr_t GetDirectMapReservationStart(uintptr_t address) { #if DCHECK_IS_ON() bool is_in_brp_pool = IsManagedByPartitionAllocBRPPool(address); bool is_in_regular_pool = IsManagedByPartitionAllocRegularPool(address); // When USE_BACKUP_REF_PTR is off, BRP pool isn't used. #if !BUILDFLAG(USE_BACKUP_REF_PTR) PA_DCHECK(!is_in_brp_pool); #endif #endif // DCHECK_IS_ON() uint16_t* offset_ptr = ReservationOffsetPointer(address); PA_DCHECK(*offset_ptr != kOffsetTagNotAllocated); if (*offset_ptr == kOffsetTagNormalBuckets) return 0; uintptr_t reservation_start = ComputeReservationStart(address, offset_ptr); #if DCHECK_IS_ON() // Make sure the reservation start is in the same pool as |address|. // In the 32-bit mode, the beginning of a reservation may be excluded from the // BRP pool, so shift the pointer. The other pools don't have this logic. PA_DCHECK(is_in_brp_pool == IsManagedByPartitionAllocBRPPool( reservation_start #if !defined(PA_HAS_64_BITS_POINTERS) + AddressPoolManagerBitmap::kBytesPer1BitOfBRPPoolBitmap * AddressPoolManagerBitmap::kGuardOffsetOfBRPPoolBitmap #endif // !defined(PA_HAS_64_BITS_POINTERS) )); PA_DCHECK(is_in_regular_pool == IsManagedByPartitionAllocRegularPool(reservation_start)); PA_DCHECK(*ReservationOffsetPointer(reservation_start) == 0); #endif // DCHECK_IS_ON() return reservation_start; } #if defined(PA_HAS_64_BITS_POINTERS) // If the given address doesn't point to direct-map allocated memory, // returns 0. // This variant has better performance than the regular one on 64-bit builds if // the Pool that an allocation belongs to is known. ALWAYS_INLINE uintptr_t GetDirectMapReservationStart(uintptr_t address, pool_handle pool, uintptr_t offset_in_pool) { PA_DCHECK(AddressPoolManager::GetInstance()->GetPoolBaseAddress(pool) + offset_in_pool == address); uint16_t* offset_ptr = ReservationOffsetPointer(pool, offset_in_pool); PA_DCHECK(*offset_ptr != kOffsetTagNotAllocated); if (*offset_ptr == kOffsetTagNormalBuckets) return 0; uintptr_t reservation_start = ComputeReservationStart(address, offset_ptr); PA_DCHECK(*ReservationOffsetPointer(reservation_start) == 0); return reservation_start; } #endif // defined(PA_HAS_64_BITS_POINTERS) // Returns true if |address| is the beginning of the first super page of a // reservation, i.e. either a normal bucket super page, or the first super page // of direct map. // |address| must belong to an allocated super page. ALWAYS_INLINE bool IsReservationStart(uintptr_t address) { uint16_t* offset_ptr = ReservationOffsetPointer(address); PA_DCHECK(*offset_ptr != kOffsetTagNotAllocated); return ((*offset_ptr == kOffsetTagNormalBuckets) || (*offset_ptr == 0)) && (address % kSuperPageSize == 0); } // Returns true if |address| belongs to a normal bucket super page. ALWAYS_INLINE bool IsManagedByNormalBuckets(uintptr_t address) { uint16_t* offset_ptr = ReservationOffsetPointer(address); return *offset_ptr == kOffsetTagNormalBuckets; } // Returns true if |address| belongs to a direct map region. ALWAYS_INLINE bool IsManagedByDirectMap(uintptr_t address) { uint16_t* offset_ptr = ReservationOffsetPointer(address); return *offset_ptr != kOffsetTagNormalBuckets && *offset_ptr != kOffsetTagNotAllocated; } // Returns true if |address| belongs to a normal bucket super page or a direct // map region, i.e. belongs to an allocated super page. ALWAYS_INLINE bool IsManagedByNormalBucketsOrDirectMap(uintptr_t address) { uint16_t* offset_ptr = ReservationOffsetPointer(address); return *offset_ptr != kOffsetTagNotAllocated; } } // namespace internal } // namespace base #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_RESERVATION_OFFSET_TABLE_H_
Java
package net.jloop.rejoice; import net.jloop.rejoice.types.Symbol; import net.jloop.rejoice.types.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class MacroHelper { public static List<Value> collect(Env env, Iterator<Value> input, Symbol terminator) { List<Value> output = new ArrayList<>(); while (true) { if (!input.hasNext()) { throw new RuntimeError("MACRO", "Input stream ended before finding the terminating symbol '" + terminator.print() + "'"); } Value next = input.next(); if (next instanceof Symbol) { if (next.equals(terminator)) { return output; } Function function = env.lookup((Symbol) next); if (function instanceof Macro) { env.trace().push((Symbol) next); Iterator<Value> values = ((Macro) function).call(env, input); while (values.hasNext()) { output.add(values.next()); } env.trace().pop(); } else { output.add(next); } } else { output.add(next); } } } @SuppressWarnings("unchecked") public static <T extends Value> T match(Iterator<Value> input, Type type) { if (!input.hasNext()) { throw new RuntimeError("MACRO", "Unexpected EOF when attempting to match " + type.print()); } Value next = input.next(); if (type == next.type()) { return (T) next; } else { throw new RuntimeError("MACRO", "Expecting to match " + type.print() + ", but found " + next.type().print() + " with value '" + next.print() + "'"); } } public static void match(Iterator<Value> input, Symbol symbol) { if (!input.hasNext()) { throw new RuntimeError("MACRO", "Unexpected EOF when attempting to match ^symbol '" + symbol.print() + "'"); } Value next = input.next(); if (!next.equals(symbol)) { throw new RuntimeError("MACRO", "Expecting to match symbol '" + symbol.print() + "' , but found " + next.type().print() + " with value '" + next.print() + "'"); } } }
Java
import React from "react"; import { Text, View } from "react-native"; import { defaultProps, propTypes } from "./caption-prop-types"; import styles from "./styles"; const renderCredits = (style, credits) => { if (!credits || credits === "") { return null; } return ( <Text style={[styles.text, styles.credits, style.text, style.credits]}> {credits.toUpperCase()} </Text> ); }; const renderText = (style, text) => { if (!text || text === "") { return null; } return <Text style={[styles.text, style.text, style.caption]}>{text}</Text>; }; const Caption = ({ children, credits, style, text }) => ( <View> {children} <View style={[styles.container, style.container]}> {renderText(style, text)} {renderCredits(style, credits)} </View> </View> ); Caption.propTypes = propTypes; Caption.defaultProps = defaultProps; export default Caption; export { default as CentredCaption } from "./centred-caption";
Java
# clojure-stemmer A Clojure version of the [porter stemming](http://tartarus.org/martin/PorterStemmer/). Use the ruby version [here](https://github.com/raypereda/stemmify/blob/master/lib/stemmify.rb) to do the contrast test. This is an open source program, you can copy it, modified it or redistribute it, but must comply with the new BSD licence. ## Usage With leiningen, you should add the following in you `project.clj`: ```clojure [clojure-stemmer "0.1.0"] ``` With maven, you should add the following configuration to you `pom.xml`: ```xml <dependency> <groupId>clojure-stemmer</groupId> <artifactId>clojure-stemmer</artifactId> <version>0.1.0</version> </dependency> ``` After you start the clojure repl with command `lein repl`, you can do as following to use it: ```clojure user=> (use '[clojure-stemmer.porter.stemmer]) nil user=> (stemming "chinese") "chines" user=> (stemming "feeds") "feed" user=> (stemming "reeds") "reed" user=> (stemming "saying") "sai" ``` You can also run the all test, if you use the lein to manager clojure project, just by typing `lein test` under the project root directory. Running result is something like : ```shell ➜ clojure-stemmer git:(master) ✗ lein test lein test clojure-stemmer.core-test Ran 10000 tests containing 10000 assertions. 0 failures, 0 errors. ➜ clojure-stemmer git:(master) ✗ ``` The code was tested under Clojure version 1.4.0 and 1.5.1 and 1.6.0. ## License Copyright © 2013-2015 m00nlight Distributed under the new BSD License.
Java
<h1>Header</h1> <p>Now, let's try something <em>inline</em>, to see if it works</p> <p>Blah blah blah <a href="http://www.slashdot.org">http://www.slashdot.org</a></p> <ul> <li>Basic list</li> <li>Basic list 2</li> </ul> <p>addss</p> <ul> <li>Lazy list</li> </ul> <p>An <a href="http://example.com" title="Title">example</a> (oops)</p> <p>Now, let's use a footnote[^1]. Not bad, eh? Let's continue.</p> <p>[^1]: Here is the text of the footnote continued on several lines. some more of the footnote, etc.</p> <pre><code>Actually, another paragraph too. </code></pre> <p>And then there is a little bit of text.</p>
Java
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\db; /** * SchemaBuilderTrait contains shortcut methods to create instances of [[ColumnSchemaBuilder]]. * * These can be used in database migrations to define database schema types using a PHP interface. * This is useful to define a schema in a DBMS independent way so that the application may run on * different DBMS the same way. * * For example you may use the following code inside your migration files: * * ```php * $this->createTable('example_table', [ * 'id' => $this->primaryKey(), * 'name' => $this->string(64)->notNull(), * 'type' => $this->integer()->notNull()->defaultValue(10), * 'description' => $this->text(), * 'rule_name' => $this->string(64), * 'data' => $this->text(), * 'CreatedDateTime' => $this->datetime()->notNull(), * 'LastModifiedDateTime' => $this->datetime(), * ]); * ``` * * @author Vasenin Matvey <vaseninm@gmail.com> * @since 2.0.6 */ trait SchemaBuilderTrait { /** * @return Connection the database connection to be used for schema building. */ protected abstract function getDb(); /** * Creates a primary key column. * @param integer $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function primaryKey($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_PK, $length); } /** * Creates a big primary key column. * @param integer $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function bigPrimaryKey($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BIGPK, $length); } /** * Creates a char column. * @param integer $length column size definition i.e. the maximum string length. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.8 */ public function char($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_CHAR, $length); } /** * Creates a string column. * @param integer $length column size definition i.e. the maximum string length. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function string($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_STRING, $length); } /** * Creates a text column. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function text() { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TEXT); } /** * Creates a smallint column. * @param integer $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function smallInteger($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_SMALLINT, $length); } /** * Creates an integer column. * @param integer $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function integer($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_INTEGER, $length); } /** * Creates a bigint column. * @param integer $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function bigInteger($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BIGINT, $length); } /** * Creates a float column. * @param integer $precision column value precision. First parameter passed to the column type, e.g. FLOAT(precision). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function float($precision = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_FLOAT, $precision); } /** * Creates a double column. * @param integer $precision column value precision. First parameter passed to the column type, e.g. DOUBLE(precision). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function double($precision = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DOUBLE, $precision); } /** * Creates a decimal column. * @param integer $precision column value precision, which is usually the total number of digits. * First parameter passed to the column type, e.g. DECIMAL(precision, scale). * This parameter will be ignored if not supported by the DBMS. * @param integer $scale column value scale, which is usually the number of digits after the decimal point. * Second parameter passed to the column type, e.g. DECIMAL(precision, scale). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function decimal($precision = null, $scale = null) { $length = []; if ($precision !== null) { $length[] = $precision; } if ($scale !== null) { $length[] = $scale; } return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DECIMAL, $length); } /** * Creates a datetime column. * @param integer $precision column value precision. First parameter passed to the column type, e.g. DATETIME(precision). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function dateTime($precision = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DATETIME, $precision); } /** * Creates a timestamp column. * @param integer $precision column value precision. First parameter passed to the column type, e.g. TIMESTAMP(precision). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function timestamp($precision = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TIMESTAMP, $precision); } /** * Creates a time column. * @param integer $precision column value precision. First parameter passed to the column type, e.g. TIME(precision). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function time($precision = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TIME, $precision); } /** * Creates a date column. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function date() { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DATE); } /** * Creates a binary column. * @param integer $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function binary($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BINARY, $length); } /** * Creates a boolean column. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function boolean() { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BOOLEAN); } /** * Creates a money column. * @param integer $precision column value precision, which is usually the total number of digits. * First parameter passed to the column type, e.g. DECIMAL(precision, scale). * This parameter will be ignored if not supported by the DBMS. * @param integer $scale column value scale, which is usually the number of digits after the decimal point. * Second parameter passed to the column type, e.g. DECIMAL(precision, scale). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 */ public function money($precision = null, $scale = null) { $length = []; if ($precision !== null) { $length[] = $precision; } if ($scale !== null) { $length[] = $scale; } return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_MONEY, $length); } }
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Document Info and Metadata - Zend Framework Manual</title> </head> <body> <table width="100%"> <tr valign="top"> <td width="85%"> <table width="100%"> <tr> <td width="25%" style="text-align: left;"> <a href="zend.pdf.interactive-features.html">Interactive Features</a> </td> <td width="50%" style="text-align: center;"> <div class="up"><span class="up"><a href="zend.pdf.html">Zend_Pdf</a></span><br /> <span class="home"><a href="manual.html">Programmer's Reference Guide</a></span></div> </td> <td width="25%" style="text-align: right;"> <div class="next" style="text-align: right; float: right;"><a href="zend.pdf.usage.html">Zend_Pdf module usage example</a></div> </td> </tr> </table> <hr /> <div id="zend.pdf.info" class="section"><div class="info"><h1 class="title">Document Info and Metadata</h1></div> <p class="para"> A <acronym class="acronym">PDF</acronym> document may include general information such as the document&#039;s title, author, and creation and modification dates. </p> <p class="para"> Historically this information is stored using special Info structure. This structure is available for read and writing as an associative array using <span class="property">properties</span> public property of <span class="classname">Zend_Pdf</span> objects: </p> <div class="programlisting php"><div class="phpcode"><div class="php" style="font-family: monospace;"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$pdf</span> = Zend_Pdf::<span style="color: #006600;">load</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$pdfPath</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><a href="http://www.php.net/echo"><span style="color: #000066;">echo</span></a> <span style="color: #0000ff;">$pdf</span>-&gt;<span style="color: #006600;">properties</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'Title'</span><span style="color: #66cc66;">&#93;</span> . <span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><a href="http://www.php.net/echo"><span style="color: #000066;">echo</span></a> <span style="color: #0000ff;">$pdf</span>-&gt;<span style="color: #006600;">properties</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'Author'</span><span style="color: #66cc66;">&#93;</span> . <span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$pdf</span>-&gt;<span style="color: #006600;">properties</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'Title'</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #ff0000;">'New Title.'</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$pdf</span>-&gt;<span style="color: #006600;">save</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$pdfPath</span><span style="color: #66cc66;">&#41;</span>;</div></li></ol></div></div></div> <p class="para"> The following keys are defined by <acronym class="acronym">PDF</acronym> v1.4 (Acrobat 5) standard: <ul class="itemizedlist"> <li class="listitem"> <p class="para"> <em class="emphasis">Title</em> - string, optional, the document&#039;s title. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">Author</em> - string, optional, the name of the person who created the document. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">Subject</em> - string, optional, the subject of the document. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">Keywords</em> - string, optional, keywords associated with the document. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">Creator</em> - string, optional, if the document was converted to <acronym class="acronym">PDF</acronym> from another format, the name of the application (for example, Adobe FrameMaker®) that created the original document from which it was converted. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">Producer</em> - string, optional, if the document was converted to <acronym class="acronym">PDF</acronym> from another format, the name of the application (for example, Acrobat Distiller) that converted it to <acronym class="acronym">PDF</acronym>.. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">CreationDate</em> - string, optional, the date and time the document was created, in the following form: &quot;D:YYYYMMDDHHmmSSOHH&#039;mm&#039;&quot;, where: <ul class="itemizedlist"> <li class="listitem"> <p class="para"> <em class="emphasis">YYYY</em> is the year. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">MM</em> is the month. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">DD</em> is the day (01–31). </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">HH</em> is the hour (00–23). </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">mm</em>is the minute (00–59). </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">SS</em> is the second (00–59). </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">O</em> is the relationship of local time to Universal Time (UT), denoted by one of the characters +, −, or Z (see below). </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">HH</em> followed by &#039; is the absolute value of the offset from UT in hours (00–23). </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">mm</em> followed by &#039; is the absolute value of the offset from UT in minutes (00–59). </p> </li> </ul> The apostrophe character (&#039;) after HH and mm is part of the syntax. All fields after the year are optional. (The prefix D:, although also optional, is strongly recommended.) The default values for MM and DD are both 01; all other numerical fields default to zero values. A plus sign (+) as the value of the O field signifies that local time is later than UT, a minus sign (−) that local time is earlier than UT, and the letter Z that local time is equal to UT. If no UT information is specified, the relationship of the specified time to UT is considered to be unknown. Whether or not the time zone is known, the rest of the date should be specified in local time. </p> <p class="para"> For example, December 23, 1998, at 7:52 PM, U.S. Pacific Standard Time, is represented by the string &quot;D:199812231952−08&#039;00&#039;&quot;. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">ModDate</em> - string, optional, the date and time the document was most recently modified, in the same form as <em class="emphasis">CreationDate</em>. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis">Trapped</em> - boolean, optional, indicates whether the document has been modified to include trapping information. <ul class="itemizedlist"> <li class="listitem"> <p class="para"> <em class="emphasis"><b><tt>TRUE</tt></b></em> - The document has been fully trapped; no further trapping is needed. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis"><b><tt>FALSE</tt></b></em> - The document has not yet been trapped; any desired trapping must still be done. </p> </li> <li class="listitem"> <p class="para"> <em class="emphasis"><b><tt>NULL</tt></b></em> - Either it is unknown whether the document has been trapped or it has been partly but not yet fully trapped; some additional trapping may still be needed. </p> </li> </ul> </p> </li> </ul> </p> <p class="para"> Since <acronym class="acronym">PDF</acronym> v 1.6 metadata can be stored in the special <acronym class="acronym">XML</acronym> document attached to the <acronym class="acronym">PDF</acronym> (XMP - <a href="http://www.adobe.com/products/xmp/" class="link external">&raquo; Extensible Metadata Platform</a>). </p> <p class="para"> This <acronym class="acronym">XML</acronym> document can be retrieved and attached to the PDF with <span class="methodname">Zend_Pdf::getMetadata()</span> and <span class="methodname">Zend_Pdf::setMetadata($metadata)</span> methods: </p> <div class="programlisting php"><div class="phpcode"><div class="php" style="font-family: monospace;"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$pdf</span> = Zend_Pdf::<span style="color: #006600;">load</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$pdfPath</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$metadata</span> = <span style="color: #0000ff;">$pdf</span>-&gt;<span style="color: #006600;">getMetadata</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$metadataDOM</span> = <span style="color: #000000; font-weight: bold;">new</span> DOMDocument<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$metadataDOM</span>-&gt;<span style="color: #006600;">loadXML</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$metadata</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$xpath</span> = <span style="color: #000000; font-weight: bold;">new</span> DOMXPath<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$metadataDOM</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$pdfPreffixNamespaceURI</span> = <span style="color: #0000ff;">$xpath</span>-&gt;<span style="color: #006600;">query</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'/rdf:RDF/rdf:Description'</span><span style="color: #66cc66;">&#41;</span></div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -&gt;<span style="color: #006600;">item</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span></div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -&gt;<span style="color: #006600;">lookupNamespaceURI</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'pdf'</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$xpath</span>-&gt;<span style="color: #006600;">registerNamespace</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'pdf'</span>, <span style="color: #0000ff;">$pdfPreffixNamespaceURI</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$titleNode</span> = <span style="color: #0000ff;">$xpath</span>-&gt;<span style="color: #006600;">query</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'/rdf:RDF/rdf:Description/pdf:Title'</span><span style="color: #66cc66;">&#41;</span>-&gt;<span style="color: #006600;">item</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$title</span> = <span style="color: #0000ff;">$titleNode</span>-&gt;<span style="color: #006600;">nodeValue</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">...</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$titleNode</span>-&gt;<span style="color: #006600;">nodeValue</span> = <span style="color: #ff0000;">'New title'</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$pdf</span>-&gt;<span style="color: #006600;">setMetadata</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$metadataDOM</span>-&gt;<span style="color: #006600;">saveXML</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #0000ff;">$pdf</span>-&gt;<span style="color: #006600;">save</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$pdfPath</span><span style="color: #66cc66;">&#41;</span>;</div></li></ol></div></div></div> <p class="para"> Common document properties are duplicated in the Info structure and Metadata document (if presented). It&#039;s user application responsibility now to keep them synchronized. </p> </div> <hr /> <table width="100%"> <tr> <td width="25%" style="text-align: left;"> <a href="zend.pdf.interactive-features.html">Interactive Features</a> </td> <td width="50%" style="text-align: center;"> <div class="up"><span class="up"><a href="zend.pdf.html">Zend_Pdf</a></span><br /> <span class="home"><a href="manual.html">Programmer's Reference Guide</a></span></div> </td> <td width="25%" style="text-align: right;"> <div class="next" style="text-align: right; float: right;"><a href="zend.pdf.usage.html">Zend_Pdf module usage example</a></div> </td> </tr> </table> </td> <td style="font-size: smaller;" width="15%"> <style type="text/css"> #leftbar { float: left; width: 186px; padding: 5px; font-size: smaller; } ul.toc { margin: 0px 5px 5px 5px; padding: 0px; } ul.toc li { font-size: 85%; margin: 1px 0 1px 1px; padding: 1px 0 1px 11px; list-style-type: none; background-repeat: no-repeat; background-position: center left; } ul.toc li.header { font-size: 115%; padding: 5px 0px 5px 11px; border-bottom: 1px solid #cccccc; margin-bottom: 5px; } ul.toc li.active { font-weight: bold; } ul.toc li a { text-decoration: none; } ul.toc li a:hover { text-decoration: underline; } </style> <ul class="toc"> <li class="header home"><a href="manual.html">Programmer's Reference Guide</a></li> <li class="header up"><a href="manual.html">Programmer's Reference Guide</a></li> <li class="header up"><a href="reference.html">Zend Framework Reference</a></li> <li class="header up"><a href="zend.pdf.html">Zend_Pdf</a></li> <li><a href="zend.pdf.introduction.html">简介</a></li> <li><a href="zend.pdf.create.html">生成和加载 PDF 文档</a></li> <li><a href="zend.pdf.save.html">保存修改到 PDF 文档</a></li> <li><a href="zend.pdf.pages.html">文档页面</a></li> <li><a href="zend.pdf.drawing.html">Drawing</a></li> <li><a href="zend.pdf.interactive-features.html">Interactive Features</a></li> <li class="active"><a href="zend.pdf.info.html">Document Info and Metadata</a></li> <li><a href="zend.pdf.usage.html">Zend_Pdf module usage example</a></li> </ul> </td> </tr> </table> </body> </html>
Java
import Control.Monad (when) import Distribution.Simple import System.Directory (doesFileExist) import System.Process (readProcess) import Data.ByteString.Char8 as BS gitVersion :: IO () gitVersion = do let filename = "app/Internal/Version.hs" versionSh = "./version.sh" hasVersionSh <- doesFileExist versionSh when hasVersionSh $ do ver <- fmap BS.pack $ readProcess "bash" [versionSh] "" let override = BS.writeFile filename ver e <- doesFileExist filename if e then do orig_ver <- BS.readFile filename when (ver /= orig_ver) $ do override else override main :: IO () main = gitVersion >> defaultMain
Java
module Vector where data Vec = V !Int !Int deriving (Show, Eq) instance Num Vec where V x1 y1 + V x2 y2 = V (x1+x2) (y1+y2) V x1 y1 - V x2 y2 = V (x1-x2) (y1-y2) V x1 y1 * V x2 y2 = V (x1*x2) (y1*y2) abs (V x y) = V (abs x) (abs y) signum (V x y) = V (signum x) (signum y) fromInteger x = V (fromInteger x) (fromInteger x)
Java
### # Copyright (c) 2005, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### from supybot.test import * class MyChannelLoggerTestCase(PluginTestCase): plugins = ('MyChannelLogger',) # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
Java
/** * Copyright (c) 2019, Łukasz Marcin Podkalicki <lpodkalicki@gmail.com> * ESP8266/005 * Blinky example using pure ESP8266 Non-OS SDK. */ #include "ets_sys.h" #include "osapi.h" #include "gpio.h" #include "os_type.h" #include "user_config.h" #define LED_PIN (2) static volatile os_timer_t blinky_timer; static void blinky_timer_handler(void *prv); void ICACHE_FLASH_ATTR user_init() { uint8_t value = 0; /* setup */ gpio_init(); // init gpio subsytem gpio_output_set(0, 0, (1 << LED_PIN), 0); // set LED pin as output with low state uart_div_modify(0, UART_CLK_FREQ / 115200); // set UART baudrate os_printf("\n\nSDK version:%s\n\n", system_get_sdk_version()); /* start timer (500ms) */ os_timer_setfn(&blinky_timer, (os_timer_func_t *)blinky_timer_handler, NULL); os_timer_arm(&blinky_timer, 500, 1); } void blinky_timer_handler(void *prv) { if (GPIO_REG_READ(GPIO_OUT_ADDRESS) & (1 << LED_PIN)) { gpio_output_set(0, (1 << LED_PIN), 0, 0); // LED off } else { gpio_output_set((1 << LED_PIN), 0, 0, 0); // LED on } }
Java
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /** Get all roles */ $authManager = Yii::$app->authManager; ?> <div class="user-assignment-form"> <?php $form = ActiveForm::begin(); ?> <?= Html::activeHiddenInput($formModel, 'userId')?> <label class="control-label"><?=$formModel->attributeLabels()['roles']?></label> <input type="hidden" name="AssignmentForm[roles]" value=""> <table class="table table-striped table-bordered detail-view"> <thead> <tr> <th style="width:1px"></th> <th style="width:150px">Name</th> <th>Description</th> </tr> <tbody> <?php foreach ($authManager->getRoles() as $role): ?> <tr> <?php $checked = true; if($formModel->roles==null||!is_array($formModel->roles)||count($formModel->roles)==0){ $checked = false; }else if(!in_array($role->name, $formModel->roles) ){ $checked = false; } ?> <td><input <?= $checked? "checked":"" ?> type="checkbox" name="AssignmentForm[roles][]" value="<?= $role->name?>"></td> <td><?= $role->name ?></td> <td><?= $role->description ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?php if (!Yii::$app->request->isAjax) { ?> <div class="form-group"> <?= Html::submitButton(Yii::t('rbac', 'Save'), ['class' => 'btn btn-success']) ?> </div> <?php } ?> <?php ActiveForm::end(); ?> </div>
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>Control.Lens.Internal.Getter</title><link href="ocean.css" rel="stylesheet" type="text/css" title="Ocean" /><script src="haddock-util.js" type="text/javascript"></script><script type="text/javascript">//<![CDATA[ window.onload = function () {pageLoad();}; //]]> </script></head><body id="mini"><div id="module-header"><p class="caption">Control.Lens.Internal.Getter</p></div><div id="interface"><div class="top"><p class="src"><a href="Control-Lens-Internal-Getter.html#v:noEffect" target="main">noEffect</a></p></div><div class="top"><p class="src"><span class="keyword">data</span> <a href="Control-Lens-Internal-Getter.html#t:AlongsideLeft" target="main">AlongsideLeft</a> f b a</p></div><div class="top"><p class="src"><span class="keyword">data</span> <a href="Control-Lens-Internal-Getter.html#t:AlongsideRight" target="main">AlongsideRight</a> f a b</p></div></div></body></html>
Java
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // IPC messages for resource loading. // // NOTE: All messages must send an |int request_id| as their first parameter. // Multiply-included message file, hence no include guard. #include "base/memory/shared_memory.h" #include "base/process/process.h" #include "content/common/content_param_traits_macros.h" #include "content/common/navigation_params.h" #include "content/common/resource_request_body.h" #include "content/common/service_worker/service_worker_types.h" #include "content/public/common/common_param_traits.h" #include "content/public/common/resource_response.h" #include "ipc/ipc_message_macros.h" #include "net/base/request_priority.h" #include "net/http/http_response_info.h" #include "net/url_request/redirect_info.h" #ifndef CONTENT_COMMON_RESOURCE_MESSAGES_H_ #define CONTENT_COMMON_RESOURCE_MESSAGES_H_ namespace net { struct LoadTimingInfo; } namespace content { struct ResourceDevToolsInfo; } namespace IPC { template <> struct ParamTraits<scoped_refptr<net::HttpResponseHeaders> > { typedef scoped_refptr<net::HttpResponseHeaders> param_type; static void Write(Message* m, const param_type& p); static bool Read(const Message* m, base::PickleIterator* iter, param_type* r); static void Log(const param_type& p, std::string* l); }; template <> struct CONTENT_EXPORT ParamTraits<storage::DataElement> { typedef storage::DataElement param_type; static void Write(Message* m, const param_type& p); static bool Read(const Message* m, base::PickleIterator* iter, param_type* r); static void Log(const param_type& p, std::string* l); }; template <> struct ParamTraits<scoped_refptr<content::ResourceDevToolsInfo> > { typedef scoped_refptr<content::ResourceDevToolsInfo> param_type; static void Write(Message* m, const param_type& p); static bool Read(const Message* m, base::PickleIterator* iter, param_type* r); static void Log(const param_type& p, std::string* l); }; template <> struct ParamTraits<net::LoadTimingInfo> { typedef net::LoadTimingInfo param_type; static void Write(Message* m, const param_type& p); static bool Read(const Message* m, base::PickleIterator* iter, param_type* r); static void Log(const param_type& p, std::string* l); }; template <> struct ParamTraits<scoped_refptr<content::ResourceRequestBody> > { typedef scoped_refptr<content::ResourceRequestBody> param_type; static void Write(Message* m, const param_type& p); static bool Read(const Message* m, base::PickleIterator* iter, param_type* r); static void Log(const param_type& p, std::string* l); }; } // namespace IPC #endif // CONTENT_COMMON_RESOURCE_MESSAGES_H_ #define IPC_MESSAGE_START ResourceMsgStart #undef IPC_MESSAGE_EXPORT #define IPC_MESSAGE_EXPORT CONTENT_EXPORT IPC_ENUM_TRAITS_MAX_VALUE( \ net::HttpResponseInfo::ConnectionInfo, \ net::HttpResponseInfo::NUM_OF_CONNECTION_INFOS - 1) IPC_ENUM_TRAITS_MAX_VALUE(content::FetchRequestMode, content::FETCH_REQUEST_MODE_LAST) IPC_ENUM_TRAITS_MAX_VALUE(content::FetchCredentialsMode, content::FETCH_CREDENTIALS_MODE_LAST) IPC_ENUM_TRAITS_MAX_VALUE(content::FetchRedirectMode, content::FetchRedirectMode::LAST) IPC_STRUCT_TRAITS_BEGIN(content::ResourceResponseHead) IPC_STRUCT_TRAITS_PARENT(content::ResourceResponseInfo) IPC_STRUCT_TRAITS_MEMBER(request_start) IPC_STRUCT_TRAITS_MEMBER(response_start) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::SyncLoadResult) IPC_STRUCT_TRAITS_PARENT(content::ResourceResponseHead) IPC_STRUCT_TRAITS_MEMBER(error_code) IPC_STRUCT_TRAITS_MEMBER(final_url) IPC_STRUCT_TRAITS_MEMBER(data) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::ResourceResponseInfo) IPC_STRUCT_TRAITS_MEMBER(request_time) IPC_STRUCT_TRAITS_MEMBER(response_time) IPC_STRUCT_TRAITS_MEMBER(headers) IPC_STRUCT_TRAITS_MEMBER(mime_type) IPC_STRUCT_TRAITS_MEMBER(charset) IPC_STRUCT_TRAITS_MEMBER(security_info) IPC_STRUCT_TRAITS_MEMBER(content_length) IPC_STRUCT_TRAITS_MEMBER(encoded_data_length) IPC_STRUCT_TRAITS_MEMBER(appcache_id) IPC_STRUCT_TRAITS_MEMBER(appcache_manifest_url) IPC_STRUCT_TRAITS_MEMBER(load_timing) IPC_STRUCT_TRAITS_MEMBER(devtools_info) IPC_STRUCT_TRAITS_MEMBER(download_file_path) IPC_STRUCT_TRAITS_MEMBER(was_fetched_via_spdy) IPC_STRUCT_TRAITS_MEMBER(was_npn_negotiated) IPC_STRUCT_TRAITS_MEMBER(was_alternate_protocol_available) IPC_STRUCT_TRAITS_MEMBER(connection_info) IPC_STRUCT_TRAITS_MEMBER(was_fetched_via_proxy) IPC_STRUCT_TRAITS_MEMBER(npn_negotiated_protocol) IPC_STRUCT_TRAITS_MEMBER(socket_address) IPC_STRUCT_TRAITS_MEMBER(was_fetched_via_service_worker) IPC_STRUCT_TRAITS_MEMBER(was_fallback_required_by_service_worker) IPC_STRUCT_TRAITS_MEMBER(original_url_via_service_worker) IPC_STRUCT_TRAITS_MEMBER(response_type_via_service_worker) IPC_STRUCT_TRAITS_MEMBER(service_worker_start_time) IPC_STRUCT_TRAITS_MEMBER(service_worker_ready_time) IPC_STRUCT_TRAITS_MEMBER(proxy_server) IPC_STRUCT_TRAITS_MEMBER(is_using_lofi) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(net::RedirectInfo) IPC_STRUCT_TRAITS_MEMBER(status_code) IPC_STRUCT_TRAITS_MEMBER(new_method) IPC_STRUCT_TRAITS_MEMBER(new_url) IPC_STRUCT_TRAITS_MEMBER(new_first_party_for_cookies) IPC_STRUCT_TRAITS_MEMBER(new_referrer) IPC_STRUCT_TRAITS_END() // Parameters for a resource request. IPC_STRUCT_BEGIN(ResourceHostMsg_Request) // The request method: GET, POST, etc. IPC_STRUCT_MEMBER(std::string, method) // The requested URL. IPC_STRUCT_MEMBER(GURL, url) // Usually the URL of the document in the top-level window, which may be // checked by the third-party cookie blocking policy. Leaving it empty may // lead to undesired cookie blocking. Third-party cookie blocking can be // bypassed by setting first_party_for_cookies = url, but this should ideally // only be done if there really is no way to determine the correct value. IPC_STRUCT_MEMBER(GURL, first_party_for_cookies) // The referrer to use (may be empty). IPC_STRUCT_MEMBER(GURL, referrer) // The referrer policy to use. IPC_STRUCT_MEMBER(blink::WebReferrerPolicy, referrer_policy) // The frame's visiblity state. IPC_STRUCT_MEMBER(blink::WebPageVisibilityState, visiblity_state) // Additional HTTP request headers. IPC_STRUCT_MEMBER(std::string, headers) // net::URLRequest load flags (0 by default). IPC_STRUCT_MEMBER(int, load_flags) // Process ID from which this request originated, or zero if it originated // in the renderer itself. // If kDirectNPAPIRequests isn't specified, then plugin requests get routed // through the renderer and and this holds the pid of the plugin process. // Otherwise this holds the render_process_id of the view that has the plugin. IPC_STRUCT_MEMBER(int, origin_pid) // What this resource load is for (main frame, sub-frame, sub-resource, // object). IPC_STRUCT_MEMBER(content::ResourceType, resource_type) // The priority of this request. IPC_STRUCT_MEMBER(net::RequestPriority, priority) // Used by plugin->browser requests to get the correct net::URLRequestContext. IPC_STRUCT_MEMBER(uint32, request_context) // Indicates which frame (or worker context) the request is being loaded into, // or kAppCacheNoHostId. IPC_STRUCT_MEMBER(int, appcache_host_id) // True if corresponding AppCache group should be resetted. IPC_STRUCT_MEMBER(bool, should_reset_appcache) // Indicates which frame (or worker context) the request is being loaded into, // or kInvalidServiceWorkerProviderId. IPC_STRUCT_MEMBER(int, service_worker_provider_id) // True if the request should not be handled by the ServiceWorker. IPC_STRUCT_MEMBER(bool, skip_service_worker) // The request mode passed to the ServiceWorker. IPC_STRUCT_MEMBER(content::FetchRequestMode, fetch_request_mode) // The credentials mode passed to the ServiceWorker. IPC_STRUCT_MEMBER(content::FetchCredentialsMode, fetch_credentials_mode) // The redirect mode used in Fetch API. IPC_STRUCT_MEMBER(content::FetchRedirectMode, fetch_redirect_mode) // The request context passed to the ServiceWorker. IPC_STRUCT_MEMBER(content::RequestContextType, fetch_request_context_type) // The frame type passed to the ServiceWorker. IPC_STRUCT_MEMBER(content::RequestContextFrameType, fetch_frame_type) // Optional resource request body (may be null). IPC_STRUCT_MEMBER(scoped_refptr<content::ResourceRequestBody>, request_body) IPC_STRUCT_MEMBER(bool, download_to_file) // True if the request was user initiated. IPC_STRUCT_MEMBER(bool, has_user_gesture) // True if load timing data should be collected for request. IPC_STRUCT_MEMBER(bool, enable_load_timing) // True if upload progress should be available for request. IPC_STRUCT_MEMBER(bool, enable_upload_progress) // True if login prompts for this request should be supressed. IPC_STRUCT_MEMBER(bool, do_not_prompt_for_login) // The routing id of the RenderFrame. IPC_STRUCT_MEMBER(int, render_frame_id) // True if |frame_id| is the main frame of a RenderView. IPC_STRUCT_MEMBER(bool, is_main_frame) // True if |parent_render_frame_id| is the main frame of a RenderView. IPC_STRUCT_MEMBER(bool, parent_is_main_frame) // Identifies the parent frame of the frame that sent the request. // -1 if unknown / invalid. IPC_STRUCT_MEMBER(int, parent_render_frame_id) IPC_STRUCT_MEMBER(ui::PageTransition, transition_type) // For navigations, whether this navigation should replace the current session // history entry on commit. IPC_STRUCT_MEMBER(bool, should_replace_current_entry) // The following two members identify a previous request that has been // created before this navigation has been transferred to a new render view. // This serves the purpose of recycling the old request. // Unless this refers to a transferred navigation, these values are -1 and -1. IPC_STRUCT_MEMBER(int, transferred_request_child_id) IPC_STRUCT_MEMBER(int, transferred_request_request_id) // Whether or not we should allow the URL to download. IPC_STRUCT_MEMBER(bool, allow_download) // Whether to intercept headers to pass back to the renderer. IPC_STRUCT_MEMBER(bool, report_raw_headers) // Whether or not to request a LoFi version of the resource or let the browser // decide. IPC_STRUCT_MEMBER(content::LoFiState, lofi_state) IPC_STRUCT_END() // Parameters for a ResourceMsg_RequestComplete IPC_STRUCT_BEGIN(ResourceMsg_RequestCompleteData) // The error code. IPC_STRUCT_MEMBER(int, error_code) // Was ignored by the request handler. IPC_STRUCT_MEMBER(bool, was_ignored_by_handler) // A copy of the data requested exists in the cache. IPC_STRUCT_MEMBER(bool, exists_in_cache) // Serialized security info; see content/common/ssl_status_serialization.h. IPC_STRUCT_MEMBER(std::string, security_info) // Time the request completed. IPC_STRUCT_MEMBER(base::TimeTicks, completion_time) // Total amount of data received from the network. IPC_STRUCT_MEMBER(int64, encoded_data_length) IPC_STRUCT_END() // Resource messages sent from the browser to the renderer. // Sent when the headers are available for a resource request. IPC_MESSAGE_CONTROL2(ResourceMsg_ReceivedResponse, int /* request_id */, content::ResourceResponseHead) // Sent when cached metadata from a resource request is ready. IPC_MESSAGE_CONTROL2(ResourceMsg_ReceivedCachedMetadata, int /* request_id */, std::vector<char> /* data */) // Sent as upload progress is being made. IPC_MESSAGE_CONTROL3(ResourceMsg_UploadProgress, int /* request_id */, int64 /* position */, int64 /* size */) // Sent when the request has been redirected. The receiver is expected to // respond with either a FollowRedirect message (if the redirect is to be // followed) or a CancelRequest message (if it should not be followed). IPC_MESSAGE_CONTROL3(ResourceMsg_ReceivedRedirect, int /* request_id */, net::RedirectInfo /* redirect_info */, content::ResourceResponseHead) // Sent to set the shared memory buffer to be used to transmit response data to // the renderer. Subsequent DataReceived messages refer to byte ranges in the // shared memory buffer. The shared memory buffer should be retained by the // renderer until the resource request completes. // // NOTE: The shared memory handle should already be mapped into the process // that receives this message. // // TODO(darin): The |renderer_pid| parameter is just a temporary parameter, // added to help in debugging crbug/160401. // IPC_MESSAGE_CONTROL4(ResourceMsg_SetDataBuffer, int /* request_id */, base::SharedMemoryHandle /* shm_handle */, int /* shm_size */, base::ProcessId /* renderer_pid */) // Sent when some data from a resource request is ready. The data offset and // length specify a byte range into the shared memory buffer provided by the // SetDataBuffer message. IPC_MESSAGE_CONTROL4(ResourceMsg_DataReceived, int /* request_id */, int /* data_offset */, int /* data_length */, int /* encoded_data_length */) // Sent when some data from a resource request has been downloaded to // file. This is only called in the 'download_to_file' case and replaces // ResourceMsg_DataReceived in the call sequence in that case. IPC_MESSAGE_CONTROL3(ResourceMsg_DataDownloaded, int /* request_id */, int /* data_len */, int /* encoded_data_length */) // Sent when the request has been completed. IPC_MESSAGE_CONTROL2(ResourceMsg_RequestComplete, int /* request_id */, ResourceMsg_RequestCompleteData) // Resource messages sent from the renderer to the browser. // Makes a resource request via the browser. IPC_MESSAGE_CONTROL3(ResourceHostMsg_RequestResource, int /* routing_id */, int /* request_id */, ResourceHostMsg_Request) // Cancels a resource request with the ID given as the parameter. IPC_MESSAGE_CONTROL1(ResourceHostMsg_CancelRequest, int /* request_id */) // Follows a redirect that occured for the resource request with the ID given // as the parameter. IPC_MESSAGE_CONTROL1(ResourceHostMsg_FollowRedirect, int /* request_id */) // Makes a synchronous resource request via the browser. IPC_SYNC_MESSAGE_ROUTED2_1(ResourceHostMsg_SyncLoad, int /* request_id */, ResourceHostMsg_Request, content::SyncLoadResult) // Sent when the renderer process is done processing a DataReceived // message. IPC_MESSAGE_CONTROL1(ResourceHostMsg_DataReceived_ACK, int /* request_id */) // Sent when the renderer has processed a DataDownloaded message. IPC_MESSAGE_CONTROL1(ResourceHostMsg_DataDownloaded_ACK, int /* request_id */) // Sent by the renderer process to acknowledge receipt of a // UploadProgress message. IPC_MESSAGE_CONTROL1(ResourceHostMsg_UploadProgress_ACK, int /* request_id */) // Sent when the renderer process deletes a resource loader. IPC_MESSAGE_CONTROL1(ResourceHostMsg_ReleaseDownloadedFile, int /* request_id */) // Sent by the renderer when a resource request changes priority. IPC_MESSAGE_CONTROL3(ResourceHostMsg_DidChangePriority, int /* request_id */, net::RequestPriority, int /* intra_priority_value */)
Java