text:
<%page args="course_overview, enrollment, show_courseware_link, cert_status, can_unenroll, credit_status, show_email_settings, course_mode_info, show_refund_option, is_paid_course, is_course_blocked, verification_status, course_requirements, dashboard_index, share_settings, related_programs, display_course_modes_on_dashboard" expression_filter="h"/>

<%!
import urllib

from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from django.core.urlresolvers import reverse
from course_modes.models import CourseMode
from course_modes.helpers import enrollment_mode_display
from openedx.core.djangolib.js_utils import dump_js_escaped_json
from openedx.core.djangolib.markup import HTML, Text
from student.helpers import (
  VERIFY_STATUS_NEED_TO_VERIFY,
  VERIFY_STATUS_SUBMITTED,
  VERIFY_STATUS_RESUBMITTED,
  VERIFY_STATUS_APPROVED,
  VERIFY_STATUS_MISSED_DEADLINE,
  VERIFY_STATUS_NEED_TO_REVERIFY,
  DISABLE_UNENROLL_CERT_STATES,
)
%>

<%
  reverify_link = reverse('verify_student_reverify')
  cert_name_short = course_overview.cert_name_short
  if cert_name_short == "":
    cert_name_short = settings.CERT_NAME_SHORT

  cert_name_long = course_overview.cert_name_long
  if cert_name_long == "":
    cert_name_long = settings.CERT_NAME_LONG
  billing_email = settings.PAYMENT_SUPPORT_EMAIL
%>

<%namespace name='static' file='../static_content.html'/>

  % if display_course_modes_on_dashboard:
    <%
        course_verified_certs = enrollment_mode_display(
            enrollment.mode,
            verification_status.get('status'),
            course_overview.id
        )
    %>
    <%
        mode_class = course_verified_certs.get('display_mode', '')
        if mode_class != '':
            mode_class = ' ' + mode_class ;
    %>
  % else:
    <% mode_class = '' %>
  % endif

  <% course_target = reverse('courseware', args=[unicode(course_overview.id)]) %>

${_('Course details')}

      % if show_courseware_link:
        % if not is_course_blocked:

        % else:

        % endif
      % else:

      % endif
      % if display_course_modes_on_dashboard and course_verified_certs.get('display_mode') != 'audit':

          ${_("Enrolled as: ")}
          % if course_verified_certs.get('show_image'):

          % endif

${course_verified_certs.get('enrollment_value')}

      % endif

          % if show_courseware_link:
            % if not is_course_blocked:
              ${course_overview.display_name_with_default}
            % else:
              ${course_overview.display_name_with_default}
            % endif
          % else:
            ${course_overview.display_name_with_default}
          % endif

          ${course_overview.display_org_with_default} -
          ${course_overview.display_number_with_default}
          <%
            if course_overview.start_date_is_still_default:
                container_string = _("Coming Soon")
                course_date = None
            else:
                format = 'shortDate'
                if course_overview.has_ended():
                    container_string = _("Ended - {date}")
                    course_date = course_overview.end
                elif course_overview.has_started():
                    container_string = _("Started - {date}")
                    course_date = course_overview.start
                elif course_overview.starts_within(days=5):
                    container_string = _("Starts - {date}")
                    course_date = course_overview.start
                    format = 'defaultFormat'
                else: ## hasn't started yet
                    container_string = _("Starts - {date}")
                    course_date = course_overview.start
                endif
            endif
          %>

                % if isinstance(course_date, str):
                    ${_(container_string).format(date=course_date)}
                % elif course_date is not None:
                    <%
                        course_date_string = course_date.strftime('%Y-%m-%dT%H:%M:%S%z')
                    %>

                % endif

            % if show_courseware_link:
              % if course_overview.has_ended():
                % if not is_course_blocked:
                  ${_('View Archived Course')} ${course_overview.display_name_with_default}
                % else:
                  ${_('View Archived Course')} ${course_overview.display_name_with_default}
                % endif
              % else:
                % if not is_course_blocked:
                  ${_('View Course')} ${course_overview.display_name_with_default}
                % else:
                  ${_('View Course')} ${course_overview.display_name_with_default}
                % endif
              % endif

              % if share_settings:
                <%
                  if share_settings.get("CUSTOM_COURSE_URLS", False):
                    if course_overview.social_sharing_url:
                      share_url = urllib.quote_plus(course_overview.social_sharing_url)
                    else:
                      share_url = ''
                  else:
                    share_url = urllib.quote_plus(request.build_absolute_uri(reverse('about_course', args=[unicode(course_overview.id)])))
                  share_window_name = 'shareWindow'
                  share_window_config = 'toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=640, height=480'
                %>
                % if share_url and share_settings.get('DASHBOARD_FACEBOOK', False):
                  <% facebook_url = 'https://www.facebook.com/sharer/sharer.php?u=' + share_url %>

                      ${_('Facebook')}

                % endif
                % if share_url and share_settings.get('DASHBOARD_TWITTER', False):
                  <% share_text_default = _("I'm learning on {platform_name}:").format(platform_name=settings.PLATFORM_NAME) %>
                  <% share_text = urllib.quote_plus(share_settings.get('DASHBOARD_TWITTER_TEXT', share_text_default)) %>
                  <% twitter_url = 'https://twitter.com/intent/tweet?text=' + share_text + '%20' + share_url %>

                      ${_('Twitter')}

                % endif
              % endif
            % endif

              <button type="button" class="action action-more" id="actions-dropdown-link-${dashboard_index}" aria-haspopup="true" aria-expanded="false" aria-controls="actions-dropdown-${dashboard_index}" data-course-number="${course_overview.number}" data-course-name="${course_overview.display_name_with_default}" data-dashboard-index="${dashboard_index}">
                ${_('Course options for')}

                  ${course_overview.display_name_with_default}

              </button>

                  % if can_unenroll:

                    % if is_paid_course and show_refund_option:
                      % if not is_course_blocked:
                      <a href="#unenroll-modal" class="action action-unenroll" rel="leanModal" data-course-id="${course_overview.id}" data-course-number="${course_overview.number}" data-course-name="${course_overview.display_name_with_default}" data-dashboard-index="${dashboard_index}"
                         data-track-info="${_("Are you sure you want to unenroll from the purchased course %(course_name)s (%(course_number)s)?")}"
                         data-refund-info="${_("You will be refunded the amount you paid.")}">
                        ${_('Unenroll')}

                      % else:

                        ${_('Unenroll')}

                      % endif
                    % elif is_paid_course and not show_refund_option:
                      % if not is_course_blocked:
                      <a href="#unenroll-modal" class="action action-unenroll" rel="leanModal" data-course-id="${course_overview.id}" data-course-number="${course_overview.number}" data-course-name="${course_overview.display_name_with_default}" data-dashboard-index="${dashboard_index}"
                         data-track-info="${_("Are you sure you want to unenroll from the purchased course %(course_name)s (%(course_number)s)?")}"
                         data-refund-info="${_("You will not be refunded the amount you paid.")}">
                        ${_('Unenroll')}

                      % else:

                        ${_('Unenroll')}

                      % endif
                    % elif enrollment.mode != "verified":
                      % if not is_course_blocked:

                        ${_('Unenroll')}

                      % else:

                        ${_('Unenroll')}

                      % endif
                    % elif show_refund_option:
                      % if not is_course_blocked:
                      <a href="#unenroll-modal" class="action action-unenroll" rel="leanModal" data-course-id="${course_overview.id}" data-course-number="${course_overview.number}" data-course-name="${course_overview.display_name_with_default}" data-dashboard-index="${dashboard_index}" data-cert-name-long="${cert_name_long}"
                         data-track-info="${_("Are you sure you want to unenroll from the verified %(cert_name_long)s track of %(course_name)s (%(course_number)s)?")}"
                         data-refund-info="${_("You will be refunded the amount you paid.")}">
                        ${_('Unenroll')}

                      % else:
                      <a class="action action-unenroll is-disabled" data-course-id="${course_overview.id}" data-course-number="${course_overview.number}" data-course-name="${course_overview.display_name_with_default}" data-dashboard-index="${dashboard_index}" data-cert-name-long="${cert_name_long}"
                         data-track-info="${_("Are you sure you want to unenroll from the verified %(cert_name_long)s track of %(course_name)s (%(course_number)s)?")}"
                         data-refund-info="${_("You will be refunded the amount you paid.")}">
                        ${_('Unenroll')}

                      % endif
                    % else:
                      % if not is_course_blocked:
                      <a href="#unenroll-modal" class="action action-unenroll" rel="leanModal" data-course-id="${course_overview.id}" data-course-number="${course_overview.number}" data-course-name="${course_overview.display_name_with_default}" data-dashboard-index="${dashboard_index}" data-cert-name-long="${cert_name_long}"
                         data-track-info="${_("Are you sure you want to unenroll from the verified %(cert_name_long)s track of %(course_name)s (%(course_number)s)?")}"
                         data-refund-info="${_("The refund deadline for this course has passed, so you will not receive a refund.")}">
                        ${_('Unenroll')}

                      % else:
                      <a class="action action-unenroll is-disabled" data-course-id="${course_overview.id}" data-course-number="${course_overview.number}" data-course-name="${course_overview.display_name_with_default}" data-dashboard-index="${dashboard_index}" data-cert-name-long="${cert_name_long}"
                         data-track-info="${_("Are you sure you want to unenroll from the verified %(cert_name_long)s track of %(course_name)s (%(course_number)s)?")}"
                         data-refund-info="${_("The refund deadline for this course has passed, so you will not receive a refund.")}">
                        ${_('Unenroll')}

                      % endif
                    % endif

                  % endif

                    % if show_email_settings:
                      % if not is_course_blocked:
                        ${_('Email Settings')}
                      % else:
                        ${_('Email Settings')}
                      % endif
                    % endif

      % if related_programs:

        ${_('Related Programs')}:

          % for program in related_programs:

            ${u'{name} {category}'.format(name=program['name'], category=program['category'])}

          % endfor

      % endif

      % if course_overview.may_certify() and cert_status:
        <%include file='_dashboard_certificate_information.html' args='cert_status=cert_status,course_overview=course_overview, enrollment=enrollment, reverify_link=reverify_link'/>
      % endif

      % if credit_status is not None:
        <%include file="_dashboard_credit_info.html" args="credit_status=credit_status"/>
      % endif

        % if verification_status.get('status') in [VERIFY_STATUS_NEED_TO_VERIFY, VERIFY_STATUS_SUBMITTED, VERIFY_STATUS_RESUBMITTED, VERIFY_STATUS_APPROVED, VERIFY_STATUS_NEED_TO_REVERIFY] and not is_course_blocked:

          % if verification_status['status'] == VERIFY_STATUS_NEED_TO_VERIFY:

              % if verification_status['days_until_deadline'] is not None:

${_('Verification not yet complete.')}

${ungettext(
                  'You only have {days} day left to verify for this course.',
                  'You only have {days} days left to verify for this course.',
                  verification_status['days_until_deadline']
                ).format(days=verification_status['days_until_deadline'])}

              % else:

${_('Almost there!')}

${_('You still need to verify for this course.')}

              % endif

              ${_('Verify Now')}

          % elif verification_status['status'] == VERIFY_STATUS_SUBMITTED:

${_('You have submitted your verification information.')}

