code
stringlengths
4
1.01M
language
stringclasses
2 values
/* * Template Name: devAid - Responsive Website Template for developers * Version: 1.1 * Author: Xiaoying Riley * Twitter: @3rdwave_themes * License: Creative Commons Attribution 3.0 License * Website: http://themes.3rdwavemedia.com/ */ /* style-4.css */ /* ======= Base ======= */ body { font-family: 'Lato', arial, sans-serif; color: #444; font-size: 16px; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } h1, h2, h3, h4, h5, h6 { font-family: 'Montserrat', sans-serif; font-weight: 700; color: #50c8c9; } a { color: #50c8c9; -webkit-transition: all 0.4s ease-in-out; -moz-transition: all 0.4s ease-in-out; -ms-transition: all 0.4s ease-in-out; -o-transition: all 0.4s ease-in-out; } a:hover { text-decoration: underline; color: #36afb0; } .btn, a.btn { -webkit-transition: all 0.4s ease-in-out; -moz-transition: all 0.4s ease-in-out; -ms-transition: all 0.4s ease-in-out; -o-transition: all 0.4s ease-in-out; font-family: 'Montserrat', arial, sans-serif; padding: 8px 16px; font-weight: bold; } .btn .fa, a.btn .fa { margin-right: 5px; } .btn:focus, a.btn:focus { color: #fff; } a.btn-cta-primary, .btn-cta-primary { background: #1e6162; border: 1px solid #1e6162; color: #fff; font-weight: 600; text-transform: uppercase; } a.btn-cta-primary:hover, .btn-cta-primary:hover { background: #184e4e; border: 1px solid #184e4e; color: #fff; } a.btn-cta-secondary, .btn-cta-secondary { background: #ffbe57; border: 1px solid #ffbe57; color: #fff; font-weight: 600; text-transform: uppercase; } a.btn-cta-secondary:hover, .btn-cta-secondary:hover { background: #ffb43e; border: 1px solid #ffb43e; color: #fff; } .text-highlight { color: #1e6162; } .offset-header { padding-top: 90px; } pre code { font-size: 16px; } /* ======= Header ======= */ .header { padding: 10px 0; background: #50c8c9; color: #fff; position: fixed; width: 100%; } .header.navbar-fixed-top { background: #fff; z-index: 9999; -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.4); -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.4); box-shadow: 0 0 4px rgba(0, 0, 0, 0.4); } .header.navbar-fixed-top .logo a { color: #50c8c9; } .header.navbar-fixed-top .main-nav .nav .nav-item a { color: #666; } .header .logo { margin: 0; font-size: 26px; padding-top: 10px; } .header .logo a { color: #fff; } .header .logo a:hover { text-decoration: none; } .header .main-nav button { background: #1e6162; color: #fff !important; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } .header .main-nav button:focus { outline: none; } .header .main-nav button .icon-bar { background-color: #fff; } .header .main-nav .navbar-collapse { padding: 0; } .header .main-nav .nav .nav-item { font-weight: normal; margin-right: 30px; font-family: 'Montserrat', sans-serif; } .header .main-nav .nav .nav-item.active a { color: #50c8c9; background: none; } .header .main-nav .nav .nav-item a { color: #2a8889; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none; font-size: 14px; padding: 15px 10px; } .header .main-nav .nav .nav-item a:hover { color: #1e6162; background: none; } .header .main-nav .nav .nav-item a:focus { outline: none; background: none; } .header .main-nav .nav .nav-item a:active { outline: none; background: none; } .header .main-nav .nav .nav-item.active { color: #50c8c9; } .header .main-nav .nav .nav-item.last { margin-right: 0; } /* ======= Promo Section ======= */ .promo { background: #50c8c9; color: #fff; padding-top: 150px; } .promo .title { font-size: 98px; color: #1e6162; margin-top: 0; } .promo .title .highlight { color: #ffbe57; } .promo .intro { font-size: 28px; max-width: 680px; margin: 0 auto; margin-bottom: 30px; } .promo .btns .btn { margin-right: 15px; font-size: 18px; padding: 8px 30px; } .promo .meta { margin-top: 120px; margin-bottom: 30px; color: #2a8889; } .promo .meta li { margin-right: 15px; } .promo .meta a { color: #2a8889; } .promo .meta a:hover { color: #1e6162; } .promo .social-media { background: #309b9c; padding: 10px 0; margin: 0 auto; } .promo .social-media li { margin-top: 15px; } .promo .social-media li.facebook-like { margin-top: 0; position: relative; top: -5px; } /* ======= Page Section ======= */ .about { padding: 80px 0; background: #f5f5f5; } .about .title { color: #1e6162; margin-top: 0; margin-bottom: 60px; } .about .intro { max-width: 800px; margin: 0 auto; margin-bottom: 60px; } .about .item { position: relative; margin-bottom: 30px; } .about .item .icon-holder { position: absolute; left: 30px; top: 0; } .about .item .icon-holder .fa { font-size: 24px; color: #1e6162; } .about .item .content { padding-left: 60px; } .about .item .content .sub-title { margin-top: 0; color: #1e6162; font-size: 18px; } /* ======= Features Section ======= */ .features { padding: 80px 0; background: #50c8c9; color: #fff; } .features .title { color: #1e6162; margin-top: 0; margin-bottom: 30px; } .features a { color: #1e6162; } .features a:hover { color: #123b3b; } .features .feature-list li { margin-bottom: 10px; color: #1e6162; } .features .feature-list li .fa { margin-right: 5px; color: #fff; } /* ======= Docs Section ======= */ .docs { padding: 80px 0; background: #f5f5f5; } .docs .title { color: #1e6162; margin-top: 0; margin-bottom: 30px; } .docs .docs-inner { max-width: 800px; background: #fff; padding: 30px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; margin: 0 auto; } .docs .block { margin-bottom: 60px; } .docs .code-block { margin: 30px inherit; } .docs .code-block pre[class*="language-"] { -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } /* ======= License Section ======= */ .license { padding: 80px 0; background: #f5f5f5; } .license .title { margin-top: 0; margin-bottom: 60px; color: #1e6162; } .license .license-inner { max-width: 800px; background: #fff; padding: 30px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; margin: 0 auto; } .license .info { max-width: 760px; margin: 0 auto; } .license .cta-container { max-width: 540px; margin: 0 auto; margin-top: 60px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } .license .cta-container .speech-bubble { background: #ecf9f9; color: #1e6162; padding: 30px; margin-bottom: 30px; position: relative; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } .license .cta-container .speech-bubble:after { position: absolute; left: 50%; bottom: -10px; margin-left: -10px; content: ""; display: inline-block; width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-top: 10px solid #ecf9f9; } .license .cta-container .icon-holder { margin-bottom: 15px; } .license .cta-container .icon-holder .fa { font-size: 56px; } .license .cta-container .intro { margin-bottom: 30px; } /* ======= Contact Section ======= */ .contact { padding: 80px 0; background: #50c8c9; color: #fff; } .contact .contact-inner { max-width: 760px; margin: 0 auto; } .contact .title { color: #1e6162; margin-top: 0; margin-bottom: 30px; } .contact .intro { margin-bottom: 60px; } .contact a { color: #1e6162; } .contact a:hover { color: #123b3b; } .contact .author-message { position: relative; margin-bottom: 60px; } .contact .author-message .profile { position: absolute; left: 30px; top: 15px; width: 100px; height: 100px; } .contact .author-message .profile img { -webkit-border-radius: 50%; -moz-border-radius: 50%; -ms-border-radius: 50%; -o-border-radius: 50%; border-radius: 50%; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } .contact .author-message .speech-bubble { margin-left: 155px; background: #44c4c5; color: #1e6162; padding: 30px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; position: relative; } .contact .author-message .speech-bubble .sub-title { color: #1e6162; font-size: 16px; margin-top: 0; margin-bottom: 30px; } .contact .author-message .speech-bubble a { color: #fff; } .contact .author-message .speech-bubble:after { position: absolute; left: -10px; top: 60px; content: ""; display: inline-block; width: 0; height: 0; border-top: 10px solid transparent; border-bottom: 10px solid transparent; border-right: 10px solid #44c4c5; } .contact .author-message .speech-bubble .source { margin-top: 30px; } .contact .author-message .speech-bubble .source a { color: #1e6162; } .contact .author-message .speech-bubble .source .title { color: #309b9c; } .contact .info .sub-title { color: #36afb0; margin-bottom: 30px; margin-top: 0; } .contact .social-icons { list-style: none; padding: 10px 0; margin-bottom: 0; display: inline-block; margin: 0 auto; } .contact .social-icons li { float: left; } .contact .social-icons li.last { margin-right: 0; } .contact .social-icons a { display: inline-block; background: #309b9c; width: 48px; height: 48px; text-align: center; padding-top: 12px; -webkit-border-radius: 50%; -moz-border-radius: 50%; -ms-border-radius: 50%; -o-border-radius: 50%; border-radius: 50%; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; margin-right: 8px; float: left; } .contact .social-icons a:hover { background: #ffaa24; } .contact .social-icons a .fa { color: #fff; } .contact .social-icons a .fa:before { font-size: 26px; text-align: center; padding: 0; } /* ======= Footer ======= */ .footer { padding: 15px 0; background: #123b3b; color: #fff; } .footer .copyright { -webkit-opacity: 0.8; -moz-opacity: 0.8; opacity: 0.8; } .footer .fa-heart { color: #fb866a; } /* Extra small devices (phones, less than 768px) */ @media (max-width: 767px) { .header .main-nav button { margin-right: 0; } .header .main-nav .navbar-collapse { padding-left: 15px; padding-right: 15px; } .promo .btns .btn { margin-right: 0; clear: both; display: block; margin-bottom: 30px; } .promo .title { font-size: 66px; } .promo .meta { margin-top: 60px; } .promo .meta li { float: none; display: block; margin-bottom: 5px; } .contact .author-message { text-align: center; } .contact .author-message .profile { position: static; margin: 0 auto; margin-bottom: 30px; } .contact .author-message .speech-bubble { margin-left: 0; } .contact .author-message .speech-bubble:after { display: none; } .contact .social-icons a { width: 36px; height: 36px; padding-top: 7px; margin-right: 2px; } .contact .social-icons a .fa:before { font-size: 18px; } } /* Small devices (tablets, 768px and up) */ /* Medium devices (desktops, 992px and up) */ /* Large devices (large desktops, 1200px and up) */
Java
using UnityEngine; using System.Collections; public class Intro : MonoBehaviour { public GameObject martin; public GameObject mrsStrump; public GameObject strumpFire; public Sprite sadMartin, slinkton, police, candles, houses, strumps; public Camera cam; // Use this for initialization void Start () { strumpFire.GetComponent<SpriteRenderer>().enabled = false; } // Update is called once per frame void Update () { if (Input.GetKeyDown ("space") || Input.GetMouseButtonDown (0)) Application.LoadLevel ("game"); float time = Time.timeSinceLevelLoad; if (time > 4.0F && time < 4.5F) { mrsStrump.transform.position = new Vector3(-13, 0, -5); } if (time > 4.5F && time < 4.6F) { mrsStrump.transform.position = new Vector3(-13, -1, -5); } if (time > 17.2F && time < 17.7F) { martin.transform.position = new Vector3(-11, 0, -5); } if (time > 17.7F && time < 17.8F) { martin.transform.position = new Vector3(-11, -1, -5); } if (time > 18.5F && time < 18.6F) { cam.transform.position = new Vector3(-4, 0, -10); } if (time > 18.6F && time < 18.7F) { martin.GetComponent<Rigidbody2D>().velocity = new Vector2(11, 0); martin.GetComponent<SpriteRenderer>().sprite = sadMartin; } if (time > 20.0F && time < 20.1F) { martin.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0); martin.transform.position = new Vector3(5.8F, -2, -5); } if (time > 33.0F && time < 33.1F) { strumpFire.GetComponent<SpriteRenderer>().enabled = true; } if (time > 35.0F && time < 35.1F) { strumpFire.GetComponent<SpriteRenderer>().sprite = slinkton; } if (time > 37.7F && time < 37.8F) { strumpFire.GetComponent<SpriteRenderer>().sprite = police; } if (time > 39.2F && time < 39.3F) { strumpFire.GetComponent<SpriteRenderer>().sprite = candles; } if (time > 41.0F && time < 41.1F) { strumpFire.GetComponent<SpriteRenderer>().sprite = houses; } if (time > 42.5F && time < 42.6F) { strumpFire.GetComponent<SpriteRenderer>().sprite = strumps; } if (time > 43.5F && time < 43.6F) { strumpFire.GetComponent<SpriteRenderer>().enabled = false; } if (time > 51.5F) Application.LoadLevel ("game"); } }
Java
module Parsers module Edi class IncomingTransaction attr_reader :errors def self.from_etf(etf, i_cache) incoming_transaction = new(etf) subscriber_policy_loop = etf.subscriber_loop.policy_loops.first find_policy = FindPolicy.new(incoming_transaction) policy = find_policy.by_subkeys({ :eg_id => subscriber_policy_loop.eg_id, :hios_plan_id => subscriber_policy_loop.hios_id }) person_loop_validator = PersonLoopValidator.new etf.people.each do |person_loop| person_loop_validator.validate(person_loop, incoming_transaction, policy) end policy_loop_validator = PolicyLoopValidator.new policy_loop_validator.validate(subscriber_policy_loop, incoming_transaction) incoming_transaction end def initialize(etf) @etf = etf @errors = [] end def valid? @errors.empty? end def import return unless valid? is_policy_term = false is_policy_cancel = false is_non_payment = false old_npt_flag = @policy.term_for_np @etf.people.each do |person_loop| begin enrollee = @policy.enrollee_for_member_id(person_loop.member_id) policy_loop = person_loop.policy_loops.first enrollee.c_id = person_loop.carrier_member_id enrollee.cp_id = policy_loop.id if(!@etf.is_shop? && policy_loop.action == :stop ) enrollee.coverage_status = 'inactive' enrollee.coverage_end = policy_loop.coverage_end if enrollee.subscriber? is_non_payment = person_loop.non_payment_change? if enrollee.coverage_start == enrollee.coverage_end is_policy_cancel = true policy_end_date = enrollee.coverage_end enrollee.policy.aasm_state = "canceled" enrollee.policy.term_for_np = is_non_payment enrollee.policy.save else is_policy_term = true policy_end_date = enrollee.coverage_end enrollee.policy.aasm_state = "terminated" enrollee.policy.term_for_np = is_non_payment enrollee.policy.save end end end rescue Exception puts @policy.eg_id puts person_loop.member_id raise $! end end save_val = @policy.save unless exempt_from_notification?(@policy, is_policy_cancel, is_policy_term, old_npt_flag == is_non_payment) Observers::PolicyUpdated.notify(@policy) end if is_policy_term # Broadcast the term reason_headers = if is_non_payment {:qualifying_reason => "urn:openhbx:terms:v1:benefit_maintenance#non_payment"} else {} end Amqp::EventBroadcaster.with_broadcaster do |eb| eb.broadcast( { :routing_key => "info.events.policy.terminated", :headers => { :resource_instance_uri => @policy.eg_id, :event_effective_date => @policy.policy_end.strftime("%Y%m%d"), :hbx_enrollment_ids => JSON.dump(@policy.hbx_enrollment_ids) }.merge(reason_headers) }, "") end elsif is_policy_cancel # Broadcast the cancel reason_headers = if is_non_payment {:qualifying_reason => "urn:openhbx:terms:v1:benefit_maintenance#non_payment"} else {} end Amqp::EventBroadcaster.with_broadcaster do |eb| eb.broadcast( { :routing_key => "info.events.policy.canceled", :headers => { :resource_instance_uri => @policy.eg_id, :event_effective_date => @policy.policy_end.strftime("%Y%m%d"), :hbx_enrollment_ids => JSON.dump(@policy.hbx_enrollment_ids) }.merge(reason_headers) }, "") end end save_val end def exempt_from_notification?(policy, is_cancel, is_term, npt_changed) return false if is_cancel return false if npt_changed return false unless is_term (policy.policy_end.day == 31) && (policy.policy_end.month == 12) end def policy_found(policy) @policy = policy end def termination_with_no_end_date(details) @errors << "File is a termination, but no or invalid end date is provided for a member: Member #{details[:member_id]}, Coverage End: #{details[:coverage_end_string]}" end def coverage_end_before_coverage_start(details) @errors << "Coverage end before coverage start: Member #{details[:member_id]}, coverage_start: #{details[:coverage_start]}, coverage_end: #{details[:coverage_end]}" end def term_or_cancel_for_2014_individual(details) @errors << "Cancel/Term issued on 2014 policy. Member #{details[:member_id]}, end date #{details[:date]}" end def effectuation_date_mismatch(details) @errors << "Effectuation date mismatch: member #{details[:member_id]}, enrollee start: #{details[:policy]}, effectuation start: #{details[:effectuation]}" end def indeterminate_policy_expiration(details) @errors << "Could not determine natural policy expiration date: member #{details[:member_id]}" end def termination_date_after_expiration(details) @errors << "Termination date after natural policy expiration: member #{details[:member_id]}, coverage end: #{details[:coverage_end]}, expiration_date: #{details[:expiration_date]}" end def policy_not_found(subkeys) @errors << "Policy not found. Details: #{subkeys}" end def plan_found(plan) @plan = plan end def plan_not_found(hios_id) @errors << "Plan not found. (hios id: #{hios_id})" end def carrier_found(carrier) @carrier = carrier end def carrier_not_found(fein) @errors << "Carrier not found. (fein: #{fein})" end def found_carrier_member_id(id) end def missing_carrier_member_id(person_loop) policy_loop = person_loop.policy_loops.first if(!policy_loop.canceled?) @errors << "Missing Carrier Member ID." end end def no_such_member(id) @errors << "Member not found in policy: #{id}" end def found_carrier_policy_id(id) end def missing_carrier_policy_id @errors << "Missing Carrier Policy ID." end def policy_id @policy ? @policy._id : nil end def carrier_id @carrier ? @carrier._id : nil end def employer_id @employer ? @employer._id : nil end end end end
Java
<!doctype html> <html> <head> <meta charset="utf-8" /> <meta content="IE=edge;chrome=1" http-equiv="X-UA-Compatible" /> <title>dognews</title> <meta content="width=device-width, initial-scale=1" name="viewport" /> <link rel="alternate" type="application/atom+xml" title="Atom Feed" href="/feed.xml" /><!--[if lt IE 9]><script src="../../js/ie8.js" type="text/javascript"></script><![endif]--><link href="../../css/all.css" media="screen" rel="stylesheet" type="text/css" /><script type="text/javascript"> (function(d,e,j,h,f,c,b){d.GoogleAnalyticsObject=f;d[f]=d[f]||function(){(d[f].q=d[f].q||[]).push(arguments)},d[f].l=1*new Date();c=e.createElement(j),b=e.getElementsByTagName(j)[0];c.async=1;c.src=h;b.parentNode.insertBefore(c,b)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("create","UA-63279904-1", location.hostname);ga("send","pageview"); </script> <link href="/favicon.png" rel="icon" type="image/png" /> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle collapsed" data-target=".navbar-ex1-collapse" data-toggle="collapse" type="button"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="/">dognews</a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li> <a href="/menu1.html"> Über Uns </a> </li> <li> <a href="/menu2.html"> Newsletter! </a> </li> <li class="dropdown"> <a aria-expanded="false" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button">Categories <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li> <a href="/tags/businessidee.html">businessidee (38)</a> </li> <li> <a href="/tags/deutschland.html">deutschland (596)</a> </li> <li> <a href="/tags/erziehung.html">erziehung (35)</a> </li> <li> <a href="/tags/fotografie.html">fotografie (5)</a> </li> <li> <a href="/tags/freizeit.html">freizeit (83)</a> </li> <li> <a href="/tags/gesetz.html">gesetz (38)</a> </li> <li> <a href="/tags/gesundheit.html">gesundheit (116)</a> </li> <li> <a href="/tags/herdenhunde.html">herdenhunde (10)</a> </li> <li> <a href="/tags/hundesachkunde.html">hundesachkunde (13)</a> </li> <li> <a href="/tags/hundesport.html">hundesport (12)</a> </li> <li> <a href="/tags/kinder.html">kinder (9)</a> </li> <li> <a href="/tags/kurioses.html">kurioses (29)</a> </li> <li> <a href="/tags/oesterreich.html">oesterreich (63)</a> </li> <li> <a href="/tags/rassen.html">rassen (8)</a> </li> <li> <a href="/tags/ratgeber.html">ratgeber (161)</a> </li> <li> <a href="/tags/rettungshunde.html">rettungshunde (3)</a> </li> <li> <a href="/tags/schweiz.html">schweiz (99)</a> </li> <li> <a href="/tags/senioren.html">senioren (10)</a> </li> <li> <a href="/tags/stars.html">stars (11)</a> </li> <li> <a href="/tags/urlaub.html">urlaub (39)</a> </li> <li> <a href="/tags/veranstaltung.html">veranstaltung (1)</a> </li> <li> <a href="/tags/wandern.html">wandern (17)</a> </li> <li> <a href="/tags/wissen.html">wissen (200)</a> </li> </ul> </li> <li class="dropdown"> <a aria-expanded="false" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button">By Year <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li> <a href="/2017.html">2017 (8)</a> </li> <li> <a href="/2016.html">2016 (55)</a> </li> <li> <a href="/2015.html">2015 (458)</a> </li> <li> <a href="/2014.html">2014 (273)</a> </li> </ul> </li> <ul class="list-unstyled list-inline nav navbar-nav navbar-right"></ul> <li><a href="https://twitter.com/cbdognews"> <i class="fa fa-lg fa-inverse fa-twitter-square"></i></a> </li> </ul> </div> </div> </nav> <div class="container"> <div class="row"> <div class="col-lg-9 col-md-9"> <h1> Archive for Jan 9 2014 </h1> <ul> <h2> <a href="/2014/01/09/gelbes-tuch-fass-mich-nicht-an.html">Gelbes Tuch: 'Fass mich nicht an!'</a> </h2> <p> <small class="label label-default">ratgeber</small> <small class="label label-default">deutschland</small> </p> <hr /> <p> <span class="glyphicon glyphicon-time"></span> Posted on Jan 9 </p> <hr /> <div class="row"> <div class="article"> <p><dummy> Wenn Kristin Friedrich mit ihrem Schäferhund Wanko unterwegs ist, trägt er jetzt stolz ein gelbes Halstuch. “Es signalisiert, dass der Hund nicht angefasst und nicht bedrängt werden möchte”, erklärt die Beeskower Hundetrainerin und Tierbetreuerin...</dummy></p> </div> </div><a class="btn btn-primary" href="/2014/01/09/gelbes-tuch-fass-mich-nicht-an.html">Read More<span class="glyphicon glyphicon-chevron-right"></span></a> <hr /> <h2> <a href="/2014/01/09/ehemaliger-ubs-handler-gab-finanzkarriere-auf-fur-dies.html">Ehemaliger UBS-Händler gab Finanzkarriere auf – für dies</a> </h2> <p> <small class="label label-default">schweiz</small> <small class="label label-default">businessidee</small> </p> <hr /> <p> <span class="glyphicon glyphicon-time"></span> Posted on Jan 9 </p> <hr /> <div class="row"> <div class="article"> <p><dummy> Ex-UBS-Händler gab Finanzkarriere auf – für ein Hunde-Spa <a href="http://www.finews.ch/news/banken/17027-mitch-marrow-ubs-hunde-spa-wellness-spot-experience-stamford-hedge-funds">Link</a></p> </div> </div><a class="btn btn-primary" href="/2014/01/09/ehemaliger-ubs-handler-gab-finanzkarriere-auf-fur-dies.html">Read More<span class="glyphicon glyphicon-chevron-right"></span></a> <hr /> </ul> <hr /> <aside> <h3> Recent Articles </h3> <ol> <li> <a href="/2017/12/05/nun-ist-es-raus-hunde-sind-kluger-als-katzen.html">Nun ist es raus: Hunde sind klüger als Katzen</a> <span>Dec 5</span> </li> <li> <a href="/2017/07/27/die-macht-der-geruche.html">Die Macht der Gerüche</a> <span>Jul 27</span> </li> <li> <a href="/2017/06/21/vorsicht-giftig-diese-lebensmittel-sollten-hunde-nicht-fressen.html">Vorsicht giftig! Diese Lebensmittel sollten Hunde nicht fressen</a> <span>Jun 21</span> </li> <li> <a href="/2017/03/27/studie-schaferhunde-konnen-brustkrebs-diagnostizieren.html">Studie: Schäferhunde können Brustkrebs diagnostizieren</a> <span>Mar 27</span> </li> <li> <a href="/2017/03/27/atopische-dermatitis-was-tun-wenn-es-juckt-und-kratzt-allergien-belasten-das-woh.html">Atopische Dermatitis: Was tun, wenn es juckt und kratzt? / Allergien belasten das Wohlbefinden ...</a> <span>Mar 27</span> </li> <li> <a href="/2017/02/27/tiermedizin-epilepsie-gen-entdeckt.html">Tiermedizin - Epilepsie-Gen entdeckt</a> <span>Feb 27</span> </li> <li> <a href="/2017/01/17/auch-haustiere-frieren-so-kommt-bello-durch-den-winter.html">Auch Haustiere frieren | So kommt Bello durch den Winter</a> <span>Jan 17</span> </li> <li> <a href="/2017/01/17/hunde-sind-bei-minusgraden-schnell-unterkuhlt.html">Hunde sind bei Minusgraden schnell unterkühlt</a> <span>Jan 17</span> </li> <li> <a href="/2016/12/08/venedig-wo-die-gondeln-hunde-tragen.html">Venedig: Wo die Gondeln Hunde tragen</a> <span>Dec 8</span> </li> <li> <a href="/2016/11/01/hunde-heulten-halbe-stunde-vor-erdbeben.html">Hunde heulten halbe Stunde vor Erdbeben</a> <span>Nov 1</span> </li> </ol> </aside> <hr> <p class="text-center"> ©2018 <a href="/">dognews</a> - <a href="/footer1.html">Disclaimer</a><br /><span class="small">Powered by<a href="https://cloudburo.net/docs/products.html"> Cloudburo Curation Engine</a></span> </p> </hr> </div> <div class="col-lg-3 col-md-3"> <div class="well"> <h4> Categories </h4> <ul class="list-unstyled"> <li> <a href="/tags/businessidee.html">businessidee</a> (38) </li> <li> <a href="/tags/deutschland.html">deutschland</a> (596) </li> <li> <a href="/tags/erziehung.html">erziehung</a> (35) </li> <li> <a href="/tags/fotografie.html">fotografie</a> (5) </li> <li> <a href="/tags/freizeit.html">freizeit</a> (83) </li> <li> <a href="/tags/gesetz.html">gesetz</a> (38) </li> <li> <a href="/tags/gesundheit.html">gesundheit</a> (116) </li> <li> <a href="/tags/herdenhunde.html">herdenhunde</a> (10) </li> <li> <a href="/tags/hundesachkunde.html">hundesachkunde</a> (13) </li> <li> <a href="/tags/hundesport.html">hundesport</a> (12) </li> <li> <a href="/tags/kinder.html">kinder</a> (9) </li> <li> <a href="/tags/kurioses.html">kurioses</a> (29) </li> <li> <a href="/tags/oesterreich.html">oesterreich</a> (63) </li> <li> <a href="/tags/rassen.html">rassen</a> (8) </li> <li> <a href="/tags/ratgeber.html">ratgeber</a> (161) </li> <li> <a href="/tags/rettungshunde.html">rettungshunde</a> (3) </li> <li> <a href="/tags/schweiz.html">schweiz</a> (99) </li> <li> <a href="/tags/senioren.html">senioren</a> (10) </li> <li> <a href="/tags/stars.html">stars</a> (11) </li> <li> <a href="/tags/urlaub.html">urlaub</a> (39) </li> <li> <a href="/tags/veranstaltung.html">veranstaltung</a> (1) </li> <li> <a href="/tags/wandern.html">wandern</a> (17) </li> <li> <a href="/tags/wissen.html">wissen</a> (200) </li> </ul> </div> <div class="well"> <h4> By year </h4> <ol> <li> <a href="/2017.html">2017</a> (8) </li> <li> <a href="/2016.html">2016</a> (55) </li> <li> <a href="/2015.html">2015</a> (458) </li> <li> <a href="/2014.html">2014</a> (273) </li> </ol> </div> </div> </div> </div> <script src="../../js/all.js" type="text/javascript"></script> </body> </html>
Java
geoserver ========= PostGI server and probably more for the Cologne Open Data community. The goal is to provide a unified, dynamic geodata access point for some important geographical datasets. At some point, there might be a tile server or some other visualization layer as well. We'll see. ## Contents ### `postgis` Scripts to set up a PostGIS environment and import geo data into the system.
Java
// // EBBannerView+Categories.h // demo // // Created by pikacode@qq.com on 2017/10/20. // Copyright © 2017年 pikacode@qq.com. All rights reserved. // #import "EBBannerView.h" #define WEAK_SELF(weakSelf) __weak __typeof(&*self)weakSelf = self; #define ScreenWidth [UIScreen mainScreen].bounds.size.width #define ScreenHeight [UIScreen mainScreen].bounds.size.height @interface EBBannerView (EBCategory) +(UIImage*)defaultIcon; +(NSString*)defaultTitle; +(NSString*)defaultDate; +(NSTimeInterval)defaultAnimationTime; +(NSTimeInterval)defaultStayTime; +(UInt32)defaultSoundID; @end @interface NSTimer (EBCategory) + (NSTimer *)eb_scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats; @end @interface UIImage (EBBannerViewCategory) +(UIColor *)colorAtPoint:(CGPoint)point; @end
Java
exports._buildExclamationKeyObject = function (tuples) { var valueMap = {}; tuples.forEach(function (tuple) { valueMap['!' + tuple.value0] = tuple.value1; }); return valueMap; }; var templatePattern = /\$\{([^}]+)\}/g; exports._getTemplateVars = function (str) { return (str.match(templatePattern) || []).map(function (str) { return str.substring(2, str.length - 1); }); };
Java
#CodeQuiz _CodeQuiz is a game made with Kivy framework._ _He is a Quiz consists of four options, Ruby, Python, Javascript and C#._ _Where he will approach curiosities and specificities of each language._ ##Install and Run 1.Clone this repo ``` git clone git@github.com:GuiCarneiro/CodeQuiz.git ``` 2.Install Kivy on your computer, take a look at their site [Kivy](http://kivy.org) 3.Then run python main.py ##To Play 1. Use the distribution release 2. Double click over the CodeQuiz.exe OBS: _Before playing I recommend you to Update the Quiz_ _Use the menu update_ ##Collaborate 1. Fork it 2. Create your branch ``` git checkout -b name-your-feature ``` 3. Commit it ``` git commit -m 'the differece' ``` 4. Push it ``` git push origin name-your-feature ``` 5. Create a Pull Request ##License This projected is licensed under the terms of the MIT license.
Java
/** * @overview * API handler action creator * Takes a key-value -pair representing the event to handle as key and its respective * handler function as the value. * * Event-to-URL mapping is done in {@link ApiEventPaths}. * * @since 0.2.0 * @version 0.3.0 */ import { Seq, Map } from 'immutable'; import { createAction } from 'redux-actions'; import { Internal } from '../records'; import { ApiEventPaths } from '../constants'; import * as apiHandlerFns from '../actions/kcsapi'; /** * Ensure that the action handlers are mapped into {@link ApiHandler} records. * @type {Immutable.Iterable<any, any>} * @since 0.2.0 */ export const handlers = Seq.Keyed(ApiEventPaths) .flatMap((path, event) => Map.of(event, new Internal.ApiHandler({ path, event, handler: apiHandlerFns[event] }))); /** * A non-`Seq` version of the @see findEventSeq function. * @param {string} findPath * @returns {string} * @since 0.2.0 * @version 0.3.0 */ export const findEvent = (findPath) => { const pathRegex = new RegExp(`^${findPath}$`); return ApiEventPaths.findKey((path) => pathRegex.test(path)); }; /** * Create a `Seq` of action handlers that is in a usable form for the Redux application. * @type {Immutable.Iterable<any, any>} * @since 0.2.0 */ export const actionHandlers = Seq.Keyed(handlers) .flatMap((handlerRecord, event) => Map.of(event, createAction(event, handlerRecord.handler)));
Java
# Fire Keeper ## Introduction Fire Keeper is a bot designed for the *Praise the Place* Dark Souls Discord server. Please do not use this bot in your server without adapation of the code, or else things will not work correctly.
Java
--- title: Prepare paperwork contexts: office365,microsoft365 source: Microsoft public sites translation: en tools: --- To kick off the employee onboarding checklist, you need to__ prepare the relevant paperwork and information__prior to the employee's first day\. Start by __recording__ the employee's __basic information__ in the__ form fields__below\. __Employee First Name__ __Employee Last Name__ __Date of Hire__ Date will be set here __Employee Contact Details__ __Employee Extra Information__ This part of the process is called__ transactional onboarding__ and focuses on completing all the necessary__forms and documents__ so your new employee can __legally start working__\. Some of the forms you need to prepare are: - 1 - W\-4 - 2 - I\-9 - 3 - Insurance forms - 4 - Direct deposit forms - 5 - The non\-disclosure agreement However, there are more forms you might need, __specific to your company__\. Good software to use is [Applicant PRO](http://www.applicantpro.com/) which operates like __CRM for onboarding __including all the necessary forms and documents and stores them in an__ online database__\. \(Source: [applicantpro\.com](http://www.applicantpro.com/products/onboarding/)\)
Java
# Doxx [![Build Status](https://travis-ci.org/FGRibreau/doxx.png)](https://travis-ci.org/FGRibreau/doxx) [![Gittip](http://badgr.co/gittip/fgribreau.png)](https://www.gittip.com/fgribreau/) [![Deps](https://david-dm.org/FGRibreau/doxx.png)](https://david-dm.org/FGRibreau/doxx) Use [dox](https://github.com/visionmedia/dox) to automatically generate beautiful html documentation. **Doxx is a total refactoring of [dox-foundation](https://github.com/punkave/dox-foundation/)**. Outputted HTML is by default based on templates and css from [Twitter Bootstrap](twitter.github.com/bootstrap/) and syntax highlighting is done by [Prism.js](http://prismjs.com/). Doxx was tested with **JavaScript** as well as generated JavaScript from **CoffeeScript**. ## Demo * [doxx/docs/compile.js](http://fgribreau.github.com/doxx/docs/compile.js.html) * [doxx/docs/dir.js](http://fgribreau.github.com/doxx/docs/dir.js.html) * [doxx/docs/parser.js](http://fgribreau.github.com/doxx/docs/parser.js.html) ## Usage JavaScript JavaDoc style ```javascript /** * Create an array of all the right files in the source dir * @param {String} source path * @param {Object} options * @param {Function} callback * @jsFiddle A jsFiddle embed URL * @return {Array} an array of string path */ function collectFiles(source, options, callback) { ... } ``` CoffeeScript JavaDoc style ```coffeescript ###* * Create an array of all the right files in the source dir * @param {String} source path * @param {Object} options * @param {Function} callback * @jsFiddle A jsFiddle embed URL * @return {Array} an array of string path ### collectFiles = (source, options, callback) -> ... ``` ## Installation Install the module with: `npm install doxx -g` ## CLI ``` $ doxx --help Usage: doxx [options] Options: -h, --help output usage information -V, --version output the version number -r, --raw output "raw" comments, leaving the markdown intact -d, --debug output parsed comments for debugging -t, --title <string> The title for the page produced -s, --source <source> The folder which should get parsed -i, --ignore <directories> Comma seperated list of directories to ignore. Default: test,public,static,views,templates -T, --target <target> The folder which will contain the results. Default: <process.cwd()>/docs -e, --target_extension <target_extension> Target files extension. Default: html --template <jade template> The jade template file to use Examples: # parse a whole folder $ doxx --source lib --target docs # parse a whole folder and use a specific template $ doxx --template ./view/myowntpl.jade --source lib --target docs ``` ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](https://github.com/cowboy/grunt). ## Release History * *0.0.1* - (dox-foundation) Initial release * *0.2.0* - (dox-foundation) Readable output * *0.3.0* - (dox-foundation) Support for folder parsing * *0.4.0* - (dox-foundation) Improved project navigation, major refactor of folder code * *0.5.0* - Initial release of doxx * *0.7.0* - Merge pull requests #16 #17 #19 #20 * *0.7.1* - Merge pull request #25 - Add target_extension option * *0.7.2* - Upgrade dox to ~0.4.4 * *0.7.4* - Merge pull requests #29 #30 ## Donate [Donate Bitcoins](https://coinbase.com/checkouts/fc3041b9d8116e0b98e7d243c4727a30) ## License Copyright (c) 2013 Francois-Guillaume Ribreau MIT License
Java
<div class="title"> <img class="icon" src="./res/img/interface.svg" /> <p class="interface">IStudentInfo.IYear</p> </div> <p> Describes school year. Contains year id and register id which are needed in order to use the the API. </p> <br /> <p class="section-title">Fields</p> <p>name: <span class="class">string</span> - school year display name, for ex. 2017/2018</p> <p>id: <span class="class">number</span> - year id</p> <p>registerId: <span class="class">number</span> - register id</p>
Java
// xParentN 2, Copyright 2005-2007 Olivier Spinelli // Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL function xParentN(e, n) { while (e && n--) e = e.parentNode; return e; }
Java
<?php /** * @file include/zot.php * @brief Hubzilla implementation of zot protocol. * * https://github.com/friendica/red/wiki/zot * https://github.com/friendica/red/wiki/Zot---A-High-Level-Overview * */ require_once('include/crypto.php'); require_once('include/items.php'); require_once('include/hubloc.php'); require_once('include/queue_fn.php'); require_once('include/perm_upgrade.php'); /** * @brief Generates a unique string for use as a zot guid. * * Generates a unique string for use as a zot guid using our DNS-based url, the * channel nickname and some entropy. * The entropy ensures uniqueness against re-installs where the same URL and * nickname are chosen. * * @note zot doesn't require this to be unique. Internally we use a whirlpool * hash of this guid and the signature of this guid signed with the channel * private key. This can be verified and should make the probability of * collision of the verified result negligible within the constraints of our * immediate universe. * * @param string $channel_nick a unique nickname of controlling entity * @returns string */ function zot_new_uid($channel_nick) { $rawstr = z_root() . '/' . $channel_nick . '.' . mt_rand(); return(base64url_encode(hash('whirlpool', $rawstr, true), true)); } /** * @brief Generates a portable hash identifier for a channel. * * Generates a portable hash identifier for the channel identified by $guid and * signed with $guid_sig. * * @note This ID is portable across the network but MUST be calculated locally * by verifying the signature and can not be trusted as an identity. * * @param string $guid * @param string $guid_sig */ function make_xchan_hash($guid, $guid_sig) { return base64url_encode(hash('whirlpool', $guid . $guid_sig, true)); } /** * @brief Given a zot hash, return all distinct hubs. * * This function is used in building the zot discovery packet and therefore * should only be used by channels which are defined on this hub. * * @param string $hash - xchan_hash * @returns array of hubloc (hub location structures) * * \b hubloc_id int * * \b hubloc_guid char(255) * * \b hubloc_guid_sig text * * \b hubloc_hash char(255) * * \b hubloc_addr char(255) * * \b hubloc_flags int * * \b hubloc_status int * * \b hubloc_url char(255) * * \b hubloc_url_sig text * * \b hubloc_host char(255) * * \b hubloc_callback char(255) * * \b hubloc_connect char(255) * * \b hubloc_sitekey text * * \b hubloc_updated datetime * * \b hubloc_connected datetime */ function zot_get_hublocs($hash) { /* Only search for active hublocs - e.g. those that haven't been marked deleted */ $ret = q("select * from hubloc where hubloc_hash = '%s' and hubloc_deleted = 0 order by hubloc_url ", dbesc($hash) ); return $ret; } /** * @brief Builds a zot notification packet. * * Builds a zot notification packet that you can either store in the queue with * a message array or call zot_zot to immediately zot it to the other side. * * @param array $channel * sender channel structure * @param string $type * packet type: one of 'ping', 'pickup', 'purge', 'refresh', 'force_refresh', 'notify', 'auth_check' * @param array $recipients * envelope information, array ( 'guid' => string, 'guid_sig' => string ); empty for public posts * @param string $remote_key * optional public site key of target hub used to encrypt entire packet * NOTE: remote_key and encrypted packets are required for 'auth_check' packets, optional for all others * @param string $secret * random string, required for packets which require verification/callback * e.g. 'pickup', 'purge', 'notify', 'auth_check'. Packet types 'ping', 'force_refresh', and 'refresh' do not require verification * @param string $extra * @returns string json encoded zot packet */ function zot_build_packet($channel, $type = 'notify', $recipients = null, $remote_key = null, $secret = null, $extra = null) { $data = array( 'type' => $type, 'sender' => array( 'guid' => $channel['channel_guid'], 'guid_sig' => base64url_encode(rsa_sign($channel['channel_guid'],$channel['channel_prvkey'])), 'url' => z_root(), 'url_sig' => base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey'])), 'sitekey' => get_config('system','pubkey') ), 'callback' => '/post', 'version' => ZOT_REVISION ); if ($recipients) { for ($x = 0; $x < count($recipients); $x ++) unset($recipients[$x]['hash']); $data['recipients'] = $recipients; } if ($secret) { $data['secret'] = $secret; $data['secret_sig'] = base64url_encode(rsa_sign($secret,$channel['channel_prvkey'])); } if ($extra) { foreach ($extra as $k => $v) $data[$k] = $v; } logger('zot_build_packet: ' . print_r($data,true), LOGGER_DATA, LOG_DEBUG); // Hush-hush ultra top-secret mode if ($remote_key) { $data = crypto_encapsulate(json_encode($data),$remote_key); } return json_encode($data); } /** * @brief * * @see z_post_url() * * @param string $url * @param array $data * @return array see z_post_url() for returned data format */ function zot_zot($url, $data) { return z_post_url($url, array('data' => $data)); } /** * @brief Look up information about channel. * * @param string $webbie * does not have to be host qualified e.g. 'foo' is treated as 'foo\@thishub' * @param array $channel * (optional), if supplied permissions will be enumerated specifically for $channel * @param boolean $autofallback * fallback/failover to http if https connection cannot be established. Default is true. * * @return array see z_post_url() and \ref mod/zfinger.php */ function zot_finger($webbie, $channel = null, $autofallback = true) { if (strpos($webbie,'@') === false) { $address = $webbie; $host = App::get_hostname(); } else { $address = substr($webbie,0,strpos($webbie,'@')); $host = substr($webbie,strpos($webbie,'@')+1); } $xchan_addr = $address . '@' . $host; if ((! $address) || (! $xchan_addr)) { logger('zot_finger: no address :' . $webbie); return array('success' => false); } logger('using xchan_addr: ' . $xchan_addr, LOGGER_DATA, LOG_DEBUG); // potential issue here; the xchan_addr points to the primary hub. // The webbie we were called with may not, so it might not be found // unless we query for hubloc_addr instead of xchan_addr $r = q("select xchan.*, hubloc.* from xchan left join hubloc on xchan_hash = hubloc_hash where xchan_addr = '%s' and hubloc_primary = 1 limit 1", dbesc($xchan_addr) ); if ($r) { $url = $r[0]['hubloc_url']; if ($r[0]['hubloc_network'] && $r[0]['hubloc_network'] !== 'zot') { logger('zot_finger: alternate network: ' . $webbie); logger('url: '.$url.', net: '.var_export($r[0]['hubloc_network'],true), LOGGER_DATA, LOG_DEBUG); return array('success' => false); } } else { $url = 'https://' . $host; } $rhs = '/.well-known/zot-info'; $https = ((strpos($url,'https://') === 0) ? true : false); logger('zot_finger: ' . $address . ' at ' . $url, LOGGER_DEBUG); if ($channel) { $postvars = array( 'address' => $address, 'target' => $channel['channel_guid'], 'target_sig' => $channel['channel_guid_sig'], 'key' => $channel['channel_pubkey'] ); $result = z_post_url($url . $rhs,$postvars); if ((! $result['success']) && ($autofallback)) { if ($https) { logger('zot_finger: https failed. falling back to http'); $result = z_post_url('http://' . $host . $rhs,$postvars); } } } else { $rhs .= '?f=&address=' . urlencode($address); $result = z_fetch_url($url . $rhs); if ((! $result['success']) && ($autofallback)) { if ($https) { logger('zot_finger: https failed. falling back to http'); $result = z_fetch_url('http://' . $host . $rhs); } } } if (! $result['success']) logger('zot_finger: no results'); return $result; } /** * @brief Refreshes after permission changed or friending, etc. * * zot_refresh is typically invoked when somebody has changed permissions of a channel and they are notified * to fetch new permissions via a finger/discovery operation. This may result in a new connection * (abook entry) being added to a local channel and it may result in auto-permissions being granted. * * Friending in zot is accomplished by sending a refresh packet to a specific channel which indicates a * permission change has been made by the sender which affects the target channel. The hub controlling * the target channel does targetted discovery (a zot-finger request requesting permissions for the local * channel). These are decoded here, and if necessary and abook structure (addressbook) is created to store * the permissions assigned to this channel. * * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are * implied until this is approved by the owner channel. A channel can also auto-populate permissions in * return and send back a refresh packet of its own. This is used by forum and group communication channels * so that friending and membership in the channel's "club" is automatic. * * @param array $them => xchan structure of sender * @param array $channel => local channel structure of target recipient, required for "friending" operations * @param array $force default false * * @returns boolean true if successful, else false */ function zot_refresh($them, $channel = null, $force = false) { if (array_key_exists('xchan_network', $them) && ($them['xchan_network'] !== 'zot')) { logger('zot_refresh: not got zot. ' . $them['xchan_name']); return true; } logger('zot_refresh: them: ' . print_r($them,true), LOGGER_DATA, LOG_DEBUG); if ($channel) logger('zot_refresh: channel: ' . print_r($channel,true), LOGGER_DATA, LOG_DEBUG); $url = null; if ($them['hubloc_url']) { $url = $them['hubloc_url']; } else { $r = null; // if they re-installed the server we could end up with the wrong record - pointing to the old install. // We'll order by reverse id to try and pick off the newest one first and hopefully end up with the // correct hubloc. If this doesn't work we may have to re-write this section to try them all. if(array_key_exists('xchan_addr',$them) && $them['xchan_addr']) { $r = q("select hubloc_url, hubloc_primary from hubloc where hubloc_addr = '%s' order by hubloc_id desc", dbesc($them['xchan_addr']) ); } if(! $r) { $r = q("select hubloc_url, hubloc_primary from hubloc where hubloc_hash = '%s' order by hubloc_id desc", dbesc($them['xchan_hash']) ); } if ($r) { foreach ($r as $rr) { if (intval($rr['hubloc_primary'])) { $url = $rr['hubloc_url']; break; } } if (! $url) $url = $r[0]['hubloc_url']; } } if (! $url) { logger('zot_refresh: no url'); return false; } $token = random_string(); $postvars = array(); $postvars['token'] = $token; if($channel) { $postvars['target'] = $channel['channel_guid']; $postvars['target_sig'] = $channel['channel_guid_sig']; $postvars['key'] = $channel['channel_pubkey']; } if (array_key_exists('xchan_addr',$them) && $them['xchan_addr']) $postvars['address'] = $them['xchan_addr']; if (array_key_exists('xchan_hash',$them) && $them['xchan_hash']) $postvars['guid_hash'] = $them['xchan_hash']; if (array_key_exists('xchan_guid',$them) && $them['xchan_guid'] && array_key_exists('xchan_guid_sig',$them) && $them['xchan_guid_sig']) { $postvars['guid'] = $them['xchan_guid']; $postvars['guid_sig'] = $them['xchan_guid_sig']; } $rhs = '/.well-known/zot-info'; $result = z_post_url($url . $rhs,$postvars); logger('zot_refresh: zot-info: ' . print_r($result,true), LOGGER_DATA, LOG_DEBUG); if ($result['success']) { $j = json_decode($result['body'],true); if (! (($j) && ($j['success']))) { logger('zot_refresh: result not decodable'); return false; } $signed_token = ((is_array($j) && array_key_exists('signed_token',$j)) ? $j['signed_token'] : null); if($signed_token) { $valid = rsa_verify('token.' . $token,base64url_decode($signed_token),$j['key']); if(! $valid) { logger('invalid signed token: ' . $url . $rhs, LOGGER_NORMAL, LOG_ERR); return false; } } else { logger('No signed token from ' . $url . $rhs, LOGGER_NORMAL, LOG_WARNING); // after 2017-01-01 this will be a hard error unless you over-ride it. if((time() > 1483228800) && (! get_config('system','allow_unsigned_zotfinger'))) { return false; } } $x = import_xchan($j, (($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED)); if(! $x['success']) return false; if($channel) { if($j['permissions']['data']) { $permissions = crypto_unencapsulate(array( 'data' => $j['permissions']['data'], 'key' => $j['permissions']['key'], 'iv' => $j['permissions']['iv']), $channel['channel_prvkey']); if($permissions) $permissions = json_decode($permissions,true); logger('decrypted permissions: ' . print_r($permissions,true), LOGGER_DATA, LOG_DEBUG); } else $permissions = $j['permissions']; $connected_set = false; if($permissions && is_array($permissions)) { $old_read_stream_perm = get_abconfig($channel['channel_id'],$x['hash'],'their_perms','view_stream'); foreach($permissions as $k => $v) { set_abconfig($channel['channel_id'],$x['hash'],'their_perms',$k,$v); } } if(array_key_exists('profile',$j) && array_key_exists('next_birthday',$j['profile'])) { $next_birthday = datetime_convert('UTC','UTC',$j['profile']['next_birthday']); } else { $next_birthday = NULL_DATE; } $r = q("select * from abook where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 limit 1", dbesc($x['hash']), intval($channel['channel_id']) ); if($r) { // connection exists // if the dob is the same as what we have stored (disregarding the year), keep the one // we have as we may have updated the year after sending a notification; and resetting // to the one we just received would cause us to create duplicated events. if(substr($r[0]['abook_dob'],5) == substr($next_birthday,5)) $next_birthday = $r[0]['abook_dob']; $y = q("update abook set abook_dob = '%s' where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 ", dbescdate($next_birthday), dbesc($x['hash']), intval($channel['channel_id']) ); if(! $y) logger('abook update failed'); else { // if we were just granted read stream permission and didn't have it before, try to pull in some posts if((! $old_read_stream_perm) && (intval($permissions['view_stream']))) Zotlabs\Daemon\Master::Summon(array('Onepoll',$r[0]['abook_id'])); } } else { // new connection $my_perms = null; $automatic = false; $role = get_pconfig($channel['channel_id'],'system','permissions_role'); if($role) { $xx = \Zotlabs\Access\PermissionRoles::role_perms($role); if($xx['perms_auto']) { $automatic = true; $default_perms = $xx['perms_connect']; $my_perms = \Zotlabs\Access\Permissions::FilledPerms($default_perms); } } if(! $my_perms) { $m = \Zotlabs\Access\Permissions::FilledAutoperms($channel['channel_id']); if($m) { $automatic = true; $my_perms = $m; } } if($my_perms) { foreach($my_perms as $k => $v) { set_abconfig($channel['channel_id'],$x['hash'],'my_perms',$k,$v); } } // Keep original perms to check if we need to notify them $previous_perms = get_all_perms($channel['channel_id'],$x['hash']); $closeness = get_pconfig($channel['channel_id'],'system','new_abook_closeness'); if($closeness === false) $closeness = 80; $y = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_created, abook_updated, abook_dob, abook_pending ) values ( %d, %d, %d, '%s', '%s', '%s', '%s', %d )", intval($channel['channel_account_id']), intval($channel['channel_id']), intval($closeness), dbesc($x['hash']), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($next_birthday), intval(($automatic) ? 0 : 1) ); if($y) { logger("New introduction received for {$channel['channel_name']}"); $new_perms = get_all_perms($channel['channel_id'],$x['hash']); // Send a clone sync packet and a permissions update if permissions have changed $new_connection = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 order by abook_created desc limit 1", dbesc($x['hash']), intval($channel['channel_id']) ); if($new_connection) { if(! \Zotlabs\Access\Permissions::PermsCompare($new_perms,$previous_perms)) Zotlabs\Daemon\Master::Summon(array('Notifier','permission_create',$new_connection[0]['abook_id'])); Zotlabs\Lib\Enotify::submit(array( 'type' => NOTIFY_INTRO, 'from_xchan' => $x['hash'], 'to_xchan' => $channel['channel_hash'], 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'], )); if(intval($permissions['view_stream'])) { if(intval(get_pconfig($channel['channel_id'],'perm_limits','send_stream') & PERMS_PENDING) || (! intval($new_connection[0]['abook_pending']))) Zotlabs\Daemon\Master::Summon(array('Onepoll',$new_connection[0]['abook_id'])); } /** If there is a default group for this channel, add this connection to it */ $default_group = $channel['channel_default_group']; if($default_group) { require_once('include/group.php'); $g = group_rec_byhash($channel['channel_id'],$default_group); if($g) group_add_member($channel['channel_id'],'',$x['hash'],$g['id']); } unset($new_connection[0]['abook_id']); unset($new_connection[0]['abook_account']); unset($new_connection[0]['abook_channel']); $abconfig = load_abconfig($channel['channel_id'],$new_connection['abook_xchan']); if($abconfig) $new_connection['abconfig'] = $abconfig; build_sync_packet($channel['channel_id'], array('abook' => $new_connection)); } } } } return true; } return false; } /** * @brief Look up if channel is known and previously verified. * * A guid and a url, both signed by the sender, distinguish a known sender at a * known location. * This function looks these up to see if the channel is known and therefore * previously verified. If not, we will need to verify it. * * @param array $arr an associative array which must contain: * * \e string \b guid => guid of conversant * * \e string \b guid_sig => guid signed with conversant's private key * * \e string \b url => URL of the origination hub of this communication * * \e string \b url_sig => URL signed with conversant's private key * * @returns array|null null if site is blacklisted or not found, otherwise an * array with an hubloc record */ function zot_gethub($arr,$multiple = false) { if($arr['guid'] && $arr['guid_sig'] && $arr['url'] && $arr['url_sig']) { if(! check_siteallowed($arr['url'])) { logger('blacklisted site: ' . $arr['url']); return null; } $limit = (($multiple) ? '' : ' limit 1 '); $sitekey = ((array_key_exists('sitekey',$arr) && $arr['sitekey']) ? " and hubloc_sitekey = '" . protect_sprintf($arr['sitekey']) . "' " : ''); $r = q("select * from hubloc where hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_url = '%s' and hubloc_url_sig = '%s' $sitekey $limit", dbesc($arr['guid']), dbesc($arr['guid_sig']), dbesc($arr['url']), dbesc($arr['url_sig']) ); if($r) { logger('zot_gethub: found', LOGGER_DEBUG); return (($multiple) ? $r : $r[0]); } } logger('zot_gethub: not found: ' . print_r($arr,true), LOGGER_DEBUG); return null; } /** * @brief Registers an unknown hub. * * A communication has been received which has an unknown (to us) sender. * Perform discovery based on our calculated hash of the sender at the * origination address. This will fetch the discovery packet of the sender, * which contains the public key we need to verify our guid and url signatures. * * @param array $arr an associative array which must contain: * * \e string \b guid => guid of conversant * * \e string \b guid_sig => guid signed with conversant's private key * * \e string \b url => URL of the origination hub of this communication * * \e string \b url_sig => URL signed with conversant's private key * * @returns array an associative array with * * \b success boolean true or false * * \b message (optional) error string only if success is false */ function zot_register_hub($arr) { $result = array('success' => false); if($arr['url'] && $arr['url_sig'] && $arr['guid'] && $arr['guid_sig']) { $guid_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); $url = $arr['url'] . '/.well-known/zot-info/?f=&guid_hash=' . $guid_hash; logger('zot_register_hub: ' . $url, LOGGER_DEBUG); $x = z_fetch_url($url); logger('zot_register_hub: ' . print_r($x,true), LOGGER_DATA, LOG_DEBUG); if($x['success']) { $record = json_decode($x['body'],true); /* * We now have a key - only continue registration if our signatures are valid * AND the guid and guid sig in the returned packet match those provided in * our current communication. */ if((rsa_verify($arr['guid'],base64url_decode($arr['guid_sig']),$record['key'])) && (rsa_verify($arr['url'],base64url_decode($arr['url_sig']),$record['key'])) && ($arr['guid'] === $record['guid']) && ($arr['guid_sig'] === $record['guid_sig'])) { $c = import_xchan($record); if($c['success']) $result['success'] = true; } else { logger('zot_register_hub: failure to verify returned packet.'); } } } return $result; } /** * @brief Takes an associative array of a fetched discovery packet and updates * all internal data structures which need to be updated as a result. * * @param array $arr => json_decoded discovery packet * @param int $ud_flags * Determines whether to create a directory update record if any changes occur, default is UPDATE_FLAGS_UPDATED * $ud_flags = UPDATE_FLAGS_FORCED indicates a forced refresh where we unconditionally create a directory update record * this typically occurs once a month for each channel as part of a scheduled ping to notify the directory * that the channel still exists * @param array $ud_arr * If set [typically by update_directory_entry()] indicates a specific update table row and more particularly * contains a particular address (ud_addr) which needs to be updated in that table. * * @return associative array * * \e boolean \b success boolean true or false * * \e string \b message (optional) error string only if success is false */ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { call_hooks('import_xchan', $arr); $ret = array('success' => false); $dirmode = intval(get_config('system','directory_mode')); $changed = false; $what = ''; if(! (is_array($arr) && array_key_exists('success',$arr) && $arr['success'])) { logger('import_xchan: invalid data packet: ' . print_r($arr,true)); $ret['message'] = t('Invalid data packet'); return $ret; } if(! ($arr['guid'] && $arr['guid_sig'])) { logger('import_xchan: no identity information provided. ' . print_r($arr,true)); return $ret; } $xchan_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); $arr['hash'] = $xchan_hash; $import_photos = false; if(! rsa_verify($arr['guid'],base64url_decode($arr['guid_sig']),$arr['key'])) { logger('import_xchan: Unable to verify channel signature for ' . $arr['address']); $ret['message'] = t('Unable to verify channel signature'); return $ret; } logger('import_xchan: ' . $xchan_hash, LOGGER_DEBUG); $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($xchan_hash) ); if(! array_key_exists('connect_url', $arr)) $arr['connect_url'] = ''; if(strpos($arr['address'],'/') !== false) $arr['address'] = substr($arr['address'],0,strpos($arr['address'],'/')); if($r) { if($r[0]['xchan_photo_date'] != $arr['photo_updated']) $import_photos = true; // if we import an entry from a site that's not ours and either or both of us is off the grid - hide the entry. /** @TODO: check if we're the same directory realm, which would mean we are allowed to see it */ $dirmode = get_config('system','directory_mode'); if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; $hidden = (1 - intval($arr['searchable'])); $hidden_changed = $adult_changed = $deleted_changed = $pubforum_changed = 0; if(intval($r[0]['xchan_hidden']) != (1 - intval($arr['searchable']))) $hidden_changed = 1; if(intval($r[0]['xchan_selfcensored']) != intval($arr['adult_content'])) $adult_changed = 1; if(intval($r[0]['xchan_deleted']) != intval($arr['deleted'])) $deleted_changed = 1; if(intval($r[0]['xchan_pubforum']) != intval($arr['public_forum'])) $pubforum_changed = 1; if(($r[0]['xchan_name_date'] != $arr['name_updated']) || ($r[0]['xchan_connurl'] != $arr['connections_url']) || ($r[0]['xchan_addr'] != $arr['address']) || ($r[0]['xchan_follow'] != $arr['follow_url']) || ($r[0]['xchan_connpage'] != $arr['connect_url']) || ($r[0]['xchan_url'] != $arr['url']) || $hidden_changed || $adult_changed || $deleted_changed || $pubforum_changed ) { $rup = q("update xchan set xchan_name = '%s', xchan_name_date = '%s', xchan_connurl = '%s', xchan_follow = '%s', xchan_connpage = '%s', xchan_hidden = %d, xchan_selfcensored = %d, xchan_deleted = %d, xchan_pubforum = %d, xchan_addr = '%s', xchan_url = '%s' where xchan_hash = '%s'", dbesc(($arr['name']) ? $arr['name'] : '-'), dbesc($arr['name_updated']), dbesc($arr['connections_url']), dbesc($arr['follow_url']), dbesc($arr['connect_url']), intval(1 - intval($arr['searchable'])), intval($arr['adult_content']), intval($arr['deleted']), intval($arr['public_forum']), dbesc($arr['address']), dbesc($arr['url']), dbesc($xchan_hash) ); logger('import_xchan: update: existing: ' . print_r($r[0],true), LOGGER_DATA, LOG_DEBUG); logger('import_xchan: update: new: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); $what .= 'xchan '; $changed = true; } } else { $import_photos = true; if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; $x = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_mimetype, xchan_photo_l, xchan_addr, xchan_url, xchan_connurl, xchan_follow, xchan_connpage, xchan_name, xchan_network, xchan_photo_date, xchan_name_date, xchan_hidden, xchan_selfcensored, xchan_deleted, xchan_pubforum ) values ( '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d) ", dbesc($xchan_hash), dbesc($arr['guid']), dbesc($arr['guid_sig']), dbesc($arr['key']), dbesc($arr['photo_mimetype']), dbesc($arr['photo']), dbesc($arr['address']), dbesc($arr['url']), dbesc($arr['connections_url']), dbesc($arr['follow_url']), dbesc($arr['connect_url']), dbesc(($arr['name']) ? $arr['name'] : '-'), dbesc('zot'), dbescdate($arr['photo_updated']), dbescdate($arr['name_updated']), intval(1 - intval($arr['searchable'])), intval($arr['adult_content']), intval($arr['deleted']), intval($arr['public_forum']) ); $what .= 'new_xchan'; $changed = true; } if ($import_photos) { require_once('include/photo/photo_driver.php'); // see if this is a channel clone that's hosted locally - which we treat different from other xchans/connections $local = q("select channel_account_id, channel_id from channel where channel_hash = '%s' limit 1", dbesc($xchan_hash) ); if ($local) { $ph = z_fetch_url($arr['photo'], true); if ($ph['success']) { $hash = import_channel_photo($ph['body'], $arr['photo_mimetype'], $local[0]['channel_account_id'], $local[0]['channel_id']); if($hash) { // unless proven otherwise $is_default_profile = 1; $profile = q("select is_default from profile where aid = %d and uid = %d limit 1", intval($local[0]['channel_account_id']), intval($local[0]['channel_id']) ); if($profile) { if(! intval($profile[0]['is_default'])) $is_default_profile = 0; } // If setting for the default profile, unset the profile photo flag from any other photos I own if($is_default_profile) { q("UPDATE photo SET photo_usage = %d WHERE photo_usage = %d AND resource_id != '%s' AND aid = %d AND uid = %d", intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), dbesc($hash), intval($local[0]['channel_account_id']), intval($local[0]['channel_id']) ); } } // reset the names in case they got messed up when we had a bug in this function $photos = array( z_root() . '/photo/profile/l/' . $local[0]['channel_id'], z_root() . '/photo/profile/m/' . $local[0]['channel_id'], z_root() . '/photo/profile/s/' . $local[0]['channel_id'], $arr['photo_mimetype'], false ); } } else { $photos = import_xchan_photo($arr['photo'], $xchan_hash); } if ($photos) { if ($photos[4]) { // importing the photo failed somehow. Leave the photo_date alone so we can try again at a later date. // This often happens when somebody joins the matrix with a bad cert. $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($xchan_hash) ); } else { $r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'", dbescdate(datetime_convert('UTC','UTC',$arr['photo_updated'])), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($xchan_hash) ); } $what .= 'photo '; $changed = true; } } // what we are missing for true hub independence is for any changes in the primary hub to // get reflected not only in the hublocs, but also to update the URLs and addr in the appropriate xchan $s = sync_locations($arr, $arr); if($s) { if($s['change_message']) $what .= $s['change_message']; if($s['changed']) $changed = $s['changed']; if($s['message']) $ret['message'] .= $s['message']; } // Which entries in the update table are we interested in updating? $address = (($ud_arr && $ud_arr['ud_addr']) ? $ud_arr['ud_addr'] : $arr['address']); // Are we a directory server of some kind? $other_realm = false; $realm = get_directory_realm(); if(array_key_exists('site',$arr) && array_key_exists('realm',$arr['site']) && (strpos($arr['site']['realm'],$realm) === false)) $other_realm = true; if($dirmode != DIRECTORY_MODE_NORMAL) { // We're some kind of directory server. However we can only add directory information // if the entry is in the same realm (or is a sub-realm). Sub-realms are denoted by // including the parent realm in the name. e.g. 'RED_GLOBAL:foo' would allow an entry to // be in directories for the local realm (foo) and also the RED_GLOBAL realm. if(array_key_exists('profile',$arr) && is_array($arr['profile']) && (! $other_realm)) { $profile_changed = import_directory_profile($xchan_hash,$arr['profile'],$address,$ud_flags, 1); if($profile_changed) { $what .= 'profile '; $changed = true; } } else { logger('import_xchan: profile not available - hiding'); // they may have made it private $r = q("delete from xprof where xprof_hash = '%s'", dbesc($xchan_hash) ); $r = q("delete from xtag where xtag_hash = '%s' and xtag_flags = 0", dbesc($xchan_hash) ); } } if(array_key_exists('site',$arr) && is_array($arr['site'])) { $profile_changed = import_site($arr['site'],$arr['key']); if($profile_changed) { $what .= 'site '; $changed = true; } } if(($changed) || ($ud_flags == UPDATE_FLAGS_FORCED)) { $guid = random_string() . '@' . App::get_hostname(); update_modtime($xchan_hash,$guid,$address,$ud_flags); logger('import_xchan: changed: ' . $what,LOGGER_DEBUG); } elseif(! $ud_flags) { // nothing changed but we still need to update the updates record q("update updates set ud_flags = ( ud_flags | %d ) where ud_addr = '%s' and not (ud_flags & %d)>0 ", intval(UPDATE_FLAGS_UPDATED), dbesc($address), intval(UPDATE_FLAGS_UPDATED) ); } if(! x($ret,'message')) { $ret['success'] = true; $ret['hash'] = $xchan_hash; } logger('import_xchan: result: ' . print_r($ret,true), LOGGER_DATA, LOG_DEBUG); return $ret; } /** * @brief Called immediately after sending a zot message which is using queue processing. * * Updates the queue item according to the response result and logs any information * returned to aid communications troubleshooting. * * @param string $hub - url of site we just contacted * @param array $arr - output of z_post_url() * @param array $outq - The queue structure attached to this request */ function zot_process_response($hub, $arr, $outq) { if (! $arr['success']) { logger('zot_process_response: failed: ' . $hub); return; } $x = json_decode($arr['body'], true); if (! $x) { logger('zot_process_response: No json from ' . $hub); logger('zot_process_response: headers: ' . print_r($arr['header'],true), LOGGER_DATA, LOG_DEBUG); } if(is_array($x) && array_key_exists('delivery_report',$x) && is_array($x['delivery_report'])) { foreach($x['delivery_report'] as $xx) { if(is_array($xx) && array_key_exists('message_id',$xx) && delivery_report_is_storable($xx)) { q("insert into dreport ( dreport_mid, dreport_site, dreport_recip, dreport_result, dreport_time, dreport_xchan ) values ( '%s', '%s','%s','%s','%s','%s' ) ", dbesc($xx['message_id']), dbesc($xx['location']), dbesc($xx['recipient']), dbesc($xx['status']), dbesc(datetime_convert($xx['date'])), dbesc($xx['sender']) ); } } } // we have a more descriptive delivery report, so discard the per hub 'queued' report. q("delete from dreport where dreport_queue = '%s' ", dbesc($outq['outq_hash']) ); // update the timestamp for this site q("update site set site_dead = 0, site_update = '%s' where site_url = '%s'", dbesc(datetime_convert()), dbesc(dirname($hub)) ); // synchronous message types are handled immediately // async messages remain in the queue until processed. if(intval($outq['outq_async'])) remove_queue_item($outq['outq_hash'],$outq['outq_channel']); logger('zot_process_response: ' . print_r($x,true), LOGGER_DEBUG); } /** * @brief * * We received a notification packet (in mod_post) that a message is waiting for us, and we've verified the sender. * Now send back a pickup message, using our message tracking ID ($arr['secret']), which we will sign with our site * private key. * The entire pickup message is encrypted with the remote site's public key. * If everything checks out on the remote end, we will receive back a packet containing one or more messages, * which will be processed and delivered before this function ultimately returns. * * @see zot_import() * * @param array $arr * decrypted and json decoded notify packet from remote site * @return array from zot_import() */ function zot_fetch($arr) { logger('zot_fetch: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); $url = $arr['sender']['url'] . $arr['callback']; // set $multiple param on zot_gethub() to return all matching hubs // This allows us to recover from re-installs when a redundant (but invalid) hubloc for // this identity is widely dispersed throughout the network. $ret_hubs = zot_gethub($arr['sender'],true); if(! $ret_hubs) { logger('zot_fetch: no hub: ' . print_r($arr['sender'],true)); return; } foreach($ret_hubs as $ret_hub) { $data = array( 'type' => 'pickup', 'url' => z_root(), 'callback_sig' => base64url_encode(rsa_sign(z_root() . '/post',get_config('system','prvkey'))), 'callback' => z_root() . '/post', 'secret' => $arr['secret'], 'secret_sig' => base64url_encode(rsa_sign($arr['secret'],get_config('system','prvkey'))) ); $datatosend = json_encode(crypto_encapsulate(json_encode($data),$ret_hub['hubloc_sitekey'])); $fetch = zot_zot($url,$datatosend); $result = zot_import($fetch, $arr['sender']['url']); if($result) return $result; } return; } /** * @brief Process incoming array of messages. * * Process an incoming array of messages which were obtained via pickup, and * import, update, delete as directed. * * The message types handled here are 'activity' (e.g. posts), 'mail' , * 'profile', 'location' and 'channel_sync'. * * @param array $arr * 'pickup' structure returned from remote site * @param string $sender_url * the url specified by the sender in the initial communication. * We will verify the sender and url in each returned message structure and * also verify that all the messages returned match the site url that we are * currently processing. * * @returns array * suitable for logging remotely, enumerating the processing results of each message/recipient combination * * [0] => \e string $channel_hash * * [1] => \e string $delivery_status * * [2] => \e string $address */ function zot_import($arr, $sender_url) { $data = json_decode($arr['body'], true); if(! $data) { logger('zot_import: empty body'); return array(); } if(array_key_exists('iv', $data)) { $data = json_decode(crypto_unencapsulate($data,get_config('system','prvkey')),true); } if(! $data['success']) { if($data['message']) logger('remote pickup failed: ' . $data['message']); return false; } $incoming = $data['pickup']; $return = array(); if(is_array($incoming)) { foreach($incoming as $i) { if(! is_array($i)) { logger('incoming is not an array'); continue; } $result = null; if(array_key_exists('iv',$i['notify'])) { $i['notify'] = json_decode(crypto_unencapsulate($i['notify'],get_config('system','prvkey')),true); } logger('zot_import: notify: ' . print_r($i['notify'],true), LOGGER_DATA, LOG_DEBUG); $hub = zot_gethub($i['notify']['sender']); if((! $hub) || ($hub['hubloc_url'] != $sender_url)) { logger('zot_import: potential forgery: wrong site for sender: ' . $sender_url . ' != ' . print_r($i['notify'],true)); continue; } $message_request = ((array_key_exists('message_id',$i['notify'])) ? true : false); if($message_request) logger('processing message request'); $i['notify']['sender']['hash'] = make_xchan_hash($i['notify']['sender']['guid'],$i['notify']['sender']['guid_sig']); $deliveries = null; if(array_key_exists('message',$i) && array_key_exists('type',$i['message']) && $i['message']['type'] === 'rating') { // rating messages are processed only by directory servers logger('Rating received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); $result = process_rating_delivery($i['notify']['sender'],$i['message']); continue; } if(array_key_exists('recipients',$i['notify']) && count($i['notify']['recipients'])) { logger('specific recipients'); $recip_arr = array(); foreach($i['notify']['recipients'] as $recip) { if(is_array($recip)) { $recip_arr[] = make_xchan_hash($recip['guid'],$recip['guid_sig']); } } $r = false; if($recip_arr) { stringify_array_elms($recip_arr); $recips = implode(',',$recip_arr); $r = q("select channel_hash as hash from channel where channel_hash in ( " . $recips . " ) and channel_removed = 0 "); } if(! $r) { logger('recips: no recipients on this site'); continue; } // It's a specifically targetted post. If we were sent a public_scope hint (likely), // get rid of it so that it doesn't get stored and cause trouble. if(($i) && is_array($i) && array_key_exists('message',$i) && is_array($i['message']) && $i['message']['type'] === 'activity' && array_key_exists('public_scope',$i['message'])) unset($i['message']['public_scope']); $deliveries = $r; // We found somebody on this site that's in the recipient list. } else { if(($i['message']) && (array_key_exists('flags',$i['message'])) && (in_array('private',$i['message']['flags'])) && $i['message']['type'] === 'activity') { if(array_key_exists('public_scope',$i['message']) && $i['message']['public_scope'] === 'public') { // This should not happen but until we can stop it... logger('private message was delivered with no recipients.'); continue; } } logger('public post'); // Public post. look for any site members who are or may be accepting posts from this sender // and who are allowed to see them based on the sender's permissions $deliveries = allowed_public_recips($i); if($i['message'] && array_key_exists('type',$i['message']) && $i['message']['type'] === 'location') { $sys = get_sys_channel(); $deliveries = array(array('hash' => $sys['xchan_hash'])); } // if the scope is anything but 'public' we're going to store it as private regardless // of the private flag on the post. if($i['message'] && array_key_exists('public_scope',$i['message']) && $i['message']['public_scope'] !== 'public') { if(! array_key_exists('flags',$i['message'])) $i['message']['flags'] = array(); if(! in_array('private',$i['message']['flags'])) $i['message']['flags'][] = 'private'; } } // Go through the hash array and remove duplicates. array_unique() won't do this because the array is more than one level. $no_dups = array(); if($deliveries) { foreach($deliveries as $d) { if(! is_array($d)) { logger('Delivery hash array is not an array: ' . print_r($d,true)); continue; } if(! in_array($d['hash'],$no_dups)) $no_dups[] = $d['hash']; } if($no_dups) { $deliveries = array(); foreach($no_dups as $n) { $deliveries[] = array('hash' => $n); } } } if(! $deliveries) { logger('zot_import: no deliveries on this site'); continue; } if($i['message']) { if($i['message']['type'] === 'activity') { $arr = get_item_elements($i['message']); $v = validate_item_elements($i['message'],$arr); if(! $v['success']) { logger('Activity rejected: ' . $v['message'] . ' ' . print_r($i['message'],true)); continue; } logger('Activity received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Activity recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $relay = ((array_key_exists('flags',$i['message']) && in_array('relay',$i['message']['flags'])) ? true : false); $result = process_delivery($i['notify']['sender'],$arr,$deliveries,$relay,false,$message_request); } elseif($i['message']['type'] === 'mail') { $arr = get_mail_elements($i['message']); logger('Mail received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Mail recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_mail_delivery($i['notify']['sender'],$arr,$deliveries); } elseif($i['message']['type'] === 'profile') { $arr = get_profile_elements($i['message']); logger('Profile received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Profile recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_profile_delivery($i['notify']['sender'],$arr,$deliveries); } elseif($i['message']['type'] === 'channel_sync') { // $arr = get_channelsync_elements($i['message']); $arr = $i['message']; logger('Channel sync received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Channel sync recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_channel_sync_delivery($i['notify']['sender'],$arr,$deliveries); } elseif($i['message']['type'] === 'location') { $arr = $i['message']; logger('Location message received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Location message recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_location_delivery($i['notify']['sender'],$arr,$deliveries); } } if($result){ $return = array_merge($return, $result); } } } return $return; } /** * @brief * * A public message with no listed recipients can be delivered to anybody who * has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are * by definition authenticated) or PERMS_SITE and is one the same site, * or PERMS_SPECIFIC and the sender is a contact who is granted permissions via * their connection permissions in the address book. * Here we take a given message and construct a list of hashes of everybody * on the site that we should try and deliver to. * Some of these will be rejected, but this gives us a place to start. * * @param array $msg * @return NULL|array */ function public_recips($msg) { require_once('include/channel.php'); $check_mentions = false; $include_sys = false; if($msg['message']['type'] === 'activity') { if(! get_config('system','disable_discover_tab')) $include_sys = true; $perm = 'send_stream'; if(array_key_exists('flags',$msg['message']) && in_array('thread_parent', $msg['message']['flags'])) { // check mention recipient permissions on top level posts only $check_mentions = true; } else { // This doesn't look like it works so I have to explain what happened. These are my // notes (below) from when I got this section of code working. You would think that // we only have to find those with the requisite stream or comment permissions, // depending on whether this is a top-level post or a comment - but you would be wrong. // ... so public_recips and allowed_public_recips is working so much better // than before, but was still not quite right. We seem to be getting all the right // results for top-level posts now, but comments aren't getting through on channels // for which we've allowed them to send us their stream, but not comment on our posts. // The reason is we were seeing if they could comment - and we only need to do that if // we own the post. If they own the post, we only need to check if they can send us their stream. // if this is a comment and it wasn't sent by the post owner, check to see who is allowing them to comment. // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up // their software. We may need this step to protect us from bad guys intentionally stuffing up their software. // If it is sent by the post owner, we don't need to do this. We only need to see who is receiving the // owner's stream (which was already set above) - as they control the comment permissions, not us. // Note that by doing this we introduce another bug because some public forums have channel_w_stream // permissions set to themselves only. We also need in this function to add these public forums to the // public recipient list based on if they are tagged or not and have tag permissions. This is complicated // by the fact that this activity doesn't have the public forum tag. It's the parent activity that // contains the tag. we'll solve that further below. if($msg['notify']['sender']['guid_sig'] != $msg['message']['owner']['guid_sig']) { $perm = 'post_comments'; } } } elseif($msg['message']['type'] === 'mail') $perm = 'post_mail'; $r = array(); $c = q("select channel_id, channel_hash from channel where channel_removed = 0"); if($c) { foreach($c as $cc) { if(perm_is_allowed($cc['channel_id'],$msg['notify']['sender']['hash'],$perm)) { $r[] = [ 'hash' => $cc['channel_hash'] ]; } } } // logger('message: ' . print_r($msg['message'],true)); if($include_sys && array_key_exists('public_scope',$msg['message']) && $msg['message']['public_scope'] === 'public') { $sys = get_sys_channel(); if($sys) $r[] = [ 'hash' => $sys['channel_hash'] ]; } // look for any public mentions on this site // They will get filtered by tgroup_check() so we don't need to check permissions now if($check_mentions) { // It's a top level post. Look at the tags. See if any of them are mentions and are on this hub. if($msg['message']['tags']) { if(is_array($msg['message']['tags']) && $msg['message']['tags']) { foreach($msg['message']['tags'] as $tag) { if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) { $address = basename($tag['url']); if($address) { $z = q("select channel_hash as hash from channel where channel_address = '%s' and channel_removed = 0 limit 1", dbesc($address) ); if($z) $r = array_merge($r,$z); } } } } } } else { // This is a comment. We need to find any parent with ITEM_UPLINK set. But in fact, let's just return // everybody that stored a copy of the parent. This way we know we're covered. We'll check the // comment permissions when we deliver them. if($msg['message']['message_top']) { $z = q("select owner_xchan as hash from item where parent_mid = '%s' ", dbesc($msg['message']['message_top']) ); if($z) $r = array_merge($r,$z); } } // There are probably a lot of duplicates in $r at this point. We need to filter those out. // It's a bit of work since it's a multi-dimensional array if($r) { $uniq = array(); foreach($r as $rr) { if(! in_array($rr['hash'],$uniq)) $uniq[] = $rr['hash']; } $r = array(); foreach($uniq as $rr) { $r[] = array('hash' => $rr); } } logger('public_recips: ' . print_r($r,true), LOGGER_DATA, LOG_DEBUG); return $r; } /** * @brief * * This is the second part of public_recips(). * We'll find all the channels willing to accept public posts from us, then * match them against the sender privacy scope and see who in that list that * the sender is allowing. * * @see public_recipes() * @param array $msg * @return array */ function allowed_public_recips($msg) { logger('allowed_public_recips: ' . print_r($msg,true),LOGGER_DATA, LOG_DEBUG); if(array_key_exists('public_scope',$msg['message'])) $scope = $msg['message']['public_scope']; // Mail won't have a public scope. // in fact, it's doubtful mail will ever get here since it almost universally // has a recipient, but in fact we don't require this, so it's technically // possible to send mail to anybody that's listening. $recips = public_recips($msg); if(! $recips) return $recips; if($msg['message']['type'] === 'mail') return $recips; if($scope === 'public' || $scope === 'network: red' || $scope === 'authenticated') return $recips; if(strpos($scope,'site:') === 0) { if(($scope === 'site: ' . App::get_hostname()) && ($msg['notify']['sender']['url'] === z_root())) return $recips; else return array(); } $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); if($scope === 'self') { foreach($recips as $r) if($r['hash'] === $hash) return array('hash' => $hash); } // note: we shouldn't ever see $scope === 'specific' in this function, but handle it anyway if($scope === 'contacts' || $scope === 'any connections' || $scope === 'specific') { $condensed_recips = array(); foreach($recips as $rr) $condensed_recips[] = $rr['hash']; $results = array(); $r = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id where abook_xchan = '%s' and channel_removed = 0 ", dbesc($hash) ); if($r) { foreach($r as $rr) if(in_array($rr['hash'],$condensed_recips)) $results[] = array('hash' => $rr['hash']); } return $results; } return array(); } /** * @brief * * @param array $sender * @param array $arr * @param array $deliveries * @param boolean $relay * @param boolean $public (optional) default false * @param boolean $request (optional) default false * @return array */ function process_delivery($sender, $arr, $deliveries, $relay, $public = false, $request = false) { $result = array(); $result['site'] = z_root(); // We've validated the sender. Now make sure that the sender is the owner or author if(! $public) { if($sender['hash'] != $arr['owner_xchan'] && $sender['hash'] != $arr['author_xchan']) { logger("process_delivery: sender {$sender['hash']} is not owner {$arr['owner_xchan']} or author {$arr['author_xchan']} - mid {$arr['mid']}"); return; } } foreach($deliveries as $d) { $local_public = $public; $DR = new Zotlabs\Zot\DReport(z_root(),$sender['hash'],$d['hash'],$arr['mid']); $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); if(! $r) { $DR->update('recipient not found'); $result[] = $DR->get(); continue; } $channel = $r[0]; $DR->addto_recipient($channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . App::get_hostname() . '>'); /* blacklisted channels get a permission denied, no special message to tip them off */ if(! check_channelallowed($sender['hash'])) { $DR->update('permission denied'); $result[] = $DR->get(); continue; } /** * @FIXME: Somehow we need to block normal message delivery from our clones, as the delivered * message doesn't have ACL information in it as the cloned copy does. That copy * will normally arrive first via sync delivery, but this isn't guaranteed. * There's a chance the current delivery could take place before the cloned copy arrives * hence the item could have the wrong ACL and *could* be used in subsequent deliveries or * access checks. So far all attempts at identifying this situation precisely * have caused issues with delivery of relayed comments. */ // if(($d['hash'] === $sender['hash']) && ($sender['url'] !== z_root()) && (! $relay)) { // $DR->update('self delivery ignored'); // $result[] = $DR->get(); // continue; // } // allow public postings to the sys channel regardless of permissions, but not // for comments travelling upstream. Wait and catch them on the way down. // They may have been blocked by the owner. if(intval($channel['channel_system']) && (! $arr['item_private']) && (! $relay)) { $local_public = true; $r = q("select xchan_selfcensored from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); // don't import sys channel posts from selfcensored authors if($r && (intval($r[0]['xchan_selfcensored']))) { $local_public = false; continue; } } $tag_delivery = tgroup_check($channel['channel_id'],$arr); $perm = 'send_stream'; if(($arr['mid'] !== $arr['parent_mid']) && ($relay)) $perm = 'post_comments'; // This is our own post, possibly coming from a channel clone if($arr['owner_xchan'] == $d['hash']) { $arr['item_wall'] = 1; } else { $arr['item_wall'] = 0; } if((! perm_is_allowed($channel['channel_id'],$sender['hash'],$perm)) && (! $tag_delivery) && (! $local_public)) { logger("permission denied for delivery to channel {$channel['channel_id']} {$channel['channel_address']}"); $DR->update('permission denied'); $result[] = $DR->get(); continue; } if($arr['mid'] != $arr['parent_mid']) { // check source route. // We are only going to accept comments from this sender if the comment has the same route as the top-level-post, // this is so that permissions mismatches between senders apply to the entire conversation // As a side effect we will also do a preliminary check that we have the top-level-post, otherwise // processing it is pointless. $r = q("select route, id from item where mid = '%s' and uid = %d limit 1", dbesc($arr['parent_mid']), intval($channel['channel_id']) ); if(! $r) { $DR->update('comment parent not found'); $result[] = $DR->get(); // We don't seem to have a copy of this conversation or at least the parent // - so request a copy of the entire conversation to date. // Don't do this if it's a relay post as we're the ones who are supposed to // have the copy and we don't want the request to loop. // Also don't do this if this comment came from a conversation request packet. // It's possible that comments are allowed but posting isn't and that could // cause a conversation fetch loop. We can detect these packets since they are // delivered via a 'notify' packet type that has a message_id element in the // initial zot packet (just like the corresponding 'request' packet type which // makes the request). // We'll also check the send_stream permission - because if it isn't allowed, // the top level post is unlikely to be imported and // this is just an exercise in futility. if((! $relay) && (! $request) && (! $local_public) && perm_is_allowed($channel['channel_id'],$sender['hash'],'send_stream')) { Zotlabs\Daemon\Master::Summon(array('Notifier', 'request', $channel['channel_id'], $sender['hash'], $arr['parent_mid'])); } continue; } if($relay) { // reset the route in case it travelled a great distance upstream // use our parent's route so when we go back downstream we'll match // with whatever route our parent has. $arr['route'] = $r[0]['route']; } else { // going downstream check that we have the same upstream provider that // sent it to us originally. Ignore it if it came from another source // (with potentially different permissions). // only compare the last hop since it could have arrived at the last location any number of ways. // Always accept empty routes and firehose items (route contains 'undefined') . $existing_route = explode(',', $r[0]['route']); $routes = count($existing_route); if($routes) { $last_hop = array_pop($existing_route); $last_prior_route = implode(',',$existing_route); } else { $last_hop = ''; $last_prior_route = ''; } if(in_array('undefined',$existing_route) || $last_hop == 'undefined' || $sender['hash'] == 'undefined') $last_hop = ''; $current_route = (($arr['route']) ? $arr['route'] . ',' : '') . $sender['hash']; if($last_hop && $last_hop != $sender['hash']) { logger('comment route mismatch: parent route = ' . $r[0]['route'] . ' expected = ' . $current_route, LOGGER_DEBUG); logger('comment route mismatch: parent msg = ' . $r[0]['id'],LOGGER_DEBUG); $DR->update('comment route mismatch'); $result[] = $DR->get(); continue; } // we'll add sender['hash'] onto this when we deliver it. $last_prior_route now has the previously stored route // *except* for the sender['hash'] which would've been the last hop before it got to us. $arr['route'] = $last_prior_route; } } $ab = q("select * from abook where abook_channel = %d and abook_xchan = '%s'", intval($channel['channel_id']), dbesc($arr['owner_xchan']) ); $abook = (($ab) ? $ab[0] : null); if(intval($arr['item_deleted'])) { // remove_community_tag is a no-op if this isn't a community tag activity remove_community_tag($sender,$arr,$channel['channel_id']); // set these just in case we need to store a fresh copy of the deleted post. // This could happen if the delete got here before the original post did. $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; $item_id = delete_imported_item($sender,$arr,$channel['channel_id'],$relay); $DR->update(($item_id) ? 'deleted' : 'delete_failed'); $result[] = $DR->get(); if($relay && $item_id) { logger('process_delivery: invoking relay'); Zotlabs\Daemon\Master::Summon(array('Notifier','relay',intval($item_id))); $DR->update('relayed'); $result[] = $DR->get(); } continue; } $r = q("select * from item where mid = '%s' and uid = %d limit 1", dbesc($arr['mid']), intval($channel['channel_id']) ); if($r) { // We already have this post. $item_id = $r[0]['id']; if(intval($r[0]['item_deleted'])) { // It was deleted locally. $DR->update('update ignored'); $result[] = $DR->get(); continue; } // Maybe it has been edited? elseif($arr['edited'] > $r[0]['edited']) { $arr['id'] = $r[0]['id']; $arr['uid'] = $channel['channel_id']; if(($arr['mid'] == $arr['parent_mid']) && (! post_is_importable($arr,$abook))) { $DR->update('update ignored'); $result[] = $DR->get(); } else { update_imported_item($sender,$arr,$r[0],$channel['channel_id']); $DR->update('updated'); $result[] = $DR->get(); if(! $relay) add_source_route($item_id,$sender['hash']); } } else { $DR->update('update ignored'); $result[] = $DR->get(); // We need this line to ensure wall-to-wall comments are relayed (by falling through to the relay bit), // and at the same time not relay any other relayable posts more than once, because to do so is very wasteful. if(! intval($r[0]['item_origin'])) continue; } } else { $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; // if it's a sourced post, call the post_local hooks as if it were // posted locally so that crosspost connectors will be triggered. if(check_item_source($arr['uid'], $arr)) call_hooks('post_local', $arr); $item_id = 0; if(($arr['mid'] == $arr['parent_mid']) && (! post_is_importable($arr,$abook))) { $DR->update('post ignored'); $result[] = $DR->get(); } else { $item_result = item_store($arr); if($item_result['success']) { $item_id = $item_result['item_id']; $parr = array('item_id' => $item_id,'item' => $arr,'sender' => $sender,'channel' => $channel); call_hooks('activity_received',$parr); // don't add a source route if it's a relay or later recipients will get a route mismatch if(! $relay) add_source_route($item_id,$sender['hash']); } $DR->update(($item_id) ? 'posted' : 'storage failed: ' . $item_result['message']); $result[] = $DR->get(); } } if($relay && $item_id) { logger('process_delivery: invoking relay'); Zotlabs\Daemon\Master::Summon(array('Notifier','relay',intval($item_id))); $DR->addto_update('relayed'); $result[] = $DR->get(); } } if(! $deliveries) $result[] = array('', 'no recipients', '', $arr['mid']); logger('process_delivery: local results: ' . print_r($result, true), LOGGER_DEBUG); return $result; } /** * @brief * * @param array $sender an associative array with * * \e string \b hash a xchan_hash * @param array $arr an associative array * * \e int \b verb * * \e int \b obj_type * * \e int \b mid * @param int $uid */ function remove_community_tag($sender, $arr, $uid) { if(! (activity_match($arr['verb'], ACTIVITY_TAG) && ($arr['obj_type'] == ACTIVITY_OBJ_TAGTERM))) return; logger('remove_community_tag: invoked'); if(! get_pconfig($uid,'system','blocktags')) { logger('remove_community tag: permission denied.'); return; } $r = q("select * from item where mid = '%s' and uid = %d limit 1", dbesc($arr['mid']), intval($uid) ); if(! $r) { logger('remove_community_tag: no item'); return; } if(($sender['hash'] != $r[0]['owner_xchan']) && ($sender['hash'] != $r[0]['author_xchan'])) { logger('remove_community_tag: sender not authorised.'); return; } $i = $r[0]; if($i['target']) $i['target'] = json_decode($i['target'],true); if($i['object']) $i['object'] = json_decode($i['object'],true); if(! ($i['target'] && $i['object'])) { logger('remove_community_tag: no target/object'); return; } $message_id = $i['target']['id']; $r = q("select id from item where mid = '%s' and uid = %d limit 1", dbesc($message_id), intval($uid) ); if(! $r) { logger('remove_community_tag: no parent message'); return; } q("delete from term where uid = %d and oid = %d and otype = %d and ttype in ( %d, %d ) and term = '%s' and url = '%s'", intval($uid), intval($r[0]['id']), intval(TERM_OBJ_POST), intval(TERM_HASHTAG), intval(TERM_COMMUNITYTAG), dbesc($i['object']['title']), dbesc(get_rel_link($i['object']['link'],'alternate')) ); } /** * @brief Just calls item_store_update() and logs result. * * @see item_store_update() * @param array $sender (unused) * @param array $item * @param int $uid (unused) */ function update_imported_item($sender, $item, $orig, $uid) { // If this is a comment being updated, remove any privacy information // so that item_store_update will set it from the original. if($item['mid'] !== $item['parent_mid']) { unset($item['allow_cid']); unset($item['allow_gid']); unset($item['deny_cid']); unset($item['deny_gid']); unset($item['item_private']); } $x = item_store_update($item); // If we're updating an event that we've saved locally, we store the item info first // because event_addtocal will parse the body to get the 'new' event details if($orig['resource_type'] === 'event') { $res = event_addtocal($orig['id'],$uid); if(! $res) logger('update event: failed'); } if(! $x['item_id']) logger('update_imported_item: failed: ' . $x['message']); else logger('update_imported_item'); } /** * @brief Deletes an imported item. * * @param array $sender * * \e string \b hash a xchan_hash * @param array $item * @param int $uid * @param boolean $relay * @return boolean|int post_id */ function delete_imported_item($sender, $item, $uid, $relay) { logger('delete_imported_item invoked', LOGGER_DEBUG); $ownership_valid = false; $item_found = false; $post_id = 0; $r = q("select id, author_xchan, owner_xchan, source_xchan, item_deleted from item where ( author_xchan = '%s' or owner_xchan = '%s' or source_xchan = '%s' ) and mid = '%s' and uid = %d limit 1", dbesc($sender['hash']), dbesc($sender['hash']), dbesc($sender['hash']), dbesc($item['mid']), intval($uid) ); if ($r) { if ($r[0]['author_xchan'] === $sender['hash'] || $r[0]['owner_xchan'] === $sender['hash'] || $r[0]['source_xchan'] === $sender['hash']) $ownership_valid = true; $post_id = $r[0]['id']; $item_found = true; } else { // perhaps the item is still in transit and the delete notification got here before the actual item did. Store it with the deleted flag set. // item_store() won't try to deliver any notifications or start delivery chains if this flag is set. // This means we won't end up with potentially even more delivery threads trying to push this delete notification. // But this will ensure that if the (undeleted) original post comes in at a later date, we'll reject it because it will have an older timestamp. logger('delete received for non-existent item - storing item data.'); /** @BUG $arr is undefined here, so this is dead code */ if ($arr['author_xchan'] === $sender['hash'] || $arr['owner_xchan'] === $sender['hash'] || $arr['source_xchan'] === $sender['hash']) { $ownership_valid = true; $item_result = item_store($arr); $post_id = $item_result['item_id']; } } if ($ownership_valid === false) { logger('delete_imported_item: failed: ownership issue'); return false; } require_once('include/items.php'); if ($item_found) { if (intval($r[0]['item_deleted'])) { logger('delete_imported_item: item was already deleted'); if (! $relay) return false; // This is a bit hackish, but may have to suffice until the notification/delivery loop is optimised // a bit further. We're going to strip the ITEM_ORIGIN on this item if it's a comment, because // it was already deleted, and we're already relaying, and this ensures that no other process or // code path downstream can relay it again (causing a loop). Since it's already gone it's not coming // back, and we aren't going to (or shouldn't at any rate) delete it again in the future - so losing // this information from the metadata should have no other discernible impact. if (($r[0]['id'] != $r[0]['parent']) && intval($r[0]['item_origin'])) { q("update item set item_origin = 0 where id = %d and uid = %d", intval($r[0]['id']), intval($r[0]['uid']) ); } } require_once('include/items.php'); // Use phased deletion to set the deleted flag, call both tag_deliver and the notifier to notify downstream channels // and then clean up after ourselves with a cron job after several days to do the delete_item_lowlevel() (DROPITEM_PHASE2). drop_item($post_id, false, DROPITEM_PHASE1); tag_deliver($uid, $post_id); } return $post_id; } function process_mail_delivery($sender, $arr, $deliveries) { $result = array(); if($sender['hash'] != $arr['from_xchan']) { logger('process_mail_delivery: sender is not mail author'); return; } foreach($deliveries as $d) { $DR = new Zotlabs\Zot\DReport(z_root(),$sender['hash'],$d['hash'],$arr['mid']); $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); if(! $r) { $DR->update('recipient not found'); $result[] = $DR->get(); continue; } $channel = $r[0]; $DR->addto_recipient($channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . App::get_hostname() . '>'); /* blacklisted channels get a permission denied, no special message to tip them off */ if(! check_channelallowed($sender['hash'])) { $DR->update('permission denied'); $result[] = $DR->get(); continue; } if(! perm_is_allowed($channel['channel_id'],$sender['hash'],'post_mail')) { logger("permission denied for mail delivery {$channel['channel_id']}"); $DR->update('permission denied'); $result[] = $DR->get(); continue; } $r = q("select id from mail where mid = '%s' and channel_id = %d limit 1", dbesc($arr['mid']), intval($channel['channel_id']) ); if($r) { if(intval($arr['mail_recalled'])) { $x = q("delete from mail where id = %d and channel_id = %d", intval($r[0]['id']), intval($channel['channel_id']) ); $DR->update('mail recalled'); $result[] = $DR->get(); logger('mail_recalled'); } else { $DR->update('duplicate mail received'); $result[] = $DR->get(); logger('duplicate mail received'); } continue; } else { $arr['account_id'] = $channel['channel_account_id']; $arr['channel_id'] = $channel['channel_id']; $item_id = mail_store($arr); $DR->update('mail delivered'); $result[] = $DR->get(); } } return $result; } /** * @brief Processes delivery of rating. * * @param array $sender * * \e string \b hash a xchan_hash * @param array $arr */ function process_rating_delivery($sender, $arr) { logger('process_rating_delivery: ' . print_r($arr,true)); if(! $arr['target']) return; $z = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); if((! $z) || (! rsa_verify($arr['target'] . '.' . $arr['rating'] . '.' . $arr['rating_text'], base64url_decode($arr['signature']),$z[0]['xchan_pubkey']))) { logger('failed to verify rating'); return; } $r = q("select * from xlink where xlink_xchan = '%s' and xlink_link = '%s' and xlink_static = 1 limit 1", dbesc($sender['hash']), dbesc($arr['target']) ); if($r) { if($r[0]['xlink_updated'] >= $arr['edited']) { logger('rating message duplicate'); return; } $x = q("update xlink set xlink_rating = %d, xlink_rating_text = '%s', xlink_sig = '%s', xlink_updated = '%s' where xlink_id = %d", intval($arr['rating']), dbesc($arr['rating_text']), dbesc($arr['signature']), dbesc(datetime_convert()), intval($r[0]['xlink_id']) ); logger('rating updated'); } else { $x = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static ) values( '%s', '%s', %d, '%s', '%s', '%s', 1 ) ", dbesc($sender['hash']), dbesc($arr['target']), intval($arr['rating']), dbesc($arr['rating_text']), dbesc($arr['signature']), dbesc(datetime_convert()) ); logger('rating created'); } } /** * @brief Processes delivery of profile. * * @see import_directory_profile() * @param array $sender an associative array * * \e string \b hash a xchan_hash * @param array $arr * @param array $deliveries (unused) */ function process_profile_delivery($sender, $arr, $deliveries) { logger('process_profile_delivery', LOGGER_DEBUG); $r = q("select xchan_addr from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); if($r) import_directory_profile($sender['hash'], $arr, $r[0]['xchan_addr'], UPDATE_FLAGS_UPDATED, 0); } function process_location_delivery($sender,$arr,$deliveries) { // deliveries is irrelevant logger('process_location_delivery', LOGGER_DEBUG); $r = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); if($r) $sender['key'] = $r[0]['xchan_pubkey']; if(array_key_exists('locations',$arr) && $arr['locations']) { $x = sync_locations($sender,$arr,true); logger('process_location_delivery: results: ' . print_r($x,true), LOGGER_DEBUG); if($x['changed']) { $guid = random_string() . '@' . App::get_hostname(); update_modtime($sender['hash'],$sender['guid'],$arr['locations'][0]['address'],UPDATE_FLAGS_UPDATED); } } } /** * @brief checks for a moved UNO channel and sets the channel_moved flag * * Currently the effect of this flag is to turn the channel into 'read-only' mode. * New content will not be processed (there was still an issue with blocking the * ability to post comments as of 10-Mar-2016). * We do not physically remove the channel at this time. The hub admin may choose * to do so, but is encouraged to allow a grace period of several days in case there * are any issues migrating content. This packet will generally be received by the * original site when the basic channel import has been processed. * * This will only be executed on the UNO system which is the old location * if a new location is reported and there is only one location record. * The rest of the hubloc syncronisation will be handled within * sync_locations */ function check_location_move($sender_hash,$locations) { if(! $locations) return; if(get_config('system','server_role') !== 'basic') return; if(count($locations) != 1) return; $loc = $locations[0]; $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($sender_hash) ); if(! $r) return; if($loc['url'] !== z_root()) { $x = q("update channel set channel_moved = '%s' where channel_hash = '%s' limit 1", dbesc($loc['url']), dbesc($sender_hash) ); // federation plugins may wish to notify connections // of the move on singleton networks $arr = array('channel' => $r[0],'locations' => $locations); call_hooks('location_move',$arr); } } /** * @brief Synchronises locations. * * @param array $sender * @param array $arr * @param boolean $absolute (optional) default false * @return array */ function sync_locations($sender, $arr, $absolute = false) { $ret = array(); if($arr['locations']) { if($absolute) check_location_move($sender['hash'],$arr['locations']); $xisting = q("select hubloc_id, hubloc_url, hubloc_sitekey from hubloc where hubloc_hash = '%s'", dbesc($sender['hash']) ); // See if a primary is specified $has_primary = false; foreach($arr['locations'] as $location) { if($location['primary']) { $has_primary = true; break; } } // Ensure that they have one primary hub if(! $has_primary) $arr['locations'][0]['primary'] = true; foreach($arr['locations'] as $location) { if(! rsa_verify($location['url'],base64url_decode($location['url_sig']),$sender['key'])) { logger('sync_locations: Unable to verify site signature for ' . $location['url']); $ret['message'] .= sprintf( t('Unable to verify site signature for %s'), $location['url']) . EOL; continue; } for($x = 0; $x < count($xisting); $x ++) { if(($xisting[$x]['hubloc_url'] === $location['url']) && ($xisting[$x]['hubloc_sitekey'] === $location['sitekey'])) { $xisting[$x]['updated'] = true; } } if(! $location['sitekey']) { logger('sync_locations: empty hubloc sitekey. ' . print_r($location,true)); continue; } // Catch some malformed entries from the past which still exist if(strpos($location['address'],'/') !== false) $location['address'] = substr($location['address'],0,strpos($location['address'],'/')); // match as many fields as possible in case anything at all changed. $r = q("select * from hubloc where hubloc_hash = '%s' and hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_url = '%s' and hubloc_url_sig = '%s' and hubloc_host = '%s' and hubloc_addr = '%s' and hubloc_callback = '%s' and hubloc_sitekey = '%s' ", dbesc($sender['hash']), dbesc($sender['guid']), dbesc($sender['guid_sig']), dbesc($location['url']), dbesc($location['url_sig']), dbesc($location['host']), dbesc($location['address']), dbesc($location['callback']), dbesc($location['sitekey']) ); if($r) { logger('sync_locations: hub exists: ' . $location['url'], LOGGER_DEBUG); // update connection timestamp if this is the site we're talking to // This only happens when called from import_xchan $current_site = false; $t = datetime_convert('UTC','UTC','now - 15 minutes'); if(array_key_exists('site',$arr) && $location['url'] == $arr['site']['url']) { q("update hubloc set hubloc_connected = '%s', hubloc_updated = '%s' where hubloc_id = %d and hubloc_connected < '%s'", dbesc(datetime_convert()), dbesc(datetime_convert()), intval($r[0]['hubloc_id']), dbesc($t) ); $current_site = true; } if($current_site && intval($r[0]['hubloc_error'])) { q("update hubloc set hubloc_error = 0 where hubloc_id = %d", intval($r[0]['hubloc_id']) ); if(intval($r[0]['hubloc_orphancheck'])) { q("update hubloc set hubloc_orphancheck = 0 where hubloc_id = %d", intval($r[0]['hubloc_id']) ); } q("update xchan set xchan_orphan = 0 where xchan_orphan = 1 and xchan_hash = '%s'", dbesc($sender['hash']) ); } // Remove pure duplicates if(count($r) > 1) { for($h = 1; $h < count($r); $h ++) { q("delete from hubloc where hubloc_id = %d", intval($r[$h]['hubloc_id']) ); $what .= 'duplicate_hubloc_removed '; $changed = true; } } if(intval($r[0]['hubloc_primary']) && (! $location['primary'])) { $m = q("update hubloc set hubloc_primary = 0, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); $r[0]['hubloc_primary'] = intval($location['primary']); hubloc_change_primary($r[0]); $what .= 'primary_hub '; $changed = true; } elseif((! intval($r[0]['hubloc_primary'])) && ($location['primary'])) { $m = q("update hubloc set hubloc_primary = 1, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); // make sure hubloc_change_primary() has current data $r[0]['hubloc_primary'] = intval($location['primary']); hubloc_change_primary($r[0]); $what .= 'primary_hub '; $changed = true; } elseif($absolute) { // Absolute sync - make sure the current primary is correctly reflected in the xchan $pr = hubloc_change_primary($r[0]); if($pr) { $what .= 'xchan_primary '; $changed = true; } } if(intval($r[0]['hubloc_deleted']) && (! intval($location['deleted']))) { $n = q("update hubloc set hubloc_deleted = 0, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); $what .= 'undelete_hub '; $changed = true; } elseif((! intval($r[0]['hubloc_deleted'])) && (intval($location['deleted']))) { logger('deleting hubloc: ' . $r[0]['hubloc_addr']); $n = q("update hubloc set hubloc_deleted = 1, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); $what .= 'delete_hub '; $changed = true; } continue; } // Existing hubs are dealt with. Now let's process any new ones. // New hub claiming to be primary. Make it so by removing any existing primaries. if(intval($location['primary'])) { $r = q("update hubloc set hubloc_primary = 0, hubloc_updated = '%s' where hubloc_hash = '%s' and hubloc_primary = 1", dbesc(datetime_convert()), dbesc($sender['hash']) ); } logger('sync_locations: new hub: ' . $location['url']); $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_network, hubloc_primary, hubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey, hubloc_updated, hubloc_connected) values ( '%s','%s','%s','%s', '%s', %d ,'%s','%s','%s','%s','%s','%s','%s')", dbesc($sender['guid']), dbesc($sender['guid_sig']), dbesc($sender['hash']), dbesc($location['address']), dbesc('zot'), intval($location['primary']), dbesc($location['url']), dbesc($location['url_sig']), dbesc($location['host']), dbesc($location['callback']), dbesc($location['sitekey']), dbesc(datetime_convert()), dbesc(datetime_convert()) ); $what .= 'newhub '; $changed = true; if($location['primary']) { $r = q("select * from hubloc where hubloc_addr = '%s' and hubloc_sitekey = '%s' limit 1", dbesc($location['address']), dbesc($location['sitekey']) ); if($r) hubloc_change_primary($r[0]); } } // get rid of any hubs we have for this channel which weren't reported. if($absolute && $xisting) { foreach($xisting as $x) { if(! array_key_exists('updated',$x)) { logger('sync_locations: deleting unreferenced hub location ' . $x['hubloc_addr']); $r = q("update hubloc set hubloc_deleted = 1, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($x['hubloc_id']) ); $what .= 'removed_hub '; $changed = true; } } } } else { logger('No locations to sync!'); } $ret['change_message'] = $what; $ret['changed'] = $changed; return $ret; } /** * @brief Returns an array with all known distinct hubs for this channel. * * @see zot_get_hublocs() * @param array $channel an associative array which must contain * * \e string \b channel_hash the hash of the channel * @return array an array with associative arrays */ function zot_encode_locations($channel) { $ret = array(); $x = zot_get_hublocs($channel['channel_hash']); if($x && count($x)) { foreach($x as $hub) { // if this is a local channel that has been deleted, the hubloc is no good - make sure it is marked deleted // so that nobody tries to use it. if(intval($channel['channel_removed']) && $hub['hubloc_url'] === z_root()) $hub['hubloc_deleted'] = 1; $ret[] = array( 'host' => $hub['hubloc_host'], 'address' => $hub['hubloc_addr'], 'primary' => (intval($hub['hubloc_primary']) ? true : false), 'url' => $hub['hubloc_url'], 'url_sig' => $hub['hubloc_url_sig'], 'callback' => $hub['hubloc_callback'], 'sitekey' => $hub['hubloc_sitekey'], 'deleted' => (intval($hub['hubloc_deleted']) ? true : false) ); } } return $ret; } /** * @brief Imports a directory profile. * * @param string $hash * @param array $profile * @param string $addr * @param number $ud_flags * @param number $suppress_update default 0 * @return boolean $updated if something changed */ function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLAGS_UPDATED, $suppress_update = 0) { logger('import_directory_profile', LOGGER_DEBUG); if (! $hash) return false; $arr = array(); $arr['xprof_hash'] = $hash; $arr['xprof_dob'] = datetime_convert('','',$profile['birthday'],'Y-m-d'); // !!!! check this for 0000 year $arr['xprof_age'] = (($profile['age']) ? intval($profile['age']) : 0); $arr['xprof_desc'] = (($profile['description']) ? htmlspecialchars($profile['description'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_gender'] = (($profile['gender']) ? htmlspecialchars($profile['gender'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_marital'] = (($profile['marital']) ? htmlspecialchars($profile['marital'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_sexual'] = (($profile['sexual']) ? htmlspecialchars($profile['sexual'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_locale'] = (($profile['locale']) ? htmlspecialchars($profile['locale'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_region'] = (($profile['region']) ? htmlspecialchars($profile['region'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_postcode'] = (($profile['postcode']) ? htmlspecialchars($profile['postcode'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_country'] = (($profile['country']) ? htmlspecialchars($profile['country'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_about'] = (($profile['about']) ? htmlspecialchars($profile['about'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_homepage'] = (($profile['homepage']) ? htmlspecialchars($profile['homepage'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_hometown'] = (($profile['hometown']) ? htmlspecialchars($profile['hometown'], ENT_COMPAT,'UTF-8',false) : ''); $clean = array(); if (array_key_exists('keywords', $profile) and is_array($profile['keywords'])) { import_directory_keywords($hash,$profile['keywords']); foreach ($profile['keywords'] as $kw) { $kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false)); $kw = trim($kw, ','); $clean[] = $kw; } } $arr['xprof_keywords'] = implode(' ',$clean); // Self censored, make it so // These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult". if(in_arrayi('nsfw',$clean) || in_arrayi('adult',$clean)) { q("update xchan set xchan_selfcensored = 1 where xchan_hash = '%s'", dbesc($hash) ); } $r = q("select * from xprof where xprof_hash = '%s' limit 1", dbesc($hash) ); if ($arr['xprof_age'] > 150) $arr['xprof_age'] = 150; if ($arr['xprof_age'] < 0) $arr['xprof_age'] = 0; if ($r) { $update = false; foreach ($r[0] as $k => $v) { if ((array_key_exists($k,$arr)) && ($arr[$k] != $v)) { logger('import_directory_profile: update ' . $k . ' => ' . $arr[$k]); $update = true; break; } } if ($update) { q("update xprof set xprof_desc = '%s', xprof_dob = '%s', xprof_age = %d, xprof_gender = '%s', xprof_marital = '%s', xprof_sexual = '%s', xprof_locale = '%s', xprof_region = '%s', xprof_postcode = '%s', xprof_country = '%s', xprof_about = '%s', xprof_homepage = '%s', xprof_hometown = '%s', xprof_keywords = '%s' where xprof_hash = '%s'", dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), intval($arr['xprof_age']), dbesc($arr['xprof_gender']), dbesc($arr['xprof_marital']), dbesc($arr['xprof_sexual']), dbesc($arr['xprof_locale']), dbesc($arr['xprof_region']), dbesc($arr['xprof_postcode']), dbesc($arr['xprof_country']), dbesc($arr['xprof_about']), dbesc($arr['xprof_homepage']), dbesc($arr['xprof_hometown']), dbesc($arr['xprof_keywords']), dbesc($arr['xprof_hash']) ); } } else { $update = true; logger('import_directory_profile: new profile '); q("insert into xprof (xprof_hash, xprof_desc, xprof_dob, xprof_age, xprof_gender, xprof_marital, xprof_sexual, xprof_locale, xprof_region, xprof_postcode, xprof_country, xprof_about, xprof_homepage, xprof_hometown, xprof_keywords) values ('%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ", dbesc($arr['xprof_hash']), dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), intval($arr['xprof_age']), dbesc($arr['xprof_gender']), dbesc($arr['xprof_marital']), dbesc($arr['xprof_sexual']), dbesc($arr['xprof_locale']), dbesc($arr['xprof_region']), dbesc($arr['xprof_postcode']), dbesc($arr['xprof_country']), dbesc($arr['xprof_about']), dbesc($arr['xprof_homepage']), dbesc($arr['xprof_hometown']), dbesc($arr['xprof_keywords']) ); } $d = array('xprof' => $arr, 'profile' => $profile, 'update' => $update); call_hooks('import_directory_profile', $d); if (($d['update']) && (! $suppress_update)) update_modtime($arr['xprof_hash'],random_string() . '@' . App::get_hostname(), $addr, $ud_flags); return $d['update']; } /** * @brief * * @param string $hash * @param array $keywords */ function import_directory_keywords($hash, $keywords) { $existing = array(); $r = q("select * from xtag where xtag_hash = '%s' and xtag_flags = 0", dbesc($hash) ); if($r) { foreach($r as $rr) $existing[] = $rr['xtag_term']; } $clean = array(); foreach($keywords as $kw) { $kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false)); $kw = trim($kw, ','); $clean[] = $kw; } foreach($existing as $x) { if(! in_array($x, $clean)) $r = q("delete from xtag where xtag_hash = '%s' and xtag_term = '%s' and xtag_flags = 0", dbesc($hash), dbesc($x) ); } foreach($clean as $x) { if(! in_array($x, $existing)) { $r = q("insert into xtag ( xtag_hash, xtag_term, xtag_flags) values ( '%s' ,'%s', 0 )", dbesc($hash), dbesc($x) ); } } } /** * @brief * * @param string $hash * @param string $guid * @param string $addr * @param int $flags (optional) default 0 */ function update_modtime($hash, $guid, $addr, $flags = 0) { $dirmode = intval(get_config('system', 'directory_mode')); if($dirmode == DIRECTORY_MODE_NORMAL) return; if($flags) { q("insert into updates (ud_hash, ud_guid, ud_date, ud_flags, ud_addr ) values ( '%s', '%s', '%s', %d, '%s' )", dbesc($hash), dbesc($guid), dbesc(datetime_convert()), intval($flags), dbesc($addr) ); } else { q("update updates set ud_flags = ( ud_flags | %d ) where ud_addr = '%s' and not (ud_flags & %d)>0 ", intval(UPDATE_FLAGS_UPDATED), dbesc($addr), intval(UPDATE_FLAGS_UPDATED) ); } } /** * @brief * * @param array $arr * @param string $pubkey * @return boolean true if updated or inserted */ function import_site($arr, $pubkey) { if( (! is_array($arr)) || (! $arr['url']) || (! $arr['url_sig'])) return false; if(! rsa_verify($arr['url'], base64url_decode($arr['url_sig']), $pubkey)) { logger('import_site: bad url_sig'); return false; } $update = false; $exists = false; $r = q("select * from site where site_url = '%s' limit 1", dbesc($arr['url']) ); if($r) { $exists = true; $siterecord = $r[0]; } $site_directory = 0; if($arr['directory_mode'] == 'normal') $site_directory = DIRECTORY_MODE_NORMAL; if($arr['directory_mode'] == 'primary') $site_directory = DIRECTORY_MODE_PRIMARY; if($arr['directory_mode'] == 'secondary') $site_directory = DIRECTORY_MODE_SECONDARY; if($arr['directory_mode'] == 'standalone') $site_directory = DIRECTORY_MODE_STANDALONE; $register_policy = 0; if($arr['register_policy'] == 'closed') $register_policy = REGISTER_CLOSED; if($arr['register_policy'] == 'open') $register_policy = REGISTER_OPEN; if($arr['register_policy'] == 'approve') $register_policy = REGISTER_APPROVE; $access_policy = 0; if(array_key_exists('access_policy',$arr)) { if($arr['access_policy'] === 'private') $access_policy = ACCESS_PRIVATE; if($arr['access_policy'] === 'paid') $access_policy = ACCESS_PAID; if($arr['access_policy'] === 'free') $access_policy = ACCESS_FREE; if($arr['access_policy'] === 'tiered') $access_policy = ACCESS_TIERED; } // don't let insecure sites register as public hubs if(strpos($arr['url'],'https://') === false) $access_policy = ACCESS_PRIVATE; if($access_policy != ACCESS_PRIVATE) { $x = z_fetch_url($arr['url'] . '/siteinfo/json'); if(! $x['success']) $access_policy = ACCESS_PRIVATE; } $directory_url = htmlspecialchars($arr['directory_url'],ENT_COMPAT,'UTF-8',false); $url = htmlspecialchars(strtolower($arr['url']),ENT_COMPAT,'UTF-8',false); $sellpage = htmlspecialchars($arr['sellpage'],ENT_COMPAT,'UTF-8',false); $site_location = htmlspecialchars($arr['location'],ENT_COMPAT,'UTF-8',false); $site_realm = htmlspecialchars($arr['realm'],ENT_COMPAT,'UTF-8',false); $site_project = htmlspecialchars($arr['project'],ENT_COMPAT,'UTF-8',false); // You can have one and only one primary directory per realm. // Downgrade any others claiming to be primary. As they have // flubbed up this badly already, don't let them be directory servers at all. if(($site_directory === DIRECTORY_MODE_PRIMARY) && ($site_realm === get_directory_realm()) && ($arr['url'] != get_directory_primary())) { $site_directory = DIRECTORY_MODE_NORMAL; } if($exists) { if(($siterecord['site_flags'] != $site_directory) || ($siterecord['site_access'] != $access_policy) || ($siterecord['site_directory'] != $directory_url) || ($siterecord['site_sellpage'] != $sellpage) || ($siterecord['site_location'] != $site_location) || ($siterecord['site_register'] != $register_policy) || ($siterecord['site_project'] != $site_project) || ($siterecord['site_realm'] != $site_realm)) { $update = true; // logger('import_site: input: ' . print_r($arr,true)); // logger('import_site: stored: ' . print_r($siterecord,true)); $r = q("update site set site_dead = 0, site_location = '%s', site_flags = %d, site_access = %d, site_directory = '%s', site_register = %d, site_update = '%s', site_sellpage = '%s', site_realm = '%s', site_type = %d, site_project = '%s' where site_url = '%s'", dbesc($site_location), intval($site_directory), intval($access_policy), dbesc($directory_url), intval($register_policy), dbesc(datetime_convert()), dbesc($sellpage), dbesc($site_realm), intval(SITE_TYPE_ZOT), dbesc($site_project), dbesc($url) ); if(! $r) { logger('import_site: update failed. ' . print_r($arr,true)); } } else { // update the timestamp to indicate we communicated with this site q("update site set site_dead = 0, site_update = '%s' where site_url = '%s'", dbesc(datetime_convert()), dbesc($url) ); } } else { $update = true; $r = q("insert into site ( site_location, site_url, site_access, site_flags, site_update, site_directory, site_register, site_sellpage, site_realm, site_type, site_project ) values ( '%s', '%s', %d, %d, '%s', '%s', %d, '%s', '%s', %d, '%s' )", dbesc($site_location), dbesc($url), intval($access_policy), intval($site_directory), dbesc(datetime_convert()), dbesc($directory_url), intval($register_policy), dbesc($sellpage), dbesc($site_realm), intval(SITE_TYPE_ZOT), dbesc($site_project) ); if(! $r) { logger('import_site: record create failed. ' . print_r($arr,true)); } } return $update; } /** * Send a zot packet to all hubs where this channel is duplicated, refreshing * such things as personal settings, channel permissions, address book updates, etc. * * @param int $uid * @param array $packet (optional) default null * @param boolean $groups_changed (optional) default false */ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) { if(get_config('system','server_role') === 'basic') return; logger('build_sync_packet'); if($packet) logger('packet: ' . print_r($packet, true),LOGGER_DATA, LOG_DEBUG); if(! $uid) $uid = local_channel(); if(! $uid) return; $r = q("select * from channel where channel_id = %d limit 1", intval($uid) ); if(! $r) return; $channel = $r[0]; translate_channel_perms_outbound($channel); if($packet && array_key_exists('abook',$packet) && $packet['abook']) { for($x = 0; $x < count($packet['abook']); $x ++) { translate_abook_perms_outbound($packet['abook'][$x]); } } if(intval($channel['channel_removed'])) return; $h = q("select * from hubloc where hubloc_hash = '%s' and hubloc_deleted = 0", dbesc($channel['channel_hash']) ); if(! $h) return; $synchubs = array(); foreach($h as $x) { if($x['hubloc_host'] == App::get_hostname()) continue; $y = q("select site_dead from site where site_url = '%s' limit 1", dbesc($x['hubloc_url']) ); if((! $y) || ($y[0]['site_dead'] == 0)) $synchubs[] = $x; } if(! $synchubs) return; $r = q("select xchan_guid, xchan_guid_sig from xchan where xchan_hash = '%s' limit 1", dbesc($channel['channel_hash']) ); if(! $r) return; $env_recips = array(); $env_recips[] = array('guid' => $r[0]['xchan_guid'],'guid_sig' => $r[0]['xchan_guid_sig']); $info = (($packet) ? $packet : array()); $info['type'] = 'channel_sync'; $info['encoding'] = 'red'; // note: not zot, this packet is very platform specific $info['relocate'] = ['channel_address' => $channel['channel_address'], 'url' => z_root() ]; if(array_key_exists($uid,App::$config) && array_key_exists('transient',App::$config[$uid])) { $settings = App::$config[$uid]['transient']; if($settings) { $info['config'] = $settings; } } if($channel) { $info['channel'] = array(); foreach($channel as $k => $v) { // filter out any joined tables like xchan if(strpos($k,'channel_') !== 0) continue; // don't pass these elements, they should not be synchronised $disallowed = array('channel_id','channel_account_id','channel_primary','channel_prvkey','channel_address','channel_deleted','channel_removed','channel_system'); if(in_array($k,$disallowed)) continue; $info['channel'][$k] = $v; } } if($groups_changed) { $r = q("select hash as collection, visible, deleted, gname as name from groups where uid = %d", intval($uid) ); if($r) $info['collections'] = $r; $r = q("select groups.hash as collection, group_member.xchan as member from groups left join group_member on groups.id = group_member.gid where group_member.uid = %d", intval($uid) ); if($r) $info['collection_members'] = $r; } $interval = ((get_config('system','delivery_interval') !== false) ? intval(get_config('system','delivery_interval')) : 2 ); logger('build_sync_packet: packet: ' . print_r($info,true), LOGGER_DATA, LOG_DEBUG); $total = count($synchubs); foreach($synchubs as $hub) { $hash = random_string(); $n = zot_build_packet($channel,'notify',$env_recips,$hub['hubloc_sitekey'],$hash); queue_insert(array( 'hash' => $hash, 'account_id' => $channel['channel_account_id'], 'channel_id' => $channel['channel_id'], 'posturl' => $hub['hubloc_callback'], 'notify' => $n, 'msg' => json_encode($info) )); Zotlabs\Daemon\Master::Summon(array('Deliver', $hash)); $total = $total - 1; if($interval && $total) @time_sleep_until(microtime(true) + (float) $interval); } } /** * @brief * * @param array $sender * @param array $arr * @param array $deliveries * @return array */ function process_channel_sync_delivery($sender, $arr, $deliveries) { if(get_config('system','server_role') === 'basic') return; require_once('include/import.php'); /** @FIXME this will sync red structures (channel, pconfig and abook). Eventually we need to make this application agnostic. */ $result = array(); foreach ($deliveries as $d) { $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); if (! $r) { $result[] = array($d['hash'],'not found'); continue; } $channel = $r[0]; $max_friends = service_class_fetch($channel['channel_id'],'total_channels'); $max_feeds = account_service_class_fetch($channel['channel_account_id'],'total_feeds'); if($channel['channel_hash'] != $sender['hash']) { logger('process_channel_sync_delivery: possible forgery. Sender ' . $sender['hash'] . ' is not ' . $channel['channel_hash']); $result[] = array($d['hash'],'channel mismatch',$channel['channel_name'],''); continue; } if(array_key_exists('config',$arr) && is_array($arr['config']) && count($arr['config'])) { foreach($arr['config'] as $cat => $k) { foreach($arr['config'][$cat] as $k => $v) set_pconfig($channel['channel_id'],$cat,$k,$v); } } if(array_key_exists('obj',$arr) && $arr['obj']) sync_objs($channel,$arr['obj']); if(array_key_exists('likes',$arr) && $arr['likes']) import_likes($channel,$arr['likes']); if(array_key_exists('app',$arr) && $arr['app']) sync_apps($channel,$arr['app']); if(array_key_exists('chatroom',$arr) && $arr['chatroom']) sync_chatrooms($channel,$arr['chatroom']); if(array_key_exists('conv',$arr) && $arr['conv']) import_conv($channel,$arr['conv']); if(array_key_exists('mail',$arr) && $arr['mail']) sync_mail($channel,$arr['mail']); if(array_key_exists('event',$arr) && $arr['event']) sync_events($channel,$arr['event']); if(array_key_exists('event_item',$arr) && $arr['event_item']) sync_items($channel,$arr['event_item'],((array_key_exists('relocate',$arr)) ? $arr['relocate'] : null)); if(array_key_exists('item',$arr) && $arr['item']) sync_items($channel,$arr['item'],((array_key_exists('relocate',$arr)) ? $arr['relocate'] : null)); // deprecated, maintaining for a few months for upward compatibility // this should sync webpages, but the logic is a bit subtle if(array_key_exists('item_id',$arr) && $arr['item_id']) sync_items($channel,$arr['item_id']); if(array_key_exists('menu',$arr) && $arr['menu']) sync_menus($channel,$arr['menu']); if(array_key_exists('file',$arr) && $arr['file']) sync_files($channel,$arr['file']); if(array_key_exists('channel',$arr) && is_array($arr['channel']) && count($arr['channel'])) { translate_channel_perms_inbound($arr['channel']); if(array_key_exists('channel_pageflags',$arr['channel']) && intval($arr['channel']['channel_pageflags'])) { // These flags cannot be sync'd. // remove the bits from the incoming flags. // These correspond to PAGE_REMOVED and PAGE_SYSTEM on redmatrix if($arr['channel']['channel_pageflags'] & 0x8000) $arr['channel']['channel_pageflags'] = $arr['channel']['channel_pageflags'] - 0x8000; if($arr['channel']['channel_pageflags'] & 0x1000) $arr['channel']['channel_pageflags'] = $arr['channel']['channel_pageflags'] - 0x1000; } $disallowed = [ 'channel_id', 'channel_account_id', 'channel_primary', 'channel_prvkey', 'channel_address', 'channel_notifyflags', 'channel_removed', 'channel_deleted', 'channel_system', 'channel_r_stream', 'channel_r_profile', 'channel_r_abook', 'channel_r_storage', 'channel_r_pages', 'channel_w_stream', 'channel_w_wall', 'channel_w_comment', 'channel_w_mail', 'channel_w_like', 'channel_w_tagwall', 'channel_w_chat', 'channel_w_storage', 'channel_w_pages', 'channel_a_republish', 'channel_a_delegate' ]; $clean = array(); foreach($arr['channel'] as $k => $v) { if(in_array($k,$disallowed)) continue; $clean[$k] = $v; } if(count($clean)) { foreach($clean as $k => $v) { $r = dbq("UPDATE channel set " . dbesc($k) . " = '" . dbesc($v) . "' where channel_id = " . intval($channel['channel_id']) ); } } } if(array_key_exists('abook',$arr) && is_array($arr['abook']) && count($arr['abook'])) { $total_friends = 0; $total_feeds = 0; $r = q("select abook_id, abook_feed from abook where abook_channel = %d", intval($channel['channel_id']) ); if($r) { // don't count yourself $total_friends = ((count($r) > 0) ? count($r) - 1 : 0); foreach($r as $rr) if(intval($rr['abook_feed'])) $total_feeds ++; } $disallowed = array('abook_id','abook_account','abook_channel','abook_rating','abook_rating_text'); foreach($arr['abook'] as $abook) { $abconfig = null; if(array_key_exists('abconfig',$abook) && is_array($abook['abconfig']) && count($abook['abconfig'])) $abconfig = $abook['abconfig']; if(! array_key_exists('abook_blocked',$abook)) { // convert from redmatrix $abook['abook_blocked'] = (($abook['abook_flags'] & 0x0001) ? 1 : 0); $abook['abook_ignored'] = (($abook['abook_flags'] & 0x0002) ? 1 : 0); $abook['abook_hidden'] = (($abook['abook_flags'] & 0x0004) ? 1 : 0); $abook['abook_archived'] = (($abook['abook_flags'] & 0x0008) ? 1 : 0); $abook['abook_pending'] = (($abook['abook_flags'] & 0x0010) ? 1 : 0); $abook['abook_unconnected'] = (($abook['abook_flags'] & 0x0020) ? 1 : 0); $abook['abook_self'] = (($abook['abook_flags'] & 0x0080) ? 1 : 0); $abook['abook_feed'] = (($abook['abook_flags'] & 0x0100) ? 1 : 0); } $clean = array(); if($abook['abook_xchan'] && $abook['entry_deleted']) { logger('process_channel_sync_delivery: removing abook entry for ' . $abook['abook_xchan']); $r = q("select abook_id, abook_feed from abook where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 limit 1", dbesc($abook['abook_xchan']), intval($channel['channel_id']) ); if($r) { contact_remove($channel['channel_id'],$r[0]['abook_id']); if($total_friends) $total_friends --; if(intval($r[0]['abook_feed'])) $total_feeds --; } continue; } // Perform discovery if the referenced xchan hasn't ever been seen on this hub. // This relies on the undocumented behaviour that red sites send xchan info with the abook // and import_author_xchan will look them up on all federated networks if($abook['abook_xchan'] && $abook['xchan_addr']) { $h = zot_get_hublocs($abook['abook_xchan']); if(! $h) { $xhash = import_author_xchan(encode_item_xchan($abook)); if(! $xhash) { logger('process_channel_sync_delivery: import of ' . $abook['xchan_addr'] . ' failed.'); continue; } } } foreach($abook as $k => $v) { if(in_array($k,$disallowed) || (strpos($k,'abook') !== 0)) continue; $clean[$k] = $v; } if(! array_key_exists('abook_xchan',$clean)) continue; $r = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($clean['abook_xchan']), intval($channel['channel_id']) ); // make sure we have an abook entry for this xchan on this system if(! $r) { if($max_friends !== false && $total_friends > $max_friends) { logger('process_channel_sync_delivery: total_channels service class limit exceeded'); continue; } if($max_feeds !== false && intval($clean['abook_feed']) && $total_feeds > $max_feeds) { logger('process_channel_sync_delivery: total_feeds service class limit exceeded'); continue; } q("insert into abook ( abook_xchan, abook_account, abook_channel ) values ('%s', %d, %d ) ", dbesc($clean['abook_xchan']), intval($channel['channel_account_id']), intval($channel['channel_id']) ); $total_friends ++; if(intval($clean['abook_feed'])) $total_feeds ++; } if(count($clean)) { foreach($clean as $k => $v) { if($k == 'abook_dob') $v = dbescdate($v); $r = dbq("UPDATE abook set " . dbesc($k) . " = '" . dbesc($v) . "' where abook_xchan = '" . dbesc($clean['abook_xchan']) . "' and abook_channel = " . intval($channel['channel_id'])); } } // This will set abconfig vars if the sender is using old-style fixed permissions // using the raw abook record as passed to us. New-style permissions will fall through // and be set using abconfig translate_abook_perms_inbound($channel,$abook); if($abconfig) { // @fixme does not handle sync of del_abconfig foreach($abconfig as $abc) { set_abconfig($channel['channel_id'],$abc['xchan'],$abc['cat'],$abc['k'],$abc['v']); } } } } // sync collections (privacy groups) oh joy... if(array_key_exists('collections',$arr) && is_array($arr['collections']) && count($arr['collections'])) { $x = q("select * from groups where uid = %d", intval($channel['channel_id']) ); foreach($arr['collections'] as $cl) { $found = false; if($x) { foreach($x as $y) { if($cl['collection'] == $y['hash']) { $found = true; break; } } if($found) { if(($y['gname'] != $cl['name']) || ($y['visible'] != $cl['visible']) || ($y['deleted'] != $cl['deleted'])) { q("update groups set gname = '%s', visible = %d, deleted = %d where hash = '%s' and uid = %d", dbesc($cl['name']), intval($cl['visible']), intval($cl['deleted']), dbesc($cl['hash']), intval($channel['channel_id']) ); } if(intval($cl['deleted']) && (! intval($y['deleted']))) { q("delete from group_member where gid = %d", intval($y['id']) ); } } } if(! $found) { $r = q("INSERT INTO `groups` ( hash, uid, visible, deleted, gname ) VALUES( '%s', %d, %d, %d, '%s' ) ", dbesc($cl['collection']), intval($channel['channel_id']), intval($cl['visible']), intval($cl['deleted']), dbesc($cl['name']) ); } // now look for any collections locally which weren't in the list we just received. // They need to be removed by marking deleted and removing the members. // This shouldn't happen except for clones created before this function was written. if($x) { $found_local = false; foreach($x as $y) { foreach($arr['collections'] as $cl) { if($cl['collection'] == $y['hash']) { $found_local = true; break; } } if(! $found_local) { q("delete from group_member where gid = %d", intval($y['id']) ); q("update groups set deleted = 1 where id = %d and uid = %d", intval($y['id']), intval($channel['channel_id']) ); } } } } // reload the group list with any updates $x = q("select * from groups where uid = %d", intval($channel['channel_id']) ); // now sync the members if(array_key_exists('collection_members', $arr) && is_array($arr['collection_members']) && count($arr['collection_members'])) { // first sort into groups keyed by the group hash $members = array(); foreach($arr['collection_members'] as $cm) { if(! array_key_exists($cm['collection'],$members)) $members[$cm['collection']] = array(); $members[$cm['collection']][] = $cm['member']; } // our group list is already synchronised if($x) { foreach($x as $y) { // for each group, loop on members list we just received foreach($members[$y['hash']] as $member) { $found = false; $z = q("select xchan from group_member where gid = %d and uid = %d and xchan = '%s' limit 1", intval($y['id']), intval($channel['channel_id']), dbesc($member) ); if($z) $found = true; // if somebody is in the group that wasn't before - add them if(! $found) { q("INSERT INTO `group_member` (`uid`, `gid`, `xchan`) VALUES( %d, %d, '%s' ) ", intval($channel['channel_id']), intval($y['id']), dbesc($member) ); } } // now retrieve a list of members we have on this site $m = q("select xchan from group_member where gid = %d and uid = %d", intval($y['id']), intval($channel['channel_id']) ); if($m) { foreach($m as $mm) { // if the local existing member isn't in the list we just received - remove them if(! in_array($mm['xchan'],$members[$y['hash']])) { q("delete from group_member where xchan = '%s' and gid = %d and uid = %d", dbesc($mm['xchan']), intval($y['id']), intval($channel['channel_id']) ); } } } } } } } if(array_key_exists('profile',$arr) && is_array($arr['profile']) && count($arr['profile'])) { $disallowed = array('id','aid','uid','guid'); foreach($arr['profile'] as $profile) { $x = q("select * from profile where profile_guid = '%s' and uid = %d limit 1", dbesc($profile['profile_guid']), intval($channel['channel_id']) ); if(! $x) { q("insert into profile ( profile_guid, aid, uid ) values ('%s', %d, %d)", dbesc($profile['profile_guid']), intval($channel['channel_account_id']), intval($channel['channel_id']) ); $x = q("select * from profile where profile_guid = '%s' and uid = %d limit 1", dbesc($profile['profile_guid']), intval($channel['channel_id']) ); if(! $x) continue; } $clean = array(); foreach($profile as $k => $v) { if(in_array($k,$disallowed)) continue; if($k === 'name') $clean['fullname'] = $v; elseif($k === 'with') $clean['partner'] = $v; elseif($k === 'work') $clean['employment'] = $v; elseif(array_key_exists($k,$x[0])) $clean[$k] = $v; /** * @TODO * We also need to import local photos if a custom photo is selected */ } if(count($clean)) { foreach($clean as $k => $v) { $r = dbq("UPDATE profile set `" . dbesc($k) . "` = '" . dbesc($v) . "' where profile_guid = '" . dbesc($profile['profile_guid']) . "' and uid = " . intval($channel['channel_id'])); } } } } $addon = array('channel' => $channel,'data' => $arr); call_hooks('process_channel_sync_delivery',$addon); // we should probably do this for all items, but usually we only send one. if(array_key_exists('item',$arr) && is_array($arr['item'][0])) { $DR = new Zotlabs\Zot\DReport(z_root(),$d['hash'],$d['hash'],$arr['item'][0]['message_id'],'channel sync processed'); $DR->addto_recipient($channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . App::get_hostname() . '>'); } else $DR = new Zotlabs\Zot\DReport(z_root(),$d['hash'],$d['hash'],'sync packet','channel sync delivered'); $result[] = $DR->get(); } return $result; } /** * @brief Returns path to /rpost * * @todo We probably should make rpost discoverable. * * @param array $observer * * \e string \b xchan_url * @return string */ function get_rpost_path($observer) { if(! $observer) return ''; $parsed = parse_url($observer['xchan_url']); return $parsed['scheme'] . '://' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '') . '/rpost?f='; } /** * @brief * * @param array $x * @return boolean|string return false or a hash */ function import_author_zot($x) { $hash = make_xchan_hash($x['guid'],$x['guid_sig']); $r = q("select hubloc_url from hubloc where hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_primary = 1 limit 1", dbesc($x['guid']), dbesc($x['guid_sig']) ); if ($r) { logger('import_author_zot: in cache', LOGGER_DEBUG); return $hash; } logger('import_author_zot: entry not in cache - probing: ' . print_r($x,true), LOGGER_DEBUG); $them = array('hubloc_url' => $x['url'], 'xchan_guid' => $x['guid'], 'xchan_guid_sig' => $x['guid_sig']); if (zot_refresh($them)) return $hash; return false; } /** * @brief Process a message request. * * If a site receives a comment to a post but finds they have no parent to attach it with, they * may send a 'request' packet containing the message_id of the missing parent. This is the handler * for that packet. We will create a message_list array of the entire conversation starting with * the missing parent and invoke delivery to the sender of the packet. * * include/deliver.php (for local delivery) and mod/post.php (for web delivery) detect the existence of * this 'message_list' at the destination and split it into individual messages which are * processed/delivered in order. * * Called from mod/post.php * * @param array $data * @return array */ function zot_reply_message_request($data) { $ret = array('success' => false); if (! $data['message_id']) { $ret['message'] = 'no message_id'; logger('no message_id'); json_return_and_die($ret); } $sender = $data['sender']; $sender_hash = make_xchan_hash($sender['guid'], $sender['guid_sig']); /* * Find the local channel in charge of this post (the first and only recipient of the request packet) */ $arr = $data['recipients'][0]; $recip_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); $c = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_hash = '%s' limit 1", dbesc($recip_hash) ); if (! $c) { logger('recipient channel not found.'); $ret['message'] .= 'recipient not found.' . EOL; json_return_and_die($ret); } /* * fetch the requested conversation */ $messages = zot_feed($c[0]['channel_id'],$sender_hash,array('message_id' => $data['message_id'])); if ($messages) { $env_recips = null; $r = q("select * from hubloc where hubloc_hash = '%s' and hubloc_error = 0 and hubloc_deleted = 0 group by hubloc_sitekey", dbesc($sender_hash) ); if (! $r) { logger('no hubs'); json_return_and_die($ret); } $hubs = $r; $private = ((array_key_exists('flags', $messages[0]) && in_array('private',$messages[0]['flags'])) ? true : false); if($private) $env_recips = array('guid' => $sender['guid'], 'guid_sig' => $sender['guid_sig'], 'hash' => $sender_hash); $data_packet = json_encode(array('message_list' => $messages)); foreach($hubs as $hub) { $hash = random_string(); /* * create a notify packet and drop the actual message packet in the queue for pickup */ $n = zot_build_packet($c[0],'notify',$env_recips,(($private) ? $hub['hubloc_sitekey'] : null),$hash,array('message_id' => $data['message_id'])); queue_insert(array( 'hash' => $hash, 'account_id' => $c[0]['channel_account_id'], 'channel_id' => $c[0]['channel_id'], 'posturl' => $hub['hubloc_callback'], 'notify' => $n, 'msg' => $data_packet )); /* * invoke delivery to send out the notify packet */ Zotlabs\Daemon\Master::Summon(array('Deliver', $hash)); } } $ret['success'] = true; json_return_and_die($ret); } function zotinfo($arr) { $ret = array('success' => false); $zhash = ((x($arr,'guid_hash')) ? $arr['guid_hash'] : ''); $zguid = ((x($arr,'guid')) ? $arr['guid'] : ''); $zguid_sig = ((x($arr,'guid_sig')) ? $arr['guid_sig'] : ''); $zaddr = ((x($arr,'address')) ? $arr['address'] : ''); $ztarget = ((x($arr,'target')) ? $arr['target'] : ''); $zsig = ((x($arr,'target_sig')) ? $arr['target_sig'] : ''); $zkey = ((x($arr,'key')) ? $arr['key'] : ''); $mindate = ((x($arr,'mindate')) ? $arr['mindate'] : ''); $token = ((x($arr,'token')) ? $arr['token'] : ''); $feed = ((x($arr,'feed')) ? intval($arr['feed']) : 0); if($ztarget) { if((! $zkey) || (! $zsig) || (! rsa_verify($ztarget,base64url_decode($zsig),$zkey))) { logger('zfinger: invalid target signature'); $ret['message'] = t("invalid target signature"); return($ret); } } $ztarget_hash = (($ztarget && $zsig) ? make_xchan_hash($ztarget,$zsig) : '' ); $r = null; if(strlen($zhash)) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_hash = '%s' limit 1", dbesc($zhash) ); } elseif(strlen($zguid) && strlen($zguid_sig)) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_guid = '%s' and channel_guid_sig = '%s' limit 1", dbesc($zguid), dbesc($zguid_sig) ); } elseif(strlen($zaddr)) { if(strpos($zaddr,'[system]') === false) { /* normal address lookup */ $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where ( channel_address = '%s' or xchan_addr = '%s' ) limit 1", dbesc($zaddr), dbesc($zaddr) ); } else { /** * The special address '[system]' will return a system channel if one has been defined, * Or the first valid channel we find if there are no system channels. * * This is used by magic-auth if we have no prior communications with this site - and * returns an identity on this site which we can use to create a valid hub record so that * we can exchange signed messages. The precise identity is irrelevant. It's the hub * information that we really need at the other end - and this will return it. * */ $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_system = 1 order by channel_id limit 1"); if(! $r) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_removed = 0 order by channel_id limit 1"); } } } else { $ret['message'] = 'Invalid request'; return($ret); } if(! $r) { $ret['message'] = 'Item not found.'; return($ret); } $e = $r[0]; $id = $e['channel_id']; $sys_channel = (intval($e['channel_system']) ? true : false); $special_channel = (($e['channel_pageflags'] & PAGE_PREMIUM) ? true : false); $adult_channel = (($e['channel_pageflags'] & PAGE_ADULT) ? true : false); $censored = (($e['channel_pageflags'] & PAGE_CENSORED) ? true : false); $searchable = (($e['channel_pageflags'] & PAGE_HIDDEN) ? false : true); $deleted = (intval($e['xchan_deleted']) ? true : false); if($deleted || $censored || $sys_channel) $searchable = false; $public_forum = false; $role = get_pconfig($e['channel_id'],'system','permissions_role'); if($role === 'forum' || $role === 'repository') { $public_forum = true; } elseif($ztarget_hash) { // check if it has characteristics of a public forum based on custom permissions. $t = q("select * from abconfig where abconfig.cat = 'my_perms' and abconfig.chan = %d and abconfig.xchan = '%s' and abconfig.k in ('tag_deliver', 'send_stream') ", intval($e['channel_id']), dbesc($ztarget_hash) ); $ch = 0; if($t) { foreach($t as $tt) { if($tt['k'] == 'tag_deliver' && $tt['v'] == 1) $ch ++; if($tt['k'] == 'send_stream' && $tt['v'] == 0) $ch ++; } if($ch == 2) $public_forum = true; } } // This is for birthdays and keywords, but must check access permissions $p = q("select * from profile where uid = %d and is_default = 1", intval($e['channel_id']) ); $profile = array(); if($p) { if(! intval($p[0]['publish'])) $searchable = false; $profile['description'] = $p[0]['pdesc']; $profile['birthday'] = $p[0]['dob']; if(($profile['birthday'] != '0000-00-00') && (($bd = z_birthday($p[0]['dob'],$e['channel_timezone'])) !== '')) $profile['next_birthday'] = $bd; if($age = age($p[0]['dob'],$e['channel_timezone'],'')) $profile['age'] = $age; $profile['gender'] = $p[0]['gender']; $profile['marital'] = $p[0]['marital']; $profile['sexual'] = $p[0]['sexual']; $profile['locale'] = $p[0]['locality']; $profile['region'] = $p[0]['region']; $profile['postcode'] = $p[0]['postal_code']; $profile['country'] = $p[0]['country_name']; $profile['about'] = $p[0]['about']; $profile['homepage'] = $p[0]['homepage']; $profile['hometown'] = $p[0]['hometown']; if($p[0]['keywords']) { $tags = array(); $k = explode(' ',$p[0]['keywords']); if($k) { foreach($k as $kk) { if(trim($kk," \t\n\r\0\x0B,")) { $tags[] = trim($kk," \t\n\r\0\x0B,"); } } } if($tags) $profile['keywords'] = $tags; } } $ret['success'] = true; // Communication details if($token) $ret['signed_token'] = base64url_encode(rsa_sign('token.' . $token,$e['channel_prvkey'])); $ret['guid'] = $e['xchan_guid']; $ret['guid_sig'] = $e['xchan_guid_sig']; $ret['key'] = $e['xchan_pubkey']; $ret['name'] = $e['xchan_name']; $ret['name_updated'] = $e['xchan_name_date']; $ret['address'] = $e['xchan_addr']; $ret['photo_mimetype'] = $e['xchan_photo_mimetype']; $ret['photo'] = $e['xchan_photo_l']; $ret['photo_updated'] = $e['xchan_photo_date']; $ret['url'] = $e['xchan_url']; $ret['connections_url']= (($e['xchan_connurl']) ? $e['xchan_connurl'] : z_root() . '/poco/' . $e['channel_address']); $ret['target'] = $ztarget; $ret['target_sig'] = $zsig; $ret['searchable'] = $searchable; $ret['adult_content'] = $adult_channel; $ret['public_forum'] = $public_forum; if($deleted) $ret['deleted'] = $deleted; if(intval($e['channel_removed'])) $ret['deleted_locally'] = true; // premium or other channel desiring some contact with potential followers before connecting. // This is a template - %s will be replaced with the follow_url we discover for the return channel. if($special_channel) $ret['connect_url'] = z_root() . '/connect/' . $e['channel_address']; // This is a template for our follow url, %s will be replaced with a webbie $ret['follow_url'] = z_root() . '/follow?f=&url=%s'; $permissions = get_all_perms($e['channel_id'],$ztarget_hash,false); if($ztarget_hash) { $permissions['connected'] = false; $b = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($ztarget_hash), intval($e['channel_id']) ); if($b) $permissions['connected'] = true; } $ret['permissions'] = (($ztarget && $zkey) ? crypto_encapsulate(json_encode($permissions),$zkey) : $permissions); if($permissions['view_profile']) $ret['profile'] = $profile; // array of (verified) hubs this channel uses $x = zot_encode_locations($e); if($x) $ret['locations'] = $x; $ret['site'] = array(); $ret['site']['url'] = z_root(); $ret['site']['url_sig'] = base64url_encode(rsa_sign(z_root(),$e['channel_prvkey'])); $ret['site']['zot_auth'] = z_root() . '/magic'; $dirmode = get_config('system','directory_mode'); if(($dirmode === false) || ($dirmode == DIRECTORY_MODE_NORMAL)) $ret['site']['directory_mode'] = 'normal'; if($dirmode == DIRECTORY_MODE_PRIMARY) $ret['site']['directory_mode'] = 'primary'; elseif($dirmode == DIRECTORY_MODE_SECONDARY) $ret['site']['directory_mode'] = 'secondary'; elseif($dirmode == DIRECTORY_MODE_STANDALONE) $ret['site']['directory_mode'] = 'standalone'; if($dirmode != DIRECTORY_MODE_NORMAL) $ret['site']['directory_url'] = z_root() . '/dirsearch'; // hide detailed site information if you're off the grid if($dirmode != DIRECTORY_MODE_STANDALONE) { $register_policy = intval(get_config('system','register_policy')); if($register_policy == REGISTER_CLOSED) $ret['site']['register_policy'] = 'closed'; if($register_policy == REGISTER_APPROVE) $ret['site']['register_policy'] = 'approve'; if($register_policy == REGISTER_OPEN) $ret['site']['register_policy'] = 'open'; $access_policy = intval(get_config('system','access_policy')); if($access_policy == ACCESS_PRIVATE) $ret['site']['access_policy'] = 'private'; if($access_policy == ACCESS_PAID) $ret['site']['access_policy'] = 'paid'; if($access_policy == ACCESS_FREE) $ret['site']['access_policy'] = 'free'; if($access_policy == ACCESS_TIERED) $ret['site']['access_policy'] = 'tiered'; $ret['site']['accounts'] = account_total(); require_once('include/channel.php'); $ret['site']['channels'] = channel_total(); $ret['site']['version'] = Zotlabs\Lib\System::get_platform_name() . ' ' . STD_VERSION . '[' . DB_UPDATE_VERSION . ']'; $ret['site']['admin'] = get_config('system','admin_email'); $visible_plugins = array(); if(is_array(App::$plugins) && count(App::$plugins)) { $r = q("select * from addon where hidden = 0"); if($r) foreach($r as $rr) $visible_plugins[] = $rr['name']; } $ret['site']['plugins'] = $visible_plugins; $ret['site']['sitehash'] = get_config('system','location_hash'); $ret['site']['sitename'] = get_config('system','sitename'); $ret['site']['sellpage'] = get_config('system','sellpage'); $ret['site']['location'] = get_config('system','site_location'); $ret['site']['realm'] = get_directory_realm(); $ret['site']['project'] = Zotlabs\Lib\System::get_platform_name() . ' ' . Zotlabs\Lib\System::get_server_role(); } check_zotinfo($e,$x,$ret); call_hooks('zot_finger',$ret); return($ret); } function check_zotinfo($channel,$locations,&$ret) { // logger('locations: ' . print_r($locations,true),LOGGER_DATA, LOG_DEBUG); // This function will likely expand as we find more things to detect and fix. // 1. Because magic-auth is reliant on it, ensure that the system channel has a valid hubloc // Force this to be the case if anything is found to be wrong with it. // @FIXME ensure that the system channel exists in the first place and has an xchan if($channel['channel_system']) { // the sys channel must have a location (hubloc) $valid_location = false; if((count($locations) === 1) && ($locations[0]['primary']) && (! $locations[0]['deleted'])) { if((rsa_verify($locations[0]['url'],base64url_decode($locations[0]['url_sig']),$channel['channel_pubkey'])) && ($locations[0]['sitekey'] === get_config('system','pubkey')) && ($locations[0]['url'] === z_root())) $valid_location = true; else logger('sys channel: invalid url signature'); } if((! $locations) || (! $valid_location)) { logger('System channel locations are not valid. Attempting repair.'); // Don't trust any existing records. Just get rid of them, but only do this // for the sys channel as normal channels will be trickier. q("delete from hubloc where hubloc_hash = '%s'", dbesc($channel['channel_hash']) ); $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_primary, hubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey, hubloc_network ) values ( '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s' )", dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_hash']), dbesc($channel['channel_address'] . '@' . App::get_hostname()), intval(1), dbesc(z_root()), dbesc(base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey']))), dbesc(App::get_hostname()), dbesc(z_root() . '/post'), dbesc(get_config('system','pubkey')), dbesc('zot') ); if($r) { $x = zot_encode_locations($channel); if($x) { $ret['locations'] = $x; } } else { logger('Unable to store sys hub location'); } } } } function delivery_report_is_storable($dr) { if(get_config('system','disable_dreport')) return false; call_hooks('dreport_is_storable',$dr); // let plugins accept or reject - if neither, continue on if(array_key_exists('accept',$dr) && intval($dr['accept'])) return true; if(array_key_exists('reject',$dr) && intval($dr['reject'])) return false; if(! ($dr['sender'])) return false; // Is the sender one of our channels? $c = q("select channel_id from channel where channel_hash = '%s' limit 1", dbesc($dr['sender']) ); if(! $c) return false; // is the recipient one of our connections, or do we want to store every report? $r = explode(' ', $dr['recipient']); $rxchan = $r[0]; $pcf = get_pconfig($c[0]['channel_id'],'system','dreport_store_all'); if($pcf) return true; // We always add ourself as a recipient to private and relayed posts // So if a remote site says they can't find us, that's no big surprise // and just creates a lot of extra report noise if(($dr['location'] !== z_root()) && ($dr['sender'] === $rxchan) && ($dr['status'] === 'recipient_not_found')) return false; // If you have a private post with a recipient list, every single site is going to report // back a failed delivery for anybody on that list that isn't local to them. We're only // concerned about this if we have a local hubloc record which says we expected them to // have a channel on that site. $r = q("select hubloc_id from hubloc where hubloc_hash = '%s' and hubloc_url = '%s'", dbesc($rxchan), dbesc($dr['location']) ); if((! $r) && ($dr['status'] === 'recipient_not_found')) return false; $r = q("select abook_id from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($rxchan), intval($c[0]['channel_id']) ); if($r) return true; return false; } function update_hub_connected($hub,$sitekey = '') { if($sitekey) { /* * This hub has now been proven to be valid. * Any hub with the same URL and a different sitekey cannot be valid. * Get rid of them (mark them deleted). There's a good chance they were re-installs. */ q("update hubloc set hubloc_deleted = 1, hubloc_error = 1 where hubloc_url = '%s' and hubloc_sitekey != '%s' ", dbesc($hub['hubloc_url']), dbesc($sitekey) ); } else { $sitekey = $hub['sitekey']; } // $sender['sitekey'] is a new addition to the protocol to distinguish // hublocs coming from re-installed sites. Older sites will not provide // this field and we have to still mark them valid, since we can't tell // if this hubloc has the same sitekey as the packet we received. // Update our DB to show when we last communicated successfully with this hub // This will allow us to prune dead hubs from using up resources $t = datetime_convert('UTC','UTC','now - 15 minutes'); $r = q("update hubloc set hubloc_connected = '%s' where hubloc_id = %d and hubloc_sitekey = '%s' and hubloc_connected < '%s' ", dbesc(datetime_convert()), intval($hub['hubloc_id']), dbesc($sitekey), dbesc($t) ); // a dead hub came back to life - reset any tombstones we might have if(intval($hub['hubloc_error'])) { q("update hubloc set hubloc_error = 0 where hubloc_id = %d and hubloc_sitekey = '%s' ", intval($hub['hubloc_id']), dbesc($sitekey) ); if(intval($r[0]['hubloc_orphancheck'])) { q("update hubloc set hubloc_orhpancheck = 0 where hubloc_id = %d and hubloc_sitekey = '%s' ", intval($hub['hubloc_id']), dbesc($sitekey) ); } q("update xchan set xchan_orphan = 0 where xchan_orphan = 1 and xchan_hash = '%s'", dbesc($hub['hubloc_hash']) ); } return $hub['hubloc_url']; } function zot_reply_ping() { $ret = array('success'=> false); // Useful to get a health check on a remote site. // This will let us know if any important communication details // that we may have stored are no longer valid, regardless of xchan details. logger('POST: got ping send pong now back: ' . z_root() , LOGGER_DEBUG ); $ret['success'] = true; $ret['site'] = array(); $ret['site']['url'] = z_root(); $ret['site']['url_sig'] = base64url_encode(rsa_sign(z_root(),get_config('system','prvkey'))); $ret['site']['sitekey'] = get_config('system','pubkey'); json_return_and_die($ret); } function zot_reply_pickup($data) { $ret = array('success'=> false); /* * The 'pickup' message arrives with a tracking ID which is associated with a particular outq_hash * First verify that that the returned signatures verify, then check that we have an outbound queue item * with the correct hash. * If everything verifies, find any/all outbound messages in the queue for this hubloc and send them back */ if((! $data['secret']) || (! $data['secret_sig'])) { $ret['message'] = 'no verification signature'; logger('mod_zot: pickup: ' . $ret['message'], LOGGER_DEBUG); json_return_and_die($ret); } $r = q("select distinct hubloc_sitekey from hubloc where hubloc_url = '%s' and hubloc_callback = '%s' and hubloc_sitekey != '' group by hubloc_sitekey ", dbesc($data['url']), dbesc($data['callback']) ); if(! $r) { $ret['message'] = 'site not found'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } foreach ($r as $hubsite) { // verify the url_sig // If the server was re-installed at some point, there could be multiple hubs with the same url and callback. // Only one will have a valid key. $forgery = true; $secret_fail = true; $sitekey = $hubsite['hubloc_sitekey']; logger('mod_zot: Checking sitekey: ' . $sitekey, LOGGER_DATA, LOG_DEBUG); if(rsa_verify($data['callback'],base64url_decode($data['callback_sig']),$sitekey)) { $forgery = false; } if(rsa_verify($data['secret'],base64url_decode($data['secret_sig']),$sitekey)) { $secret_fail = false; } if((! $forgery) && (! $secret_fail)) break; } if($forgery) { $ret['message'] = 'possible site forgery'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } if($secret_fail) { $ret['message'] = 'secret validation failed'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } /* * If we made it to here, the signatures verify, but we still don't know if the tracking ID is valid. * It wouldn't be an error if the tracking ID isn't found, because we may have sent this particular * queue item with another pickup (after the tracking ID for the other pickup was verified). */ $r = q("select outq_posturl from outq where outq_hash = '%s' and outq_posturl = '%s' limit 1", dbesc($data['secret']), dbesc($data['callback']) ); if(! $r) { $ret['message'] = 'nothing to pick up'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } /* * Everything is good if we made it here, so find all messages that are going to this location * and send them all. */ $r = q("select * from outq where outq_posturl = '%s'", dbesc($data['callback']) ); if($r) { logger('mod_zot: successful pickup message received from ' . $data['callback'] . ' ' . count($r) . ' message(s) picked up', LOGGER_DEBUG); $ret['success'] = true; $ret['pickup'] = array(); foreach($r as $rr) { if($rr['outq_msg']) { $x = json_decode($rr['outq_msg'],true); if(! $x) continue; if(is_array($x) && array_key_exists('message_list',$x)) { foreach($x['message_list'] as $xx) { $ret['pickup'][] = array('notify' => json_decode($rr['outq_notify'],true),'message' => $xx); } } else $ret['pickup'][] = array('notify' => json_decode($rr['outq_notify'],true),'message' => $x); remove_queue_item($rr['outq_hash']); } } } $encrypted = crypto_encapsulate(json_encode($ret),$sitekey); json_return_and_die($encrypted); /* pickup: end */ } function zot_reply_auth_check($data,$encrypted_packet) { $ret = array('success' => false); /* * Requestor visits /magic/?dest=somewhere on their own site with a browser * magic redirects them to $destsite/post [with auth args....] * $destsite sends an auth_check packet to originator site * The auth_check packet is handled here by the originator's site * - the browser session is still waiting * inside $destsite/post for everything to verify * If everything checks out we'll return a token to $destsite * and then $destsite will verify the token, authenticate the browser * session and then redirect to the original destination. * If authentication fails, the redirection to the original destination * will still take place but without authentication. */ logger('mod_zot: auth_check', LOGGER_DEBUG); if (! $encrypted_packet) { logger('mod_zot: auth_check packet was not encrypted.'); $ret['message'] .= 'no packet encryption' . EOL; json_return_and_die($ret); } $arr = $data['sender']; $sender_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); // garbage collect any old unused notifications // This was and should be 10 minutes but my hosting provider has time lag between the DB and // the web server. We should probably convert this to webserver time rather than DB time so // that the different clocks won't affect it and allow us to keep the time short. Zotlabs\Zot\Verify::purge('auth','30 MINUTE'); $y = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($sender_hash) ); // We created a unique hash in mod/magic.php when we invoked remote auth, and stored it in // the verify table. It is now coming back to us as 'secret' and is signed by a channel at the other end. // First verify their signature. We will have obtained a zot-info packet from them as part of the sender // verification. if ((! $y) || (! rsa_verify($data['secret'], base64url_decode($data['secret_sig']),$y[0]['xchan_pubkey']))) { logger('mod_zot: auth_check: sender not found or secret_sig invalid.'); $ret['message'] .= 'sender not found or sig invalid ' . print_r($y,true) . EOL; json_return_and_die($ret); } // There should be exactly one recipient, the original auth requestor $ret['message'] .= 'recipients ' . print_r($recipients,true) . EOL; if ($data['recipients']) { $arr = $data['recipients'][0]; $recip_hash = make_xchan_hash($arr['guid'], $arr['guid_sig']); $c = q("select channel_id, channel_account_id, channel_prvkey from channel where channel_hash = '%s' limit 1", dbesc($recip_hash) ); if (! $c) { logger('mod_zot: auth_check: recipient channel not found.'); $ret['message'] .= 'recipient not found.' . EOL; json_return_and_die($ret); } $confirm = base64url_encode(rsa_sign($data['secret'] . $recip_hash,$c[0]['channel_prvkey'])); // This additionally checks for forged sites since we already stored the expected result in meta // and we've already verified that this is them via zot_gethub() and that their key signed our token $z = Zotlabs\Zot\Verify::match('auth',$c[0]['channel_id'],$data['secret'],$data['sender']['url']); if (! $z) { logger('mod_zot: auth_check: verification key not found.'); $ret['message'] .= 'verification key not found' . EOL; json_return_and_die($ret); } $u = q("select account_service_class from account where account_id = %d limit 1", intval($c[0]['channel_account_id']) ); logger('mod_zot: auth_check: success', LOGGER_DEBUG); $ret['success'] = true; $ret['confirm'] = $confirm; if ($u && $u[0]['account_service_class']) $ret['service_class'] = $u[0]['account_service_class']; // Set "do not track" flag if this site or this channel's profile is restricted // in some way if (intval(get_config('system','block_public'))) $ret['DNT'] = true; if (! perm_is_allowed($c[0]['channel_id'],'','view_profile')) $ret['DNT'] = true; if (get_pconfig($c[0]['channel_id'],'system','do_not_track')) $ret['DNT'] = true; if (get_pconfig($c[0]['channel_id'],'system','hide_online_status')) $ret['DNT'] = true; json_return_and_die($ret); } json_return_and_die($ret); } function zot_reply_purge($sender,$recipients) { $ret = array('success' => false); if ($recipients) { // basically this means "unfriend" foreach ($recipients as $recip) { $r = q("select channel.*,xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_guid = '%s' and channel_guid_sig = '%s' limit 1", dbesc($recip['guid']), dbesc($recip['guid_sig']) ); if ($r) { $r = q("select abook_id from abook where uid = %d and abook_xchan = '%s' limit 1", intval($r[0]['channel_id']), dbesc(make_xchan_hash($sender['guid'],$sender['guid_sig'])) ); if ($r) { contact_remove($r[0]['channel_id'],$r[0]['abook_id']); } } } $ret['success'] = true; } else { // Unfriend everybody - basically this means the channel has committed suicide $arr = $sender; $sender_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); remove_all_xchan_resources($sender_hash); $ret['success'] = true; } json_return_and_die($ret); } function zot_reply_refresh($sender,$recipients) { $ret = array('success' => false); // remote channel info (such as permissions or photo or something) // has been updated. Grab a fresh copy and sync it. // The difference between refresh and force_refresh is that // force_refresh unconditionally creates a directory update record, // even if no changes were detected upon processing. if($recipients) { // This would be a permissions update, typically for one connection foreach ($recipients as $recip) { $r = q("select channel.*,xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_guid = '%s' and channel_guid_sig = '%s' limit 1", dbesc($recip['guid']), dbesc($recip['guid_sig']) ); $x = zot_refresh(array( 'xchan_guid' => $sender['guid'], 'xchan_guid_sig' => $sender['guid_sig'], 'hubloc_url' => $sender['url'] ), $r[0], (($msgtype === 'force_refresh') ? true : false)); } } else { // system wide refresh $x = zot_refresh(array( 'xchan_guid' => $sender['guid'], 'xchan_guid_sig' => $sender['guid_sig'], 'hubloc_url' => $sender['url'] ), null, (($msgtype === 'force_refresh') ? true : false)); } $ret['success'] = true; json_return_and_die($ret); } function zot_reply_notify($data) { $ret = array('success' => false); logger('notify received from ' . $data['sender']['url']); $async = get_config('system','queued_fetch'); if($async) { // add to receive queue // qreceive_add($data); } else { $x = zot_fetch($data); $ret['delivery_report'] = $x; } $ret['success'] = true; json_return_and_die($ret); }
Java
/** * */ package org.edtoktay.dynamic.compiler; /** * @author deniz.toktay * */ public interface ExampleInterface { void addObject(String arg1, String arg2); Object getObject(String arg1); }
Java
import React, { Component } from 'react'; import { StyleSheet, Text, View, Navigator, ScrollView, ListView, } from 'react-native' import NavigationBar from 'react-native-navbar'; var REQUEST_URL = 'https://calm-garden-29993.herokuapp.com/index/groupsinfo/?'; class GroupDetails extends Component { constructor(props, context) { super(props, context); this.state = { loggedIn: true, loaded: false, rando: "a", }; this.fetchData(); } backOnePage () { this.props.navigator.pop(); } renderRide (ride) { return ( <View> <Text style={styles.title}>{ride.title}</Text> </View> ); } componentDidMount () { this.fetchData(); } toQueryString(obj) { return obj ? Object.keys(obj).sort().map(function (key) { var val = obj[key]; if (Array.isArray(val)) { return val.sort().map(function (val2) { return encodeURIComponent(key) + '=' + encodeURIComponent(val2); }).join('&'); } return encodeURIComponent(key) + '=' + encodeURIComponent(val); }).join('&') : ''; } fetchData() { console.log(this.props.group_info.pk); fetch(REQUEST_URL + this.toQueryString({"group": this.props.group_info.pk})) .then((response) => response.json()) .then((responseData) => { console.log(responseData); this.setState({ group_info: responseData, loaded: true, }); }) .done(); } render () { if (!this.state.loaded) { return (<View> <Text>Loading!</Text> </View>); } else if (this.state.loggedIn) { console.log(this.props.group_info.fields); console.log(this.state); console.log(this.state.group_info[0]); const backButton = { title: "Back", handler: () => this.backOnePage(), }; return ( <ScrollView> <NavigationBar style={{ backgroundColor: "white", }} leftButton={backButton} statusBar={{ tintColor: "white", }} /> <Text style={styles.headTitle}> Group Name: {this.state.group_info.name} </Text> <Text style={styles.headerOtherText}>Group Leader: {this.state.group_info.admin}</Text> <Text style={styles.headerOtherText}>{this.state.group_info.users} people in this group.</Text> </ScrollView> ); } else { this.props.navigator.push({id: "LoginPage", name:"Index"}) } } } var styles = StyleSheet.create({ headerOtherText : { color: 'black', fontSize: 15 , fontWeight: 'normal', fontFamily: 'Helvetica Neue', alignSelf: "center", }, headTitle: { color: 'black', fontSize: 30 , fontWeight: 'normal', fontFamily: 'Helvetica Neue', alignSelf: "center", }, header: { marginTop: 20, flex: 1, flexDirection: "column", justifyContent: "center", alignItems: "center", }, container: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#ff7f50', }, rightContainer: { flex: 1, }, title: { fontSize: 20, marginBottom: 8, textAlign: 'center', }, year: { textAlign: 'center', }, thumbnail: { width: 53, height: 81, }, listView: { backgroundColor: '#0000ff', paddingBottom: 200, }, }); module.exports = GroupDetails;
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>W28677_text</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;"> <div style="float: left;"> <a href="page9.html">&laquo;</a> </div> <div style="float: right;"> </div> </div> <hr/> <div style="position: absolute; margin-left: 219px; margin-top: 1017px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 302px; margin-top: 1815px;"> <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 220px; margin-top: 2090px;"> <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Choke manifold minimum 3” 5k </p> </div> <div style="position: absolute; margin-left: 577px; margin-top: 54px;"> <p class="styleSans58.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">11” SK psi BOP stack <br/>High Pressure <br/>. . rotating Fill-up line head <br/>- Drillingcmka _ — — <br/>Annular <br/> <br/>Preventer <br/> <br/>I Variable rams - Blind rams - <br/> m Kill line minimum 2" <br/>Drilling Spool <br/>' Spacer spool <br/>4‘ 5000 psi casing head </p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 55px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 165px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 330px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 495px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 660px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 825px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 1155px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 1320px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 1760px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 1925px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 990px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 1485px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> </body> </html>
Java
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me cantango_user end
Java
process.stderr.write('Test');
Java
# README SportzBall is a community driven application used to bring people together for intramural sports. From football to quidditch we want you to SPORTZ! To set up repository on your local machine clone and set up database (instructions below) Rails 5.0.1 Ruby ~> 2.3.0 * Configuration * Database creation and initialization `rails db:seed` * To run tests ask Stephen * Deployment instructions to come * API setup to come Contributers - FinGrayson - Jefferson-Faseler
Java
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wellspring.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Java
package org.squirrel; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.Timer; import org.squirrel.managers.PrisonerControllor; import org.squirrel.managers.inputManager; import org.squirrel.objects.Player; import org.squirrel.ui.Hud; import org.squirrel.world.World; public class Game extends JPanel implements ActionListener{ private static final long serialVersionUID = -8805039320208612585L; public static String name = JOptionPane.showInputDialog(null,"What is your name?","Welcome to Prison Survival", JOptionPane.QUESTION_MESSAGE); Timer gameLoop; Player player; PrisonerControllor prict; Hud hud; World world1; public Game(){ setFocusable(true); gameLoop = new Timer(10, this); gameLoop.start(); player = new Player(300, 300); prict = new PrisonerControllor(); hud = new Hud(); world1 = new World(); addKeyListener(new inputManager(player)); } public void paint(Graphics g){ super.paint(g); Graphics2D g2d = (Graphics2D) g; //Camera int offsetMaxX = 1600 - 800; int offsetMaxY = 1200 - 600; int offsetMinX = 0; int offsetMinY = 0; int camX = player.getxPos() - 800 /2; int camY = player.getyPos() - 600 /2; //if (camX > offsetMaxX){ // camX = offsetMaxX; //} //else if (camX < offsetMinX){ // camX = offsetMinX; //} //if (camY > offsetMaxY){ // camY = offsetMaxY; //} //else if (camY < offsetMinY){ // camY = offsetMinY; //} g2d.translate(-camX, -camY); // Render everything world1.draw(g2d); hud.draw(g2d); prict.draw(g2d); player.draw(g2d); g.translate(camX, camY); } @Override public void actionPerformed(ActionEvent e) { try { player.update(); hud.update(); prict.update(); world1.update(); repaint(); } catch (Exception e1) { e1.printStackTrace(); } } }
Java
/* jqModal base Styling courtesy of; Brice Burgess <bhb@iceburg.net> */ /* The Window's CSS z-index value is respected (takes priority). If none is supplied, the Window's z-index value will be set to 3000 by default (via jqModal.js). */ .jqmWrap { display: none; position: fixed; top: 20%; left: 50%; margin-left: -175px; width: 350px; background: #555; background: rgba(0,0,0,0.3); border-radius: 5px; } .jqmInner { background: #fff; color: #333; border-radius: 3px; margin: 6px; padding: 13px; font:100% Arial,sans-serif; } .jqmInner h1,h2,h3 { margin: 0; padding: 0; } .jqmInner h1 { font-size: 20px; font-weight: 700; } .jqmInner h2 { font-size: 12px; color: #888; font-weight: 400; padding: 6px 0 0; } .jqmInner h3 { font-size: 14px; font-weight: 700; margin-top: 10px; padding-top: 13px; border-top: 1px solid #ddd; } .jqmInner h3 a { color: #47c; text-decoration: none; } .jqmInner h3 a:hover { color: #47c; text-decoration: underline; } .jqmOverlay { background-color: #000; } /* Background iframe styling for IE6. Prevents ActiveX bleed-through (<select> form elements, etc.) */ * iframe.jqm {position:absolute;top:0;left:0;z-index:-1; width: expression(this.parentNode.offsetWidth+'px'); height: expression(this.parentNode.offsetHeight+'px'); } /* Fixed posistioning emulation for IE6 Star selector used to hide definition from browsers other than IE6 For valid CSS, use a conditional include instead */ * html .jqmWindow { position: absolute; top: expression((document.documentElement.scrollTop || document.body.scrollTop) + Math.round(17 * (document.documentElement.offsetHeight || document.body.clientHeight) / 100) + 'px'); }
Java
(function () { 'use strict'; angular .module('app') .service('UploadUserLogoService', UploadUserLogoService); function UploadUserLogoService($http, $log, TokenService, UserService, $rootScope) { this.uploadImage = uploadImage; //// /** * Upload Image * @description For correct uploading we must send FormData object * With 'transformRequest: angular.identity' prevents Angular to do anything on our data (like serializing it). * By setting ‘Content-Type’: undefined, the browser sets the Content-Type to multipart/form-data for us * and fills in the correct boundary. * Manually setting ‘Content-Type’: multipart/form-data will fail to fill in the boundary parameter of the request * All this for correct request typing and uploading * @param formdata * @param callback */ function uploadImage(formdata, callback) { let userToken = TokenService.get(); let request = { method: 'POST', url: '/api/user/avatar', transformRequest: angular.identity, headers: { 'Content-Type': undefined, 'Autorization': userToken }, data: formdata }; let goodResponse = function successCallback(response) { let res = response.data; if (res.success) { let currentUser = UserService.get(); currentUser.avatarUrl = res.data.avatarUrl; UserService.save(currentUser); } if (callback && typeof callback === 'function') { callback(res); } }; let badResponse = function errorCallback(response) { $log.debug('Bad, some problems ', response); if (callback && typeof callback === 'function') { callback(response); } }; $http(request).then(goodResponse, badResponse); } } })();
Java
<?php include 'vendor/autoload.php'; ini_set('error_reporting', E_ALL); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1');
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>simple-io: 27 s 🏆</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.9.0 / simple-io - 1.3.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> simple-io <small> 1.3.0 <span class="label label-success">27 s 🏆</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-04 03:17:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-04 03:17:13 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 camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.9.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.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Li-yao Xia &lt;lysxia@gmail.com&gt;&quot; authors: &quot;Li-yao Xia&quot; homepage: &quot;https://github.com/Lysxia/coq-simple-io&quot; bug-reports: &quot;https://github.com/Lysxia/coq-simple-io/issues&quot; license: &quot;MIT&quot; dev-repo: &quot;git+https://github.com/Lysxia/coq-simple-io.git&quot; build: [make &quot;build&quot;] run-test: [make &quot;test&quot;] install: [make &quot;install&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.13~&quot;} &quot;coq-ext-lib&quot; &quot;ocamlbuild&quot; {with-test} ] tags: [ &quot;date:2020-03-08&quot; &quot;logpath:SimpleIO&quot; &quot;keyword:extraction&quot; &quot;keyword:effects&quot; ] synopsis: &quot;IO monad for Coq&quot; description: &quot;&quot;&quot; This library provides tools to implement IO programs directly in Coq, in a similar style to Haskell. Facilities for formal verification are not included. IO is defined as a parameter with a purely functional interface in Coq, to be extracted to OCaml. Some wrappers for the basic types and functions in the OCaml Pervasives module are provided. Users are free to define their own APIs on top of this IO type.&quot;&quot;&quot; url { src: &quot;https://github.com/Lysxia/coq-simple-io/archive/1.3.0.tar.gz&quot; checksum: &quot;sha512=bcf7746e7877c4672e509e8c80db28b93cffbb064e114cf4df4465d9be3d55274c84a7406b38eaf510deda8a2574e42f3b40c8f716841bd92557e7b59d86e7cb&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-simple-io.1.3.0 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>0</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>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-simple-io.1.3.0 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>1 m 13 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-simple-io.1.3.0 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>27 s</dd> </dl> <h2>Installation size</h2> <p>Total: 478 K</p> <ul> <li>50 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unix.vo</code></li> <li>43 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Stdlib.vo</code></li> <li>28 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_UnsafeNat.vo</code></li> <li>28 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_RawChar.vo</code></li> <li>28 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_String.vo</code></li> <li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Bytes.vo</code></li> <li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unsafe.vo</code></li> <li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Float.vo</code></li> <li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Random.vo</code></li> <li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Sys.vo</code></li> <li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/SimpleIO.vo</code></li> <li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_StdlibAxioms.vo</code></li> <li>16 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Stdlib.glob</code></li> <li>15 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unix.glob</code></li> <li>14 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Monad.vo</code></li> <li>13 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unix.v</code></li> <li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Stdlib.v</code></li> <li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Monad.glob</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_UnsafeNat.glob</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Monad.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Exceptions.vo</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_String.glob</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_RawChar.glob</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_String.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_RawChar.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Float.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unsafe.glob</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unsafe.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Bytes.glob</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Bytes.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Float.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_UnsafeNat.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Exceptions.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Random.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Exceptions.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Random.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Sys.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Sys.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_StdlibAxioms.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/SimpleIO.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/SimpleIO.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_StdlibAxioms.v</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-simple-io.1.3.0</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"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </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>
Java
class Sprite(object): def __init__(self, xPos, yPos): self.x = xPos self.y = yPos self.th = 32 self.tw = 32 def checkCollision(self, otherSprite): if (self.x < otherSprite.x + otherSprite.tw and otherSprite.x < self.x + self.tw and self.y < otherSprite.y + otherSprite.th and otherSprite.y < self.y + self.th): return True else: return False class Actor(Sprite): def __init__(self, xPos, yPos): super(Actor, self).__init__(xPos, yPos) self.speed = 5 self.dy = 0 self.d = 3 self.dir = "right" # self.newdir = "right" self.state = "standing" self.walkR = [] self.walkL = [] def loadPics(self): self.standing = loadImage("gripe_stand.png") self.falling = loadImage("grfalling.png") for i in range(8): imageName = "gr" + str(i) + ".png" self.walkR.append(loadImage(imageName)) for i in range(8): imageName = "gl" + str(i) + ".png" self.walkL.append(loadImage(imageName)) def checkWall(self, wall): if wall.state == "hidden": if (self.x >= wall.x - self.d and (self.x + 32 <= wall.x + 32 + self.d)): return False def move(self): if self.dir == "right": if self.state == "walking": self.im = self.walkR[frameCount % 8] self.dx = self.speed elif self.state == "standing": self.im = self.standing self.dx = 0 elif self.state == "falling": self.im = self.falling self.dx = 0 self.dy = 5 elif self.dir == "left": if self.state == "walking": self.im = self.walkL[frameCount % 8] self.dx = -self.speed elif self.state == "standing": self.im = self.standing self.dx = 0 elif self.state == "falling": self.im = self.falling self.dx = 0 self.dy = 5 else: self.dx = 0 self.x += self.dx self.y += self.dy if self.x <= 0: self.x = 0 if self.x >= 640 - self.tw: self.x = 640 -self.tw def display(self): image(self.im, self.x, self.y) class Block(Sprite): def __init__(self, xPos, yPos): super(Block, self).__init__(xPos, yPos) self.state = "visible" def loadPics(self): self.im = loadImage("block.png") def display(self): if self.state == "visible": image(self.im, self.x, self.y)
Java
<?php /** * This file is part of the Carrot framework. * * Copyright (c) 2011 Ricky Christie <seven.rchristie@gmail.com>. * * Licensed under the MIT License. * */ /** * Docs storage. * * Represents a documents storage and provides ways to access * the documents inside the storage. This class reads folders and * .html files inside a directory and creates a hierarchical docs * structure from it. * * @author Ricky Christie <seven.rchristie@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php MIT License * */ namespace Carrot\Docs; use Exception, InvalidArgumentException, DirectoryIterator; class Storage { /** * @var string The directory that contains the document files, * without trailing directory separator. */ protected $rootDirectory; /** * Constructor. * * If no path was given, the root directory will default to: * * <code> * __DIR__ . DIRECTORY_SEPARATOR . 'Files' * </code> * * The directory contains documentation files in HTML format and * can contain as many folders as you need. You can provide * 'section.html' file on each directory to be loaded when that * section is requested. * * @param string $rootDirectory The directory that contains the * document files. * */ public function __construct($rootDirectory = NULL) { if ($rootDirectory == NULL) { $rootDirectory = __DIR__ . DIRECTORY_SEPARATOR . 'Files'; } $this->setRootDirectory($rootDirectory); } /** * Set the directory that contains the document files. * * @throws InvalidArgumentException If the root directory given * is not a valid path or it's not a directory. * @param string $rootDirectory The directory that contains the * document files. * */ protected function setRootDirectory($rootDirectory) { $rootDirectoryAbsolute = realpath($rootDirectory); if ($rootDirectoryAbsolute == FALSE) { throw new InvalidArgumentException("Storage error in instantiation. The given path '{$rootDirectory}' does not exist."); } if (is_dir($rootDirectoryAbsolute) == FALSE) { throw new InvalidArgumentException("Storage error in instantiation. The given path '{$rootDirectory}' is not directory."); } $this->rootDirectory = $rootDirectoryAbsolute; } /** * Get an instance of page from the given hierarchical path. * * The path array contains the hierarchical path to the * documentation. The array contains item IDs. Example: * * <code> * $path = array( * '1-introduction', * '1-calculator-tutorial', * '1-creating-your-controller' * ); * </code> * * @param array $pagePathArray The hierarchical path to the * documentation page to retrieve. * @return Page|FALSE The documentation page, or FALSE if failed. * */ public function getPage(array $pagePathArray) { if (empty($pagePathArray)) { return $this->getIndexPage(); } $pageInfo = $this->getPageInfo($pagePathArray); if (!is_array($pageInfo)) { return FALSE; } return new Page( $pageInfo['title'], $pageInfo['content'], $pageInfo['parentSections'], $pageInfo['navigation'] ); } /** * Get the page containing the index to be returned. * * Will try to load the contents of the 'section.html' file in * the route, if it fails, will simply return an empty body with * the root navigation. * * @return Page * */ public function getIndexPage() { $parentSections = array(); $navigation = $this->getNavigationItemsFromDirectory($this->rootDirectory, array()); $title = ''; $content = $this->getSectionIndexContent($this->rootDirectory); return new Page( $title, $content, $parentSections, $navigation ); } /** * Get information about the page from the given hierarchical * path. * * Assumes the array is not empty. The structure of the array * returned is as follows: * * <code> * $pageInfo = array( * 'parentSections' => $parentSections, * 'navigation' => $navigation, * 'title' => $title, * 'content' => $content * ); * </code> * * The array $parentSections contains the page's parent sections. * Each section is represented by a {@see NavigationItem} * instance: * * <code> * $parentSections = array( * 0 => $sectionA, * 1 => $sectionB, * 2 => $sectionC * ... * ); * </code> * * The array $navigation contains the list of accessible items * for the current open section, be it a page or another section, * but with the item ID as the indexes: * * <code> * $navigation = array( * '1-introduction' => $navItemA, * '2-autoloading' => $navItemB, * '3-dependency-injection' => $navItemC, * ... * ); * </code> * * @param array $pagePathArray The hierarchical path to the * documentation page to retrieve. * */ protected function getPageInfo(array $pagePathArray) { $parentSections = array(); $navigation = array(); $title = ''; $content = ''; $directory = $this->rootDirectory; $segmentsTraversed = array(); $highestLevel = count($pagePathArray) - 1; foreach ($pagePathArray as $level => $itemID) { $isHighestLevel = ($level == $highestLevel); $availableItems = $this->getNavigationItemsFromDirectory( $directory, $segmentsTraversed ); if (!array_key_exists($itemID, $availableItems)) { return FALSE; } $navItem = $availableItems[$itemID]; if ($isHighestLevel) { if ($navItem->isSection()) { $parentSections[] = $navItem; $segmentsTraversed[] = $itemID; $directory = $navItem->getRealPath(); $navigation = $this->getNavigationItemsFromDirectory( $directory, $segmentsTraversed ); $content = $this->getSectionIndexContent($directory); } else { $navigation = $availableItems; $navigation[$itemID]->markAsCurrent(); $content = $this->getFileContent($navItem->getRealPath()); } return array( 'parentSections' => $parentSections, 'navigation' => $navigation, 'title' => $navItem->getTitle(), 'content' => $content ); } $parentSections[] = $navItem; $segmentsTraversed[] = $itemID; $directory = $navItem->getRealPath(); } } /** * Get the list of navigational items from the given directory. * * Iterates through the given directory and creates instances of * {@see NavigationItem} from its contents. Uses the given root * path segments to construct routing argument arrays of each * NavigationItem instance. * * The root path segments array structure: * * <code> * $rootPathSegments = array( * '1-Introduction', * '1-Calculator-Tutorial' * ); * </code> * * Returns an array containing instances of NavigationItem: * * <code> * $navigationItems = array( * $navItemA, * $navItemB, * $navItemC, * ... * ); * </code> * * @param string $directory Absolute path to the directory to * search the files from. * @param array $rootPathSegments The root path segments leading * to the given directory, to be used in constructing * routing arguments on each NavigationItem instances. * @return array Array containing instances of * {@see NavigationItem}. Returns an empty array if it * fails to retrieve data from the directory. * */ protected function getNavigationItemsFromDirectory($directory, array $rootPathSegments) { $items = array(); try { $iterator = new DirectoryIterator($directory); } catch (Exception $exception) { return $items; } foreach ($iterator as $key => $content) { $navItem = NULL; if ($content->isFile()) { $fileName = $content->getFilename(); $realPath = $content->getPathname(); $navItem = $this->getNavigationItemFromFile( $fileName, $realPath, $rootPathSegments ); } if ($content->isDir() AND $content->isDot() == FALSE) { $fileName = $content->getFilename(); $realPath = $content->getPathname(); $navItem = $this->getNavigationItemFromDirectory( $fileName, $realPath, $rootPathSegments ); } if ($navItem instanceof NavigationItem) { $items[$navItem->getItemID()] = $navItem; } } return $items; } /** * Get a {@see NavigationItem} instance from the given file name * and file path. * * Only accepts '.html' files with the following pattern as the * file name: * * <code> * 1. File Name.html * A. File Name.html * a. File Name.html * </code> * * @see getNavigationItemsFromDirectory() * @param string $fileName The name of the file. * @param string $realPath The real path to the file. * @param array $rootPathSegments The root path segments leading * to the given file, to be used in constructing routing * arguments array. * @return NavigationItem * */ protected function getNavigationItemFromFile($fileName, $realPath, array $rootPathSegments) { $fileNamePattern = '/^([A-Za-z0-9]+\\. (.+))\.html$/uD'; $replaceDotAndSpacesPattern = '/[\\. ]+/u'; if (preg_match($fileNamePattern, $fileName, $matches)) { $title = $matches[2]; $itemID = preg_replace($replaceDotAndSpacesPattern, '-', $matches[1]); $routingArgs = $rootPathSegments; $routingArgs[] = $itemID; return new NavigationItem( $title, 'doc', $routingArgs, $realPath ); } } /** * Get a {@see NavigationItem} instance from the given directory. * * All directory names are accepted. * * @see getNavigationItemsFromDirectory() * @param string $fileName The name of the file. * @param string $realPath The real path to the file. * @param array $rootPathSegments The root path segments leading * to the given file, to be used in constructing routing * arguments array. * @return NavigationItem * */ protected function getNavigationItemFromDirectory($directoryName, $realPath, array $rootPathSegments) { $directoryPattern = '/^([A-Za-z0-9]+\\. (.+))$/uD'; $replaceDotAndSpacesPattern = '/[\\. ]+/u'; if (preg_match($directoryPattern, $directoryName, $matches)) { $title = $matches[2]; $itemID = preg_replace($replaceDotAndSpacesPattern, '-', $matches[1]); $routingArgs = $rootPathSegments; $routingArgs[] = $itemID; return new NavigationItem( $title, 'section', $routingArgs, $realPath ); } } /** * Get the content for section index. * * Will try to get an 'section.html' file on the given directory. * If none found, an empty string will be returned instead. * * @param string $directory The physical counterpart of the * section whose index content we wanted to get, without * trailing directory separator. * @return string * */ protected function getSectionIndexContent($directory) { $filePath = $directory . DIRECTORY_SEPARATOR . 'section.html'; return $this->getFilecontent($filePath); } /** * Get the content from the give file. * * If the file doesn't exist, will return an empty string * instead. * * @param string $filePath Path to the file to get. * */ protected function getFileContent($filePath) { if (!file_exists($filePath)) { return ''; } return file_get_contents($filePath); } }
Java
<div class="panel panel-primary"> <div ng-show="error" class="alert alert-danger">{{ error }}</div> <div class="panel-heading"> <p class="panel-title">Neuer Gig</p> </div> <div class="panel-body"> <form name="addGig" class="form-horizontal" ng-submit="insertGig(gig)"> <fieldset> <div class="form-group"> <label for="date" class="control-label col-lg-2">Datum:</label> <div class="col-lg-4"> <input type="date" class="form-control" name="date" ng-model="gig.date" placeholder="yyyy-MM-dd" min="2008-01-01" max="2100-12-31" required /> </div> </div> <div class="form-group"> <label for="title" class="control-label col-lg-2">Titel:</label> <div class="col-lg-4"> <input type="text" class="form-control" name="title" ng-model="gig.title" required /> </div> </div> <div class="form-group"> <label for="loc" class="control-label col-lg-2">Location:</label> <div class="col-lg-4"> <input type="text" class="form-control" name="loc" ng-model="gig.loc" /> </div> </div> <div class="form-group"> <label for="status" class="control-label col-lg-2">Status:</label> <div class="col-lg-4"> <select class="form-control" id="status" ng-model="status"> <option>Angefragt</option> <option>Gebucht</option> </select> </div> </div> <div class="form-group"> <label for="contact" class="control-label col-lg-2">Kontakt:</label> <div class="col-lg-4"> <input type="text" class="form-control" name="contact" ng-model="gig.contact" /> </div> </div> <div class="form-group"> <label for="notes" class="control-label col-lg-2">Info:</label> <div class="col-lg-4"> <input type="text" class="form-control" name="notes" ng-model="gig.notes" /> </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <button class="btn btn-default" ng-click="back()">Abbrechen</button> <button type="submit" class="btn btn-primary">Speichern</button> </div> </div> </fieldset> </form> </div> </div>
Java
class CreateTeams < ActiveRecord::Migration def self.up create_table :teams do |t| t.string :name t.string :abbreviation t.string :hometown t.timestamps end end def self.down drop_table :teams end end
Java
/***************************************************************************** * x264: h264 encoder ***************************************************************************** * Copyright (C) 2005 Tuukka Toivonen <tuukkat@ee.oulu.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. *****************************************************************************/ #ifndef X264_VISUALIZE_H #define X264_VISUALIZE_H #include "common.h" void x264_visualize_init( x264_t *h ); void x264_visualize_mb( x264_t *h ); void x264_visualize_show( x264_t *h ); void x264_visualize_close( x264_t *h ); #endif
Java
angular.module('tips.tips').controller('TipsController', ['$scope', '$routeParams', '$location', 'Global', 'Tips', function ($scope, $routeParams, $location, Global, Tips) { $scope.global = Global; $scope.createTip = function () { var tips = new Tips({ text: this.text, likes: this.likes, category: this.category }); tips.$save(function (response) { $location.path("/"); }); this.title = ""; }; $scope.showTip = function () { Tips.query(function (tips) { $scope.tips = tips; tips.linkEdit = 'tips/edit/'; // show tips size function Settings (minLikes, maxLikes) { var that = this; that.size = { min: 26, max: 300 }; that.maxLikes = maxLikes; that.minLikes = tips[0].likes; that.valueOfdivision = (function(){ return (that.size.max - that.size.min)/that.maxLikes })() } function startIsotope(){ var el = $('#isotope-container'); el.isotope({ itemSelector: '.isotope-element', layoutMode: 'fitRows', sortBy: 'number', sortAscending: true, }); return el; } var maxLikes = 0; var minLikes = 0; for (var i = 0; i < tips.length; i++) { if(maxLikes <= tips[i].likes)maxLikes = tips[i].likes; if(minLikes >= tips[i].likes)minLikes = tips[i].likes; }; tips.settingsView = new Settings(minLikes, maxLikes); $scope.$watch('tips', function () { $scope.$evalAsync(function () { var isotope = startIsotope(); }); }) }); }; $scope.updateTip = function (tip) { var tip = new Tips(tip); tip.$update(tip, function(){ console.log("update updateTip: ", tip._id); }, function(){ console.warn("error updateTip:", tip._id); }); }; $scope.getTip = function () { Tips.query(function (tip) { $scope.tip = tip; console.log(tip); }); }; $scope.editTip = function(tip){ console.log("edit tip"); }; }])
Java
--- layout: post title: Log č. 5 - Áčkové předměty v 2.semestru --- ## Průchod 1. semestrem Těšíte se na 1. semestr? Vážně?! A víte, na co se musíte připravit? <img src="/images/radost.gif" alt="CO"> <h2>VIKBA06 Informační věda 2</h2> <p><i>Oficiální popis:</i>Přímo navazuje na předmět VIKBA01 Informační věda 1. Objasňuje podstatu, smysl, základy, terminologii, dosavadní vývoj, aktuální stav a další možný vývoj vědního a studijního oboru informační věda. </p> <p><i>Názor dálkaře: </i>Přednášky se staly zajímavé a dá se i zapojit. Pro ukončení se píší průběžné testy, na které se musí nastudovat článek v angličtině. Dále se musí vytvořit medailonek nebo skupinová práce. Zatím zajímavý předmět. </p> <h2>VIKBA07 Nástroje a možnosti Internetu</h2> <p><i>Oficiální popis:</i>Cílem předmětu je porozumění možnostem práce s informacemi pomocí nástrojů, které vznikly díky celosvětově dostupné síti internet. </p> <p><i>Názor dálkaře: </i> Když už se po 1 semestru člověk těší na zbavení se transformací, dostane tohle a pokud nejste programátoři nebo jako dálkař máte mimo soukromého i pracovní život, tak se s tím soukromým na následující půl rok rozlučte. Pro tvorbu týdenních úkolu z tohoto předmětu totiž potřebujete všechen volný čas. </p> <h2>VIKBA28 Úvod do studia médií</h2> <p><i>Oficiální popis:</i> Na konci kurzu budete umět vysvětlit strukturu a dynamiku mediálních a kulturních průmyslů. </p> <p><i>Názor dálkaře: </i> Nevím, co napsat, tak nějak jsem neměla čas dojít na žádnou z hodin :-) . </p> <h2>VIKBA30 Psaní odborných textů</h2> <p><i>Oficiální popis:</i>Hlavním cílem předmětu je získat dostatečný přehled o procesu tvorby odborného textu a naučit se psát různorodé odborné texty potřebné nejen pro vysokoškolské studium. </p> <p><i>Názor dálkaře: </i>Pro ukončení musíte napsat seminárku, které předchází vypracování rešerší a projektu. Naprostou náhodou jako dálkař zjistíte pár dní před ukončením odevzdávání, že máte ještě jeden úkol k vytvoření. Takže pozor, ještě se vytváří redukovaný text, což zjistíte, když si otevřete odevzdávárny předmětu. </p> <h2>VIK_PoZ Postupová zkouška</h2> <p><i>Oficiální popis:</i>Postupová zkouška je kontrolní zkouškou završující první rok studia. Je prerekvizitou k předmětům třetího a čtvrtého semestru. </p> <p><i>Názor dálkaře: </i>Zatím mám nachystané podklady, tak těžko říct, co z toho nakonec vyleze. </p> <p></p> <p></p> <p></p> <p><u>Zdroje informací: </u></p> <p><a href="https://kisk.phil.muni.cz/cs">1. Stránky KISKu </a></p> <p><a href="http://www.phil.muni.cz/wff">2. Stránky FF MUNI </a></p>
Java
# Get Single Promotion This gets an XML document with the specific promotion by the ID. ## Single Promotion Options [MadMimi's Promotion Documentation](https://madmimi.com/developer/api/promotions) should give you an idea of what you need to send to the API. This options object makes some of the methods easier. ### Method Reference `Single::setPromotionId($promotionId)` - Sets the promotion ID to retrieve ## Exceptions The following exceptions may be thrown throughout the duration of a options object. - `MadMimi\Exception\InvalidOptionException` During options object creation, a value in the array of the constructor argument that's key was not defined as a protected property of this options class
Java
# Laravel Favorite (Laravel 5, 6, 7, 8 Package) [![Latest Version on Packagist][ico-version]][link-packagist] [![Packagist Downloads][ico-downloads]][link-packagist] [![Software License][ico-license]](LICENSE.md) [![Build Status][ico-travis]][link-travis] **Allows Laravel Eloquent models to implement a 'favorite' or 'remember' or 'follow' feature.** ## Index - [Installation](#installation) - [Models](#models) - [Usage](#usage) - [Testing](#testing) - [Change log](#change-log) - [Contributions](#contributions) - [Pull Requests](#pull-requests) - [Security](#security) - [Credits](#credits) - [License](#license) ## Installation 1) Install the package via Composer ```bash $ composer require christiankuri/laravel-favorite ``` 2) In Laravel >=5.5 this package will automatically get registered. For older versions, update your `config/app.php` by adding an entry for the service provider. ```php 'providers' => [ // ... ChristianKuri\LaravelFavorite\FavoriteServiceProvider::class, ]; ``` 3) Publish the database from the command line: ```shell php artisan vendor:publish --provider="ChristianKuri\LaravelFavorite\FavoriteServiceProvider" ``` 4) Migrate the database from the command line: ```shell php artisan migrate ``` ## Models Your User model should import the `Traits/Favoriteability.php` trait and use it, that trait allows the user to favorite the models. (see an example below): ```php use ChristianKuri\LaravelFavorite\Traits\Favoriteability; class User extends Authenticatable { use Favoriteability; } ``` Your models should import the `Traits/Favoriteable.php` trait and use it, that trait have the methods that you'll use to allow the model be favoriteable. In all the examples I will use the Post model as the model that is 'Favoriteable', thats for example propuses only. (see an example below): ```php use ChristianKuri\LaravelFavorite\Traits\Favoriteable; class Post extends Model { use Favoriteable; } ``` That's it ... your model is now **"favoriteable"**! Now the User can favorite models that have the favoriteable trait. ## Usage The models can be favorited with and without an authenticated user (see examples below): ### Add to favorites and remove from favorites: If no param is passed in the favorite method, then the model will asume the auth user. ``` php $post = Post::find(1); $post->addFavorite(); // auth user added to favorites this post $post->removeFavorite(); // auth user removed from favorites this post $post->toggleFavorite(); // auth user toggles the favorite status from this post ``` If a param is passed in the favorite method, then the model will asume the user with that id. ``` php $post = Post::find(1); $post->addFavorite(5); // user with that id added to favorites this post $post->removeFavorite(5); // user with that id removed from favorites this post $post->toggleFavorite(5); // user with that id toggles the favorite status from this post ``` The user model can also add to favorites and remove from favrites: ``` php $user = User::first(); $post = Post::first(); $user->addFavorite($post); // The user added to favorites this post $user->removeFavorite($post); // The user removed from favorites this post $user->toggleFavorite($post); // The user toggles the favorite status from this post ``` ### Return the favorite objects for the user: A user can return the objects he marked as favorite. You just need to pass the **class** in the `favorite()` method in the `User` model. ``` php $user = Auth::user(); $user->favorite(Post::class); // returns a collection with the Posts the User marked as favorite ``` ### Return the favorites count from an object: You can return the favorites count from an object, you just need to return the `favoritesCount` attribute from the model ``` php $post = Post::find(1); $post->favoritesCount; // returns the number of users that have marked as favorite this object. ``` ### Return the users who marked this object as favorite You can return the users who marked this object, you just need to call the `favoritedBy()` method in the object ``` php $post = Post::find(1); $post->favoritedBy(); // returns a collection with the Users that marked the post as favorite. ``` ### Check if the user already favorited an object You can check if the Auth user have already favorited an object, you just need to call the `isFavorited()` method in the object ``` php $post = Post::find(1); $post->isFavorited(); // returns a boolean with true or false. ``` ## Testing The package have integrated testing, so everytime you make a pull request your code will be tested. ## Change log Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. ## Contributions Contributions are **welcome** and will be fully **credited**. We accept contributions via Pull Requests on [Github](https://github.com/ChristianKuri/laravel-favorite). ### Pull Requests - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - Check the code style with ``$ composer check-style`` and fix it with ``$ composer fix-style``. - **Add tests!** - Your patch won't be accepted if it doesn't have tests. - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. - **Create feature branches** - Don't ask us to pull from your master branch. - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. ## Security Please report any issue you find in the issues page. Pull requests are welcome. ## Credits - [Christian Kuri][link-author] - [All Contributors][link-contributors] ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. [ico-version]: https://img.shields.io/packagist/v/ChristianKuri/laravel-favorite.svg?style=flat-square [ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square [ico-travis]: https://img.shields.io/travis/ChristianKuri/laravel-favorite/master.svg?style=flat-square [ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/ChristianKuri/laravel-favorite.svg?style=flat-square [ico-code-quality]: https://img.shields.io/scrutinizer/g/ChristianKuri/laravel-favorite.svg?style=flat-square [ico-downloads]: https://img.shields.io/packagist/dt/ChristianKuri/laravel-favorite.svg?style=flat-square [link-packagist]: https://packagist.org/packages/ChristianKuri/laravel-favorite [link-travis]: https://travis-ci.org/ChristianKuri/laravel-favorite [link-scrutinizer]: https://scrutinizer-ci.com/g/ChristianKuri/laravel-favorite/code-structure [link-code-quality]: https://scrutinizer-ci.com/g/ChristianKuri/laravel-favorite [link-downloads]: https://packagist.org/packages/ChristianKuri/laravel-favorite [link-author]: https://github.com/ChristianKuri [link-contributors]: ../../contributors
Java
package com.xeiam.xchange.cryptotrade.dto; import java.io.IOException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.xeiam.xchange.cryptotrade.dto.CryptoTradeOrderType.CryptTradeOrderTypeDeserializer; @JsonDeserialize(using = CryptTradeOrderTypeDeserializer.class) public enum CryptoTradeOrderType { Buy, Sell; static class CryptTradeOrderTypeDeserializer extends JsonDeserializer<CryptoTradeOrderType> { @Override public CryptoTradeOrderType deserialize(final JsonParser jsonParser, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final ObjectCodec oc = jsonParser.getCodec(); final JsonNode node = oc.readTree(jsonParser); final String orderType = node.asText(); return CryptoTradeOrderType.valueOf(orderType); } } }
Java
module Mailplug class Plugin::Example < Mailplug::Middleware # Message Envelope Methods def return_path end def recipients end def message # returns Mail::Message end # Hash of state and inter-stack data memo[classname][key]=value def memo end # SMTP State Changes def open(remote_ip) end def helo(server_name) end def mail_from(email) end def rcpt_to(email) end def data end def data_line(line) end def data_stop end def save # false(i don't queue), true (i queued), error msg end def quit end def close end def header(name, value) end def abort(code, msg) # Stop it with reason end def continue # don't stop end def log(msg) end def status(number, message, close, waitseconds=0) end # SMTP Responses http://www.greenend.org.uk/r def service_ready # 220 end end end
Java
import apiConfig from './MovieDBConfig'; import TmdbApi from 'moviedb-api'; var api = new TmdbApi({ consume: false, apiKey: apiConfig.apiKey }); const makeAndList = (list) => { return list.map(item => item.value).join(); }; export const getGenres = (input='', callback) => { api.request('/genre/movie/list', 'GET') .then(res => { return res.genres.map(item => { return {label: item.name, value: item.id}; }) }) .then(json => callback(null, {options: json, complete: false})) .catch(err => console.log(err)); }; export const getKeywords = (input='', callback) => { api.request('/search/keyword', 'GET', {query: input}) .then(res => { return res.results.map(item => { return {label: item.name, value: item.id}; }); }) .then(json => callback(null, {options: json, complete: false})) .catch(err => console.log(err)); }; export const getActors = (input='', callback) => { api.request('/search/person', 'GET', {query: input}) .then(res => { return res.results.map(item => { return {label: item.name, value: item.id}; }); }) .then(json => callback(null, {options: json, complete: false})) .catch(err => console.log(err)); }; export const discover = (genres=null, keywords=null, actors, minYear, maxYear, page=1) => { let g = genres ? makeAndList(genres) : null; let k = keywords ? makeAndList(keywords) : null; let a = actors ? makeAndList(actors) : null; return api.request('/discover/movie', 'GET', { with_genres: g, with_keywords: k, with_cast: a, "release_date.gte": minYear, "release_date.lte": maxYear, page }) .then(res => res) }; export const getVideos = (id, language='en') => { return api.request(`/movie/${id}/videos`, 'GET', {language}) }; export const getMovieKeywords = (id, language='en') => { return api.request(`/movie/${id}/keywords`, 'GET', {language}) }; export const discoverWithVideo = (genres=null, keywords=null, actors, minYear, maxYear) => { return discover(genres, keywords, actors, minYear, maxYear) .then(res => { return Promise.all( res.results.map(item => getVideos(item.id) .then(videos => videos.results[0]) ) ).then(list => { return { ...res, results: res.results.map((item, index) => { item.youtube = list[index]; return item; }) } }) }) }; export const getDetails = (id, language='en') => { return api.request(`/movie/${id}`, 'GET', {language, append_to_response: "keywords,videos"}) };
Java
const excludedTables = ["blacklist", "musicCache", "timedEvents"]; const statPoster = require("../../modules/statPoster.js"); module.exports = async guild => { let tables = await r.tableList().run(); for(let table of tables) { let indexes = await r.table(table).indexList().run(); if(~indexes.indexOf("guildID")) r.table(table).getAll(guild.id, { index: "guildID" }).delete().run(); else r.table(table).filter({ guildID: guild.id }).delete().run(); } if(bot.config.bot.serverChannel) { let owner = bot.users.get(guild.ownerID); let botCount = guild.members.filter(member => member.bot).length; let botPercent = ((botCount / guild.memberCount) * 100).toFixed(2); let userCount = guild.memberCount - botCount; let userPercent = ((userCount / guild.memberCount) * 100).toFixed(2); let content = "❌ LEFT GUILD ❌\n"; content += `Guild: ${guild.name} (${guild.id})\n`; content += `Owner: ${owner.username}#${owner.discriminator} (${owner.id})\n`; content += `Members: ${guild.memberCount} **|** `; content += `Users: ${userCount} (${userPercent}%) **|** `; content += `Bots: ${botCount} (${botPercent}%)`; try { await bot.createMessage(bot.config.bot.serverChannel, content); } catch(err) { console.error(`Failed to send message to server log: ${err.message}`); } } statPoster(); };
Java
using System.Collections.Generic; using System.IO; using System.Reflection; using IDI.Core.Common.Extensions; namespace IDI.Core.Localization { public abstract class Package { public List<PackageItem> Items { get; private set; } = new List<PackageItem>(); public Package(string assemblyName, string packageName) { var assembly = Assembly.Load(new AssemblyName(assemblyName)); if (assembly == null) return; using (Stream stream = assembly.GetManifestResourceStream(packageName)) { if (stream == null) return; using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); this.Items = json.To<List<PackageItem>>(); } } } } }
Java
--- layout: page title: Twoer Summit Electronics Award Ceremony date: 2016-05-24 author: Hannah Shah tags: weekly links, java status: published summary: Morbi feugiat purus a risus. banner: images/banner/leisure-02.jpg booking: startDate: 10/11/2017 endDate: 10/13/2017 ctyhocn: PHXCNHX groupCode: TSEAC published: true --- Aliquam posuere ante nec dui pulvinar, eu ultrices turpis feugiat. Nullam quis turpis nisi. Sed auctor purus sit amet orci consectetur consectetur. Ut euismod nec nisi vitae efficitur. Phasellus sit amet ipsum sed libero dapibus egestas. Proin nunc nunc, finibus in accumsan eu, rutrum vitae enim. Sed posuere, purus vel tincidunt faucibus, neque lacus rutrum libero, at tristique leo leo vel lectus. Ut eleifend lobortis libero. * Mauris et nulla in arcu viverra rhoncus * Mauris ornare metus in consequat finibus * Phasellus eget libero euismod, volutpat dolor nec, tincidunt justo. Morbi eu nulla felis. Donec pretium ex maximus, efficitur lorem non, fringilla metus. Nullam id nulla eleifend, congue velit id, laoreet ante. Donec imperdiet ut orci ullamcorper congue. Sed sed risus urna. Etiam ultrices tortor eget neque vehicula dictum. Sed eu nulla imperdiet massa porttitor malesuada fringilla non enim. Suspendisse potenti. Duis in orci ex. Praesent lectus lorem, posuere ut venenatis a, elementum et ligula. Sed aliquam erat auctor lacus convallis, et sodales arcu fermentum. Maecenas blandit augue sed quam consectetur, sit amet semper augue pretium. Proin ut tincidunt turpis. Integer est ipsum, pulvinar non tempor eget, maximus non enim. Nullam sollicitudin nisl eu nunc ultrices, et aliquet dolor commodo. Integer imperdiet dignissim accumsan. Nam nisi sapien, volutpat at ante vel, egestas volutpat turpis. Aliquam laoreet quam eget neque lobortis dictum. Nunc at nibh turpis. Fusce ac nisl urna. Morbi congue nisi iaculis lobortis venenatis. Nulla rhoncus faucibus est.
Java
// // UIView+BluredSnapshot.h // CustomTransitionAndBlur // // Created by Gao Song on 11/1/15. // Copyright © 2015 Gao Song. All rights reserved. // #import <UIKit/UIKit.h> @interface UIView (BluredSnapshot) -(UIImage *)blurredSnapshot; @end
Java
-- collate4.test -- -- execsql { -- CREATE TABLE collate4t3(a COLLATE NOCASE, b COLLATE TEXT); -- INSERT INTO collate4t3 VALUES( 'a', 'a' ); -- INSERT INTO collate4t3 VALUES( 'b', 'b' ); -- INSERT INTO collate4t3 VALUES( NULL, NULL ); -- INSERT INTO collate4t3 VALUES( 'B', 'B' ); -- INSERT INTO collate4t3 VALUES( 'A', 'A' ); -- CREATE INDEX collate4i2 ON collate4t3(a COLLATE TEXT, b COLLATE NOCASE); -- } CREATE TABLE collate4t3(a COLLATE NOCASE, b COLLATE TEXT); INSERT INTO collate4t3 VALUES( 'a', 'a' ); INSERT INTO collate4t3 VALUES( 'b', 'b' ); INSERT INTO collate4t3 VALUES( NULL, NULL ); INSERT INTO collate4t3 VALUES( 'B', 'B' ); INSERT INTO collate4t3 VALUES( 'A', 'A' ); CREATE INDEX collate4i2 ON collate4t3(a COLLATE TEXT, b COLLATE NOCASE);
Java
import { computed, get } from '@ember/object'; import { getOwner } from '@ember/application'; import { deprecate } from '@ember/debug'; export function ability(abilityName, resourceName) { deprecate( 'Using ability() computed property is deprecated. Use getters and Can service directly.', false, { for: 'ember-can', since: { enabled: '4.0.0', }, id: 'ember-can.deprecate-ability-computed', until: '5.0.0', } ); resourceName = resourceName || abilityName; return computed(resourceName, function () { let canService = getOwner(this).lookup('service:abilities'); return canService.abilityFor(abilityName, get(this, resourceName)); }).readOnly(); }
Java
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20140216162246) do create_table "active_admin_comments", force: true do |t| t.string "namespace" t.text "body" t.string "resource_id", null: false t.string "resource_type", null: false t.integer "author_id" t.string "author_type" t.datetime "created_at" t.datetime "updated_at" end add_index "active_admin_comments", ["author_type", "author_id"], name: "index_active_admin_comments_on_author_type_and_author_id" add_index "active_admin_comments", ["namespace"], name: "index_active_admin_comments_on_namespace" add_index "active_admin_comments", ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id" create_table "admin_users", force: true do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at" t.datetime "updated_at" end add_index "admin_users", ["email"], name: "index_admin_users_on_email", unique: true add_index "admin_users", ["reset_password_token"], name: "index_admin_users_on_reset_password_token", unique: true create_table "deposit_addresses", force: true do |t| t.integer "sponsor_id" t.integer "project_id" t.string "bitcoin_address" t.datetime "created_at" t.datetime "updated_at" t.integer "month_donations", limit: 8 t.integer "year_donations", limit: 8 end add_index "deposit_addresses", ["project_id"], name: "index_deposit_addresses_on_project_id" add_index "deposit_addresses", ["sponsor_id"], name: "index_deposit_addresses_on_sponsor_id" create_table "deposits", force: true do |t| t.integer "deposit_address_id" t.integer "amount", limit: 8 t.string "input_tx" t.integer "confirmations" t.string "output_tx" t.datetime "created_at" t.datetime "updated_at" end add_index "deposits", ["deposit_address_id"], name: "index_deposits_on_deposit_address_id" create_table "projects", force: true do |t| t.string "name" t.text "about" t.string "url" t.string "bitcoin_address" t.datetime "created_at" t.datetime "updated_at" t.string "donation_page_url" t.integer "month_donations", limit: 8 t.datetime "moderated_at" t.integer "year_donations", limit: 8 end create_table "sponsors", force: true do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.string "confirmation_token" t.datetime "confirmed_at" t.datetime "confirmation_sent_at" t.string "unconfirmed_email" t.datetime "created_at" t.datetime "updated_at" t.string "avatar" t.string "name" t.string "url" t.string "location" t.boolean "private_donations", default: false t.integer "month_donations", limit: 8 t.integer "year_donations", limit: 8 end add_index "sponsors", ["confirmation_token"], name: "index_sponsors_on_confirmation_token", unique: true add_index "sponsors", ["email"], name: "index_sponsors_on_email", unique: true add_index "sponsors", ["reset_password_token"], name: "index_sponsors_on_reset_password_token", unique: true end
Java
/* global requirejs, require */ /*jslint node: true */ 'use strict'; import Ember from 'ember'; import _keys from 'lodash/object/keys'; /* This function looks through all files that have been loaded by Ember CLI and finds the ones under /mirage/[factories, fixtures, scenarios, models]/, and exports a hash containing the names of the files as keys and the data as values. */ export default function(prefix) { let modules = ['factories', 'fixtures', 'scenarios', 'models', 'serializers']; let mirageModuleRegExp = new RegExp(`^${prefix}/mirage/(${modules.join("|")})`); let modulesMap = modules.reduce((memo, name) => { memo[name] = {}; return memo; }, {}); _keys(requirejs.entries).filter(function(key) { return mirageModuleRegExp.test(key); }).forEach(function(moduleName) { if (moduleName.match('.jshint')) { // ignore autogenerated .jshint files return; } let moduleParts = moduleName.split('/'); let moduleType = moduleParts[moduleParts.length - 2]; let moduleKey = moduleParts[moduleParts.length - 1]; Ember.assert('Subdirectories under ' + moduleType + ' are not supported', moduleParts[moduleParts.length - 3] === 'mirage'); if (moduleType === 'scenario'){ Ember.assert('Only scenario/default.js is supported at this time.', moduleKey !== 'default'); } let module = require(moduleName, null, null, true); if (!module) { throw new Error(moduleName + ' must export a ' + moduleType); } let data = module['default']; modulesMap[moduleType][moduleKey] = data; }); return modulesMap; }
Java
/* tslint:disable:no-unused-variable */ import { TestBed, async } from '@angular/core/testing'; import { DpsBarChartComponent } from './dps-bar-chart.component'; describe('Component: DpsBarChart', () => { it('should create an instance', () => { let component = new DpsBarChartComponent(); expect(component).toBeTruthy(); }); });
Java
<?php /** * @author tshirtecommerce - www.tshirtecommerce.com * @date: 2015-01-10 * * @copyright Copyright (C) 2015 tshirtecommerce.com. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE * */ if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> <script src="<?php echo base_url('assets/plugins/jquery-fancybox/jquery.fancybox.js'); ?>" type="text/javascript"></script> <script src="<?php echo base_url('assets/plugins/validate/validate.js'); ?>" type="text/javascript"></script> <link href="<?php echo base_url('assets/plugins/jquery-fancybox/jquery.fancybox.css'); ?>" rel="stylesheet"/> <form name="setting" class="setting-save" method="POST" action="<?php echo site_url('m_product/admin/setting/save/'.$id); ?>"> <div class="tabpanel" role="tabpanel"> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#tab-general" aria-controls="tab-general" role="tab" data-toggle="tab"><?php echo lang('general');?></a></li> <li role="presentation"><a href="#tab-design" aria-controls="tab-design" role="tab" data-toggle="tab"><?php echo lang('design_options'); ?></a></li> <li class="button-back pull-right"><a href="javascript:void(0)" onclick="grid.module.setting('m_product')" title="Back to list"><i class="clip-arrow-left-2"></i></a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="tab-general"> <div class="form-group"> <label><?php echo lang('title');?><span class="symbol required"></span></label> <input type="text" class="form-control input-sm validate required" name="title" placeholder="<?php echo lang('title');?>" value="<?php echo $m_product->title; ?>" data-minlength="2" data-maxlength="200" data-msg="<?php echo lang('m_product_admin_setting_title_validate');?>"> </div> <?php $options = json_decode($m_product->options); ?> <div class="form-group"> <div class="row"> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_show_title');?></label> <?php $show_title = array( 'yes'=>lang('yes'), 'no'=>lang('no'), ); if(isset($options->show_title)) $default = $options->show_title; else $default = ''; echo form_dropdown('options[show_title]', $show_title, $default, 'class="form-control input-sm"'); ?> </div> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_count_cols_title');?></label> <?php $cols = array( '1'=>1, '2'=>2, '3'=>3, '4'=>4, '6'=>6, ); if(isset($options->cols)) $default = $options->cols; else $default = ''; echo form_dropdown('options[cols]', $cols, $default, 'class="form-control input-sm"'); ?> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_show_product_title');?></label> <?php $show_product = array( 'lastest'=>lang('m_product_admin_setting_lastest_title'), 'future'=>lang('m_product_admin_setting_future_title'), 'sale_price'=>lang('m_product_admin_setting_sale_title'), ); if(isset($options->show_product)) $default = $options->show_product; else $default = ''; echo form_dropdown('options[show_product]', $show_product, $default, 'class="form-control input-sm"'); ?> </div> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_count_product_title');?></label> <input type="text" name="options[count]" class="form-control input-sm" value="<?php if(isset($options->count) && $options->count != '') echo $options->count; else echo 8; ?>" placeholder="<?php echo lang('m_product_admin_setting_count_product_title');?>"/> </div> </div> </div> </div> <!-- design options --> <?php $params = json_decode($m_product->params, true); ?> <div role="tabpanel" class="tab-pane" id="tab-design"> <div class="design-box"> <div class="design-box-left"> <div class="box-css"> <label><?php echo lang('css');?></label> <div class="box-margin"> <label><?php echo lang('margin');?></label> <input type="text" class="box-input" name="params[margin][left]" value="<?php echo setParams($params, 'margin', 'left'); ?>" id="margin-left"> <input type="text" class="box-input" name="params[margin][right]" value="<?php echo setParams($params, 'margin', 'right'); ?>" id="margin-right"> <input type="text" class="box-input" name="params[margin][top]" value="<?php echo setParams($params, 'margin', 'top'); ?>" id="margin-top"> <input type="text" class="box-input" name="params[margin][bottom]" value="<?php echo setParams($params, 'margin', 'bottom'); ?>" id="margin-bottom"> <div class="box-border"> <label><?php echo lang('border');?></label> <input type="text" class="box-input" name="params[border][left]" value="<?php echo setParams($params, 'border', 'left'); ?>" id="border-left"> <input type="text" class="box-input" name="params[border][right]" value="<?php echo setParams($params, 'border', 'right'); ?>" id="border-right"> <input type="text" class="box-input" name="params[border][top]" value="<?php echo setParams($params, 'border', 'top'); ?>" id="border-top"> <input type="text" class="box-input" name="params[border][bottom]" value="<?php echo setParams($params, 'border', 'bottom'); ?>" id="border-bottom"> <div class="box-padding"> <label><?php echo lang('padding');?></label> <input type="text" class="box-input" name="params[padding][left]" value="<?php echo setParams($params, 'padding', 'left'); ?>" id="padding-left"> <input type="text" class="box-input" name="params[padding][right]" value="<?php echo setParams($params, 'padding', 'right'); ?>" id="padding-right"> <input type="text" class="box-input" name="params[padding][top]" value="<?php echo setParams($params, 'padding', 'top'); ?>" id="padding-top"> <input type="text" class="box-input" name="params[padding][bottom]" value="<?php echo setParams($params, 'padding', 'bottom'); ?>" id="padding-bottom"> <div class="box-elment"> </div> </div> </div> </div> </div> </div> <div class="design-box-right"> <label><?php echo lang('border');?></label> <div class="row col-md-12"> <div class="form-group pick-color"> <div class="input-group"> <input type="text" class="form-control color input-sm" name="params[borderColor]" value="<?php echo setParams($params, 'borderColor'); ?>"> <div class="input-group-addon pick-color-btn"><?php echo lang('select_color');?></div> </div> <a href="#" class="btn btn-default btn-sm pick-color-clear"><?php echo lang('clear');?></a> </div> </div> <div class="row col-md-12"> <div class="form-group"> <?php $options = array('Defaults', 'Solid','Dotted','Dashed','None','Hidden','Double','Groove','Ridge','Inset','Outset','Initial','Inherit'); ?> <select class="form-control input-sm" name="params[borderStyle]"> <?php for($i=0; $i<12; $i++){ ?> <?php $border_style = setParams($params, 'borderStyle'); if($border_style == $options[$i]) $check = 'selected="selected"'; else $check = ''; ?> <option value="<?php echo $options[$i]; ?>" <?php echo $check;?>><?php echo $options[$i]; ?></option> <?php } ?> </select> </div> </div> <label><?php echo lang('background');?></label> <div class="row col-md-12"> <div class="form-group pick-color"> <div class="input-group"> <input type="text" class="form-control color input-sm" name="params[background][color]" value="<?php echo setParams($params, 'background', 'color'); ?>"> <div class="input-group-addon pick-color-btn"><?php echo lang('select_color');?></div> </div> <a href="#" class="btn btn-default btn-sm pick-color-clear"><?php echo lang('clear');?></a> </div> </div> <div class="row col-md-12"> <div class="form-group"> <?php $image = setParams($params, 'background', 'image'); if($image != '') { echo '<div id="gird-box-bg" style="display:inline;">'; echo '<img src="'.base_url($image).'" class="pull-left box-image" style="width: 80px;" alt="" width="100" />'; }else { echo '<div id="gird-box-bg" style="display:none;">'; } ?> <a href="javascript:void(0)" class="gird-box-bg-remove" onclick="gridRemoveImg(this)"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a> </div> <input type="hidden" name="params[background][image]" id="gird-box-bg-img" value="<?php echo $image; ?>"> <a class="gird-box-image" href="javascript:void(0)" onclick="jQuery.fancybox( {href : '<?php echo site_url().'admin/media/modals/productImg/1'; ?>', type: 'iframe'} );"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></a> </div> </div> <div class="row col-md-12"> <div class="form-group"> <?php $options = array('Defaults','Repeat','No repeat'); ?> <select class="form-control input-sm" name="params[background][style]"> <?php for($i=0; $i<3; $i++){ ?> <?php $background_style = setParams($params, 'background', 'style'); if($background_style == $options[$i]) $check = 'selected="selected"'; else $check = ''; ?> <option value="<?php echo $options[$i]; ?>" <?php echo $check; ?>><?php echo $options[$i]; ?></option> <?php } ?> </select> </div> </div> </div> </div> </div> </div> </div> </form> <script type="text/javascript"> function productImg(images) { if(images.length > 0) { var e = jQuery('#gird-box-bg'); if(e.children('img').length > 0) e.children('img').attr('src', images[0]); else e.append('<img src="'+images[0]+'" class="pull-left box-image" style="width: 80px;" alt="" width="100" />'); e.css('display', 'inline'); var str = images[0]; str = str.replace("<?php echo base_url();?>", ""); jQuery('#gird-box-bg-img').val(str); jQuery.fancybox.close(); } } function gridRemoveImg(e){ var e = jQuery('#gird-box-bg'); e.children('img').remove(); e.css('display', 'none'); jQuery('#gird-box-bg-img').val(''); } </script>
Java
# Botfather configs [BotFather](https://telegram.me/botfather) allows you to create Telegram bots, and instanciates authentication tokens. But it does more than that. To get the same settings as FiddleGram, follow this: * Go to Botfather, use `/start` and follow the instructions to create your bot. Put the auth token in `token.js` * Set up description and about text as you please * Use /setcommands and give the following block: ``` start - [language] start a new repl session stop - stop current repl session languages - list currently supported languages version - list bot and languages versions help - display help ``` This will enable auto-completion on commands. All done! Your Fiddlegram is ready to rock.
Java
<?php declare(strict_types=1); namespace AlphaVantageTest\Api; use AlphaVantage\Api\ForeignExchange; class ForeignExchangeTest extends TestCase { public function testCurrencyExchangeRate() { $actual = (new ForeignExchange($this->option))->currencyExchangeRate('BTC', 'CNY'); $this->assertIsArray($actual); $this->assertCount(1, $actual); $this->assertArrayHasKey('Realtime Currency Exchange Rate', $actual); $this->assertNotEmpty($actual['Realtime Currency Exchange Rate']); $this->assertCount(9, $actual['Realtime Currency Exchange Rate']); } }
Java
local u = require "lib/util" local Node = require "lib/espalier/node" local Section = require "Orbit/section" local own = require "Orbit/own" local D = setmetatable({}, { __index = Node }) D.id = "doc" D.__tostring = function (doc) local phrase = "" for _,v in ipairs(doc) do local repr = tostring(v) if repr ~= "" and repr ~= "\n" then phrase = phrase .. repr .. "\n" end end return phrase end D.__index = D D.own = own function D.dotLabel(doc) return "doc - " .. tostring(doc.linum) end function D.toMarkdown(doc) local phrase = "" for _, node in ipairs(doc) do if node.toMarkdown then phrase = phrase .. node:toMarkdown() else u.freeze("no toMarkdown method for " .. node.id) end end return phrase end local d = {} function D.parentOf(doc, level) local i = level - 1 local parent = nil while i >= 0 do parent = doc.lastOf[i] if parent then return parent else i = i - 1 end end return doc end function D.addSection(doc, section, linum, finish) assert(section.id == "section", "type of putative section is " .. section.id) assert(section.first, "no first in section at line " .. tostring(linum)) assert(type(finish) == "number", "finish is of type " .. type(finish)) if not doc.latest then doc[1] = section else if linum > 0 then doc.latest.line_last = linum - 1 doc.latest.last = finish end local atLevel = doc.latest.level if atLevel < section.level then -- add the section under the latest section doc.latest:addSection(section, linum, finish) else local parent = doc:parentOf(section.level) if parent.id == "doc" then if section.level == 1 and doc.latest.level == 1 then doc[#doc + 1] = section else doc.latest:addSection(section, linum, finish) end else parent:addSection(section, linum, finish) end end end doc.latest = section doc.lastOf[section.level] = section return doc end function D.addLine(doc, line, linum, finish) if doc.latest then doc.latest:addLine(line) doc.latest.last = finish else -- a virtual zero block doc[1] = Section(0, linum, 1, #line, doc.str) doc.latest = doc[1] doc.latest:addLine(line) doc.latest.last = finish end return doc end local function new(Doc, str) local doc = setmetatable({}, D) doc.str = str doc.first = 1 doc.last = #str doc.latest = nil doc.lines = {} doc.lastOf = {} -- for now lets set root to 'false' doc.root = false return doc:own(str) end setmetatable(D, Node) d["__call"] = new return setmetatable({}, d)
Java
package com.github.aureliano.evtbridge.output.file; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.Test; import com.github.aureliano.evtbridge.annotation.validation.NotNull; import com.github.aureliano.evtbridge.annotation.validation.apply.ConstraintViolation; import com.github.aureliano.evtbridge.annotation.validation.apply.ObjectValidator; import com.github.aureliano.evtbridge.core.config.OutputConfigTypes; public class FileOutputConfigTest { ObjectValidator validator = ObjectValidator.instance(); @Test public void testGetDefaults() { FileOutputConfig c = new FileOutputConfig(); assertNull(c.getFile()); assertEquals("UTF-8", c.getEncoding()); assertFalse(c.isAppend()); assertTrue(c.isUseBuffer()); } @Test public void testConfiguration() { FileOutputConfig c = new FileOutputConfig() .withAppend(true) .withEncoding("ISO-8859-1") .withFile("/there/is/not/file"); assertEquals("/there/is/not/file", c.getFile().getPath()); assertEquals("ISO-8859-1", c.getEncoding()); assertTrue(c.isAppend()); } @Test public void testClone() { FileOutputConfig c1 = new FileOutputConfig() .withAppend(true) .withUseBuffer(false) .withEncoding("ISO-8859-1") .withFile("/there/is/not/file") .putMetadata("test", "my test"); FileOutputConfig c2 = c1.clone(); assertEquals(c1.getFile(), c2.getFile()); assertEquals(c1.getEncoding(), c2.getEncoding()); assertEquals(c1.isAppend(), c2.isAppend()); assertEquals(c1.isUseBuffer(), c2.isUseBuffer()); assertEquals(c1.getMetadata("test"), c2.getMetadata("test")); } @Test public void testOutputType() { assertEquals(OutputConfigTypes.FILE_OUTPUT.name(), new FileOutputConfig().id()); } @Test public void testValidation() { FileOutputConfig c = this.createValidConfiguration(); assertTrue(this.validator.validate(c).isEmpty()); this._testValidateFile(); } private void _testValidateFile() { FileOutputConfig c = new FileOutputConfig(); Set<ConstraintViolation> violations = this.validator.validate(c); assertTrue(violations.size() == 1); assertEquals(NotNull.class, violations.iterator().next().getValidator()); } private FileOutputConfig createValidConfiguration() { return new FileOutputConfig().withFile("/path/to/file"); } }
Java
// THIS CODE IS MACHINE-GENERATED, DO NOT EDIT! package fallk.jfunktion; /** * Represents a predicate (boolean-valued function) of a {@code float}-valued and a generic argument. * This is the primitive type specialization of * {@link java.util.function.BiPredicate} for {@code float}/{@code char}. * * @see java.util.function.BiPredicate */ @FunctionalInterface public interface FloatObjectPredicate<E> { /** * Evaluates this predicate on the given arguments. * * @param v1 the {@code float} argument * @param v2 the generic argument * @return {@code true} if the input arguments match the predicate, * otherwise {@code false} */ boolean apply(float v1, E v2); }
Java
#<%= taskname %> <%= description %> ##Usage
Java
console.log("VS: loading content_script.js..." + new Date()); // Check if the communication between page and background.js has broken. var last_message_time = new Date().getTime(); new Promise((resolve) => setTimeout(resolve, 1000000)).then(() => { var now = new Date().getTime(); if (now - last_message_time > 500000) { sendAlert('Not having message from background for at least 500s, force reloading'); reloadPage(); } }); chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { // Update timestamp first. last_message_time = new Date().getTime(); console.log("VS: received data from content_script.js" + new Date()); console.log(request); var action = request["action"]; takeAction(action, request); }); var already_logging_in = false; function takeAction(action, request) { var url = window.location.href; console.log("VS: Taking action: " + action + " in " + url); if (action === ACTION_FOR_HOMEPAGE) { homePage(request); } else if (action === ACTION_FOR_LOGIN_PAGE) { loginPage(request); } else if (action === ACTION_FOR_ASYNC_LOGIN) { loginPage(request); } else if (action === ACTION_FOR_DASHBOARD_PAGE) { dashboardPage(request); } else { // Other cases. console.log("VS: unknown action:" + new Date()); console.log(action); return; } } function dashboardPage(request) { console.log("VS: In dashboard page" + new Date()); //var val = $('[data-reactid=".0.0.3.0.0.0.0.0.1.0.0.1.0"]'); //if (val) { // var ts = new Date().getTime(); // var amount = val.text(); // if (!amount) { // console.log("Failed to parse data from html page. " + new Date()); // } else { // saveGenerationData({'amount': amount, 'time': ts}); // } //} else { // sendAlert('Failed to read data from Dashboard page' + window.location.href); //} //console.log("VS: setting to reload page in 60s: " + new Date()); //window.setInterval(function() { console.log("VS: polling account data" + new Date()); $.ajax({url: "/api/fusion/accounts"}).done(function(msg) { console.log("VS: got account data" + new Date()); var j = msg; if (typeof(j) === "object" && 'accounts' in j) { console.log(j['accounts']); var acct = j['accounts'][0]['account_no']; var newUrl = '/api/fusion/accounts/' + acct; console.log("VS: polling account detail data" + new Date()); $.ajax({url: newUrl}).done(function(msg) { console.log("VS: got account detail data" + new Date()); var j = msg; if (typeof(j) === "object" && 'energyToday' in j) { var ts = new Date().getTime(); var amount = j['energyToday'] / 1000.0; console.log("VS: saveing energy data" + new Date()); saveGenerationData({'time': ts, 'amount': amount}); return; } sendAlert("Failed parse detailed account info from AJAX for: " + textStatus); reloadPage(); }).fail(function(jqXHR, textStatus) { sendAlert("Request failed for loading detailed account info from AJAX for: " + textStatus); reloadPage(); }); return; } sendAlert('Failed to parse account data'); reloadPage(); }).fail(function(jqXHR, textStatus) { sendAlert("Request failed for loading accounts AJAX for: " + textStatus); reloadPage(); }); //}, 60000); } function loginPage(request) { if (request) { asyncLogin(request); } else { chrome.runtime.sendMessage({"action": ACTION_FOR_ASYNC_LOGIN}); } } function homePage(request) { var links = $('A'); for (var i in links) { var link = links[i]; if (link.href == LOGIN_PAGE) { link.click(); } } } function asyncLogin(request) { if (already_logging_in) { console.log("VS: already logging in. This is possible, ignoring.." + new Date()); return; } already_logging_in = true; console.log("VS: gettting new data to login" + new Date()); console.log(request); context = request['data']; if ($("INPUT[data-reactid='.0.0.0.0.0.1.1']").val(context.username).length > 0 && $("INPUT[data-reactid='.0.0.0.0.0.2.0']").val(context.passwd).length > 0) { $("BUTTON[data-reactid='.0.0.0.0.0.4.0']").click(); new Promise((resolve) => setTimeout(resolve, 100000)).then(() => { sendAlert('Login failed for username' + context.username + ' and passwd: ' + context.passwd); }); } $('.email-input.js-initial-focus').val(context.username); $('.js-password-field').val(context.passwd); new Promise((resolve) => setTimeout(resolve, 1500)).then(() => { $('button.submit').click(); }); } var action = urlToAction(window.location.href); console.log("VS: intercepted action:" + action + " at " + new Date()); if (action != '') { takeAction(action, null); } console.log("VS: loaded:" + window.location.href); console.log("VS: registered on load event here handler in content_script.js" + new Date());
Java
Flappy_Flyer ============ A Flappy Birds clone for iOS. Raw XCode project along with original artwork.
Java
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Books extends Model { protected $table = 'books'; protected $fillable = [ 'guid', 'author', 'title', 'description', 'abstract', 'edition', 'publish_date', 'status']; }
Java
--- author: ejames categories: - Essay comments: true date: 2011-04-16T00:00:00.000Z title: Motivations url: /2011/04/motivations/ aliases: - /2011/04/16/motivations/ --- Over the past couple months or so we've had a number of non-programmers contacting us, looking for hackers to hire for their startup/project/idea/next-Facebook-to-be. The logic goes — and you can <em>almost </em>hear it in their emails — that a university hacker is a good, cheap resource. One particular ad asked us for a candidate with 'many scholarships, lots of research papers, and we'll pay you $1000!' — which might be a joke, but if true ignores the fact that such a candidate would be Google material, for close to $80,000 a year. I find most of these shoutouts rather sad. "Saw the email from x?" I'd sometimes ask Angad. "What do you think of it?" And in fact good ads are so rare that when we get one we rush to post it to our mailing list. What most of these ads lack is an understanding of hacker motivations. When you're posting a help-wanted ad, what you're really asking a potential candidate to do is to weigh the cost/benefits of working for your unknown, unproven startup, when they can: <ol> <li><strong>Code for Google Summer of Code </strong>— which is incredibly attractive because you not only earn USD$5000 for 3 months of work, but you also get to work on an open source project (good for your resume); learn several new programming practices; and give back to the world.</li> <li><strong>Intern with a elite program such as <a href="//sg.startuproots.org/">Startup Roots</a></strong> — (which we endorse, by the way).</li> <li><strong>Code on personal projects</strong> — all hackers have one or two on the side, for fun; or</li> <li><strong>Intern at a bank</strong></li> </ol> But then there's an added problem. Some people who email us are business founders looking for technical people. And more often than not the ideas that they have are either laughably bad, or of unknown quality. (The only way to make that unknown known is to implement it yourself and see the response. Which is a chicken and egg problem.) So how do you hire a hacker if you're not one yourself? One answer is to get the motivations for hacking right. Chris Dixon wrote a post recently titled <em><a href="//cdixon.org/2011/04/12/showing-up/">Showing Up</a></em>, where he says: <blockquote>We went to places like the Media Lab and basically just sat ourselves down at lunch counters and awkwardly introduced ourselves: “Hi, my name is Chris Dixon and this is Tom Pinckney and we are starting a company and would love to talk to you about it.” Most students ignored us or thought we were annoying. I remember one student staring at us quizzically saying “startups still exist?” Most of our trips were fruitless. At one point after a failed trip we were on the Redline back to our office in downtown Boston and joked, depressingly, that we felt so out of place that people looked at us like time travelers from the dot-com bubble. Our first breakthough came after a series of trips when a particularly talented programmer/designer named <a href="//larifari.org/">Hugo Liu</a> re-approached us and said something like “hey, actually I thought about it and your idea doesn’t suck.” Then his friend <a href="//www.linkedin.com/profile/view?id=2104665&amp;authType=NAME_SEARCH&amp;authToken=xHpy&amp;locale=en_US&amp;srchid=6b2a8ef5-cf44-4377-ab54-7557dc9d5472-0&amp;srchindex=1&amp;srchtotal=8&amp;pvs=ps&amp;pohelp=&amp;goback=%2Efps_*1_David_Gatenby_*1_*1_*1_*1_*51_*1_Y_*1_*1_*1_false_1_R_true_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2">David Gatenby</a> talked to about joining us. We eventually recruited Hugo and David along with a brilliant undergraduate <a href="//mattgattis.com/about/">Matt Gattis</a>. We had finally broken through. Matt and Hugo now work with us at <a href="//hunch.com/">Hunch</a> along with some of their friends from MIT they brought along.</blockquote> When you're asking a student programmer to work for you, you're selling him two things: 1) your idea, and 2) yourself. If you're not demonstrably smart, or if your project isn't interesting, then it's not likely that any hacker would want to work for you. Not with so many other options on the table. This is, however, a cop-out. The truth is that it's hard to sell your idea when you have bad ideas, and it's even harder to sell yourself if you're not already a hacker (Pinkney, Dixon's friend, is a <a href="//cdixon.posterous.com/mit-is-a-national-treasure"><em>brilliant</em> programmer</a>). The non-technical people who start companies and go on to do great things tend to do so with hackers who they're <em>already</em> friends with. Which leaves us with: if you have bad ideas, or if you have absolutely no freaking clue of hacker culture, than nothing mentioned here will ever help you. So what <em>can</em> help you? Here are a couple of things that I've found to be attractive in a <em>'programmer-wanted'</em> ad: <ol> <li><strong>Know your problem space really, really well.</strong> Hackers have finely-tuned sensors for bullshit, because we absolutely hate it, and know it when we see it. This is a function of preferring to build things vs sitting around and talking about them. If you're not a domain expert in whatever you're doing — it's harder to get a hacker interested.</li> <li><strong>Sell the problem.</strong> If you know something really deeply, it's also likely that you know the problems that people in the aforementioned field need to solve. Problems are very attractive to programmers. In fact, problems are <em>especially </em>attractive to programmers if they're well defined. Fortunately for you, problems in the real world are rarely as clear as problems in programming puzzles, even if real world problems are ultimately more important. Your job as a startup founder is to make that problem space definable, and then sell <em>that</em> to a hacker.</li> <li><strong>Sell experience, not money</strong>. Most of us are attracted to people who try very hard to solve interesting problems. Some of us — the ones you <em>can </em>hire — think that the experience of doing something like that is more valuable than the money. It helps to take money (as an issue) off the table as soon as possible; know that there's no way you can compete with Google Summer of Code, or even a bank internship.</li> </ol> In a nutshell: give us interesting problems to solve. Because if you can't do that, then it's a signal that you either have a lame startup, or you're not particularly good at doing startups, or you're a copycat. And there's nothing to save you from that. (Note: notice that 'interesting problem' can mean a lot more than a 'startup that solves an interesting problem'. For instance, travel search engines are boring, but a travel search engine written in node.js (or Haskell, say) is <em>incredibly </em>attractive to a hacker. Unfortunately you have to be a hacker to understand that, and so we're back at square one.) Semi-related: <a href="//metacog.tumblr.com/post/1436899565/why-business-co-founders-should-learn-to-code">why business co-founders should learn to code</a>. <strong>Update:</strong> A number of people have observed that point 3 was 'off the mark'. It's not. What I mean by it is that you should pay market rate — or enough, whatever that amount is — to take the issue off the table. Don't sell yourself based on salary; it's unlikely that you'll win. <a href="//news.ycombinator.com/item?id=2455323">Discuss this article at HN.</a>
Java
namespace gView.Plugins.DbTools.Relates { partial class TableRelationsDialog { /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom Windows Form-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { this.btnRemove = new System.Windows.Forms.Button(); this.btnEdit = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.btnClose = new System.Windows.Forms.Button(); this.lstRelates = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // // btnRemove // this.btnRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnRemove.Enabled = false; this.btnRemove.Location = new System.Drawing.Point(323, 60); this.btnRemove.Name = "btnRemove"; this.btnRemove.Size = new System.Drawing.Size(125, 23); this.btnRemove.TabIndex = 9; this.btnRemove.Text = "Remove"; this.btnRemove.UseVisualStyleBackColor = true; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // btnEdit // this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnEdit.Enabled = false; this.btnEdit.Location = new System.Drawing.Point(323, 31); this.btnEdit.Name = "btnEdit"; this.btnEdit.Size = new System.Drawing.Size(125, 23); this.btnEdit.TabIndex = 8; this.btnEdit.Text = "Edit..."; this.btnEdit.UseVisualStyleBackColor = true; this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click); // // btnAdd // this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnAdd.Location = new System.Drawing.Point(323, 2); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(125, 23); this.btnAdd.TabIndex = 7; this.btnAdd.Text = "Add..."; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnClose // this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnClose.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnClose.Location = new System.Drawing.Point(323, 180); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(125, 23); this.btnClose.TabIndex = 6; this.btnClose.Text = "Close"; this.btnClose.UseVisualStyleBackColor = true; // // lstRelates // this.lstRelates.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lstRelates.FormattingEnabled = true; this.lstRelates.Location = new System.Drawing.Point(2, 2); this.lstRelates.Name = "lstRelates"; this.lstRelates.Size = new System.Drawing.Size(315, 199); this.lstRelates.TabIndex = 5; this.lstRelates.SelectedIndexChanged += new System.EventHandler(this.lstRelates_SelectedIndexChanged); // // TableRelatesDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(450, 206); this.Controls.Add(this.btnRemove); this.Controls.Add(this.btnEdit); this.Controls.Add(this.btnAdd); this.Controls.Add(this.btnClose); this.Controls.Add(this.lstRelates); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.Name = "TableRelatesDialog"; this.Text = "Relates Dialog"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnRemove; private System.Windows.Forms.Button btnEdit; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.ListBox lstRelates; } }
Java
<?php /* * This file is part of the Schemer package. * * Copyright © 2013 Erin Millard * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Eloquent\Schemer\Constraint; interface SchemaInterface extends ConstraintInterface { }
Java
collectd-network-bandwidth-usage ================================ Collectd exec plugin for monitoring the network bandwitdh usage. Installation ----------- Uncomment exec plugin in your collectd.conf: ```bash LoadPlugin exec ``` Configure plugin: ```bash <Plugin exec> Exec username "/path/to/exec-network-bandwidth-usage.sh" "your-network-interface-name" </Plugin> ``` Restart collectd: ```bash service collectd restart ``` Screenshots ----------- ![Example graph ](https://github.com/Cosmologist/collectd-network-bandwidth-usage/blob/master/screenshots/counter.png?raw=true "Example graph")
Java
/* header bar */ .navbar { margin-bottom:0; } /* aside */ .content,aside { margin-top:20px; margin-bottom:30px; margin-left:0px; margin-right:0px; } .home { background: url(/images/home.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } aside .nav { margin-top:10px; margin-left:10px; margin-right:10px; } /* footer formatting */ footer { margin-bottom:25px; }
Java
<!DOCTYPE html> <html lang="en"> <head> <title>Basic Demo</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;"/> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="red" /> <link href="../../dist/flip.css" rel="stylesheet"> <link href="../../dist/transitions/fade.css" rel="stylesheet"> <link rel="stylesheet" href="assets/css/bootstrap.css"> <link rel="stylesheet" href="assets/css/bootstrap-responsive.css"> <style> @media (min-width: 980px) { body { padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */ } } </style> </head> <body class="flipper" onload="flip()"> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="#">Main</a> <div class="nav-collapse"> <ul class="nav"> <li class="active"><a href="home">Home</a></li> <li><a href="about.html">About</a></li> <li><a href="settings.html">Settings</a></li> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <div id="main" class="container-fluid"> <section class="row-fluid" data-route="/"> <div class="span12"> <ul> <li><a href="about.html">About</a></li> <li><a href="settings.html">Settings</a></li> <li><a href="deferred.html">Deferred Example</a></li> <li><a href="multi.html">Multi Flip Example</a></li> </ul> </div> </section> <section class="row-fluid" id="settings" data-route="settings.html" data-title="Settings"> <form class="well"> <label>Label name</label> <input type="text" class="span3" placeholder="Type something…"> <span class="help-inline">Associated help text!</span> <label class="checkbox"> <input type="checkbox"> Check me out </label> <button type="submit" class="btn">Submit</button> </form> </section> <section class="row-fluid" id="about" data-route="about.html"> <h2>About</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pharetra eros id quam vestibulum faucibus. In a libero ipsum, eu pulvinar nibh. Nulla non congue lacus. Pellentesque ligula risus, mollis vel placerat vel, consectetur ac ante. Vestibulum convallis fringilla est quis accumsan. Aliquam mollis neque eu turpis euismod eget blandit lectus lacinia. Proin purus dolor, scelerisque sed tempor volutpat, aliquet in lectus. Fusce euismod mauris sed enim suscipit id laoreet arcu imperdiet.</p> <p>Vestibulum vel aliquam lectus. Quisque ipsum nibh, auctor mollis dictum eget, sodales ut lectus. Vivamus fermentum dictum odio quis hendrerit. Nam cursus varius metus, a varius lorem mollis sit amet. Nulla imperdiet ultrices lorem non egestas. Praesent faucibus magna vel dui tempus eget commodo sem lacinia. Quisque iaculis magna nec metus suscipit dapibus pellentesque felis convallis. Donec diam nibh, varius sed viverra suscipit, bibendum sed lacus. Aenean eu nunc et ipsum viverra ullamcorper. Quisque lacus eros, suscipit sed sollicitudin eget, lacinia sed metus.</p> </section> <section class="row-fluid" id="not-found"> <h1>Whoops!</h1> <p>The page you're looking for cannot be found. Sorry!</p> </section> </div> <script src="../modernizr.custom.js"></script> <script src="https://raw.github.com/DmitryBaranovskiy/eve/master/eve.min.js"></script> <script src="https://raw.github.com/DamonOehlman/classtweak/master/classtweak.min.js"></script> <script src="https://raw.github.com/cujojs/when/master/when.js"></script> <script src="../../dist/flip.js"></script> <script src="../../dist/plugins/bootstrap.js"></script> <script src="../../dist/plugins/history.js"></script> <script src="assets/js/jquery.js"></script> <script src="assets/js/bootstrap-collapse.js"></script> </body> </html>
Java
package com.carbon108.tilde; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.Collection; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author K Moroz * @version 1.0 */ public class PrimaryModelFactoryTest { private PrimaryModelFactory factory; @Before public void setUp() { factory = new PrimaryModelFactory(); } @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void getIDsGetsAllValidModelIDs() { Collection<String> factoryIDs = factory.getIDs(); assertEquals(2, factoryIDs.size()); assertEquals(true, factoryIDs.contains(ModelID.LINEAR)); assertEquals(true, factoryIDs.contains(ModelID.CONSTANT)); // check immutability exception.expect(UnsupportedOperationException.class); factoryIDs.add("someString"); } @Test public void makeValidModelIDGetsModel() { TildeModel model1 = factory.make(ModelID.LINEAR); TildeModel model2 = factory.make(ModelID.CONSTANT); assertEquals(ModelID.LINEAR, model1.getID()); assertEquals(ModelID.CONSTANT, model2.getID()); } @Test public void makeInvalidIDGetsNullModel() { TildeModel m1null = factory.make(null); TildeModel m1blank = factory.make(""); TildeModel m2invalid = factory.make("invalidModelID"); assertTrue(m1null.isNullModel()); assertTrue(m1blank.isNullModel()); assertTrue(m2invalid.isNullModel()); } @Test public void makeAll() { Collection<TildeModel> models = factory.makeAll(); assertEquals(2, models.size()); assertEquals(true, models.contains(new LinearModel())); assertEquals(true, models.contains(new ConstantModel())); } }
Java
var namespace_kluster_kite_1_1_large_objects_1_1_tests = [ [ "ParcelsTest", "class_kluster_kite_1_1_large_objects_1_1_tests_1_1_parcels_test.html", "class_kluster_kite_1_1_large_objects_1_1_tests_1_1_parcels_test" ] ];
Java
namespace QuanLySinhVien_GUI { partial class frmtimkiemdiemsinhvientheomasv { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmtimkiemdiemsinhvientheomasv)); this.btnThoat = new System.Windows.Forms.Button(); this.cmbMaMH = new System.Windows.Forms.ComboBox(); this.dgvKetQua = new System.Windows.Forms.DataGridView(); this.btnTim = new System.Windows.Forms.Button(); this.txtMaSV = new System.Windows.Forms.TextBox(); this.lblMaMH = new System.Windows.Forms.Label(); this.lblMaSV = new System.Windows.Forms.Label(); this.lblTittle = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dgvKetQua)).BeginInit(); this.SuspendLayout(); // // btnThoat // this.btnThoat.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnThoat.BackgroundImage"))); this.btnThoat.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.btnThoat.Location = new System.Drawing.Point(580, 418); this.btnThoat.Name = "btnThoat"; this.btnThoat.Size = new System.Drawing.Size(72, 30); this.btnThoat.TabIndex = 32; this.btnThoat.Text = " Thoát"; this.btnThoat.UseVisualStyleBackColor = true; // // cmbMaMH // this.cmbMaMH.FormattingEnabled = true; this.cmbMaMH.Location = new System.Drawing.Point(382, 109); this.cmbMaMH.Name = "cmbMaMH"; this.cmbMaMH.Size = new System.Drawing.Size(121, 21); this.cmbMaMH.TabIndex = 31; // // dgvKetQua // this.dgvKetQua.AllowUserToAddRows = false; this.dgvKetQua.AllowUserToDeleteRows = false; this.dgvKetQua.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvKetQua.Location = new System.Drawing.Point(96, 183); this.dgvKetQua.Name = "dgvKetQua"; this.dgvKetQua.ReadOnly = true; this.dgvKetQua.Size = new System.Drawing.Size(537, 214); this.dgvKetQua.TabIndex = 30; // // btnTim // this.btnTim.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnTim.BackgroundImage"))); this.btnTim.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.btnTim.Location = new System.Drawing.Point(580, 105); this.btnTim.Name = "btnTim"; this.btnTim.Size = new System.Drawing.Size(72, 30); this.btnTim.TabIndex = 29; this.btnTim.Text = " Tìm"; this.btnTim.UseVisualStyleBackColor = true; // // txtMaSV // this.txtMaSV.Location = new System.Drawing.Point(114, 111); this.txtMaSV.Name = "txtMaSV"; this.txtMaSV.Size = new System.Drawing.Size(125, 20); this.txtMaSV.TabIndex = 28; // // lblMaMH // this.lblMaMH.AutoSize = true; this.lblMaMH.Location = new System.Drawing.Point(302, 111); this.lblMaMH.Name = "lblMaMH"; this.lblMaMH.Size = new System.Drawing.Size(60, 13); this.lblMaMH.TabIndex = 26; this.lblMaMH.Text = "Mã Học Kỳ"; // // lblMaSV // this.lblMaSV.AutoSize = true; this.lblMaSV.Location = new System.Drawing.Point(43, 111); this.lblMaSV.Name = "lblMaSV"; this.lblMaSV.Size = new System.Drawing.Size(39, 13); this.lblMaSV.TabIndex = 27; this.lblMaSV.Text = "Mã SV"; // // lblTittle // this.lblTittle.AutoSize = true; this.lblTittle.Font = new System.Drawing.Font("Times New Roman", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblTittle.ForeColor = System.Drawing.Color.Red; this.lblTittle.Location = new System.Drawing.Point(151, 30); this.lblTittle.Name = "lblTittle"; this.lblTittle.Size = new System.Drawing.Size(408, 31); this.lblTittle.TabIndex = 25; this.lblTittle.Text = "Tìm Kiếm Điểm Theo Mã Sinh Viên"; // // frmtimkiemdiemsinhvientheomasv // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(695, 479); this.Controls.Add(this.btnThoat); this.Controls.Add(this.cmbMaMH); this.Controls.Add(this.dgvKetQua); this.Controls.Add(this.btnTim); this.Controls.Add(this.txtMaSV); this.Controls.Add(this.lblMaMH); this.Controls.Add(this.lblMaSV); this.Controls.Add(this.lblTittle); this.Name = "frmtimkiemdiemsinhvientheomasv"; this.Text = "TÌM KIẾM ĐIỂM SINH VIÊN"; ((System.ComponentModel.ISupportInitialize)(this.dgvKetQua)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnThoat; private System.Windows.Forms.ComboBox cmbMaMH; private System.Windows.Forms.DataGridView dgvKetQua; private System.Windows.Forms.Button btnTim; private System.Windows.Forms.TextBox txtMaSV; private System.Windows.Forms.Label lblMaMH; private System.Windows.Forms.Label lblMaSV; private System.Windows.Forms.Label lblTittle; } }
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>cantor: 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.11.2 / cantor - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> cantor <small> 8.9.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-08-17 11:46:38 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-17 11:46:38 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.2 Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.0 Official release 4.10.0 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;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/cantor&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Cantor&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: ordinals&quot; &quot;keyword: well-foundedness&quot; &quot;keyword: termination&quot; &quot;keyword: rpo&quot; &quot;keyword: Goodstein sequences&quot; &quot;category: Mathematics/Logic/See also&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Number theory&quot; &quot;date: 2006-05-22&quot; ] authors: [ &quot;Pierre Castéran &lt;pierre.casteran@labri.fr&gt; [http://www.labri.fr/~casteran/]&quot; &quot;Évelyne Contejean &lt;contejea@lri.fr&gt; [http://www.lri.fr/~contejea]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/cantor/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/cantor.git&quot; synopsis: &quot;On Ordinal Notations&quot; description: &quot;&quot;&quot; This contribution contains data structures for ordinals less than Gamma0 under Cantor and Veblen normal forms. Well-foundedness is established thanks to RPO with status for generic terms. This contribution also includes termination proofs of Hydra battles and Goodstein sequences as well as a computation of the length of the Goodstein sequence starting from 4 in base 2. This work is supported by INRIA-Futurs (Logical project-team), CNRS and the French ANR via the A3PAT project (http://www3.iie.cnam.fr/~urbain/a3pat/).&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/cantor/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=00ebfdf7bee8dea49d327079fdcf1048&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-cantor.8.9.0 coq.8.11.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2). The following dependencies couldn&#39;t be met: - coq-cantor -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) 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-cantor.8.9.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>
Java
// Copyright (c) 2012 The Eurobit developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef CHECKQUEUE_H #define CHECKQUEUE_H #include <boost/thread/mutex.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/condition_variable.hpp> #include <vector> #include <algorithm> template<typename T> class CCheckQueueControl; /** Queue for verifications that have to be performed. * The verifications are represented by a type T, which must provide an * operator(), returning a bool. * * One thread (the master) is assumed to push batches of verifications * onto the queue, where they are processed by N-1 worker threads. When * the master is done adding work, it temporarily joins the worker pool * as an N'th worker, until all jobs are done. */ template<typename T> class CCheckQueue { private: // Mutex to protect the inner state boost::mutex mutex; // Worker threads block on this when out of work boost::condition_variable condWorker; // Master thread blocks on this when out of work boost::condition_variable condMaster; // The queue of elements to be processed. // As the order of booleans doesn't matter, it is used as a LIFO (stack) std::vector<T> queue; // The number of workers (including the master) that are idle. int nIdle; // The total number of workers (including the master). int nTotal; // The temporary evaluation result. bool fAllOk; // Number of verifications that haven't completed yet. // This includes elements that are not anymore in queue, but still in // worker's own batches. unsigned int nTodo; // Whether we're shutting down. bool fQuit; // The maximum number of elements to be processed in one batch unsigned int nBatchSize; // Internal function that does bulk of the verification work. bool Loop(bool fMaster = false) { boost::condition_variable &cond = fMaster ? condMaster : condWorker; std::vector<T> vChecks; vChecks.reserve(nBatchSize); unsigned int nNow = 0; bool fOk = true; do { { boost::unique_lock<boost::mutex> lock(mutex); // first do the clean-up of the previous loop run (allowing us to do it in the same critsect) if (nNow) { fAllOk &= fOk; nTodo -= nNow; if (nTodo == 0 && !fMaster) // We processed the last element; inform the master he can exit and return the result condMaster.notify_one(); } else { // first iteration nTotal++; } // logically, the do loop starts here while (queue.empty()) { if ((fMaster || fQuit) && nTodo == 0) { nTotal--; bool fRet = fAllOk; // reset the status for new work later if (fMaster) fAllOk = true; // return the current status return fRet; } nIdle++; cond.wait(lock); // wait nIdle--; } // Decide how many work units to process now. // * Do not try to do everything at once, but aim for increasingly smaller batches so // all workers finish approximately simultaneously. // * Try to account for idle jobs which will instantly start helping. // * Don't do batches smaller than 1 (duh), or larger than nBatchSize. nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1))); vChecks.resize(nNow); for (unsigned int i = 0; i < nNow; i++) { // We want the lock on the mutex to be as short as possible, so swap jobs from the global // queue to the local batch vector instead of copying. vChecks[i].swap(queue.back()); queue.pop_back(); } // Check whether we need to do work at all fOk = fAllOk; } // execute work BOOST_FOREACH(T &check, vChecks) if (fOk) fOk = check(); vChecks.clear(); } while(true); } public: // Create a new check queue CCheckQueue(unsigned int nBatchSizeIn) : nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {} // Worker thread void Thread() { Loop(); } // Wait until execution finishes, and return whether all evaluations where succesful. bool Wait() { return Loop(true); } // Add a batch of checks to the queue void Add(std::vector<T> &vChecks) { boost::unique_lock<boost::mutex> lock(mutex); BOOST_FOREACH(T &check, vChecks) { queue.push_back(T()); check.swap(queue.back()); } nTodo += vChecks.size(); if (vChecks.size() == 1) condWorker.notify_one(); else if (vChecks.size() > 1) condWorker.notify_all(); } ~CCheckQueue() { } friend class CCheckQueueControl<T>; }; /** RAII-style controller object for a CCheckQueue that guarantees the passed * queue is finished before continuing. */ template<typename T> class CCheckQueueControl { private: CCheckQueue<T> *pqueue; bool fDone; public: CCheckQueueControl(CCheckQueue<T> *pqueueIn) : pqueue(pqueueIn), fDone(false) { // passed queue is supposed to be unused, or NULL if (pqueue != NULL) { assert(pqueue->nTotal == pqueue->nIdle); assert(pqueue->nTodo == 0); assert(pqueue->fAllOk == true); } } bool Wait() { if (pqueue == NULL) return true; bool fRet = pqueue->Wait(); fDone = true; return fRet; } void Add(std::vector<T> &vChecks) { if (pqueue != NULL) pqueue->Add(vChecks); } ~CCheckQueueControl() { if (!fDone) Wait(); } }; #endif
Java
## [Section 1.2 - Procedures and the Processes They Generate](https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2) ## Exercises ```scheme ;; ====================================================== ;; Load definitions and functions from earlier chapters ;; ====================================================== (load "c01s01.scm") ;; ====================================================== ``` **Exercise 1.9** Each of the following two procedures defines a method for adding two positive integers in terms of the procedures inc, which increments its argument by 1, and dec, which decrements its argument by 1. ```scheme (define (+ a b) (if (= a 0) b (inc (+ (dec a) b)))) (define (+ a b) (if (= a 0) b (+ (dec a) (inc b)))) ``` Using the substitution model, illustrate the process generated by each procedure in evaluating (+ 4 5). Are these processes iterative or recursive? **Exercise 1.10** The following procedure computes a mathematical function called Ackermann's function. ```scheme (define (A x y) (cond ((= y 0) 0) ((= x 0) (* 2 y)) ((= y 1) 2) (else (A (- x 1) (A x (- y 1)))))) ``` What are the values of the following expressions? ```scheme (A 1 10) (A 2 4) (A 3 3) ``` Consider the following procedures, where A is the procedure defined above: ```scheme (define (f n) (A 0 n)) (define (g n) (A 1 n)) (define (h n) (A 2 n)) (define (k n) (* 5 n n)) ``` Give concise mathematical definitions for the functions computed by the procedures f, g, and h for positive integer values of n. For example, (k n) computes 5n^2. ```scheme (A 1 10) ; 2^10 because the final argument, (A x (- y 1)) ; will evaluate 9 times before y = 1 and the ; function stops at 2 (A 2 4) ; 2^16 because the function first evaluates to (A 1 (A 2 3)) ; = (A 1 (A 1 (A 2 2))) ; = (A 1 (A 1 (A 1 (A 2 1)))) ; = (A 1 (A 1 (A 1 2))) ; = (A 1 (A 1 (A 0 (A 1 1)))) ; = (A 1 (A 1 (A 0 2))) ; = (A 1 (A 1 (2 * 2))) ; = (A 1 (A 1 4)) ; = (A 1 (A 0 (A 1 3))) ; = (A 1 (A 0 (A 0 (A 1 2)))) ; = (A 1 (A 0 (A 0 (A 1 2)))) ; = (A 1 (A 0 (A 0 (A 0 (A 1 1))))) ; = (A 1 (A 0 (A 0 (A 0 2)))) ; = (A 1 (A 0 (A 0 (2 * 2)))) ; = (A 1 (A 0 (A 0 4))) ; = (A 1 (A 0 (2 * 4))) ; = (A 1 (A 0 8)) ; = (A 1 (2 * 8)) ; = (A 1 16) ; which as we saw above will evaluate to 2^16 (A 3 3) ; 2^16 because the function first evaluates to (A 2 (A 3 2)) ; = (A 2 (A 2 (A 3 1))) ; = (A 2 (A 2 2)) ; = (A 2 (A 1 (A 2 1))) ; = (A 2 (A 1 2)) ; = (A 2 (A 0 (A 1 1))) ; = (A 2 (A 0 2)) ; = (A 2 (2 * 2)) ; = (A 2 4) ; which as we saw above will evaluate to 2^16 (define (f n) (A 0 n)) ; f(n) = 2*n (define (g n) (A 1 n)) ; g(n) = 2^n (define (h n) (A 2 n)) ; h(n) = 2^(n^2) ``` **Exercise 1.11** A function f is defined by the rule that f(n) = n if n < 3 and f(n) = f(n-1) + f(n-2) + f(n-3) if n >= 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process. ```scheme ; Recursive solution (define (f n) (cond ((< n 3) n) (else (+ (+ (f (- n 1)) (* 2 (f (- n 2)))) (* 3 (f (- n 3))))))) ; Iterative solution ; a <- a + 2*b + 3*c ; b <- a ; c <- b (define (f n) (f-iter 2 1 0 n)) (define (f-iter a b c count) (if (= count 0) c (f-iter (+ a (* b 2) (* c 3)) a b (- count 1)))) ``` **Exercise 1.12** The following pattern of numbers is called Pascal's triangle. ```Tex 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ``` The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it. Write a procedure that computes elements of Pascal's triangle by means of a recursive process. ```scheme (define (pascal row col) (cond ((= row 1) 1) ((= row col) 1) ((= col 1) 1) (else (+ (pascal (- row 1) (- col 1)) (pascal (- row 1) col))))) (pascal 1 1) ;Value: 1 (pascal 2 1) ;Value: 1 (pascal 2 2) ;Value: 1 (pascal 3 1) ;Value: 1 (pascal 3 2) ;Value: 2 (pascal 3 3) ;Value: 1 (pascal 4 2) ;Value: 3 (pascal 4 3) ;Value: 3 (pascal 5 3) ;Value: 6 ``` **Exercise 1.13** Prove that Fib(n) is the closest integer to (phi^n)/5, where phi = (1 + sqrt(5))/2. Hint: Let psi = (1 - sqrt(5))/2. Use induction and the definition of the Fibonacci numbers (see section 1.2.2) to prove that Fib(n) = (n - n)/5. ```Text Base case: show for n = 0 and n = 1 n=0: Fib(0) = (phi^0 - rho^0)/sqrt(5) 0 = (0 - 0)/sqrt(5) 0 = 0 n=1: Fib(1) = (phi^1 - rho^1)/sqrt(5) 1 = ((1 + sqrt(5))/2 - (1 - sqrt(5))/2)/sqrt(5) 1 = ((2*(sqrt(5)))/2) / sqrt(5) 1 = (sqrt(5)) / sqrt(5) 1 = 1 Induction case: take k >= 1 as given and assume relation is true for all n >= 0 Fib(k + 1) = Fib(k) + Fib(k - 1) By the induction hypothesis, we have that Fib(k + 1) = ((phi^(k) - rho^(k))/sqrt(5)) + ((phi^(k - 1) - rho^(k - 1))/sqrt(5)) Fib(k + 1) = ((phi)^(k) + (phi)^(k - 1))/sqrt(5) - ((rho)^(k) + (rho)^(k - 1))/sqrt(5) Since phi^2 = phi + 1 and rho^2 = rho + 1, we observe that Fib(k + 1) = (((phi)^(k - 1)(phi + 1)) - ((rho)^(k - 1)(rho + 1)))/sqrt(5) Fib(k + 1) = (((phi)^(k - 1)(phi^2)) - ((rho)^(k - 1)(rho^2)))/sqrt(5) Fib(k + 1) = ((phi)^(k + 1) - (rho)^(k + 1))/sqrt(5) ``` **Exercise 1.14** Draw the tree illustrating the process generated by the count-change procedure of section 1.2.2 in making change for 11 cents. What are the orders of growth of the space and number of steps used by this process as the amount to be changed increases? **Exercise 1.15** The sine of an angle (specified in radians) can be computed by making use of the approximation sin x ~ x if x is sufficiently small, and the trigonometric identity sin r = 3 sin r/3 - 4 sin^3 r/3 to reduce the size of the argument of sin. (For purposes of this exercise an angle is considered "sufficiently small" if its magnitude is not greater than 0.1 radians.) These ideas are incorporated in the following procedures: ```scheme (define (cube x) (* x x x)) (define (p x) (- (* 3 x) (* 4 (cube x)))) (define (sine angle) (if (not (> (abs angle) 0.1)) angle (p (sine (/ angle 3.0))))) ``` a. How many times is the procedure p applied when (sine 12.15) is evaluated? > 6 b. What is the order of growth in space and number of steps (as a function of a) used by the process generated by the sine procedure when (sine a) is evaluated? > n **Exercise 1.16** Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that (b^(n/2))^2 = (b^2)^(n/2), keep, along with the exponent n and the base b, an additional state variable a, and define the state transformation in such a way that the product a bn is unchanged from state to state. At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.) ```scheme ; define the iterative algorithm (define (rapid-expt-iter b n product) (cond ((= n 0) product) ; use successive squaring for even powers greater than 2 ((and (even? n) (> n 2)) (rapid-expt-iter b (/ n 2) (* product (* b b)))) ; else use simple iteration (else (rapid-expt-iter b (- n 1) (* product b))))) ; call iterative algorithm in a shorter-form function which initializes a to be 1 (define (rapid-expt b n) (rapid-expt-iter b n 1)) ; Test some outputs (rapid-expt 2 4) ; Value: 16 (rapid-expt 3 5) ; Value: 243 ``` **Exercise 1.17** The exponentiation algorithms in this section are based on performing exponentiation by means of repeated multiplication. In a similar way, one can perform integer multiplication by means of repeated addition. The following multiplication procedure (in which it is assumed that our language can only add, not multiply) is analogous to the expt procedure: ```scheme (define (* a b) (if (= b 0) 0 (+ a (* a (- b 1))))) ``` This algorithm takes a number of steps that is linear in b. Now suppose we include, together with addition, operations double, which doubles an integer, and halve, which divides an (even) integer by 2. Using these, design a multiplication procedure analogous to fast-expt that uses a logarithmic number of steps. ```scheme ; define double (define (double x) (* x 2)) ; define halve (define (halve x) (/ x 2)) ; define the iterative algorithm (define (rapid-mult-iter a b product) (cond ((= b 0) product) ; if b can be halved and is greater than 2, halve it and double the product of the multiplication ((and (even? b) (> b 2)) (+ product (double (rapid-mult-iter a (halve b) 0)))) ; else use simple iteration (else (rapid-mult-iter a (- b 1) (+ product a))))) ; call iterative algorithm in a shorter-form function which initializes a to be 1 (define (rapid-mult a b) (rapid-mult-iter a b 0)) ```
Java
# beautiful-components A collection of webcomponents, inspired by the design work at http://tympanus.net/codrops/
Java
// // BallVC.h // KenshinPro // // Created by apple on 2019/1/31. // Copyright © 2019 Kenshin. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface BallVC : UIViewController @end NS_ASSUME_NONNULL_END
Java
## Your Names # 1) Michael Yao # 2) Benjamin Heidebrink # We spent [1.25] hours on this challenge. # Bakery Serving Size portion calculator. def serving_size_calc(item_to_make, num_of_ingredients) library = {"cookie" => 1, "cake" => 5, "pie" => 7} raise ArgumentError.new("#{item_to_make} is not a valid input") unless library[item_to_make] # fail ArgumentError, "#{item_to_make} is not a valid input" unless library.key?(item_to_make) serving_size = library[item_to_make] remaining_ingredients = num_of_ingredients % serving_size baking_plan = "Calculations complete: Make #{num_of_ingredients / serving_size} of #{item_to_make}" return baking_plan if remaining_ingredients.zero? baking_plan + ", you have #{remaining_ingredients} leftover ingredients. Suggested baking items: #{leftovers(remaining_ingredients)}" end def leftovers(remaining_ingredients) cakes=remaining_ingredients/5 cookies=remaining_ingredients%5 "#{cakes} cakes and #{cookies} cookies." end p serving_size_calc("pie", 7) p serving_size_calc("pie", 8) p serving_size_calc("cake", 5) p serving_size_calc("cake", 7) p serving_size_calc("cookie", 1) p serving_size_calc("cookie", 10) p serving_size_calc("THIS IS AN ERROR", 5) # Reflection # What did you learn about making code readable by working on this challenge? # It's preeettty important. Also we learned some new methods/syntax to make it more readable and truthy/falsey # Did you learn any new methods? What did you learn about them? # .zero? .key? .nil? .values_at # What did you learn about accessing data in hashes? # .values_at returns an array, .key checks for keys., if we show one argument it will return an array of hash/key # What concepts were solidified when working through this challenge? # refactoring, some syntax
Java
module PalmTasksHelper end
Java
import 'css.escape' import { createFootnote, FootnoteElements } from './footnote' import { bindScrollHandler } from './scroll' import { Adapter } from '../core' import { addClass, removeClass, unmount } from './element' export const CLASS_CONTENT = 'littlefoot__content' export const CLASS_WRAPPER = 'littlefoot__wrapper' export type HTMLAdapterSettings = Readonly<{ allowDuplicates: boolean anchorParentSelector: string anchorPattern: RegExp buttonTemplate: string contentTemplate: string footnoteSelector: string numberResetSelector: string scope: string }> type TemplateData = Readonly<{ number: number id: string content: string reference: string }> type Original = Readonly<{ reference: HTMLElement referenceId: string body: HTMLElement }> type OriginalData = Readonly<{ original: Original data: TemplateData }> const CLASS_PRINT_ONLY = 'littlefoot--print' const CLASS_HOST = 'littlefoot' const setPrintOnly = (el: Element) => addClass(el, CLASS_PRINT_ONLY) function queryAll<E extends Element>( parent: ParentNode, selector: string ): readonly E[] { return Array.from(parent.querySelectorAll<E>(selector)) } function getByClassName<E extends Element>(element: E, className: string): E { return ( element.querySelector<E>('.' + className) || (element.firstElementChild as E | null) || element ) } function createElementFromHTML(html: string): HTMLElement { const container = document.createElement('div') container.innerHTML = html return container.firstElementChild as HTMLElement } function children(element: Element, selector: string): readonly Element[] { return Array.from(element.children).filter( (child) => child.nodeType !== 8 && child.matches(selector) ) } function isDefined<T>(value?: T): value is T { return value !== undefined } function findFootnoteLinks( document: Document, pattern: RegExp, scope: string ): readonly HTMLAnchorElement[] { return queryAll<HTMLAnchorElement>(document, scope + ' a[href*="#"]').filter( (link) => (link.href + link.rel).match(pattern) ) } function findReference( document: Document, allowDuplicates: boolean, anchorParentSelector: string, footnoteSelector: string ) { const processed: Element[] = [] return (link: HTMLAnchorElement): Original | undefined => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const fragment = link.href.split('#')[1]! const related = queryAll(document, '#' + CSS.escape(fragment)).find( (footnote) => allowDuplicates || !processed.includes(footnote) ) const body = related?.closest<HTMLElement>(footnoteSelector) if (body) { processed.push(body) const reference = link.closest<HTMLElement>(anchorParentSelector) || link const referenceId = reference.id || link.id return { reference, referenceId, body } } } } function recursiveHideFootnoteContainer(element: HTMLElement): void { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const container = element.parentElement! const visibleElements = children(container, `:not(.${CLASS_PRINT_ONLY})`) const visibleSeparators = visibleElements.filter((el) => el.tagName === 'HR') if (visibleElements.length === visibleSeparators.length) { visibleSeparators.concat(container).forEach(setPrintOnly) recursiveHideFootnoteContainer(container) } } function recursiveUnmount(element: HTMLElement) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const parent = element.parentElement! unmount(element) const html = parent.innerHTML.replace('[]', '').replace('&nbsp;', ' ').trim() if (!html) { recursiveUnmount(parent) } } function prepareTemplateData(original: Original, idx: number): OriginalData { const content = createElementFromHTML(original.body.outerHTML) const backlinkSelector = '[href$="#' + original.referenceId + '"]' queryAll<HTMLElement>(content, backlinkSelector).forEach(recursiveUnmount) const html = content.innerHTML.trim() return { original, data: { id: String(idx + 1), number: idx + 1, reference: 'lf-' + original.referenceId, content: html.startsWith('<') ? html : '<p>' + html + '</p>', }, } } const resetNumbers = (resetSelector: string) => { let current = 0 let previousParent: Element | null = null return ({ original, data }: OriginalData): OriginalData => { const parent = original.reference.closest(resetSelector) current = previousParent === parent ? current + 1 : 1 previousParent = parent return { original, data: { ...data, number: current } } } } function interpolate(template: string) { const pattern = /<%=?\s*(\w+?)\s*%>/g return (replacement: TemplateData) => template.replace(pattern, (_, key: keyof TemplateData) => String(replacement[key] ?? '') ) } function createElements(buttonTemplate: string, popoverTemplate: string) { const renderButton = interpolate(buttonTemplate) const renderPopover = interpolate(popoverTemplate) return ({ original, data, }: OriginalData): OriginalData & FootnoteElements => { const id = data.id const host = createElementFromHTML( `<span class="${CLASS_HOST}">${renderButton(data)}</span>` ) const button = host.firstElementChild as HTMLElement button.setAttribute('aria-expanded', 'false') button.dataset.footnoteButton = '' button.dataset.footnoteId = id const popover = createElementFromHTML(renderPopover(data)) popover.dataset.footnotePopover = '' popover.dataset.footnoteId = id const wrapper = getByClassName(popover, CLASS_WRAPPER) const content = getByClassName(popover, CLASS_CONTENT) bindScrollHandler(content, popover) return { original, data, id, button, host, popover, content, wrapper } } } function attachFootnote(reference: HTMLElement, host: HTMLElement): void { reference.insertAdjacentElement('beforebegin', host) } export function setup({ allowDuplicates, anchorParentSelector, anchorPattern, buttonTemplate, contentTemplate, footnoteSelector, numberResetSelector, scope, }: HTMLAdapterSettings): Adapter<HTMLElement> { const footnoteElements = findFootnoteLinks(document, anchorPattern, scope) .map( findReference( document, allowDuplicates, anchorParentSelector, footnoteSelector ) ) .filter(isDefined) .map(prepareTemplateData) .map(numberResetSelector ? resetNumbers(numberResetSelector) : (i) => i) .map(createElements(buttonTemplate, contentTemplate)) footnoteElements.forEach(({ original, host }) => { setPrintOnly(original.reference) setPrintOnly(original.body) recursiveHideFootnoteContainer(original.body) attachFootnote(original.reference, host) }) const footnotes = footnoteElements.map(createFootnote) return { footnotes, unmount() { footnotes.forEach((footnote) => footnote.destroy()) queryAll(document, '.' + CLASS_PRINT_ONLY).forEach((element) => removeClass(element, CLASS_PRINT_ONLY) ) }, } }
Java
require File.expand_path("spec_helper", File.dirname(File.dirname(__FILE__))) describe 'response.cache_control' do it 'sets the Cache-Control header' do app(:caching) do |r| response.cache_control :public=>true, :no_cache=>true, :max_age => 60 end header('Cache-Control').split(', ').sort.should == ['max-age=60', 'no-cache', 'public'] end it 'does not add a Cache-Control header if it would be empty' do app(:caching) do |r| response.cache_control({}) end header('Cache-Control').should == nil end end describe 'response.expires' do it 'sets the Cache-Control and Expires header' do app(:caching) do |r| response.expires 60, :public=>true, :no_cache=>true end header('Cache-Control').split(', ').sort.should == ['max-age=60', 'no-cache', 'public'] ((Time.httpdate(header('Expires')) - Time.now).round - 60).abs.should <= 1 end it 'can be called with only one argument' do app(:caching) do |r| response.expires 60 end header('Cache-Control').split(', ').sort.should == ['max-age=60'] ((Time.httpdate(header('Expires')) - Time.now).round - 60).abs.should <= 1 end end describe 'response.finish' do it 'removes Content-Type and Content-Length for 304 responses' do app(:caching) do |r| response.status = 304 end header('Content-Type').should == nil header('Content-Length').should == nil end it 'does not change non-304 responses' do app(:caching) do |r| response.status = 200 end header('Content-Type').should == 'text/html' header('Content-Length').should == '0' end end describe 'request.last_modified' do it 'ignores nil' do app(:caching) do |r| r.last_modified nil end header('Last-Modified').should == nil end it 'does not change a status other than 200' do app(:caching) do |r| response.status = 201 r.last_modified Time.now end status.should == 201 status('HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2030 23:43:52 GMT').should == 201 status('HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2000 23:43:52 GMT').should == 201 end end describe 'request.last_modified' do def res(a={}) s, h, b = req(a) h['Last-Modified'].should == @last_modified.httpdate [s, b.join] end before(:all) do lm = @last_modified = Time.now app(:caching) do |r| r.last_modified lm 'ok' end end it 'just sets Last-Modified if no If-Modified-Since header' do res.should == [200, 'ok'] end it 'just sets Last-Modified if bogus If-Modified-Since header' do res('HTTP_IF_MODIFIED_SINCE' => 'a really weird date').should == [200, 'ok'] end it 'just sets Last-Modified if modified since If-Modified-Since header' do res('HTTP_IF_MODIFIED_SINCE' => (@last_modified - 1).httpdate).should == [200, 'ok'] end it 'sets Last-Modified and returns 304 if modified on If-Modified-Since header' do res('HTTP_IF_MODIFIED_SINCE' => @last_modified.httpdate).should == [304, ''] end it 'sets Last-Modified and returns 304 if modified before If-Modified-Since header' do res('HTTP_IF_MODIFIED_SINCE' => (@last_modified + 1).httpdate).should == [304, ''] end it 'sets Last-Modified if If-None-Match header present' do res('HTTP_IF_NONE_MATCH' => '*', 'HTTP_IF_MODIFIED_SINCE' => (@last_modified + 1).httpdate).should == [200, 'ok'] end it 'sets Last-Modified if modified before If-Unmodified-Since header' do res('HTTP_IF_UNMODIFIED_SINCE' => (@last_modified + 1).httpdate).should == [200, 'ok'] end it 'sets Last-Modified if modified on If-Unmodified-Since header' do res('HTTP_IF_UNMODIFIED_SINCE' => @last_modified.httpdate).should == [200, 'ok'] end it 'sets Last-Modified and returns 412 if modified after If-Unmodified-Since header' do res('HTTP_IF_UNMODIFIED_SINCE' => (@last_modified - 1).httpdate).should == [412, ''] end end describe 'request.etag' do before(:all) do app(:caching) do |r| r.is "" do response.status = r.env['status'] if r.env['status'] etag_opts = {} etag_opts[:new_resource] = r.env['new_resource'] if r.env.has_key?('new_resource') etag_opts[:weak] = r.env['weak'] if r.env.has_key?('weak') r.etag 'foo', etag_opts 'ok' end end end it 'uses a weak etag with the :weak option' do header('ETag', 'weak'=>true).should == 'W/"foo"' end describe 'for GET requests' do def res(a={}) s, h, b = req(a) h['ETag'].should == '"foo"' [s, b.join] end it "sets etag if no If-None-Match" do res.should == [200, 'ok'] end it "sets etag and returns 304 if If-None-Match is *" do res('HTTP_IF_NONE_MATCH' => '*').should == [304, ''] end it "sets etag and if If-None-Match is * and it is a new resource" do res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>true).should == [200, 'ok'] end it "sets etag and returns 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"').should == [304, ''] end it "sets etag and returns 304 if If-None-Match includes etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [304, ''] end it "sets etag if If-None-Match does not include etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok'] end it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok'] end it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [304, ''] end it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [304, ''] end it "sets etag if If-Match is *" do res('HTTP_IF_MATCH' => '*').should == [200, 'ok'] end it "sets etag if If-Match is etag" do res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok'] end it "sets etag if If-Match includes etag" do res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok'] end it "sets etag and returns 412 if If-Match is * for new resources" do res('HTTP_IF_MATCH' => '*', 'new_resource'=>true).should == [412, ''] end it "sets etag if If-Match does not include etag" do res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, ''] end end describe 'for PUT requests' do def res(a={}) s, h, b = req(a.merge('REQUEST_METHOD'=>'PUT')) h['ETag'].should == '"foo"' [s, b.join] end it "sets etag if no If-None-Match" do res.should == [200, 'ok'] end it "sets etag and returns 412 if If-None-Match is *" do res('HTTP_IF_NONE_MATCH' => '*').should == [412, ''] end it "sets etag and if If-None-Match is * and it is a new resource" do res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>true).should == [200, 'ok'] end it "sets etag and returns 412 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"').should == [412, ''] end it "sets etag and returns 412 if If-None-Match includes etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [412, ''] end it "sets etag if If-None-Match does not include etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok'] end it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok'] end it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [412, ''] end it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [412, ''] end it "sets etag if If-Match is *" do res('HTTP_IF_MATCH' => '*').should == [200, 'ok'] end it "sets etag if If-Match is etag" do res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok'] end it "sets etag if If-Match includes etag" do res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok'] end it "sets etag and returns 412 if If-Match is * for new resources" do res('HTTP_IF_MATCH' => '*', 'new_resource'=>true).should == [412, ''] end it "sets etag if If-Match does not include etag" do res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, ''] end end describe 'for POST requests' do def res(a={}) s, h, b = req(a.merge('REQUEST_METHOD'=>'POST')) h['ETag'].should == '"foo"' [s, b.join] end it "sets etag if no If-None-Match" do res.should == [200, 'ok'] end it "sets etag and returns 412 if If-None-Match is * and it is not a new resource" do res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>false).should == [412, ''] end it "sets etag and if If-None-Match is *" do res('HTTP_IF_NONE_MATCH' => '*').should == [200, 'ok'] end it "sets etag and returns 412 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"').should == [412, ''] end it "sets etag and returns 412 if If-None-Match includes etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [412, ''] end it "sets etag if If-None-Match does not include etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok'] end it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok'] end it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [412, ''] end it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [412, ''] end it "sets etag if If-Match is * and this is not a new resource" do res('HTTP_IF_MATCH' => '*', 'new_resource'=>false).should == [200, 'ok'] end it "sets etag if If-Match is etag" do res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok'] end it "sets etag if If-Match includes etag" do res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok'] end it "sets etag and returns 412 if If-Match is * for new resources" do res('HTTP_IF_MATCH' => '*').should == [412, ''] end it "sets etag if If-Match does not include etag" do res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, ''] end end end
Java
{% extends '__base__.html' %} {% block title %}创建账户{% endblock %} {% block beforehead %} <script> var action = '{{ action }}'; function initVM(account) { var vm = new Vue({ el: '#vm', data: account, methods: { submit: function (event) { this.$data.date = $('#date').val(); event.preventDefault(); var $form = $('#vm').find('form'); $form.postJSON(action, this.$data, function (err, r) { if (err) { $form.showFormError(err); } else { return location.assign('/account/' + r.id); } }); } } }); $('#vm').show(); } $(function () { $('#loading').hide(); initVM({ name: '', buy_strategy: '', sell_strategy: '', commission_rate: 0.0002, initial_funding: 0, initial_bank_funding: 0, initial_security_funding: 0, date: getTodayString() }); }); </script> {% endblock %} {% block content %} <div id="error" class="uk-width-1-1"> </div> <div id="loading" class="uk-width-1-1 uk-text-center"> <span><i class="uk-icon-spinner uk-icon-medium uk-icon-spin"></i> 正在加载...</span> </div> <div id="vm" class="uk-width-1-1"> <form v-on="submit: submit" class="uk-form uk-form-stacked"> <div class="uk-alert uk-alert-danger uk-hidden"></div> <div class="uk-form-row"> <label class="uk-form-label">账户名称:</label> <div class="uk-form-controls"> <input v-model="name" name="name" type="text" placeholder="账户名称" class="uk-width-1-1"> </div> </div> <div class="uk-form-row"> <label class="uk-form-label">买入策略:</label> <div class="uk-form-controls"> <input v-model="buy_strategy" name="buy_strategy" type="text" placeholder="买入策略" class="uk-width-1-1"> </div> </div> <div class="uk-form-row"> <label class="uk-form-label">卖出策略:</label> <div class="uk-form-controls"> <input v-model="sell_strategy" name="sell_strategy" type="text" placeholder="卖出策略" class="uk-width-1-1"> </div> </div> <div class="uk-form-row"> <label class="uk-form-label">手续费率:</label> <div class="uk-form-controls"> <input v-model="commission_rate" name="commission_rate" type="text" placeholder="手续费率" class="uk-width-1-1"> </div> </div> <div class="uk-form-row"> <label class="uk-form-label">初始本金:</label> <div class="uk-form-controls"> <input v-model="initial_funding" name="initial_funding" type="text" placeholder="初始本金" class="uk-width-1-1"> </div> </div> <div class="uk-form-row"> <label class="uk-form-label">现有银行资金:</label> <div class="uk-form-controls"> <input v-model="initial_bank_funding" name="initial_bank_funding" type="text" placeholder="现有银行资金" class="uk-width-1-1"> </div> </div> <div class="uk-form-row"> <label class="uk-form-label">现有银证资金:</label> <div class="uk-form-controls"> <input v-model="initial_security_funding" name="initial_security_funding" type="text" placeholder="现有银证资金" class="uk-width-1-1"> </div> </div> <div class="uk-form-row"> <label class="uk-form-label">起始日期:</label> <div class="uk-form-controls"> <input id="date" v-model="date" name="date" type="text" data-uk-datepicker="{format:'YYYY-MM-DD'}" class="uk-width-1-1"> </div> </div> <div class="uk-form-row"> <button type="submit" class="uk-button uk-button-primary"><i class="uk-icon-save"></i> 保存</button> <a href="/account/create" class="uk-button"><i class="uk-icon-compress"></i> 基本选项</a> <a href="/" class="uk-button"><i class="uk-icon-times"></i> 取消</a> </div> </form> </div> {% endblock %}
Java
class RemoveOdTokenFromUsers < ActiveRecord::Migration def change remove_column :users, :od_token end end
Java
(function() { angular.module('starter.controllers').controller('DetailController', DetailController); DetailController.$inject = ['CarService', '$stateParams']; function DetailController (CarService, $stateParams) { var vm = this; CarService.getCar($stateParams.id).$promise.then(function(data) { vm.car = data; CarService.setCurrentCar(data); } ); } })();
Java
# Deploying Development Office 365 Sites to Microsoft Azure # ### Summary ### When developing any type a web application, most development is done locally using http://localhost. Some projects use local resources or a mix of local and remote resources. Taking these projects from local development environments involves a handful of tasks to perform like changing database connection strings, URLs, configurations, etc. Web projects that leverage the Office 365 APIs are no different. These projects leverage Microsoft's Azure AD service to authenticate the applications and obtain OAuth 2.0 access tokens. These tokens are used by the web applications to authenticate with the Office 365 APIs. This page explains the steps involved in taking an Office 365 API development project and launching it to a working sample hosted entirely in Microsoft Azure using [Office 365](http://products.office.com/en-us/business/explore-office-365-for-business), [Azure Active Directory](http://azure.microsoft.com/en-us/services/active-directory/) & [Azure Websites](http://azure.microsoft.com/en-us/services/websites/. Deploying an Office 365 API web application to Microsoft Azure from a local development environment requires three high-level steps to be performed as outlined in this page: - [Create and Configure an Azure Website](#create-and-configure-an-azure-website) - [Configure the Azure AD Application](#configure-the-azure-ad-application) - [Configure the ASP.NET Project](#configure-the-aspnet-project) - [Deploy the Office 365 API ASP.NET Web Application](#deploy-the-office-365-api-aspnet-web-application) > This page assumes that you have a local working ASP.NET application that uses the Office 365 APIs. For reference, it will use the **[O365-WebApp-SingleTenant](https://github.com/OfficeDev/O365-WebApp-SingleTenant)** project found in the **[OfficeDev](https://github.com/OfficeDev)** account in GitHub. # Create and Configure an Azure Website In this step you will create an Azure website that will be used to host the web application. 1. Navigate to the [Azure Management Portal](https://manage.windowsazure.com) and login using your Organization ID account. 1. After logging in, using the navigation sidebar, select **WEBSITES**. 1. On the **websites** page, click the **NEW** link in the footer found in the lower-left corner of the page. 1. In the wizard that appears, select **Quick Create**, enter a name for the site in the **URL** field, select a **Web Hosting Plan** and **Subscription**. ![](media/Move-O365Api-Project-from-Dev-To-Prod/Move-O365Api-Project-from-Dev-To-Prod-01.png) > Make sure to keep a note of the name of the website you create as it will be needed later. 1. Finally click the **Create Website** link to create the site. Give Azure a few moments to create the site. After creating the site you can specify *app settings* through the web interface. This allows you to override any `<appSettings>` within the project's `web.config` file through the web administration interface for the website without deploying your site codebase for simple `web.config` changes. 1. Click the website that you just created within the **Azure Management Portal**. 1. CLick the **CONFIGURE** link in the top navigation. 1. Scroll down to the **App Settings** section and add three new entries: - **ida:ClientID** - **ida:Password** - **ida:TenantID** 1. Copy the corresponding values from the working project's `web.config` to these settings values in your Azure website as shown in the following figure: ![](media/Move-O365Api-Project-from-Dev-To-Prod/Move-O365Api-Project-from-Dev-To-Prod-02.png) 1. In the footer, click the **SAVE** button to save your changes. At this point the Azure website is setup and configured to host the Office 365 API web project that you will deploy in a later step. [back to top](#deploying-development-office-365-sites-to-microsoft-azure) # Configure the Azure AD Application In this step you will modify the Azure AD application used in the development & testing of the Office 365 application. 1. Navigate to the [Azure Management Portal](https://manage.windowsazure.com) and login using your Organization ID account. 1. After logging in, using the navigation sidebar, select **ACTIVE DIRECTORY**. 1. On the **active directory** page, select the directory that is linked to your Office 365 tenant. 1. Next, click the **APPLICATIONS** item in the top navigation. 1. Within the **Properties** section, update the **SIGN-ON URL** to point to the default URL of the Azure Website you created. Take note to use the HTTPS endpoint that is provided with all Azure websites. ![](media/Move-O365Api-Project-from-Dev-To-Prod/Move-O365Api-Project-from-Dev-To-Prod-03.png) 1. Within the **Single Sign-On** section, update the **App ID URI** to use the domain for the Azure website (shown in the following figure). 1. Next, update the **REPLY URL** so the only URL listed is the homepage of the Azure website: ![](media/Move-O365Api-Project-from-Dev-To-Prod/Move-O365Api-Project-from-Dev-To-Prod-04.png) 1. In the footer, click the **SAVE** button to save your changes. At this point, the Azure AD application used by the Office 365 API web project has been configured to work with the new Azure website. [back to top](#deploying-development-office-365-sites-to-microsoft-azure) # Configure the ASP.NET Project In this step you will configure the ASP.NET project in your application to use the new Azure Website. For the sample application used in the example for this guidance, no extra work is actually required. However the web application does contain the settings within the `web.config` file for the Azure AD application and Azure AD tenant used during development. Some developers may choose to use different Azure AD applications or even different Azure subscriptions for their development and production instances. In a previous step outlined in this page, when you created the Azure website you set the add-in settings for the application that are typically found in the `web.config`. To ensure the web application receives these values from the Azure website configuration, it's recommended you replace the values within the `web.config` with placeholder values instead. 1. Open the project's `web.config` file. 1. Locate the add-in settings for the **ida:ClientID**, **ida:Password** and **ida:TenantId**. 1. Replace the values of these settings with a placeholder value: ````xml <add key="ida:TenantId" value="set-in-azure-website-config" /> <add key="ida:ClientID" value="set-in-azure-website-config" /> <add key="ida:Password" value="set-in-azure-website-config" /> ```` 1. Save you changes. At this point the web application, Azure website & application in Azure AD are all configured correctly and ready to be deployed. [back to top](#deploying-development-office-365-sites-to-microsoft-azure) # Deploy the Office 365 API ASP.NET Web Application In this step you will publish the Office 365 API web application to the Azure website. Once the site has been deployed you will test it to ensure everything works as desired. > This step assumes you have he Microsoft [Azure SDK](http://azure.microsoft.com/en-us/downloads/), version 2.0 or higher, installed. ## Deploy the ASP.NET Web Application 1. Open your Office 365 API web application in Visual Studio 2013. 1. Within the Solution Explorer tool window, right-click the project and select **Publish** start the **Publish Web** wizard. 1. On the **Profile** tab, select **Microsoft Azure Website**. At this point you will be prompted to login to your Azure subscription using your Organization ID. 1. After logging in, select the website that you created in a previous step from this page and click **OK**. ![](media/Move-O365Api-Project-from-Dev-To-Prod/Move-O365Api-Project-from-Dev-To-Prod-05.png) 1. On the **Connection** tab, click the **Validate Connection** button to ensure the connection profile was successfully downloaded and applied. ![](media/Move-O365Api-Project-from-Dev-To-Prod/Move-O365Api-Project-from-Dev-To-Prod-06.png) 1. Click the **Publish** button to publish the web application to the Azure website. ## Test the ASP.NET Web Application After publishing the web application to the Azure website, Visual Studio will open a browser and navigate to the site's homepage. By default this is the HTTP endpoint. Recall from the previous step when you configured the Azure AD application that you set it to only accept sign ons from the HTTPS endpoint. Before you use the application update the url to point to the HTTPS endpoint. 1. In the browser, update the URL to go to the HTTPS homepage for the Azure website. In the example in this page, that is https://o365api-01.azurewebsites.net. 1. Click the **Sign In** link in the header at the top-right of the page. This will redirect you to the Azure AD sign on page. > If you get an error at this point, it's likely an issue with the three add-in settings you created for the Azure website. Go back and make sure the values are the correct values from the Azure AD tenant & application. You should see a URL that looks 1. After successfully logging in, you will be redirected back to the homepage for the web application of the Azure website you created. At this point you have successfully deployed your Office 365 API web application project to run in an Azure website. [back to top](#deploying-development-office-365-sites-to-microsoft-azure) ---------- ### Related links ### - [O365-WebApp-SingleTenant](https://github.com/OfficeDev/O365-WebApp-SingleTenant) ### Applies to ### - Office 365 Multi Tenant (MT) - Office 365 Dedicated (D) ### Author Andrew Connell - [@andrewconnell](https://twitter.com/andrewconnell) ### Version history ### Version | Date | Comments ---------| -----| -------- 0.1 | January 2, 2015 | First draft
Java
# -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main()
Java
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Filter\PlatformRequirementFilter\IgnoreListPlatformRequirementFilter; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface; use Composer\Package\BasePackage; use Composer\Package\AliasPackage; /** * @author Nils Adermann <naderman@naderman.de> * @phpstan-import-type ReasonData from Rule */ class RuleSetGenerator { /** @var PolicyInterface */ protected $policy; /** @var Pool */ protected $pool; /** @var RuleSet */ protected $rules; /** @var array<int, BasePackage> */ protected $addedMap = array(); /** @var array<string, BasePackage[]> */ protected $addedPackagesByNames = array(); public function __construct(PolicyInterface $policy, Pool $pool) { $this->policy = $policy; $this->pool = $pool; $this->rules = new RuleSet; } /** * Creates a new rule for the requirements of a package * * This rule is of the form (-A|B|C), where B and C are the providers of * one requirement of the package A. * * @param BasePackage $package The package with a requirement * @param BasePackage[] $providers The providers of the requirement * @param Rule::RULE_* $reason A RULE_* constant describing the reason for generating this rule * @param mixed $reasonData Any data, e.g. the requirement name, that goes with the reason * @return Rule|null The generated rule or null if tautological * * @phpstan-param ReasonData $reasonData */ protected function createRequireRule(BasePackage $package, array $providers, $reason, $reasonData = null): ?Rule { $literals = array(-$package->id); foreach ($providers as $provider) { // self fulfilling rule? if ($provider === $package) { return null; } $literals[] = $provider->id; } return new GenericRule($literals, $reason, $reasonData); } /** * Creates a rule to install at least one of a set of packages * * The rule is (A|B|C) with A, B and C different packages. If the given * set of packages is empty an impossible rule is generated. * * @param BasePackage[] $packages The set of packages to choose from * @param Rule::RULE_* $reason A RULE_* constant describing the reason for * generating this rule * @param mixed $reasonData Additional data like the root require or fix request info * @return Rule The generated rule * * @phpstan-param ReasonData $reasonData */ protected function createInstallOneOfRule(array $packages, $reason, $reasonData): Rule { $literals = array(); foreach ($packages as $package) { $literals[] = $package->id; } return new GenericRule($literals, $reason, $reasonData); } /** * Creates a rule for two conflicting packages * * The rule for conflicting packages A and B is (-A|-B). A is called the issuer * and B the provider. * * @param BasePackage $issuer The package declaring the conflict * @param BasePackage $provider The package causing the conflict * @param Rule::RULE_* $reason A RULE_* constant describing the reason for generating this rule * @param mixed $reasonData Any data, e.g. the package name, that goes with the reason * @return ?Rule The generated rule * * @phpstan-param ReasonData $reasonData */ protected function createRule2Literals(BasePackage $issuer, BasePackage $provider, $reason, $reasonData = null): ?Rule { // ignore self conflict if ($issuer === $provider) { return null; } return new Rule2Literals(-$issuer->id, -$provider->id, $reason, $reasonData); } /** * @param BasePackage[] $packages * @param Rule::RULE_* $reason A RULE_* constant * @param mixed $reasonData * @return Rule * * @phpstan-param ReasonData $reasonData */ protected function createMultiConflictRule(array $packages, $reason, $reasonData): Rule { $literals = array(); foreach ($packages as $package) { $literals[] = -$package->id; } if (\count($literals) == 2) { return new Rule2Literals($literals[0], $literals[1], $reason, $reasonData); } return new MultiConflictRule($literals, $reason, $reasonData); } /** * Adds a rule unless it duplicates an existing one of any type * * To be able to directly pass in the result of one of the rule creation * methods null is allowed which will not insert a rule. * * @param RuleSet::TYPE_* $type A TYPE_* constant defining the rule type * @param Rule $newRule The rule about to be added * * @return void */ private function addRule($type, Rule $newRule = null): void { if (!$newRule) { return; } $this->rules->add($newRule, $type); } /** * @return void */ protected function addRulesForPackage(BasePackage $package, PlatformRequirementFilterInterface $platformRequirementFilter): void { /** @var \SplQueue<BasePackage> */ $workQueue = new \SplQueue; $workQueue->enqueue($package); while (!$workQueue->isEmpty()) { $package = $workQueue->dequeue(); if (isset($this->addedMap[$package->id])) { continue; } $this->addedMap[$package->id] = $package; if (!$package instanceof AliasPackage) { foreach ($package->getNames(false) as $name) { $this->addedPackagesByNames[$name][] = $package; } } else { $workQueue->enqueue($package->getAliasOf()); $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package, array($package->getAliasOf()), Rule::RULE_PACKAGE_ALIAS, $package)); // aliases must be installed with their main package, so create a rule the other way around as well $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package->getAliasOf(), array($package), Rule::RULE_PACKAGE_INVERSE_ALIAS, $package->getAliasOf())); // if alias package has no self.version requires, its requirements do not // need to be added as the aliased package processing will take care of it if (!$package->hasSelfVersionRequires()) { continue; } } foreach ($package->getRequires() as $link) { $constraint = $link->getConstraint(); if ($platformRequirementFilter->isIgnored($link->getTarget())) { continue; } elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) { $constraint = $platformRequirementFilter->filterConstraint($link->getTarget(), $constraint); } $possibleRequires = $this->pool->whatProvides($link->getTarget(), $constraint); $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package, $possibleRequires, Rule::RULE_PACKAGE_REQUIRES, $link)); foreach ($possibleRequires as $require) { $workQueue->enqueue($require); } } } } /** * @return void */ protected function addConflictRules(PlatformRequirementFilterInterface $platformRequirementFilter): void { /** @var BasePackage $package */ foreach ($this->addedMap as $package) { foreach ($package->getConflicts() as $link) { // even if conlict ends up being with an alias, there would be at least one actual package by this name if (!isset($this->addedPackagesByNames[$link->getTarget()])) { continue; } $constraint = $link->getConstraint(); if ($platformRequirementFilter->isIgnored($link->getTarget())) { continue; } elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) { $constraint = $platformRequirementFilter->filterConstraint($link->getTarget(), $constraint); } $conflicts = $this->pool->whatProvides($link->getTarget(), $constraint); foreach ($conflicts as $conflict) { // define the conflict rule for regular packages, for alias packages it's only needed if the name // matches the conflict exactly, otherwise the name match is by provide/replace which means the // package which this is an alias of will conflict anyway, so no need to create additional rules if (!$conflict instanceof AliasPackage || $conflict->getName() === $link->getTarget()) { $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRule2Literals($package, $conflict, Rule::RULE_PACKAGE_CONFLICT, $link)); } } } } foreach ($this->addedPackagesByNames as $name => $packages) { if (\count($packages) > 1) { $reason = Rule::RULE_PACKAGE_SAME_NAME; $this->addRule(RuleSet::TYPE_PACKAGE, $this->createMultiConflictRule($packages, $reason, $name)); } } } /** * @return void */ protected function addRulesForRequest(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter): void { foreach ($request->getFixedPackages() as $package) { if ($package->id == -1) { // fixed package was not added to the pool as it did not pass the stability requirements, this is fine if ($this->pool->isUnacceptableFixedOrLockedPackage($package)) { continue; } // otherwise, looks like a bug throw new \LogicException("Fixed package ".$package->getPrettyString()." was not added to solver pool."); } $this->addRulesForPackage($package, $platformRequirementFilter); $rule = $this->createInstallOneOfRule(array($package), Rule::RULE_FIXED, array( 'package' => $package, )); $this->addRule(RuleSet::TYPE_REQUEST, $rule); } foreach ($request->getRequires() as $packageName => $constraint) { if ($platformRequirementFilter->isIgnored($packageName)) { continue; } elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) { $constraint = $platformRequirementFilter->filterConstraint($packageName, $constraint); } $packages = $this->pool->whatProvides($packageName, $constraint); if ($packages) { foreach ($packages as $package) { $this->addRulesForPackage($package, $platformRequirementFilter); } $rule = $this->createInstallOneOfRule($packages, Rule::RULE_ROOT_REQUIRE, array( 'packageName' => $packageName, 'constraint' => $constraint, )); $this->addRule(RuleSet::TYPE_REQUEST, $rule); } } } /** * @return void */ protected function addRulesForRootAliases(PlatformRequirementFilterInterface $platformRequirementFilter): void { foreach ($this->pool->getPackages() as $package) { // ensure that rules for root alias packages and aliases of packages which were loaded are also loaded // even if the alias itself isn't required, otherwise a package could be installed without its alias which // leads to unexpected behavior if (!isset($this->addedMap[$package->id]) && $package instanceof AliasPackage && ($package->isRootPackageAlias() || isset($this->addedMap[$package->getAliasOf()->id])) ) { $this->addRulesForPackage($package, $platformRequirementFilter); } } } /** * @return RuleSet */ public function getRulesFor(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter = null): RuleSet { $platformRequirementFilter = $platformRequirementFilter ?: PlatformRequirementFilterFactory::ignoreNothing(); $this->addRulesForRequest($request, $platformRequirementFilter); $this->addRulesForRootAliases($platformRequirementFilter); $this->addConflictRules($platformRequirementFilter); // Remove references to packages $this->addedMap = $this->addedPackagesByNames = array(); $rules = $this->rules; $this->rules = new RuleSet; return $rules; } }
Java
package spider.cli import command._ import spider.Util.errorExit import com.typesafe.scalalogging.Logger object CLI { lazy val logger = Logger("spider.cli") def go(args: Array[String]): Unit = args.toSeq match { case e if args.isEmpty ⇒ Help(args) case "scrape" +: tail ⇒ Scrape(tail) case "wait" +: tail ⇒ Wait(tail) case "help" +: tail ⇒ Help(tail) case "remove" +: tail ⇒ Remove(tail) case "getcat" +: tail ⇒ GetCategory(tail) case other +: tail ⇒ errorExit(s"unknown command $other") } }
Java
/** * @author alteredq / http://alteredqualia.com/ */ THREE.DepthPassPlugin = function () { this.enabled = false; this.renderTarget = null; var _gl, _renderer, _lights, _webglObjects, _webglObjectsImmediate, _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin, _frustum = new THREE.Frustum(), _projScreenMatrix = new THREE.Matrix4(), _renderList = []; this.init = function ( renderer, lights, webglObjects, webglObjectsImmediate ) { _gl = renderer.context; _renderer = renderer; _lights = lights; _webglObjects = webglObjects; _webglObjectsImmediate = webglObjectsImmediate; var depthShader = THREE.ShaderLib[ "depthRGBA" ]; var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } ); _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } ); _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } ); _depthMaterial._shadowPass = true; _depthMaterialMorph._shadowPass = true; _depthMaterialSkin._shadowPass = true; _depthMaterialMorphSkin._shadowPass = true; }; this.render = function ( scene, camera ) { if ( ! this.enabled ) return; this.update( scene, camera ); }; this.update = function ( scene, camera ) { var i, il, j, jl, n, program, buffer, material, webglObject, object, light, renderList, fog = null; // set GL state for depth map _gl.clearColor( 1, 1, 1, 1 ); _gl.disable( _gl.BLEND ); _renderer.state.setDepthTest( true ); // update scene if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); // update camera matrices and frustum camera.matrixWorldInverse.getInverse( camera.matrixWorld ); _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); _frustum.setFromMatrix( _projScreenMatrix ); // render depth map _renderer.setRenderTarget( this.renderTarget ); _renderer.clear(); // set object matrices & frustum culling _renderList.length = 0; projectObject(scene, scene, camera); // render regular objects var objectMaterial, useMorphing, useSkinning; for ( j = 0, jl = _renderList.length; j < jl; j ++ ) { webglObject = _renderList[ j ]; object = webglObject.object; buffer = webglObject.buffer; // todo: create proper depth material for particles if ( object instanceof THREE.PointCloud && ! object.customDepthMaterial ) continue; objectMaterial = getObjectMaterial( object ); if ( objectMaterial ) _renderer.setMaterialFaces( object.material ); useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets; useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning; if ( object.customDepthMaterial ) { material = object.customDepthMaterial; } else if ( useSkinning ) { material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin; } else if ( useMorphing ) { material = _depthMaterialMorph; } else { material = _depthMaterial; } if ( buffer instanceof THREE.BufferGeometry ) { _renderer.renderBufferDirect( camera, _lights, fog, material, buffer, object ); } else { _renderer.renderBuffer( camera, _lights, fog, material, buffer, object ); } } // set matrices and render immediate objects for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) { webglObject = _webglObjectsImmediate[ j ]; object = webglObject.object; if ( object.visible ) { object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); _renderer.renderImmediateObject( camera, _lights, fog, _depthMaterial, object ); } } // restore GL state var clearColor = _renderer.getClearColor(), clearAlpha = _renderer.getClearAlpha(); _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha ); _gl.enable( _gl.BLEND ); }; function projectObject(scene, object,camera) { if ( object.visible ) { var webglObjects = _webglObjects[object.id]; if (webglObjects && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) { for (var i = 0, l = webglObjects.length; i < l; i ++) { var webglObject = webglObjects[i]; object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); _renderList.push(webglObject); } } for (var i = 0, l = object.children.length; i < l; i ++) { projectObject(scene, object.children[i], camera); } } } // For the moment just ignore objects that have multiple materials with different animation methods // Only the first material will be taken into account for deciding which depth material to use function getObjectMaterial( object ) { return object.material instanceof THREE.MeshFaceMaterial ? object.material.materials[ 0 ] : object.material; } };
Java
import path from 'path' let { context, file, mocha, options } = module.parent.context let { it } = context context.it = function (name, callback) { if (callback) { return it(...arguments); } else { callback = name name = path.basename(file, '.js') } }
Java
/** * @copyright Copyright (C) DocuSign, Inc. All rights reserved. * * This source code is intended only as a supplement to DocuSign SDK * and/or on-line documentation. * * This sample is designed to demonstrate DocuSign features and is not intended * for production use. Code and policy for a production application must be * developed to meet the specific data and security requirements of the * application. * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ package net.docusign.sample; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import net.docusign.api_3_0.APIServiceSoap; import net.docusign.api_3_0.ArrayOfString2; import net.docusign.api_3_0.EnvelopePDF; import net.docusign.api_3_0.EnvelopeStatusFilter; import net.docusign.api_3_0.FilteredEnvelopeStatuses; import net.docusign.api_3_0.RequestRecipientTokenAuthenticationAssertion; import net.docusign.api_3_0.RequestRecipientTokenAuthenticationAssertionAuthenticationMethod; import net.docusign.api_3_0.RequestRecipientTokenClientURLs; /** * Servlet implementation class GetStatusAndDocs */ public class GetStatusAndDocs extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public GetStatusAndDocs() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().setAttribute(Utils.SESSION_EMBEDTOKEN, ""); HttpSession session = request.getSession(); // Make sure we're logged in if (session.getAttribute(Utils.SESSION_LOGGEDIN) == null || session.getAttribute(Utils.SESSION_LOGGEDIN).equals(false)) { response.sendRedirect(Utils.CONTROLLER_LOGIN); } else { // Do we have envelope IDs in this session? if (session.getAttribute(Utils.SESSION_ENVELOPEIDS) != null) { APIServiceSoap api = Utils.getAPI(request); // Grab all the envelope IDs in this session ArrayOfString2 envIDs = new ArrayOfString2(); envIDs.getEnvelopeId().addAll((List<String>) session.getAttribute(Utils.SESSION_ENVELOPEIDS)); // Create a filter so we only retrieve these envelope statuses EnvelopeStatusFilter filter = new EnvelopeStatusFilter(); filter.setAccountId(session.getAttribute(Utils.SESSION_ACCOUNT_ID).toString()); filter.setEnvelopeIds(envIDs); try { // Call requestStatusesEx on these envelopes FilteredEnvelopeStatuses statuses = api.requestStatusesEx(filter); session.setAttribute(Utils.SESSION_STATUSES, statuses.getEnvelopeStatuses().getEnvelopeStatus()); } catch (Exception e) { } } response.sendRedirect(Utils.PAGE_GETSTATUS); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the parameter names Enumeration paramNames = request.getParameterNames(); // Loop through the parameter names while (paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); if (paramName.startsWith(Utils.NAME_STARTSIGNING)) { // We want to start this user signing startSigning(paramName, request); response.sendRedirect(Utils.PAGE_GETSTATUS); } else if (paramName.startsWith(Utils.NAME_DOWNLOAD)) { // We want to download the specified envelope downloadEnvelope(paramName, request, response); } } } protected void downloadEnvelope(String param, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String eid = param.split("\\+")[1]; // Request the PDF of the envelope APIServiceSoap api = Utils.getAPI(request); EnvelopePDF pdf = api.requestPDF(eid); // Start download of the resulting PDF byte[] documentBytes = pdf.getPDFBytes(); response.setHeader("Content-Disposition", "attachment;filename=Envelope.pdf"); response.setContentLength(documentBytes.length); response.setContentType("application/pdf"); response.getOutputStream().write(documentBytes); return; } protected void startSigning(String param, HttpServletRequest request) throws ServletException, IOException { // Parse out envelope id, email, username, client user id String[] params = param.split("\\&"); String eid = "", cid = "", uname = "", email = ""; for (int i = 0; i < params.length; i++) { String[] pair = params[i].split("\\+"); if(pair[0].equals("SignDocEnvelope")) { eid = pair[1]; } else if (pair[0].equals("Email")) { email = pair[1]; } else if (pair[0].equals("UserName")) { uname = pair[1]; } else if (pair[0].equals("CID")) { cid = pair[1]; } } // Request the token try { getToken(request, eid, email, uname, cid); } catch (DatatypeConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void getToken(HttpServletRequest request, String eid, String email, String username, String CID) throws DatatypeConfigurationException { String token = null; // Create the assertion RequestRecipientTokenAuthenticationAssertion assertion = new RequestRecipientTokenAuthenticationAssertion(); assertion.setAssertionID(UUID.randomUUID().toString()); // wsdl2java translates this to XMLGregorianCalendar GregorianCalendar gcal = new GregorianCalendar(); gcal.setTime(new Date()); assertion.setAuthenticationInstant(DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal)); assertion.setAuthenticationMethod(RequestRecipientTokenAuthenticationAssertionAuthenticationMethod.PASSWORD); assertion.setSecurityDomain("DocuSign2010Q1Sample"); // Create the URLs that DocuSign will redirect the iframe to after different events RequestRecipientTokenClientURLs urls = new RequestRecipientTokenClientURLs(); String urlbase = Utils.getCallbackURL(request, Utils.PAGE_POP); urls.setOnAccessCodeFailed(urlbase + "?event=AccessCodeFailed&uname=" + username); urls.setOnCancel(urlbase + "?event=Cancel&uname=" + username); urls.setOnDecline(urlbase + "?event=Decline&uname=" + username); urls.setOnException(urlbase + "?event=Exception&uname=" + username); urls.setOnFaxPending(urlbase + "?event=FaxPending&uname=" + username); urls.setOnIdCheckFailed(urlbase + "?event=IdCheckFailed&uname=" + username); urls.setOnSessionTimeout(urlbase + "?event=SessionTimeout&uname=" + username); urls.setOnTTLExpired(urlbase + "?event=TTLExpired&uname=" + username); urls.setOnViewingComplete(urlbase + "?event=ViewingComplete&uname=" + username); urls.setOnSigningComplete(urlbase + "?event=SigningComplete&uname=" + username); // Get the API service and call RequestRecipientToken for this recipient APIServiceSoap api = Utils.getAPI(request); token = api.requestRecipientToken(eid, CID, username, email, assertion, urls); // Set the iframe to the token request.getSession().setAttribute(Utils.SESSION_EMBEDTOKEN, token); } }
Java
# # MIT License # # Copyright (c) 2016 Paul Taylor # # 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 OR COPYRIGHT HOLDERS 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. # module PPool class BasicProcessController def initialize @time_started = Time.now.to_i end def running? return true end def num_processes return 1 end def process_started(pid, num_processes) puts "> process started #{pid}; num_processes #{num_processes}" end def run_process info "#{Process.pid} running" exit 0 end def process_ended(pid, status) puts "> process ended - pid #{pid}, status #{status}" end def progress(stats) puts "> active #{stats[:active_processes]} started #{stats[:processes_started]} ended #{stats[:processes_ended]} errors #{stats[:errors]}" end def delay return 0.1 end def info(m) puts "+ #{m}" end def time_running secs = time_running_secs hours = (secs / (60 * 60)) % 24 mins = (secs / 60) % 60 secs = secs % 60 return "%.2d:%.2d:%.2d" % [hours, mins,secs] end def time_running_secs Time.now.to_i - @time_started end end end
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Mon Aug 31 23:15:52 CEST 2015 --> <title>Uses of Interface starkcoder.failfast.fails.objects.floats.IObjectFloatNullFail (FailFast v.1.3)</title> <meta name="date" content="2015-08-31"> <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 Interface starkcoder.failfast.fails.objects.floats.IObjectFloatNullFail (FailFast v.1.3)"; } //--> </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="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">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?starkcoder/failfast/fails/objects/floats/class-use/IObjectFloatNullFail.html" target="_top">Frames</a></li> <li><a href="IObjectFloatNullFail.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 Interface starkcoder.failfast.fails.objects.floats.IObjectFloatNullFail" class="title">Uses of Interface<br>starkcoder.failfast.fails.objects.floats.IObjectFloatNullFail</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#starkcoder.failfast.fails">starkcoder.failfast.fails</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#starkcoder.failfast.fails.objects">starkcoder.failfast.fails.objects</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#starkcoder.failfast.fails.objects.floats">starkcoder.failfast.fails.objects.floats</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="starkcoder.failfast.fails"> <!-- --> </a> <h3>Uses of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/package-summary.html">starkcoder.failfast.fails</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation"> <caption><span>Subinterfaces of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/package-summary.html">starkcoder.failfast.fails</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Interface and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../starkcoder/failfast/fails/IFailer.html" title="interface in starkcoder.failfast.fails">IFailer</a></strong></code> <div class="block">Failer specification.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../starkcoder/failfast/fails/package-summary.html">starkcoder.failfast.fails</a> that implement <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../starkcoder/failfast/fails/AFailer.html" title="class in starkcoder.failfast.fails">AFailer</a></strong></code> <div class="block">Abstract implementation of <a href="../../../../../../starkcoder/failfast/fails/IFailer.html" title="interface in starkcoder.failfast.fails"><code>IFailer</code></a>.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../starkcoder/failfast/fails/Failer.html" title="class in starkcoder.failfast.fails">Failer</a></strong></code> <div class="block">Default concrete implementation of <a href="../../../../../../starkcoder/failfast/fails/IFailer.html" title="interface in starkcoder.failfast.fails"><code>IFailer</code></a> using abstract implementation <a href="../../../../../../starkcoder/failfast/fails/AFailer.html" title="class in starkcoder.failfast.fails"><code>AFailer</code></a>.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="starkcoder.failfast.fails.objects"> <!-- --> </a> <h3>Uses of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/objects/package-summary.html">starkcoder.failfast.fails.objects</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation"> <caption><span>Subinterfaces of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/objects/package-summary.html">starkcoder.failfast.fails.objects</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Interface and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../starkcoder/failfast/fails/objects/IObjectFailer.html" title="interface in starkcoder.failfast.fails.objects">IObjectFailer</a></strong></code> <div class="block">Specification grouping all object fail specifications.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="starkcoder.failfast.fails.objects.floats"> <!-- --> </a> <h3>Uses of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/objects/floats/package-summary.html">starkcoder.failfast.fails.objects.floats</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation"> <caption><span>Subinterfaces of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/objects/floats/package-summary.html">starkcoder.failfast.fails.objects.floats</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Interface and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatFailer.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatFailer</a></strong></code> <div class="block">Specification grouping all Float fail specifications.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </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="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">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?starkcoder/failfast/fails/objects/floats/class-use/IObjectFloatNullFail.html" target="_top">Frames</a></li> <li><a href="IObjectFloatNullFail.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 ======= --> <p class="legalCopy"><small><i>The MIT License (MIT) - Copyright &#169; 2014-2015 Keld Oelykke. All Rights Reserved.</i></small></p> </body> </html>
Java
using System.Linq; using EspaceClient.FrontOffice.Business.Depots; using EspaceClient.FrontOffice.Domaine; namespace EspaceClient.FrontOffice.Data.Depots { public partial class DepotTypeRenduBloc : Depot<TypeRenduBloc>, IDepotTypeRenduBloc { public TypeRenduBloc GetByCode(string code, string codeTypeBloc) { var query = from trb in DbContext.TypeRenduBlocs where trb.Code == code where trb.TypeBloc.Code == codeTypeBloc select trb; return query.FirstOrDefault(); } } }
Java
# lnet update 2015-03-28 Now multi-httpserver supported! See 'httpserver.lua'. # lnet update 2015-03-25 Now cosocket supported! What is cosocket? 'cosocket' is a socket API wapper for http handlers in lnet httpserver. It provides tcp/udp block operations but actually non-block in lnet httpserver thread. Yes, the name 'cosocket' means 'coroutine socket'. We yield out of the running corouine while doing some block operation (like connect and etc.), and resume back when the socket is ready. To use cosocket, you have to require 'lnet.cosocket' explicitly in your lua code, and it returns an object: local Socket = require "lnet.cosocket" - tcp = Socket:tcp(ip, port) -- create a tcp socket object - udp = Socket:udp(ip, port) -- create a udp socket object - ret, err = Socket:connect(ip, port) - sndlen, err = Socket:send(data, ip, port) - rcvlen, data, ip, port = Socket:recv(condition) - Socket.settimeout(sec) To learn more, see 'lnet/cosocket.lua' and 'lnet/model_http/handler/test_socket.lua'. # lnet update 2015-03-18 Now webpage supported! 1. static web pages: custom root directory, default pages, mime types, and etc. 2. dynamic web pages: Lua code embedded in html (very similar to PHP), see 'lnet/model_http/root/index.lua' for example. So far, the Lua APIs for webpage and handler: - echo (output messages into html, like php) - http.peer.ip - http.peer.port - http.req.headline - http.req.protocol - http.req.method - http.req.uri - http.req.uri_path - http.req.uri_args[key] = value - http.req.headers[header] = info - http.req.content - http.resp.statusline - http.resp.protocol - http.resp.code - http.resp.desc - http.resp.headers[header] = info - http.resp.content - http:exit(code, err) # lnet This new toy is for those people who believe in that Lua can do everything, including httpserver. The name 'lnet' is short for 'Lua Net', and what I have done here are as below: 1. Lua socket API (C extension library) 2. Lua IO poll API with multi-thread support (C extension library) 3. An event-model TCP server framework (Lua code) 4. An httpserver with restful HTTP services framework (Lua code) You can use 'lnet' to do: 1. Normal socket develop 2. Custom TCP server develop 3. Server(backend) REST API develop How to make, configure, and use 'lnet' httpserver: 1. Make sure you have already installed 'lua' or 'luajit'. 2. Make C library 'lnet/core.dll' (if Linux, run 'make'). 3. Modify 'lnet/model_http/config/default.lua' as you like. How to configue? See annotations in config file, and to learn it yourself. 4. Modify 'httpserver.lua', set server parameters. 5. Run 'httpserver.lua'. 'lnet' is designed for good at restful HTTP services developping. As 'lnet' and its restful HTTP services framework is not perfect so far, it is still under construction, so you have to read source code for more infomations. Thank you!
Java
'use strict' const { EventEmitter } = require('events') const { Multiaddr } = require('multiaddr') /** * @typedef {import('libp2p-interfaces/src/transport/types').Listener} Listener */ /** * @param {import('../')} libp2p * @returns {Listener} a transport listener */ module.exports = (libp2p) => { const listeningAddrs = new Map() /** * Add swarm handler and listen for incoming connections * * @param {Multiaddr} addr * @returns {Promise<void>} */ async function listen (addr) { const addrString = String(addr).split('/p2p-circuit').find(a => a !== '') const relayConn = await libp2p.dial(new Multiaddr(addrString)) const relayedAddr = relayConn.remoteAddr.encapsulate('/p2p-circuit') listeningAddrs.set(relayConn.remotePeer.toB58String(), relayedAddr) listener.emit('listening') } /** * Get fixed up multiaddrs * * NOTE: This method will grab the peers multiaddrs and expand them such that: * * a) If it's an existing /p2p-circuit address for a specific relay i.e. * `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the * address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where * `QmPeer` is this peers id * b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit * addr, such when dialing over a relay with this address, it will create the circuit using * the encapsulated transport address. This is useful when for example, a peer should only * be dialed over TCP rather than any other transport * * @returns {Multiaddr[]} */ function getAddrs () { const addrs = [] for (const addr of listeningAddrs.values()) { addrs.push(addr) } return addrs } /** @type Listener */ const listener = Object.assign(new EventEmitter(), { close: () => Promise.resolve(), listen, getAddrs }) // Remove listeningAddrs when a peer disconnects libp2p.connectionManager.on('peer:disconnect', (connection) => { const deleted = listeningAddrs.delete(connection.remotePeer.toB58String()) if (deleted) { // Announce listen addresses change listener.emit('close') } }) return listener }
Java
using System.Collections.Generic; namespace BlobTransfer { public class TransferResult { public List<string> Succeeded { get; set; } = new List<string>(); public List<string> Skipped { get; set; } = new List<string>(); public List<string> Failed { get; set; } = new List<string>(); } }
Java
<H1>CARDS LIST</h1> <div ng-repeat="card in CardCtrl.cardlist" ng-bind="card.title"></div>
Java
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Twainsoft.FHDO.Compiler.App")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Twainsoft.FHDO.Compiler.App")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c67323cd-9d0c-4fbd-9ff4-3c0cad27d20c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Java
(function() { $(function() { $('.tooltip-examples a, .tooltip-paragraph-examples a').tooltip({ animation: false }); $('.top-sign-in').on("click", function(e) { $('.login-box').fadeIn("fast"); return false; }); $('.login-box-close').on("click", function(e) { $(this).closest(".login-box").fadeOut("fast"); return false; }); prettyPrint(); $(".slider-browser-center").animate({ bottom: $(".slider-browser-center").data('position-bottom') }, "fast", function() { return $(".slider-browser-left").animate({ bottom: $(".slider-browser-left").data('position-bottom') }, "fast", function() { return $(".slider-browser-right").animate({ bottom: $(".slider-browser-right").data('position-bottom') }, "fast"); }); }); $('.carousel').carousel({ interval: false }); return $('a[data-toggle="testimonial"]').on("click", function(e) { $(this).closest('.testimonials-users').find('a[data-toggle="testimonial"]').removeClass("active"); $(this).addClass("active"); $('.testimonials-speech').removeClass('active'); $('.testimonials-speech' + $(this).attr('href')).addClass('active'); return false; }); }); $("body").on("touchstart.dropdown", ".dropdown-menu", function(e) { return e.stopPropagation(); }); return $(document).on("click", ".dropdown-menu a", function() { return document.location = $(this).attr("href"); }); }).call(this);
Java
# # Testing rufus-sixjo # # jmettraux at gmail.org # # Fri Aug 8 15:14:45 JST 2008 # require 'test/unit' require 'testmixins' # # the "test" app # module HeadApp extend Rufus::Sixjo get '/toto' do "toto" end end class HeadTest < Test::Unit::TestCase include SixjoTestMixin def setup @app = HeadApp.new_sixjo_rack_app(nil, :environment => 'test') end def test_0 assert_equal 200, head('/toto').status assert_equal '', @response.body end end
Java
/* Generated by Font Squirrel (http://www.fontsquirrel.com) on April 1, 2011 08:28:28 AM America/New_York */ @font-face { font-family: 'UbuntuRegular'; src: url('Ubuntu-Regular-webfont.eot'); src: url('Ubuntu-Regular-webfont.eot?iefix') format('eot'), url('Ubuntu-Regular-webfont.woff') format('woff'), url('Ubuntu-Regular-webfont.ttf') format('truetype'), url('Ubuntu-Regular-webfont.svg#webfontHLBpjp3B') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'UbuntuItalic'; src: url('Ubuntu-Italic-webfont.eot'); src: url('Ubuntu-Italic-webfont.eot?iefix') format('eot'), url('Ubuntu-Italic-webfont.woff') format('woff'), url('Ubuntu-Italic-webfont.ttf') format('truetype'), url('Ubuntu-Italic-webfont.svg#webfontthRLUYUD') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'UbuntuBold'; src: url('Ubuntu-Bold-webfont.eot'); src: url('Ubuntu-Bold-webfont.eot?iefix') format('eot'), url('Ubuntu-Bold-webfont.woff') format('woff'), url('Ubuntu-Bold-webfont.ttf') format('truetype'), url('Ubuntu-Bold-webfont.svg#webfont1d3fIoP8') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'UbuntuBoldItalic'; src: url('Ubuntu-BoldItalic-webfont.eot'); src: url('Ubuntu-BoldItalic-webfont.eot?iefix') format('eot'), url('Ubuntu-BoldItalic-webfont.woff') format('woff'), url('Ubuntu-BoldItalic-webfont.ttf') format('truetype'), url('Ubuntu-BoldItalic-webfont.svg#webfontir7CsQCC') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'UbuntuLight'; src: url('Ubuntu-Light-webfont.eot'); src: url('Ubuntu-Light-webfont.eot?iefix') format('eot'), url('Ubuntu-Light-webfont.woff') format('woff'), url('Ubuntu-Light-webfont.ttf') format('truetype'), url('Ubuntu-Light-webfont.svg#webfontRPnMKj6g') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'UbuntuLightItalic'; src: url('Ubuntu-LightItalic-webfont.eot'); src: url('Ubuntu-LightItalic-webfont.eot?iefix') format('eot'), url('Ubuntu-LightItalic-webfont.woff') format('woff'), url('Ubuntu-LightItalic-webfont.ttf') format('truetype'), url('Ubuntu-LightItalic-webfont.svg#webfontpehCzxnt') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'UbuntuMedium'; src: url('Ubuntu-Medium-webfont.eot'); src: url('Ubuntu-Medium-webfont.eot?iefix') format('eot'), url('Ubuntu-Medium-webfont.woff') format('woff'), url('Ubuntu-Medium-webfont.ttf') format('truetype'), url('Ubuntu-Medium-webfont.svg#webfontcsgXxJIo') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'UbuntuMediumItalic'; src: url('Ubuntu-MediumItalic-webfont.eot'); src: url('Ubuntu-MediumItalic-webfont.eot?iefix') format('eot'), url('Ubuntu-MediumItalic-webfont.woff') format('woff'), url('Ubuntu-MediumItalic-webfont.ttf') format('truetype'), url('Ubuntu-MediumItalic-webfont.svg#webfonteCMdxuKx') format('svg'); font-weight: normal; font-style: normal; }
Java
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> <!-- [Dependencies[ --> <script src="transform.js"></script> <!-- ]] --> <style type="text/css"> body { background: #00406c; padding: 60px 10px 20px 20px; } div { padding: 10px; margin: 10px; background: #fff; float: left; } </style> </head> <body> <div id="test1"> Click to transform (rotate) </div> <div id="test2"> Click for transition (opacity) </div> <div id="test3"> Click for transform-transtion </div> </body> </html>
Java
using Owin; using SimpleInjector; using SimpleInjector.Extensions.ExecutionContextScoping; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Reporter.WebAPI.Infrastructure.Owin { public static class OwinContextExecutionScopeMiddleware { public static void UseOwinContextExecutionScope(this IAppBuilder app, Container container) { // Create an OWIN middleware to create an execution context scope app.Use(async (context, next) => { using (var scope = container.BeginExecutionContextScope()) { await next.Invoke(); } }); } } }
Java
# heppyplot A package for plotting histogrammed data with special support for high energy physics applications. ![Scale variation example](examples/scales/scales.png) ![PDF variation example](examples/pdf/H_pT_nojet_j30.png) ## Installation Currently we use a custom fork of the excellent [seaborn](http://stanford.edu/~mwaskom/software/seaborn/) package. ``` git clone https://github.com/ebothmann/heppyplot.git cd heppyplot git submodule update --init cd seaborn pip install -e . cd .. pip install -e . ```
Java