${_('You will see a message on your dashboard when the verification process is complete (usually within 1-2 days).')}

          % elif verification_status['status'] == VERIFY_STATUS_RESUBMITTED:

${_('Your current verification will expire soon!')}

${_('You have submitted your reverification information. You will see a message on your dashboard when the verification process is complete (usually within 1-2 days).')}

          % elif verification_status['status'] == VERIFY_STATUS_APPROVED:

${_('You have successfully verified your ID with edX')}

            % if verification_status.get('verification_good_until') is not None:

${_('Your current verification is effective until {date}.').format(date=verification_status['verification_good_until'])}
            % endif
          % elif verification_status['status'] == VERIFY_STATUS_NEED_TO_REVERIFY:

${_('Your current verification will expire soon.')}

            ## Translators: start_link and end_link will be replaced with HTML tags;
            ## please do not translate these.

${Text(_('Your current verification will expire in {days} days. {start_link}Re-verify your identity now{end_link} using a webcam and a government-issued photo ID.')).format(
                start_link=HTML('').format(href=reverse('verify_student_reverify')),
                end_link=HTML(''),
                days=settings.VERIFY_STUDENT.get("EXPIRING_SOON_WINDOW")
              )}

          % endif

        % endif

        % if course_mode_info['show_upsell'] and not is_course_blocked:

                    ${_("Pursue a {cert_name_long} to highlight the knowledge and skills you gain in this course.").format(cert_name_long=cert_name_long)}

                    ${Text(_("It's official. It's easily shareable. "
                        "It's a proven motivator to complete the course. {line_break}"
                        "{link_start}Learn more about the verified {cert_name_long}{link_end}.")).format(
                          line_break=HTML('
'),
                          link_start=HTML('').format(
                            marketing_link('WHAT_IS_VERIFIED_CERT'),
                            enrollment.course_id
                          ),
                          link_end=HTML(''),
                          cert_name_long=cert_name_long
                        )}

                  % if use_ecommerce_payment_flow and course_mode_info['verified_sku']:

                  % else:

                  % endif

                      ${_("Upgrade to Verified")}
                         ${_(course_overview.display_name_with_default)}

        %endif

        % if course_program_info and course_program_info.get('category'):
          %for program_data in course_program_info.get('course_program_list', []):
            <%include file = "_dashboard_program_info.html" args="program_data=program_data, enrollment_mode=enrollment.mode, category=course_program_info['category']" />
          %endfor
        % endif

        % if is_course_blocked:

            ${Text(_("You can no longer access this course because payment has not yet been received. "
                "You can {contact_link_start}contact the account holder{contact_link_end} "
                "to request payment, or you can "
                "{unenroll_link_start}unenroll{unenroll_link_end} "
                "from this course")).format(
              contact_link_start=HTML('<button type="button">'),
              contact_link_end=HTML('</button>'),
              unenroll_link_start=HTML(
                ''
              ).format(
                course_id=course_overview.id,
                course_number=course_overview.number,
                course_name=course_overview.display_name_with_default,
              ),
              unenroll_link_end=HTML(''),
            )}

        %endif

        % if course_requirements:
        ## Multiple pre-requisite courses are not supported on frontend that's why we are pulling first element
        <% prc_target = reverse('about_course', args=[unicode(course_requirements['courses'][0]['key'])]) %>

            ${Text(_("You must successfully complete {link_start}{prc_display}{link_end} before you begin this course.")).format(
                link_start=HTML('').format(prc_target),
                link_end=HTML(''),
                prc_display=course_requirements['courses'][0]['display'],
              )}

        % endif

<%static:require_module_async module_name="js/dateutil_factory" class_name="DateUtilFactory">
    DateUtilFactory.transform(iterationKey=".localized-datetime");
</%static:require_module_async>


text:
export class AppConfig {

  public static API_BASE_URL = 'http://localhost:3000';

}

redpajama_set_name: RedPajamaGithub


text:
require 'rails_helper'

describe QueueListener do
  let(:client) { double }

  before do
    allow(ActionKitConnector::Client).to receive(:new) { client }
  end

  subject { QueueListener.new }

  describe "#perform" do
    describe 'update_pages' do
      before do
        allow(client).to receive(:update_donation_page)
        allow(client).to receive(:update_petition_page)
        CampaignRepository.set(234, "http://dummy-campaign")
      end

      let(:params) do
        {
          type: 'update_pages',
          petition_uri:  "/rest/v1/petitionpage/1234/",
          donation_uri:  "/rest/v1/donationpage/5678/",
          params: {
            tags: ["/rest/v1/tag/5678/"],
            campaign_id: 234
          }
        }
      end

      it 'calls update_donation_page on client' do
        expected_params = {
          tags: ["/rest/v1/tag/5678/"],
          id: '5678',
          multilingual_campaign: "http://dummy-campaign"
        }

        expect(client).to receive(:update_donation_page).with(expected_params)
        subject.perform(nil, params)
      end

      it 'calls update_petition_page on client' do
        expected_params = {
          tags: ["/rest/v1/tag/5678/"],
          id: '1234',
          multilingual_campaign: "http://dummy-campaign"
        }

        expect(client).to receive(:update_petition_page).with(expected_params)
        subject.perform(nil, params)
      end

      context 'missing resource URI' do
        context 'for just petition' do
          before :each do
            params[:petition_uri] = nil
            subject.perform(nil, params)
          end

          it 'does not call update_petition_page on client' do
            expect(client).not_to have_received(:update_petition_page)
          end

          it 'calls update_donation_page on client' do
            expect(client).to have_received(:update_donation_page)
          end
        end

        context 'for just donation' do
          before :each do
            params[:donation_uri] = nil
            subject.perform(nil, params)
          end

          it 'calls update_petition_page on client' do
            expect(client).to have_received(:update_petition_page)
          end

          it 'does not call update_donation_page on client' do
            expect(client).not_to have_received(:update_donation_page)
          end
        end

        context 'for both' do
          before do
            params[:donation_uri] = nil
            params[:petition_uri] = nil
          end

          it 'does not call update_petition_page or update_donation_page on client' do
            expect{ subject.perform(nil, params) }.to raise_error(ArgumentError)
          end
        end
      end
    end

    describe 'subscribe member' do
      let(:internal_params) do
        {
          email: "guybrush_threepwood@example.com",
          name: "Guybrush Threepwood",
          country: "United Kingdom",
          postal: "12345"
        }
      end
      let(:params) { { type: 'subscribe_member', params: internal_params } }
      let(:unset_msg) { "Your ActionKit page for subscriptions from the home page has not been set for locales '' or 'EN'" }
      let(:api_fail_msg) { "Member subscription failed with PARSED_ERRORS!" }
      let(:res) { double(success?: true, parsed_response: {'errors' => 'PARSED_ERRORS' }) }

      before :each do
        allow(client).to receive(:create_action){ res }
      end

      it 'raises an error when there is no locale or AK_SUBSCRIPTION_PAGE_EN' do
        allow(ENV).to receive(:[]).with("AK_SUBSCRIPTION_PAGE_EN"){ nil }
        allow(ENV).to receive(:[]).with("AK_SUBSCRIPTION_PAGE_"){ nil }
        expect{ subject.perform('subscribe_member', params) }.to raise_error(unset_msg)
      end

      it "uses the English subscription page if no locale given" do
        allow(ENV).to receive(:[]).with("AK_SUBSCRIPTION_PAGE_EN"){ 'registration' }
        allow(ENV).to receive(:[]).with("AK_SUBSCRIPTION_PAGE_"){ nil }
        expect{ subject.perform('subscribe_member', params) }.not_to raise_error
        expect(client).to have_received(:create_action).with(internal_params.merge(page: 'registration'))
      end

      it "uses the English subscription page if current locale doesn't have one" do
        allow(ENV).to receive(:[]).with("AK_SUBSCRIPTION_PAGE_EN"){ "registration" }
        allow(ENV).to receive(:[]).with("AK_SUBSCRIPTION_PAGE_DE"){ nil }
        internal_params[:locale] = 'DE'
        expect{ subject.perform('subscribe_member', params) }.not_to raise_error
        expect(client).to have_received(:create_action).with(internal_params.merge(page: 'registration'))
      end

      it "uses the right subscription page if current locale has one" do
        allow(ENV).to receive(:[]).with("AK_SUBSCRIPTION_PAGE_DE"){ "registration_german" }
        internal_params[:locale] = 'de'
        expect{ subject.perform('subscribe_member', params) }.not_to raise_error
        expect(client).to have_received(:create_action).with(internal_params.merge(page: 'registration_german'))
      end

      it 'raises an error when the API call is not successful' do
        allow(ENV).to receive(:[]).with("AK_SUBSCRIPTION_PAGE_EN"){ 'registration' }
        allow(res).to receive(:success?){ false }
        internal_params[:locale] = 'EN'
        expect{ subject.perform('subscribe_member', params) }.to raise_error(api_fail_msg)
      end
    end

    describe 'creating a US action with an invalid zip code' do
      let(:internal_params) do
        {
            page:         "foo-bar",
            name:         "Pablo José Francisco de María",
            postal:       "abc123",
            address1:     "Mill st 123",
            address2:     "apt 1043",
            city:         "London",
            country:      "United States",
            email:        "test@example.com",
            source:       'FB',
            akid:         '3.4234.fsdf'
        }
      end

      let(:action) { Action.create(form_data: {}) }
      let(:params) { { type: 'action', params: internal_params, meta: { action_id: action.id, member_id: 1} } }
      let(:res) { double(success?: true, parsed_response: {'errors' => 'PARSED_ERRORS' }, body: "{}") }

      before do
        allow(client).to receive(:create_action){ res }
        allow(res).to receive(:[]).with('resource_uri'){'resource_uri'}
        allow(ENV).to receive(:[]).and_call_original
        allow(ENV).to receive(:[]).with("BYPASS_ZIP_VALIDATION"){ 'true' }
      end

      context 'Environment variables are correctly set' do
        it 'falls back to a default zip code' do
          allow(ENV).to receive(:[]).with("DEFAULT_US_ZIP"){ '20001' }
          expect{ subject.perform('action', params) }.not_to raise_error
          expect(client).to have_received(:create_action).with(internal_params)
        end
      end

      context 'With default us zip value missing' do
        it 'complains about missing configuration' do
          expect{ subject.perform('action', params) }.to raise_error /Your default US zip code has not been set/
        end
      end

    end
  end
end


text:
<?php

namespace Psalm\Tests;

use Psalm\Config;
use Psalm\Config\ProjectFileFilter;
use Psalm\Internal\IncludeCollector;
use SimpleXMLElement;

use function getcwd;

use const DIRECTORY_SEPARATOR;

class TestConfig extends Config
{
    /** @var ProjectFileFilter|null */
    private static $cached_project_files = null;

    public function __construct()
    {
        parent::__construct();

        foreach ($this->php_extensions as $ext => $_enabled) {
            $this->php_extensions[$ext] = true;
        }

        $this->throw_exception = true;
        $this->use_docblock_types = true;
        $this->level = 1;
        $this->cache_directory = null;

        $this->base_dir = getcwd() . DIRECTORY_SEPARATOR;

        if (!self::$cached_project_files) {
            self::$cached_project_files = ProjectFileFilter::loadFromXMLElement(
                new SimpleXMLElement($this->getContents()),
                $this->base_dir,
                true
            );
        }

        $this->project_files = self::$cached_project_files;
        $this->setIncludeCollector(new IncludeCollector());

        $this->collectPredefinedConstants();
        $this->collectPredefinedFunctions();
    }

    protected function getContents(): string
    {
        return '<?xml version="1.0"?>
                <projectFiles>
                    <directory name="src" />
                    <file name="tests/somefile.php" />
                    <ignoreFiles>
                        <directory name="src/Psalm/Internal/Stubs" />
                    </ignoreFiles>
                </projectFiles>';
    }

    /**
     * @return false
     */
    public function getComposerFilePathForClassLike(string $fq_classlike_name): bool
    {
        return false;
    }

    public function getProjectDirectories(): array
    {
        return [];
    }
}


text:
class CListFrame : public CFrameWnd
{
  DECLARE_DYNCREATE(CListFrame)
protected:
  CListFrame();           // protected constructor used by dynamic creation

// Attributes
public:
  static int client_width;
  CStatusBar listStatus;
  CToolBar fileBar;

// Operations
public:

// Overrides
  // ClassWizard generated virtual function overrides
  //{{AFX_VIRTUAL(CListFrame)
  protected:
  virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
  //}}AFX_VIRTUAL
  virtual void OnUpdateFrameTitle(BOOL);

// Implementation
protected:
  virtual ~CListFrame();
  CToolBar listTools;

  // Generated message map functions
  //{{AFX_MSG(CListFrame)
  afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
  afx_msg void OnViewTbDLPRtree();
  afx_msg void OnUpdateViewTbDLPRtree(CCmdUI* pCmdUI);
  //}}AFX_MSG
  DECLARE_MESSAGE_MAP()
};

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_LISTFRAME_H__BF032481_C5D0_11D3_8FA0_00A0C9C7BE10__INCLUDED_)


text:
function init(){

	//load listeners
	ContentMessager.receiveMessages();

	//check prepare page
	loadCss();
	loadJquery()
	loadAnnotations();

}
init();


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ProtocolHandler (JxBrowser 6.12 API)</title>
<meta name="date" content="2017-01-31">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.teamdev.jxbrowser.chromium

Interface ProtocolHandler

public interface ProtocolHandler

Interface for handing URL requests and responses.

Since:

6.11

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

URLResponse
onRequest(URLRequest request)

This method is invoked for each URL request whose protocol equals to
 the protocol associated with the current ProtocolHandler instance.

Method Detail

onRequest

URLResponse onRequest(URLRequest request)

This method is invoked for each URL request whose protocol equals to
 the protocol associated with the current ProtocolHandler instance.

 If the method throws an exception, it will be treated as if the method
 returns null - Chromium engine will handle request.

Parameters:

request - provides information about URL request.

Returns:

URLResponse instance if the request is handled, or
 null if the given request must be handled by Chromium engine.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package pl.com.softproject.utils.freshmail.dto.response;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import pl.com.softproject.utils.freshmail.databind.deserializer.DateDeserializer;
import pl.com.softproject.utils.freshmail.databind.serializer.DateSerializer;

import java.io.Serializable;
import java.util.Date;

/**
 * Class SubscribersList.
 *
 * @author Marcin Jasiński {@literal <mkjasinski@gmail.com>}
 */
public class SubscribersList implements Serializable {

    @JsonProperty("subscriberListHash")
    private String hash;

    private String name;

    private String description;

    @JsonProperty("creation_date")
    @JsonSerialize(using = DateSerializer.class)
    @JsonDeserialize(using = DateDeserializer.class)
    private Date creationDate;

    @JsonProperty("subscribers_number")
    private int subscribersCount;

    public SubscribersList() {
    }

    public String getHash() {
        return hash;
    }

    public void setHash(String hash) {
        this.hash = hash;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public int getSubscribersCount() {
        return subscribersCount;
    }

    public void setSubscribersCount(int subscribersCount) {
        this.subscribersCount = subscribersCount;
    }

    @Override
    public String toString() {
        return "SubscribersList{" +
               "hash='" + hash + '\'' +
               ", name='" + name + '\'' +
               ", description='" + description + '\'' +
               ", creationDate=" + creationDate +
               ", subscribersCount=" + subscribersCount +
               '}';
    }
}


text:
<?php namespace Scrape;

/**
 * A basic web scraper class
 * @author Markus Östberg <markusos@kth.se>
 */

use \DOMXPath;
use \DOMDocument;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;

/**
 * Class Scrape
 * @package Scrape
 */
class Scrape
{
    /**
     * @var Client
     */
    private $webClient;
    /**
     * @var DOMDocument
     */
    private $dom;

    /**
     * Init scraper to scrape $site
     * @param string $site Site to scrape
     * @param int $timeout seconds before request times out. Default 2 seconds.
     */
    public function __construct($site, $timeout = 2)
    {
        $this->webClient = new Client(['base_uri' => $site, 'timeout' => $timeout]);
    }

    /**
     * Load sub page to site.
     * E.g, '/' loads the site root page
     * @param string $page Page to load
     * @return $this
     */
    public function load($page) {

        try {
            $response = $this->webClient->get($page);
        } catch(ConnectException $e) {
            throw new \RuntimeException($e->getHandlerContext()['error']);
        }

        $html = $response->getBody();

        $this->dom = new DOMDocument;

        // Ignore errors caused by unsupported HTML5 tags
        libxml_use_internal_errors(true);
        $this->dom->loadHTML($html);
        libxml_clear_errors();

        return $this;
    }

    /**
     * Get first nodes matching xpath query below parent node in DOM tree
     * @param $xpath string selector to query the DOM
     * @param $parent \DOMNode to use as query root node
     * @return \DOMNode
     */
    public function getNode($xpath, $parent=null) {
        $nodes = $this->getNodes($xpath, $parent);

        if ($nodes->length === 0) {
            throw new \RuntimeException("No matching node found");
        }

        return $nodes[0];
    }

    /**
     * Get all nodes matching xpath query below parent node in DOM tree
     * @param $xpath string selector to query the DOM
     * @param $parent \DOMNode to use as query root node
     * @return \DOMNodeList
     */
    public function getNodes($xpath, $parent=null) {
        $DomXpath = new DOMXPath($this->dom);
        $nodes = $DomXpath->query($xpath, $parent);
        return $nodes;
    }
}


text:
import { getObjectType } from '../getObjectType';

describe('getObjectType', () => {
  test('returns the type of a string', () => {
    expect(getObjectType('string')).toEqual('String');
  });

  test('returns the type of a number', () => {
    expect(getObjectType(2)).toEqual('Number');
  });

  test('returns the type of a boolean', () => {
    expect(getObjectType(true)).toEqual('Boolean');
    expect(getObjectType(false)).toEqual('Boolean');
  });

  test('returns the type of an object', () => {
    expect(getObjectType({})).toEqual('Object');
  });

  test('returns the type of an array', () => {
    expect(getObjectType([])).toEqual('Array');
  });

  test('returns the type of a date', () => {
    expect(getObjectType(new Date())).toEqual('Date');
  });

  test('returns the type of a function', () => {
    expect(getObjectType(function () {})).toEqual('Function');
  });

  test('returns the type of undefined', () => {
    expect(getObjectType(undefined)).toEqual('Undefined');
  });

  test('returns the type of null', () => {
    expect(getObjectType(null)).toEqual('Null');
  });
});


text:
package com.google.cloud.pubsub.spi.v1;

import com.google.api.gax.testing.MockGrpcService;
import com.google.protobuf.GeneratedMessageV3;
import io.grpc.ServerServiceDefinition;
import java.util.List;

@javax.annotation.Generated("by GAPIC")
public class MockSubscriber implements MockGrpcService {
  private final MockSubscriberImpl serviceImpl;

  public MockSubscriber() {
    serviceImpl = new MockSubscriberImpl();
  }

  @Override
  public List<GeneratedMessageV3> getRequests() {
    return serviceImpl.getRequests();
  }

  @Override
  public void setResponses(List<GeneratedMessageV3> responses) {
    serviceImpl.setResponses(responses);
  }

  @Override
  public ServerServiceDefinition getServiceDefinition() {
    return serviceImpl.bindService();
  }

  @Override
  public void reset() {
    serviceImpl.reset();
  }
}


text:
package lib

import (
	"bytes"
	"errors"
	"fmt"
	"net"
	"time"
)

type IPAddr struct {
	IP    net.IP
	IPNet *net.IPNet
}

func NewIPAddr(addr string) (*IPAddr, error) {
	a := new(IPAddr)
	err := a.UnmarshalText([]byte(addr))
	if err != nil {
		return nil, err
	}
	return a, nil
}

func (a IPAddr) String() string {
	b, _ := a.MarshalText()
	return string(b)
}

func (a IPAddr) MarshalText() (text []byte, err error) {
	text, err = a.IP.MarshalText()
	if err != nil {
		return nil, err
	}
	if a.IPNet != nil {
		ones, _ := a.IPNet.Mask.Size()
		text = append(text, []byte(fmt.Sprintf("/%d", ones))...)
	}
	return text, nil
}

func (a *IPAddr) UnmarshalText(text []byte) error {
	if bytes.Index(text, []byte{'/'}) == -1 {
		ip := net.ParseIP(string(text))
		if ip == nil {
			return errors.New("Invalid IP address text was passed")
		}
		a.IP = ip
	} else {
		ip, ipnet, err := net.ParseCIDR(string(text))
		if err != nil {
			return err
		}
		a.IP = ip
		a.IPNet = ipnet
	}
	return nil
}

type IPAddrList []IPAddr

func (as IPAddrList) String() string {
	b, _ := as.MarshalText()
	return string(b)
}

func (as IPAddrList) MarshalText() (text []byte, err error) {
	var tmp [][]byte
	for _, a := range as {
		txt, err := a.MarshalText()
		if err != nil {
			return nil, err
		}
		tmp = append(tmp, txt)
	}
	return bytes.Join(tmp, []byte{' '}), nil
}

type CustomNs int

func (ns CustomNs) MarshalText() (text []byte, err error) {
	if ns == CustomNs(0) {
		return []byte{'0'}, nil
	}
	return []byte{'1'}, nil
}

type Timestamp struct {
	time.Time
}

const (
	DataTimestampFormat string = "2006-01-02 15:04:05.000000-0700"
)

var ArgTimestampFormats []string = []string{"2006-01-02 15:04 MST", "2006-01-02 15:04 -0700"}

func ParseArgTimestampFormat(s string) (time.Time, error) {
	var err error
	var tm time.Time
	for _, e := range ArgTimestampFormats {
		tm, err = time.Parse(e, s)
		if err == nil {
			return tm, nil
		}
	}
	return time.Time{}, errors.New("the string didn't match any timestamp format")
}

func ArgTimestampFormatStr() (s string) {
	if len(ArgTimestampFormats) == 0 {
		return s
	}
	s = "'" + ArgTimestampFormats[0] + "'"
	last := len(ArgTimestampFormats) - 2
	for i, e := range ArgTimestampFormats[1:] {
		if i == last {
			s += fmt.Sprintf(` or '%s'`, e)
		} else {
			s += fmt.Sprintf(`, '%s'`, e)
		}
	}
	return s
}

func (t Timestamp) String() string {
	b, _ := t.MarshalText()
	return string(b)
}

func (t Timestamp) MarshalText() ([]byte, error) {
	return []byte(t.Format(DataTimestampFormat)), nil
}

func parseDateTimestampFormat(text []byte) (time.Time, error) {
	var sep byte
	if bytes.IndexRune(text, '+') != -1 {
		sep = '+'
	} else if bytes.IndexRune(text, '-') != 1 {
		sep = '-'
	} else {
		return time.Time{}, errors.New("Invalid timestamp")
	}
	dtzone := bytes.Split(text, []byte{sep})
	if len(dtzone) != 2 {
		return time.Time{}, errors.New("Invalid timestamp")
	}

	var norm []byte
	norm = append(norm, dtzone[0]...)

	n := 6
	if bytes.IndexRune(dtzone[0], '.') != -1 {
		dtms := bytes.Split(dtzone[0], []byte{'.'})
		if len(dtms) != 2 {
			return time.Time{}, errors.New("Invalid timestamp")
		}
		n -= len(dtms[1])
	} else {
		norm = append(norm, '.')
	}
	norm = append(norm, bytes.Repeat([]byte{'0'}, n)...)
	norm = append(norm, sep)

	n = 4
	n -= len(dtzone[1])
	norm = append(norm, dtzone[1]...)
	norm = append(norm, bytes.Repeat([]byte{'0'}, n)...)

	return time.Parse(DataTimestampFormat, string(norm))
}

func (t *Timestamp) UnmarshalText(text []byte) error {
	if tm, err := parseDateTimestampFormat(text); err == nil {
		*t = Timestamp{tm}
		return nil
	}
	if tm, err := time.Parse(time.UnixDate, string(text)); err == nil {
		*t = Timestamp{tm}
		return nil
	}
	return errors.New("Can't unmarshal timestamp: " + string(text))
}


text: triggered when a firmware version is received, the major version is passed as an argument


text:
<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Orm\Zed\Dataset\Persistence;

use Spryker\Zed\Dataset\Persistence\Propel\AbstractSpyDatasetColumnQuery as BaseSpyDatasetColumnQuery;

/**
 * Skeleton subclass for performing query and update operations on the 'spy_dataset_column' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements. This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 */
class SpyDatasetColumnQuery extends BaseSpyDatasetColumnQuery
{
}


text:
'use strict';

var compile_juttle = require('./specs/juttle-test-utils').compile_juttle;
var expect = require('chai').expect;

describe('Juttle source validation', function() {
    var did_not_invalidate_err = new Error('Did not detect invalid graph!');

    it('counts a single source', function() {
        return compile_juttle({program: 'emit | view result'})
            .then(function(program) {
                var sources = program.get_sources();
                expect(sources.length).to.equal(1);
            });
    });

    it('counts multiple, parallel sources', function() {
        return compile_juttle({program: '( emit | view result; emit | view result )'})
            .then(function(program) {
                var sources = program.get_sources();
                expect(sources.length).to.equal(2);
            });
    });

    it('detects invalid sources in series', function() {
        return compile_juttle({program: 'emit | emit | view result'})
            .then(function() {
                throw did_not_invalidate_err;
            })
            .catch(function(e) {
                expect(e.message).to.match(/emit may not come before a source/);
            });
    });

    it('detects source that is not a head', function() {
        return compile_juttle({program: '( emit | view result1; put a=1 | emit | view result1 )'})
            .then(function() {
                throw did_not_invalidate_err;
            })
            .catch(function(e) {
                expect(e.message).to.match(/put may not come before a source/);
            });
    });

    it('detects flowgraph that doesn\'t begin with a source', function() {
        return compile_juttle({program: 'put a=1 | emit | view result'})
            .then(function() {
                throw did_not_invalidate_err;
            })
            .catch(function(e) {
                expect(e.message).to.match(/put may not come before a source/);
            });
    });
});


text:
# Conversion to .NET 6.0 TODO

* Translators (handle properties)
* Default includes, InternalOnly, SubDefault includes, Conditional includes?
* JObject expansion
* web api interface
* Custom Serializer interface?
* ActionResult handler
* Tests
* Pre and Post actions
* DEpendency injection in GetSourceValue
* Type Configuration with a dynamic action rather than a static Type so we can do something like 'all versions of MyClass<T>' or 'Everything that implements IMyPublicInterface'


text:
/**
 * Created by redrock on 2015/1/31.
 */
require.config({
    baseUrl : 'public/js/lib',
    shim : {
        'underscore' : {
            exports : '_'
        },
        bdshare : ['share']
    },
    paths : {
        jquery : 'jquery',
        port : '../template/microm_sub/port',
        microm_play : '../widget/microm_play/microm_play',
        microm_comment : '../widget/microm_comment/microm_comment',
        go_top : '../widget/go_top/go_top',
        login_box : '../widget/login_box/login_box',
        microm_intro : '../widget/microm_intro/microm_intro',
        bdshare : '../widget/bdshare/bdshare',
        share : '../widget/bdshare/share',
        comment : '../widget/comment/comment',
        footer : '../widget/footer/footer'
    }
});

//加载依赖项
define(['microm_play','microm_comment','go_top', 'login_box', 'microm_intro',  'share','bdshare', 'comment', 'footer'], function(){
    console.log('microm_sub init');
});


text:
class Spree::SamportPayment < ActiveRecord::Base
  has_many :payments, :as => :source

  attr_accessible :samport_key, :card_type

  def actions
  end

  def get_samport_key(payment_method, order)
    logger.debug "\n----------- SamportPayment.get_samport_key -----------\n"
    terminal_id = payment_method.preferred(:terminal_id)
    direct_capture = payment_method.preferred(:direct_capture)
    transaction_type = payment_method.preferred(:transaction_type)
    iso_language_code = payment_method.preferred(:iso_language_code)
    iso_currency = payment_method.preferred(:iso_currency)
    @request_input = {}
    data = []
    payment_amount = 0
    # Add products
    order.line_items.each do |item|
      logger.debug "\n----------- Item: #{item.quantity}, #{item.product.sku}, #{item.product.name}, #{item.product.price} -----------\n"
      # <ArtNo>:<Description>:<Quantity>:<Price in the lowest value (ören, cent etc.)>
      price = item.product.price * 100
      data << clean_string("#{item.product.sku}:#{item.product.name}:#{item.quantity}:#{price.to_i}")
      payment_amount += item.product.price
    end

    # Shipping cost
    #shipping_cost = order.ship_total * 100
    #shipping_cost = (1 + Spree::TaxRate.default) * shipping_cost if Spree::Config[:shipment_inc_vat]
    #
    #data << clean_string("1:#{order.shipping_method.name}:1:#{shipping_cost.to_i}")

    order.adjustments.eligible.each do |adjustment|
      next if (adjustment.originator_type == 'Spree::TaxRate') or (adjustment.amount === 0)

      amount = 100 * adjustment.amount
      data << clean_string("1:#{adjustment.label}:1:#{amount.to_i}")
      payment_amount += adjustment.amount
    end

    if order.tax_totals.present?
      order.tax_totals.keys.each do |key|
        amount = 100 * order.tax_totals[key]
        data << clean_string("1:#{key}:1:#{amount.to_i}")
        payment_amount += order.tax_totals[key]
      end
    end

    order.payments.first.update_attribute(:amount, payment_amount)

    data = data.join(',')

    logger.debug "\n\n\n#{data}\n\n\n"

    @domain = "http://unix.telluspay.com/Add/?"
    @querystring = "TP01=#{direct_capture}&TP700=#{terminal_id}&TP701=#{order.number}&TP740=#{data}&TP901=#{transaction_type}&TP491=#{iso_language_code}&TP490=#{iso_currency}&TP801=#{clean_string(order.email)}&TP8021=#{clean_string(order.bill_address.firstname)}&TP8022=#{clean_string(order.bill_address.lastname)}&TP803=#{clean_string(order.bill_address.address1)}&TP804=#{clean_string(order.bill_address.zipcode)}&TP805=#{clean_string(order.bill_address.city)}&TP806=#{order.bill_address.country.iso}&TP8071=#{order.user.id}&TP900=#{self.client_ip}"
    logger.debug "\n----------- SamportPayment.create url -----------\n"
    logger.debug "\n----------- #{@domain}#{@querystring} -----------\n"

    require 'uri'
    require 'open-uri'
    response = open("#{@domain}#{@querystring}").read
    logger.debug "\n----------- #{response} -----------\n"
    response
  end

  private
  def clean_string(string)
    URI.encode(string).sub('&',I18n.t(:and)).sub(',','')
  end

  def gateway_error(text)
    msg = "#{I18n.t(:gateway_error)} ... #{text}"
    logger.error(msg)
    raise Spree::Core::GatewayError.new(msg)
  end
end


text:
extern "C" {
  #include <git2.h>
  {% each cDependencies as dependency %}
    #include <{{ dependency }}>
  {% endeach %}
}

#include <iostream>
#include "../include/lock_master.h"
#include "../include/functions/copy.h"
#include "../include/{{ filename }}.h"
#include "../include/functions/sleep_for_ms.h"

{% each dependencies as dependency %}
  #include "{{ dependency }}"
{% endeach %}

using namespace v8;
using namespace node;
using namespace std;

// generated from struct_content.cc
{{ cppClassName }}::{{ cppClassName }}() {
  {% if ignoreInit == true %}
  {{ cType }}* wrappedValue = new {{ cType }};
  {% else %}
  {{ cType }} wrappedValue = {{ cType|upper }}_INIT;
  {% endif %}
  this->raw = ({{ cType }}*) malloc(sizeof({{ cType }}));
  memcpy(this->raw, &wrappedValue, sizeof({{ cType }}));

  this->ConstructFields();
  this->selfFreeing = true;
}

{{ cppClassName }}::{{ cppClassName }}({{ cType }}* raw, bool selfFreeing) {
  this->raw = raw;
  this->ConstructFields();
  this->selfFreeing = selfFreeing;
}

{{ cppClassName }}::~{{ cppClassName }}() {
  {% each fields|fieldsInfo as field %}
    {% if not field.ignore %}
      {% if not field.isEnum %}
        {% if field.isCallbackFunction %}
  if (this->{{ field.name }} != NULL) {
    delete this->{{ field.name }};
    this->raw->{{ fields|payloadFor field.name }} = NULL;
  }
        {% endif %}
      {% endif %}
    {% endif %}
  {% endeach %}

  if (this->selfFreeing) {
    free(this->raw);
  }
}

void {{ cppClassName }}::ConstructFields() {
  {% each fields|fieldsInfo as field %}
    {% if not field.ignore %}
      {% if not field.isEnum %}
        {% if field.hasConstructor |or field.isLibgitType %}
          Local<Object> {{ field.name }}Temp = {{ field.cppClassName }}::New(
            &this->raw->{{ field.name }},
            false
          )->ToObject();
          this->{{ field.name }}.Reset({{ field.name }}Temp);

        {% elsif field.isCallbackFunction %}

          // Set the static method call and set the payload for this function to be
          // the current instance
          this->raw->{{ field.name }} = NULL;
          this->raw->{{ fields|payloadFor field.name }} = (void *)this;
          this->{{ field.name }} = NULL;
        {% elsif field.payloadFor %}

          Local<Value> {{ field.name }} = Nan::Undefined();
          this->{{ field.name }}.Reset({{ field.name }});
        {% endif %}
      {% endif %}
    {% endif %}
  {% endeach %}
}

void {{ cppClassName }}::InitializeComponent(Local<v8::Object> target) {
  Nan::HandleScope scope;

  Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(JSNewFunction);

  tpl->InstanceTemplate()->SetInternalFieldCount(1);
  tpl->SetClassName(Nan::New("{{ jsClassName }}").ToLocalChecked());

  {% each fields as field %}
    {% if not field.ignore %}
    {% if not field | isPayload %}
      Nan::SetAccessor(tpl->InstanceTemplate(), Nan::New("{{ field.jsFunctionName }}").ToLocalChecked(), Get{{ field.cppFunctionName}}, Set{{ field.cppFunctionName}});
    {% endif %}
    {% endif %}
  {% endeach %}

  Local<Function> _constructor_template = Nan::GetFunction(tpl).ToLocalChecked();
  constructor_template.Reset(_constructor_template);
  Nan::Set(target, Nan::New("{{ jsClassName }}").ToLocalChecked(), _constructor_template);
}

NAN_METHOD({{ cppClassName }}::JSNewFunction) {
  {{ cppClassName }}* instance;

  if (info.Length() == 0 || !info[0]->IsExternal()) {
    instance = new {{ cppClassName }}();
  }
  else {
    instance = new {{ cppClassName }}(static_cast<{{ cType }}*>(Local<External>::Cast(info[0])->Value()), Nan::To<bool>(info[1]).FromJust());
  }

  instance->Wrap(info.This());

  info.GetReturnValue().Set(info.This());
}

Local<v8::Value> {{ cppClassName }}::New(void* raw, bool selfFreeing) {
  Nan::EscapableHandleScope scope;

  Local<v8::Value> argv[2] = { Nan::New<External>((void *)raw), Nan::New<Boolean>(selfFreeing) };
  return scope.Escape(Nan::NewInstance(Nan::New({{ cppClassName }}::constructor_template), 2, argv).ToLocalChecked());
}

{{ cType }} *{{ cppClassName }}::GetValue() {
  return this->raw;
}

{{ cType }} **{{ cppClassName }}::GetRefValue() {
  return this->raw == NULL ? NULL : &this->raw;
}

void {{ cppClassName }}::ClearValue() {
  this->raw = NULL;
}

{% partial fieldAccessors . %}

Nan::Persistent<Function> {{ cppClassName }}::constructor_template;


text:
<?php

$final =[];
function query($url) {
	// setup curl options
	$options = array(
		CURLOPT_URL => $url,
		CURLOPT_HEADER => false,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_RETURNTRANSFER => true
		);

    // perform request
	$cUrl = curl_init();
	curl_setopt_array( $cUrl, $options );
	$response = curl_exec( $cUrl );
	curl_close( $cUrl );

    // decode the response into an array
	$decoded = json_decode( $response, true );

	return $decoded;
}
// if ($_GET['link']) {
if ($_SERVER['REQUEST_URI']) {

	// $route = $_GET['link'];
	$route = $_SERVER['REQUEST_URI'];
 // echo $route;

	$singleContent ='/dist/singleContent/';
	$singleEvent ='/dist/singleEvent/';
	$profile ='/dist/profile/';
// echo $route;
	if (substr($route, 0, strlen($singleContent)) === $singleContent) {
		// echo "content";
		$contentUrl = 'https://campusbox.org/dist/api/public/content/';
		$contentId = substr($route, 20);

		$finalUrl = $contentUrl . $contentId;
		$decoded = query($finalUrl);
		// foreach ($decoded['data']['Items']['data'][0] as $value) {
		// 	if(){

		// 	}
		// }
		$final["all"] =$decoded['data'];
		$final["title"] =$decoded['data']['title'];
		$final["description"] =$decoded['data']['Items']['data'][0]['description'];
		$final['image'] =$decoded['data']['created']['by']['image'];
	}

	elseif (substr($route, 0, strlen($profile)) === $profile) {
		// echo "profile";
		$contentUrl = 'https://campusbox.org/dist/api/public/student/';
		$contentId = substr($route, 14);
		$finalUrl = $contentUrl . $contentId;
		// echo $finalUrl;
		$decoded = query($finalUrl);
		// print_r($decoded);
		$final["all"] =$decoded['data'];

		$final["title"] =$decoded['data']['name'];
		$final["description"] =$decoded['data']['subtitle'];
		$final['image'] =$decoded['data']['photo'];
	}

	elseif (substr($route, 0, strlen($singleEvent)) === $singleEvent) {
	// elseif (false){
		// echo "event";
		$contentUrl = 'https://campusbox.org/dist/api/public/event/';
		$contentId = substr($route, 18);
		$finalUrl = $contentUrl . $contentId;
		// echo $finalUrl;
		$decoded = query($finalUrl);
		//print_r ($decoded);
		$final["all"] =$decoded['data'];

		$final["title"] =$decoded['data'][0]['title'];
		$final["description"] =$decoded['data'][0]['subtitle'];
		$final['image'] =$decoded['data'][0]['image'];

	}
	$final["description"]= substr($final["description"],20);
?>
	<title><?php print_r($final['title']) ?></title>
	<!-- <meta name="description" content="<?php print_r($final['description']) ?>"> </meta> -->
	<meta name="image" content="<?php print_r($final['image']) ?>"> </meta>
	<meta property="og:title" content="<?php print_r($final["title"]); ?>" />
	<!-- <meta property="og:description" content="<?php print_r($final["description"]); ?>" /> -->
	<meta property="og:image" content="<?php print_r($final["image"]); ?>" />
	<meta property="og:site_name" content="campusbox.org" />

	<meta property="fb:app_id" content="1250377088376164" />
 	<meta property="og:type"   content="website" />
<?php }
?>


text:
#include <errno.h>
#include <stdio.h>

#include "sol-log.h"
#include "sol-arena.h"
#include "sol-util-internal.h"

/* TODO: check if it's worthwhile to implement this as a single
 * growing buffer. */

struct sol_arena {
    struct sol_ptr_vector str_vector;
};

SOL_API struct sol_arena *
sol_arena_new(void)
{
    struct sol_arena *arena;

    arena = calloc(1, sizeof(struct sol_arena));
    SOL_NULL_CHECK(arena, NULL);

    sol_ptr_vector_init(&arena->str_vector);
    return arena;
}

SOL_API void
sol_arena_del(struct sol_arena *arena)
{
    char *s;
    uint16_t i;

    SOL_NULL_CHECK(arena);

    SOL_PTR_VECTOR_FOREACH_IDX (&arena->str_vector, s, i)
        free(s);

    sol_ptr_vector_clear(&arena->str_vector);
    free(arena);
}

SOL_API int
sol_arena_slice_dup_str_n(struct sol_arena *arena, struct sol_str_slice *dst, const char *str, size_t n)
{
    struct sol_str_slice slice;
    int r;

    SOL_NULL_CHECK(arena, -EINVAL);
    SOL_NULL_CHECK(str, -EINVAL);
    SOL_INT_CHECK(n, <= 0, -EINVAL);

    slice.data = strndup(str, n);
    SOL_NULL_CHECK(slice.data, -errno);

    slice.len = n;

    r = sol_ptr_vector_append(&arena->str_vector, (char *)slice.data);
    if (r < 0) {
        free((char *)slice.data);
        return r;
    }

    *dst = slice;
    return 0;
}

SOL_API int
sol_arena_slice_dup_str(struct sol_arena *arena, struct sol_str_slice *dst, const char *str)
{
    SOL_NULL_CHECK(str, -EINVAL);
    return sol_arena_slice_dup_str_n(arena, dst, str, strlen(str));
}

SOL_API int
sol_arena_slice_dup(struct sol_arena *arena, struct sol_str_slice *dst, struct sol_str_slice slice)
{
    return sol_arena_slice_dup_str_n(arena, dst, slice.data, slice.len);
}

SOL_API int
sol_arena_slice_sprintf(struct sol_arena *arena, struct sol_str_slice *dst, const char *fmt, ...)
{
    va_list ap;
    char *str;
    int r;

    va_start(ap, fmt);
    r = vasprintf(&str, fmt, ap);
    va_end(ap);
    SOL_INT_CHECK(r, < 0, r);

    dst->data = str;
    dst->len = r;

    r = sol_ptr_vector_append(&arena->str_vector, str);
    if (r < 0) {
        free(str);
        return r;
    }

    return 0;
}

SOL_API char *
sol_arena_strdup(struct sol_arena *arena, const char *str)
{
    SOL_NULL_CHECK(str, NULL);
    return sol_arena_strndup(arena, str, strlen(str));
}

SOL_API char *
sol_arena_strndup(struct sol_arena *arena, const char *str, size_t n)
{
    char *result;
    int r;

    SOL_NULL_CHECK(arena, NULL);
    SOL_NULL_CHECK(str, NULL);
    SOL_INT_CHECK(n, <= 0, NULL);

    result = strndup(str, n);
    SOL_NULL_CHECK(result, NULL);

    r = sol_ptr_vector_append(&arena->str_vector, result);
    if (r < 0) {
        free(result);
        return NULL;
    }

    return result;
}

SOL_API char *
sol_arena_strdup_slice(struct sol_arena *arena, const struct sol_str_slice slice)
{
    return sol_arena_strndup(arena, slice.data, slice.len);
}


text:
package com.fixedorgo.neuron;

/**
 * Interface for fuzzy Membership Function. Determines an membership degree based
 * on an input signal value.
 *
 * @author Timur Zagorsky
 * @since 0.1
 */
public interface MembershipFunction {

    /**
     * Returns membership degree of applying this function to {@code x}.
     * @param x represents input signal value
     * @return membership degree according to input signal
     */
    double apply(double x);

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using Common;
using Fairweather.Service;
using System.Linq;
using Common.Sage;
using Versioning;

namespace Common.Posting
{
    public class Cost_Code_Entered : Rule_Base
    {
        readonly int ver;
        public Cost_Code_Entered(int ver) {
            this.ver = ver;
        }

        public override bool
        Inspect_Line(Data_Line data, int ix, bool is_last,
             out bool skip, out IEnumerable<Validation_Error> errors) {

            H.assign(out skip, out errors);

            var type_str = data.Clean(TT_Rules.STR_TYPE);

            if (type_str.Trim().IsNullOrEmpty())
                // not our problem
                return true;

            var type = data.TYPE;

            if (!type.CC_Required(ver))
                return true;

            var cc = data.Clean(TT_Rules.STR_COST_CODE);

            if (cc.IsNullOrEmpty())
                return true;

            var proj = data.Clean(TT_Rules.STR_PROJECT_REF);
            if (!proj.IsNullOrEmpty())
                return true;

            errors = new[] { new Validation_Error(ix, "'" + type.Short_String() + TT_Rules.CC_Required_Error) };

            return false;

        }

    }
}


text:
campos
======

campos can generate forms from your model objects or help you to easily create
them using fields as building blocks. Take a minute to check examples dir.

Requirements
============

* Python 3+
* QtPy
* You need PyQt5, PyQt4 or PySide installed in your system to make use of
  *campos*. If several of these packages are found, ``PyQt5`` is used by
  default unless you set the ``QT_API`` environment variable.

  ``QT_API`` can take the following values:

    - pyqt5 (to use PyQt5).
    - pyqt or pyqt4 (to use PyQt4).
    - pyside (to use PySide).

Installation
============

You can use pip

``pip install campos``

or install it from the source package

``python setup.py install``

License
=======

This project is licensed under the MIT license.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace SageFrame.PaymentGateWay
{
    /// <summary>
    /// Business logic for Payment Gateway
    /// </summary>
    public class PaymentController
    {
        /// <summary>
        /// Saves Payment Gateway and their setting in json data format.
        /// </summary>
        /// <param name="objPaymentInfo"></param>
        public void SavePaymentGateways(PaymentGatewayInfo objPaymentInfo)
        {
            try
            {
                PaymentDataProvider objDataProvider = new PaymentDataProvider();
                objDataProvider.SavePaymentGateways(objPaymentInfo);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// Returns  Payment Gateways and their setting values.
        /// </summary>
        /// <param name="portalID">portalID</param>
        /// <returns>PaymentGatewayInfo object containg settingkey and values of Payment Gateway.</returns>
        public PaymentGatewayInfo GetPaymentGatewaysSetting(int portalID)
        {
            try
            {
                PaymentDataProvider objDataProvider = new PaymentDataProvider();
                return objDataProvider.GetPaymentGatewaysSetting(portalID);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// Fetch payment gateway settings key value collection
        /// </summary>
        /// <param name="portalID">portalID</param>
        /// <returns>PaymentGatewaySetting object containing the payment gateway setting keys and values</returns>
        public PaymentGatewaySetting FetchSetting(int portalID)
        {
            try
            {
                PaymentGatewayInfo objGatewayInfo = new PaymentGatewayInfo();
                objGatewayInfo = GetPaymentGatewaysSetting(portalID);
                PaymentGatewaySetting objSettings = new JavaScriptSerializer().Deserialize<PaymentGatewaySetting>(objGatewayInfo.SettingValue);
                return objSettings;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}


text:
package org.arakhne.afc.gis.road.layer;

import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import org.eclipse.xtext.xbase.lib.Pure;

import org.arakhne.afc.gis.road.primitive.RoadType;

/**
 * Constants for the road network layer API.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 * @since 14.0
 */
@SuppressWarnings("checkstyle:magicnumber")
public final class RoadNetworkLayerConstants {

	/** Defaults colors for the different types of roads. The array
	 * contains pairs of colors: one for the inner part, and one for the borders.
	 */
	public static final int[] DEFAULT_ROAD_COLORS;

	/** Default flag indicating if the internal data structures
	 * of the road networks may be drawn on the displayers.
	 */
	public static final boolean DEFAULT_ROAD_INTERN_DRAWING = false;

	/** Color of the internal data structures
	 * of the road networks when they are drawn on the displayers.
	 */
	public static final int DEFAULT_ROAD_INTERN_COLOR = 0xFF00FF;

	/** Default size of the road borders (in pixels).
	 */
	public static final int DEFAULT_BORDER_SIZE = 1;

	static {
		DEFAULT_ROAD_COLORS = new int[RoadType.values().length * 2];
		DEFAULT_ROAD_COLORS[2 * RoadType.FREEWAY.ordinal()] = 0xffc345;
		DEFAULT_ROAD_COLORS[2 * RoadType.FREEWAY.ordinal() + 1] = 0xe3a339;
		DEFAULT_ROAD_COLORS[2 * RoadType.MAJOR_ROAD.ordinal()] = 0xfffd8b;
		DEFAULT_ROAD_COLORS[2 * RoadType.MAJOR_ROAD.ordinal() + 1] = 0xe6d8a3;
		DEFAULT_ROAD_COLORS[2 * RoadType.LOCAL_ROAD.ordinal()] = 0xffffff;
		DEFAULT_ROAD_COLORS[2 * RoadType.LOCAL_ROAD.ordinal() + 1] = 0x505050;
		DEFAULT_ROAD_COLORS[2 * RoadType.BIKEWAY.ordinal()] = 0xfaf9f6;
		DEFAULT_ROAD_COLORS[2 * RoadType.BIKEWAY.ordinal() + 1] = 0xe3e3e3;
		DEFAULT_ROAD_COLORS[2 * RoadType.INTERCHANGE_RAMP.ordinal()] = DEFAULT_ROAD_COLORS[2 * RoadType.MAJOR_ROAD.ordinal()];
		DEFAULT_ROAD_COLORS[2 * RoadType.INTERCHANGE_RAMP.ordinal() + 1] =
				DEFAULT_ROAD_COLORS[2 * RoadType.MAJOR_ROAD.ordinal() + 1];
		DEFAULT_ROAD_COLORS[2 * RoadType.MAJOR_URBAN_AXIS.ordinal()] = DEFAULT_ROAD_COLORS[2 * RoadType.MAJOR_ROAD.ordinal()];
		DEFAULT_ROAD_COLORS[2 * RoadType.MAJOR_URBAN_AXIS.ordinal() + 1] =
				DEFAULT_ROAD_COLORS[2 * RoadType.MAJOR_ROAD.ordinal() + 1];
		DEFAULT_ROAD_COLORS[2 * RoadType.OTHER.ordinal()] = DEFAULT_ROAD_COLORS[2 * RoadType.LOCAL_ROAD.ordinal()];
		DEFAULT_ROAD_COLORS[2 * RoadType.OTHER.ordinal() + 1] = DEFAULT_ROAD_COLORS[2 * RoadType.LOCAL_ROAD.ordinal() + 1];
		DEFAULT_ROAD_COLORS[2 * RoadType.PRIVACY_PATH.ordinal()] = DEFAULT_ROAD_COLORS[2 * RoadType.BIKEWAY.ordinal()];
		DEFAULT_ROAD_COLORS[2 * RoadType.PRIVACY_PATH.ordinal() + 1] = DEFAULT_ROAD_COLORS[2 * RoadType.BIKEWAY.ordinal() + 1];
		DEFAULT_ROAD_COLORS[2 * RoadType.SECONDARY_ROAD.ordinal()] = DEFAULT_ROAD_COLORS[2 * RoadType.MAJOR_ROAD.ordinal()];
		DEFAULT_ROAD_COLORS[2 * RoadType.SECONDARY_ROAD.ordinal() + 1] =
				DEFAULT_ROAD_COLORS[2 * RoadType.MAJOR_ROAD.ordinal() + 1];
		DEFAULT_ROAD_COLORS[2 * RoadType.TRACK.ordinal()] = DEFAULT_ROAD_COLORS[2 * RoadType.BIKEWAY.ordinal()];
		DEFAULT_ROAD_COLORS[2 * RoadType.TRACK.ordinal() + 1] = DEFAULT_ROAD_COLORS[2 * RoadType.BIKEWAY.ordinal() + 1];
	}

	private RoadNetworkLayerConstants() {
		//
	}

	/** Replies the preferences for the road network layer.
	 *
	 * @return the preferences.
	 */
	@Pure
	public static Preferences getPreferences() {
		return Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
	}

	/** Replies the preferred size of the roazd borders (in pixels).
	 *
	 * @return size of the road borders.
	 */
	@Pure
	public static int getPreferredRoadBorderSize() {
		return getPreferredRoadBorderSize(true);
	}

	/** Replies the preferred size of the roazd borders (in pixels).
	 *
	 * @param useSystemValue indicates if the null value
	 *     must be replaced by the default system value:
	 * {@link #DEFAULT_BORDER_SIZE}.
	 * @return size of the road borders.
	 */
	@Pure
	public static Integer getPreferredRoadBorderSize(boolean useSystemValue) {
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
		if (prefs != null) {
			final int size = prefs.getInt("ROAD_BORDER_SIZE", -1); //$NON-NLS-1$
			if (size >= 0) {
				return size;
			}
		}
		if (useSystemValue) {
			return DEFAULT_BORDER_SIZE;
		}
		return null;
	}

	/** Set the preferred size of the roazd borders (in pixels).
	 *
	 * @param size is the preferred size of the roazd borders (in pixels).
	 */
	public static void setPreferredRoadBorderSize(Integer size) {
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
		if (prefs != null) {
			if (size == null || size.intValue() == DEFAULT_BORDER_SIZE) {
				prefs.remove("ROAD_BORDER_SIZE"); //$NON-NLS-1$
			} else {
				prefs.putInt("ROAD_BORDER_SIZE", size.intValue()); //$NON-NLS-1$
			}
			try {
				prefs.flush();
			} catch (BackingStoreException exception) {
				//
			}
		}
	}

	/** Replies the preferred color to draw the content of the roads of the given type.
	 *
	 * @param roadType is the type of road for which the color should be replied.
	 * @return the color of the inner parts of the roads.
	 */
	@Pure
	public static int getPreferredRoadColor(RoadType roadType) {
		return getPreferredRoadColor(roadType, true);
	}

	/** Replies the preferred color to draw the content of the roads of the given type.
	 *
	 * @param roadType is the type of road for which the color should be replied.
	 * @param useSystemValue indicates if the null value
	 *     must be replaced by the default system value in
	 * {@link #DEFAULT_ROAD_COLORS} (if true).
	 * @return the color of the inner parts of the roads.
	 */
	@Pure
	public static int  getPreferredRoadColor(RoadType roadType, boolean useSystemValue) {
		final RoadType rt = roadType == null ? RoadType.OTHER : roadType;
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
		if (prefs != null) {
			final String str = prefs.get("ROAD_COLOR_" + rt.name().toUpperCase(), null); //$NON-NLS-1$
			if (str != null) {
				try {
					return Integer.valueOf(str);
				} catch (Throwable exception) {
					//
				}
			}
		}
		if (useSystemValue) {
			return DEFAULT_ROAD_COLORS[rt.ordinal() * 2];
		}
		return 0;
	}

	/** Set the preferred color to draw the content of the roads of the given type.
	 *
	 * @param roadType is the type of road for which the color should be replied.
	 * @param color is the color or null to restore the default value.
	 */
	public static void setPreferredRoadColor(RoadType roadType, Integer color) {
		final RoadType rt = roadType == null ? RoadType.OTHER : roadType;
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
		if (prefs != null) {
			if (color == null || color.intValue() == DEFAULT_ROAD_COLORS[rt.ordinal() * 2]) {
				prefs.remove("ROAD_COLOR_" + rt.name().toUpperCase()); //$NON-NLS-1$
			} else {
				prefs.put("ROAD_COLOR_" + rt.name().toUpperCase(), Integer.toString(color.intValue())); //$NON-NLS-1$
			}
			try {
				prefs.flush();
			} catch (BackingStoreException exception) {
				//
			}
		}
	}

	/** Replies the preferred color to draw the borders of the roads of the given type.
	 *
	 * @param roadType is the type of road for which the color should be replied.
	 * @return the color of the inner parts of the roads.
	 */
	@Pure
	public static int getPreferredBorderColor(RoadType roadType) {
		return getPreferredBorderColor(roadType, true);
	}

	/** Replies the preferred color to draw the borders of the roads of the given type.
	 *
	 * @param roadType is the type of road for which the color should be replied.
	 * @param useSystemValue indicates if the null value
	 *     must be replaced by the default system value in
	 * {@link #DEFAULT_ROAD_COLORS} (if true).
	 * @return the color of the inner parts of the roads.
	 */
	@Pure
	public static int getPreferredBorderColor(RoadType roadType, boolean useSystemValue) {
		final RoadType rt = roadType == null ? RoadType.OTHER : roadType;
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
		if (prefs != null) {
			final String str = prefs.get("BORDER_COLOR_" + rt.name().toUpperCase(), null); //$NON-NLS-1$
			if (str != null) {
				try {
					return Integer.valueOf(str);
				} catch (Throwable exception) {
					//
				}
			}
		}
		if (useSystemValue) {
			return DEFAULT_ROAD_COLORS[rt.ordinal() * 2 + 1];
		}
		return 0;
	}

	/** Set the preferred color to draw the borders of the roads of the given type.
	 *
	 * @param roadType is the type of road for which the color should be replied.
	 * @param color is the color or null to restore the default value.
	 */
	public static void setPreferredBorderColor(RoadType roadType, Integer color) {
		final RoadType rt = roadType == null ? RoadType.OTHER : roadType;
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
		if (prefs != null) {
			if (color == null || color.intValue() == DEFAULT_ROAD_COLORS[rt.ordinal() * 2 + 1]) {
				prefs.remove("BORDER_COLOR_" + rt.name().toUpperCase()); //$NON-NLS-1$
			} else {
				prefs.put("BORDER_COLOR_" + rt.name().toUpperCase(), Integer.toString(color.intValue())); //$NON-NLS-1$
			}
			try {
				prefs.flush();
			} catch (BackingStoreException exception) {
				//
			}
		}
	}

	/** Replies if the internal data structure used to store the road network
	 * may be drawn on the displayers.
	 *
	 * @return true if the internal data structures may be
	 *     drawn on the displayers, otherwise false.
	 */
	@Pure
	public static boolean getPreferredRoadInternDrawing() {
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
		if (prefs != null) {
			return prefs.getBoolean("ROAD_INTERN_DRAWING", DEFAULT_ROAD_INTERN_DRAWING); //$NON-NLS-1$
		}
		return DEFAULT_ROAD_INTERN_DRAWING;
	}

	/** Set if the internal data structure used to store the road network
	 * may be drawn on the displayers.
	 *
	 * @param draw is true if the internal data structures may be
	 *     drawn on the displayers, false if the internal data structures
	 *     may not be drawn on the displayers, null to restore
	 *     the default value given by {@link #DEFAULT_ROAD_INTERN_DRAWING}.
	 */
	public static void setPreferredRoadInternDrawing(Boolean draw) {
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
		if (prefs != null) {
			if (draw == null) {
				prefs.remove("ROAD_INTERN_DRAWING"); //$NON-NLS-1$
			} else {
				prefs.putBoolean("ROAD_INTERN_DRAWING", draw); //$NON-NLS-1$
			}
			try {
				prefs.flush();
			} catch (BackingStoreException exception) {
				//
			}
		}
	}

	/** Replies the color of the internal data structures used when they
	 * are drawn on the displayers.
	 *
	 * @return the color of the internal data structures, never null.
	 */
	@Pure
	public static int getPreferredRoadInternColor() {
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
		if (prefs != null) {
			final String color = prefs.get("ROAD_INTERN_COLOR", null); //$NON-NLS-1$
			if (color != null) {
				try {
					return Integer.valueOf(color);
				} catch (Throwable exception) {
					//
				}
			}
		}
		return DEFAULT_ROAD_INTERN_COLOR;
	}

	/** Set the color of the internal data structures used when they
	 * are drawn on the displayers.
	 *
	 * @param color is the color of the internal data structures, never null.
	 */
	public static void setPreferredRoadInternColor(Integer color) {
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkLayerConstants.class);
		if (prefs != null) {
			if (color == null) {
				prefs.remove("ROAD_INTERN_COLOR"); //$NON-NLS-1$
			} else {
				prefs.put("ROAD_INTERN_COLOR", Integer.toString(color.intValue())); //$NON-NLS-1$
			}
			try {
				prefs.flush();
			} catch (BackingStoreException exception) {
				//
			}
		}
	}
}


text:
using System.Diagnostics;
using ShutDown.Models;

namespace ShutDown.MachineState
{
    public class ShutdownExecutor : IExecutor
    {
        public void Execute(ShutDownOperation operation, bool force)
        {
            string cmd = @"shutdown";
            string args = operation.GetCommandLineArgs(force);

            var start = new ProcessStartInfo(cmd, args)
            {
                ErrorDialog = true
            };
            Debug.WriteLine("cmd: " + (cmd ?? "null"));
            Debug.WriteLine("args: " + (args ?? "null"));
            start.UseShellExecute = false;
            start.CreateNoWindow = true;
            using (Process proc = Process.Start(start))
            {
                proc?.WaitForExit();
            }
        }
    }
}


text:
require('aurita/plugin_controller')
Aurita.import_plugin_controller :calendar, :event
Aurita.import_plugin_model :calendar, :event

module Aurita
module Plugins
module Calendar

  class Calendar_Controller < Plugin_Controller

    use_cache Cache::Simple
    cache_actions :show, :show_string, :day

    def calendar_box
      return unless Aurita.user.may(:see_calendar)

      box        = Box.new(:type  => 'Calendar::calendar',
                           :class => :topic,
                           :id    => 'calendar_box')
      body       = []
      box.header = tl(:calendar)

      if Aurita.user.may(:create_events) then
        body << Toolbar_Button.new(:icon => :add_event,
                                   :action => 'Calendar::Event/add') {
          tl(:add_event)
        }
      end
      body    << HTML.div(:id => :calendar_box_month) { calendar_box_body }
      box.body = body

      return box
    end

    def calendar_box_body(year=nil, month=nil)
      return unless Aurita.user.may(:see_calendar)

      if month.nil? or year.nil? then
        d     = Time.now
        year  = d.year
        month = d.month
      end

      HTML.div {
        view_string(:calendar,
                    :year  => year.to_i,
                    :month => month.to_i,
                    :date  => Date.civil(year.to_i, month.to_i))
      }
    end

    def show
      return unless Aurita.user.may(:see_calendar)

      year  = param(:year)
      month = param(:month)
      calendar_box_body(year, month)
    end

    def day
      render_controller(Event_Controller, :list, :day => param(:date))
    end

  end

end
end
end


text:
import MySQLdb
import os
import sys

import wpmu

home = os.getenv('HOME')

daily_filename = '%s/Desktop/daily.txt' % (home)
total_filename = '%s/Desktop/total.txt' % (home)

daily_users_filename = '%s/Desktop/daily_users.txt' % (home)
total_users_filename = '%s/Desktop/total_users.txt' % (home)

blog_deletions = {'2009-06-03': 2350,
                  '2009-07-01': 22,
                  '2009-08-03': 9,
                  '2009-09-01': 26,
                  '2009-10-01': 47,
                  '2009-11-05': 21}

def main():
#    output_daily_user_registrations()
#    output_total_users()
    output_daily_registrations()
    output_total_registrations()

def get_daily_blog_registrations():
    daily_blog_registrations = {}
    try:
        wpmu.cursor.execute("SELECT date_registered FROM wp_registration_log")
        result = wpmu.cursor.fetchall()
        for record in result:
            date_registered = record[0].strftime('%Y-%m-%d')
            if date_registered not in daily_blog_registrations:
                daily_blog_registrations[date_registered] = 0
            daily_blog_registrations[date_registered] += 1

    except MySQLdb.Error, error:  # if there's an error
        sys.stderr.write('ERROR:\t%s\n' % (error))  # write to the error log
        sys.exit(1)  # exit the script

    return daily_blog_registrations

def get_daily_user_registrations():
    daily_user_registrations = {}
    try:
        wpmu.cursor.execute("SELECT user_registered FROM wp_users")
        result = wpmu.cursor.fetchall()
        for record in result:
            user_registered = record[0].strftime('%Y-%m-%d')
            if user_registered not in daily_user_registrations:
                daily_user_registrations[user_registered] = 0
            daily_user_registrations[user_registered] += 1

    except MySQLdb.Error, error:  # if there's an error
        sys.stderr.write('ERROR:\t%s\n' % (error))  # write to the error log
        sys.exit(1)  # exit the script

    return daily_user_registrations

def get_daily_registrations():
    """The key for daily_registrations is the day, the value is a list where
    the first element is the number of blog registrations that day and the
    second is the number of user registrations that day
    """
    daily_registrations = {}
    daily_blog_registrations = get_daily_blog_registrations()
    daily_user_registrations = get_daily_user_registrations()

    # update daily registrations with blog data
    for day in daily_blog_registrations:
        daily_registrations[day] = []
        daily_registrations[day].append(daily_blog_registrations[day])

    # update daily registrations with user data
    for day in daily_user_registrations:
        if day not in daily_registrations:
            daily_registrations[day] = [0]
        daily_registrations[day].append(daily_user_registrations[day])

    # insert 0 values for missing user data
    for day in daily_registrations:
        if len(daily_registrations[day]) < 2:
            daily_registrations[day].append(0)

    return daily_registrations

def output_daily_registrations():
    daily_registrations = get_daily_registrations()

    daily_file = open(daily_filename, 'w')
    for day in sorted(daily_registrations):
        daily_file.write('%s\t%s\t%s\n' % (day, daily_registrations[day][0],
                daily_registrations[day][1]))
    daily_file.close()

def output_total_registrations():
    total_registrations = {}
    daily_registrations = get_daily_registrations()

    blog_total = 0
    user_total = 0
    for day in sorted(daily_registrations):
        total_registrations[day] = [blog_total + daily_registrations[day][0],
                                    user_total + daily_registrations[day][1]]
        if day in blog_deletions:
            total_registrations[day][0] = total_registrations[day][0] - blog_deletions[day]
        blog_total = total_registrations[day][0]
        user_total = total_registrations[day][1]

    total_file = open(total_filename, 'w')
    for day in sorted(total_registrations):
        total_file.write('%s\t%s\t%s\n' % (day, total_registrations[day][0],
                total_registrations[day][1]))
    total_file.close()

def output_daily_user_registrations():
    daily_user_registrations = get_daily_user_registrations()
    daily_users_file = open(daily_users_filename, 'w')
    for day in sorted(daily_user_registrations):
        daily_users_file.write('%s\t%s\n' % (day, daily_user_registrations[day]))
    daily_users_file.close()

def output_total_users():
    total_users = {}
    daily_user_registrations = get_daily_user_registrations()

    current_total = 0
    for day in sorted(daily_user_registrations):
        total_users[day] = current_total + daily_user_registrations[day]
        current_total = total_users[day]

    total_users_file = open(total_users_filename, 'w')
    for day in sorted(total_users):
        total_users_file.write('%s\t%s\n' % (day, total_users[day]))
    total_users_file.close()

def output_daily_blog_registrations():
    daily_blog_registrations = get_daily_blog_registrations()
    daily_users_file = open(daily_users_filename, 'w')
    for day in sorted(daily_user_registrations):
        daily_users_file.write('%s\t%s\n' % (day, daily_user_registrations[day]))
    daily_users_file.close()

def output_total_blogs():
    total_users = {}
    daily_user_registrations = get_daily_user_registrations()

    current_total = 0
    for day in sorted(daily_user_registrations):
        total_users[day] = current_total + daily_user_registrations[day]
        current_total = total_users[day]

    total_users_file = open(total_users_filename, 'w')
    for day in sorted(total_users):
        total_users_file.write('%s\t%s\n' % (day, total_users[day]))
    total_users_file.close()

# calls the main() function
if __name__=='__main__':
    main()


text:
package org.apache.tamaya.spisupport;

import java.util.HashMap;
import java.util.Map;
import org.apache.tamaya.spi.PropertySource;
import org.apache.tamaya.spi.PropertyValue;

/**
 *
 * @author William.Lieurance 2018.02.17
 */
public class MockedPropertySource implements PropertySource {

    private String name = "MockedPropertySource";
    private int ordinal = 10;

    public MockedPropertySource() {
        this("MockedPropertySource", 10);
    }

    public MockedPropertySource(String id, int ordinal) {
        this.name = id;
        this.ordinal = ordinal;
    }

    @Override
    public int getOrdinal() {
        return ordinal;
    }

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public PropertyValue get(String key) {
        if (key.contains("Null")) {
            return null;
        } else if (key.contains("missing")){
            return null;
        }
        return PropertyValue.createValue(key, "valueFromMockedPropertySource");
    }

    @Override
    public Map<String, PropertyValue> getProperties() {
        Map<String, PropertyValue> returnable = new HashMap<>();
        returnable.put("shouldBeNull", get("shouldBeNull"));
        returnable.put("Filterednull", get("shouldBeFiltered"));
        returnable.put("someKey", get("someKey"));

        return returnable;
    }

}


text:
/* NOTE: This file is autogenerated, do not edit this file directly.*/

#ifndef TRChartsJNI_PerUnitDateFormatter_hpp
#define TRChartsJNI_PerUnitDateFormatter_hpp

#include <TRChartsJNI/Support/Common.hpp>

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT jlong JNICALL Java_com_thomsonreuters_corptech_charts_PerUnitDateFormatter_nativeCreate(JNIEnv *env, jobject obj);

JNIEXPORT void JNICALL Java_com_thomsonreuters_corptech_charts_PerUnitDateFormatter_nativeDestroy(JNIEnv *env, jobject obj, jlong ptr);

JNIEXPORT void JNICALL Java_com_thomsonreuters_corptech_charts_PerUnitDateFormatter_nativeSetUnitFormat(JNIEnv * env, jobject obj, jlong ptr, jobject unit, jstring format);

JNIEXPORT jstring JNICALL Java_com_thomsonreuters_corptech_charts_PerUnitDateFormatter_nativeGetUnitFormat(JNIEnv * env, jobject obj, jlong ptr, jobject unit);

JNIEXPORT void JNICALL Java_com_thomsonreuters_corptech_charts_PerUnitDateFormatter_nativeSetZeroUnitFormat(JNIEnv * env, jobject obj, jlong ptr, jobject unit, jstring format);

JNIEXPORT jstring JNICALL Java_com_thomsonreuters_corptech_charts_PerUnitDateFormatter_nativeGetZeroUnitFormat(JNIEnv * env, jobject obj, jlong ptr, jobject unit);

#ifdef __cplusplus
}
#endif
#endif


text:
#ifndef HEADER_CURL_MBEDTLS_H
#define HEADER_CURL_MBEDTLS_H

#include BOSS_CURL_U_curl_setup_h //original-code:"curl_setup.h"

#ifdef USE_MBEDTLS

#include <mbedtls/sha256.h>

/* Called on first use mbedTLS, setup threading if supported */
int  Curl_mbedtls_init(void);
void Curl_mbedtls_cleanup(void);
int Curl_mbedtls_data_pending(const struct connectdata *conn, int sockindex);

CURLcode Curl_mbedtls_connect(struct connectdata *conn, int sockindex);

CURLcode Curl_mbedtls_connect_nonblocking(struct connectdata *conn,
                                           int sockindex,
                                           bool *done);

/* tell mbedTLS to close down all open information regarding connections (and
   thus session ID caching etc) */
void Curl_mbedtls_close_all(struct Curl_easy *data);

 /* close a SSL connection */
void Curl_mbedtls_close(struct connectdata *conn, int sockindex);

void Curl_mbedtls_session_free(void *ptr);
size_t Curl_mbedtls_version(char *buffer, size_t size);
int Curl_mbedtls_shutdown(struct connectdata *conn, int sockindex);

/* this backends supports CURLOPT_PINNEDPUBLICKEY */
#define have_curlssl_pinnedpubkey 1

/* API setup for mbedTLS */
#define curlssl_init() Curl_mbedtls_init()
#define curlssl_cleanup() Curl_mbedtls_cleanup()
#define curlssl_connect Curl_mbedtls_connect
#define curlssl_connect_nonblocking Curl_mbedtls_connect_nonblocking
#define curlssl_session_free(x)  Curl_mbedtls_session_free(x)
#define curlssl_close_all Curl_mbedtls_close_all
#define curlssl_close Curl_mbedtls_close
#define curlssl_shutdown(x,y) 0
#define curlssl_set_engine(x,y) (x=x, y=y, CURLE_NOT_BUILT_IN)
#define curlssl_set_engine_default(x) (x=x, CURLE_NOT_BUILT_IN)
#define curlssl_engines_list(x) (x=x, (struct curl_slist *)NULL)
#define curlssl_version Curl_mbedtls_version
#define curlssl_check_cxn(x) (x=x, -1)
#define curlssl_data_pending(x,y) Curl_mbedtls_data_pending(x, y)
#define CURL_SSL_BACKEND CURLSSLBACKEND_MBEDTLS
#define curlssl_sha256sum(a,b,c,d) mbedtls_sha256(a,b,c,0)

/* This might cause libcurl to use a weeker random!
   TODO: implement proper use of Polarssl's CTR-DRBG or HMAC-DRBG and use that
*/
#define curlssl_random(x,y,z) (x=x, y=y, z=z, CURLE_NOT_BUILT_IN)

#endif /* USE_MBEDTLS */
#endif /* HEADER_CURL_MBEDTLS_H */


text:
import accrue.cryptoerase.runtime.Condition;

class C {
    static final Condition{L} c = new Condition();

    int xTESTOUTPUT = 7;
    int yTESTOUTPUT = 7;

    void m() {
	int pubK = (PUBKEY(H){L /this.c H}) 42;
	int privK = (PRIVKEY(H){L /this.c H}) 42;

	this.xTESTOUTPUT = pubK;
	this.yTESTOUTPUT = privK;

    }

    public static void main(String[] args) {
	new C().m();
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.dialogflow.v3.model;

/**
 * Browse Carousel Card for Actions on Google.
 * https://developers.google.com/actions/assistant/responses#browsing_carousel
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard extends com.google.api.client.json.GenericJson {

  /**
   * Optional. Settings for displaying the image. Applies to every image in items.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String imageDisplayOptions;

  /**
   * Required. List of items in the Browse Carousel Card. Minimum of two items, maximum of ten.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem> items;

  /**
   * Optional. Settings for displaying the image. Applies to every image in items.
   * @return value or {@code null} for none
   */
  public java.lang.String getImageDisplayOptions() {
    return imageDisplayOptions;
  }

  /**
   * Optional. Settings for displaying the image. Applies to every image in items.
   * @param imageDisplayOptions imageDisplayOptions or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard setImageDisplayOptions(java.lang.String imageDisplayOptions) {
    this.imageDisplayOptions = imageDisplayOptions;
    return this;
  }

  /**
   * Required. List of items in the Browse Carousel Card. Minimum of two items, maximum of ten.
   * @return value or {@code null} for none
   */
  public java.util.List<GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem> getItems() {
    return items;
  }

  /**
   * Required. List of items in the Browse Carousel Card. Minimum of two items, maximum of ten.
   * @param items items or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard setItems(java.util.List<GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem> items) {
    this.items = items;
    return this;
  }

  @Override
  public GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard set(String fieldName, Object value) {
    return (GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard clone() {
    return (GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard) super.clone();
  }

}


text:
package com.example.compareit;

/**
 * Created by Nacho on 10/21/13.
 */

        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.io.UnsupportedEncodingException;
        import java.net.URI;
        import java.net.URISyntaxException;
        import java.util.ArrayList;
        import java.util.List;

        import org.apache.http.HttpResponse;
        import org.apache.http.NameValuePair;
        import org.apache.http.client.ClientProtocolException;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.entity.UrlEncodedFormEntity;
        import org.apache.http.client.methods.HttpGet;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.entity.StringEntity;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.apache.http.message.BasicNameValuePair;
        import org.apache.http.params.HttpParams;
        import org.json.JSONObject;

        import android.app.ProgressDialog;
        import android.content.Context;
        import android.os.AsyncTask;
        import android.util.Log;

public class httpTask extends AsyncTask<JSONObject, Void, String>{

    public static final int GET=0;
    public static final int POST=1;

    private int method;
    private String url;

    private ProgressDialog dialog;
    private Context context;
    AsyncStuff listener;

    public httpTask(Context context, int method, String url){

        this.url = url;
        this.method = method;

        context = context;
        try{
            dialog = new ProgressDialog(context);
        }catch(Exception e){}
    }

    public void setListener(AsyncStuff listener) {
        this.listener = listener;
    }

    private  String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    private String get(JSONObject... args){

        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet();
        try {
            get.setURI(new URI(this.url));
            HttpResponse r = client.execute(get);
            return this.convertStreamToString(r.getEntity().getContent());

        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    private String post(JSONObject... args){

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(this.url);

        try {
            post.addHeader("Content-Type", "application/json");

            StringEntity se = new StringEntity(args[0].toString());

            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");

            post.setEntity(se);
            HttpResponse r = client.execute(post);
            return this.convertStreamToString(r.getEntity().getContent());

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        if(this.listener != null){
            this.listener.doStuff(result);
        }
        Log.i("httpTask",result);
        try{
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }catch(Exception e){}
    }

    protected void onPreExecute(){
        try{
            this.dialog.setMessage("Loading...");
            this.dialog.show();
        }catch(Exception e){}
    }
    @Override
    protected String doInBackground(JSONObject... params) {
        if(this.method == POST){
            return post(params);
        }else if (this.method == GET){
            return get(params);
        }else{
            return null;
        }
    }

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace Entitas.Unity.VisualDebugging {
    public class DictionaryTypeDrawer : ITypeDrawer {
        public bool HandlesType(Type type) {
            return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>);
        }

        public object DrawAndGetNewValue(Type type, string fieldName, object value, Entity entity, int index, IComponent component) {
            var dictionary = (IDictionary)value;
            var keyType = type.GetGenericArguments()[0];
            var valueType = type.GetGenericArguments()[1];

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(fieldName);
            if (GUILayout.Button("+", GUILayout.Width(19), GUILayout.Height(14))) {
                object defaultKey;
                if (EntityEditor.CreateDefault(keyType, out defaultKey)) {
                    object defaultValue;
                    if (EntityEditor.CreateDefault(valueType, out defaultValue)) {
                        dictionary[defaultKey] = defaultValue;
                    }
                }
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space();

            if (dictionary.Count > 0) {
                var indent = EditorGUI.indentLevel;
                EditorGUI.indentLevel = indent + 1;

                var keys = new ArrayList(dictionary.Keys);
                for (int i = 0; i < keys.Count; i++) {
                    var key = keys[i];
                    EntityEditor.DrawAndSetElement(keyType, "key", key,
                        entity, index, component, newValue => {
                        var tmpValue = dictionary[key];
                        dictionary.Remove(key);
                        if (newValue != null) {
                            dictionary[newValue] = tmpValue;
                        }
                    });

                    EntityEditor.DrawAndSetElement(valueType, "value", dictionary[key],
                        entity, index, component, newValue => dictionary[key] = newValue);

                    EditorGUILayout.Space();
                }

                EditorGUI.indentLevel = indent;
            }

            return dictionary;
        }
    }
}