code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
(function () { "use strict"; angular.module('projectManagerSPA').controller('userLoginController', ['authenticationService', '$scope', '$state',function (authenticationService, $scope, $state) { $scope.logIn = function () { authenticationService.logIn($scope.username, $scope.password, function () { $state.go('organizationList'); }); }; $scope.logOut = function () { $state.go('userLogout'); }; }]); })();
ivanthescientist/ProjectManager
src/main/resources/public/js/controller/user.login.controller.js
JavaScript
mit
503
require 'spec_helper' describe ChequeFormatter do describe ".date_to_ddmmyy" do subject { ChequeFormatter.date_to_ddmmyy(date) } context "5-Nov-2011" do let(:date) { "5-Nov-2011" } it { should == '051111' } end context "2011-11-05" do let(:date) { "5-Nov-2011" } it { should == '051111' } end end describe ".amount_to_text" do # Source: http://www.moneysense.gov.sg/resource/publications/quick_tips/Graphicised%20cheque%20-%20FINAL.pdf subject { ChequeFormatter.amount_to_text(number) } context "handles negative numbers" do let(:number) { -1000 } it { should == 'One Thousand And Cents Zero Only' } end context "1000" do let(:number) { 1000 } it { should == 'One Thousand And Cents Zero Only' } end context "1001" do let(:number) { 1001 } it { should == 'One Thousand And One And Cents Zero Only' } end context "1010" do let(:number) { 1010 } it { should == 'One Thousand And Ten And Cents Zero Only' } end context "1100" do let(:number) { 1100 } it { should == 'One Thousand One Hundred And Cents Zero Only' } end context "1303.53" do let(:number) { 1303.53 } it { should == 'One Thousand Three Hundred And Three And Cents Fifty Three Only' } end end describe ".amount_to_number" do subject { ChequeFormatter.amount_to_number(number) } context "handles negative numbers" do let(:number) { -1000 } it { should == '1,000.00' } end context "1" do let(:number) { 1 } it { should == '1.00' } end context "10" do let(:number) { 10 } it { should == '10.00' } end context "100" do let(:number) { 100 } it { should == '100.00' } end context "1000" do let(:number) { 1000 } it { should == '1,000.00' } end context "1000000" do let(:number) { 1000000 } it { should == '1,000,000.00' } end context "1000000.50" do let(:number) { 1000000.50 } it { should == '1,000,000.50' } end end end
pivotalexperimental/cheques
spec/lib/cheque_formatter_spec.rb
Ruby
mit
2,124
#!/bin/bash # Distill standard library documentation from the stdops.c file. cat Interpreter/stdops.c | grep '//' | colrm 1 3 | tail -n +10 > Documentation/Standard\ Library.mkd
wandernauta/Staple
Support/mkstdlibdoc.sh
Shell
mit
180
""" SensitiveFloat objects for expectations involving r_s and c_s. Args: vs: A vector of variational parameters Attributes: Each matrix has one row for each color and a column for star / galaxy. Row 3 is the gamma distribute baseline brightness, and all other rows are lognormal offsets. - E_l_a: A NUM_BANDS x NUM_SOURCE_TYPES matrix of expectations and derivatives of color terms. The rows are bands, and the columns are star / galaxy. - E_ll_a: A NUM_BANDS x NUM_SOURCE_TYPES matrix of expectations and derivatives of squared color terms. The rows are bands, and the columns are star / galaxy. """ struct SourceBrightness{T<:Number} # [E[l|a=0], E[l]|a=1]] E_l_a::Matrix{SensitiveFloat{T}} # [E[l^2|a=0], E[l^2]|a=1]] E_ll_a::Matrix{SensitiveFloat{T}} end function SourceBrightness(vs::Vector{T}; calculate_gradient=true, calculate_hessian=true) where {T<:Number} flux_loc = vs[ids.flux_loc] flux_scale = vs[ids.flux_scale] color_mean = vs[ids.color_mean] color_var = vs[ids.color_var] # E_l_a has a row for each of the five colors and columns # for star / galaxy. E_l_a = Matrix{SensitiveFloat{T}}(NUM_BANDS, NUM_SOURCE_TYPES) E_ll_a = Matrix{SensitiveFloat{T}}(NUM_BANDS, NUM_SOURCE_TYPES) for i = 1:NUM_SOURCE_TYPES for b = 1:NUM_BANDS E_l_a[b, i] = SensitiveFloat{T}(length(BrightnessParams), 1, calculate_gradient, calculate_hessian) end E_l_a[3, i].v[] = exp(flux_loc[i] + 0.5 * flux_scale[i]) E_l_a[4, i].v[] = exp(color_mean[3, i] + .5 * color_var[3, i]) E_l_a[5, i].v[] = exp(color_mean[4, i] + .5 * color_var[4, i]) E_l_a[2, i].v[] = exp(-color_mean[2, i] + .5 * color_var[2, i]) E_l_a[1, i].v[] = exp(-color_mean[1, i] + .5 * color_var[1, i]) if calculate_gradient # band 3 is the reference band, relative to which the colors are # specified. # It is denoted r_s and has a lognormal expectation. E_l_a[3, i].d[bids.flux_loc] = E_l_a[3, i].v[] E_l_a[3, i].d[bids.flux_scale] = E_l_a[3, i].v[] * .5 if calculate_hessian set_hess!(E_l_a[3, i], bids.flux_loc, bids.flux_loc, E_l_a[3, i].v[]) set_hess!(E_l_a[3, i], bids.flux_loc, bids.flux_scale, E_l_a[3, i].v[] * 0.5) set_hess!(E_l_a[3, i], bids.flux_scale, bids.flux_scale, E_l_a[3, i].v[] * 0.25) end # The remaining indices involve c_s and have lognormal # expectations times E_c_3. # band 4 = band 3 * color 3. E_l_a[4, i].d[bids.color_mean[3]] = E_l_a[4, i].v[] E_l_a[4, i].d[bids.color_var[3]] = E_l_a[4, i].v[] * .5 if calculate_hessian set_hess!(E_l_a[4, i], bids.color_mean[3], bids.color_mean[3], E_l_a[4, i].v[]) set_hess!(E_l_a[4, i], bids.color_mean[3], bids.color_var[3], E_l_a[4, i].v[] * 0.5) set_hess!(E_l_a[4, i], bids.color_var[3], bids.color_var[3], E_l_a[4, i].v[] * 0.25) end multiply_sfs!(E_l_a[4, i], E_l_a[3, i]) # Band 5 = band 4 * color 4. E_l_a[5, i].d[bids.color_mean[4]] = E_l_a[5, i].v[] E_l_a[5, i].d[bids.color_var[4]] = E_l_a[5, i].v[] * .5 if calculate_hessian set_hess!(E_l_a[5, i], bids.color_mean[4], bids.color_mean[4], E_l_a[5, i].v[]) set_hess!(E_l_a[5, i], bids.color_mean[4], bids.color_var[4], E_l_a[5, i].v[] * 0.5) set_hess!(E_l_a[5, i], bids.color_var[4], bids.color_var[4], E_l_a[5, i].v[] * 0.25) end multiply_sfs!(E_l_a[5, i], E_l_a[4, i]) # Band 2 = band 3 * color 2. E_l_a[2, i].d[bids.color_mean[2]] = E_l_a[2, i].v[] * -1. E_l_a[2, i].d[bids.color_var[2]] = E_l_a[2, i].v[] * .5 if calculate_hessian set_hess!(E_l_a[2, i], bids.color_mean[2], bids.color_mean[2], E_l_a[2, i].v[]) set_hess!(E_l_a[2, i], bids.color_mean[2], bids.color_var[2], E_l_a[2, i].v[] * -0.5) set_hess!(E_l_a[2, i], bids.color_var[2], bids.color_var[2], E_l_a[2, i].v[] * 0.25) end multiply_sfs!(E_l_a[2, i], E_l_a[3, i]) # Band 1 = band 2 * color 1. E_l_a[1, i].d[bids.color_mean[1]] = E_l_a[1, i].v[] * -1. E_l_a[1, i].d[bids.color_var[1]] = E_l_a[1, i].v[] * .5 if calculate_hessian set_hess!(E_l_a[1, i], bids.color_mean[1], bids.color_mean[1], E_l_a[1, i].v[]) set_hess!(E_l_a[1, i], bids.color_mean[1], bids.color_var[1], E_l_a[1, i].v[] * -0.5) set_hess!(E_l_a[1, i], bids.color_var[1], bids.color_var[1], E_l_a[1, i].v[] * 0.25) end multiply_sfs!(E_l_a[1, i], E_l_a[2, i]) else # Simply update the values if not calculating derivatives. E_l_a[4, i].v[] *= E_l_a[3, i].v[] E_l_a[5, i].v[] *= E_l_a[4, i].v[] E_l_a[2, i].v[] *= E_l_a[3, i].v[] E_l_a[1, i].v[] *= E_l_a[2, i].v[] end # Derivs ################################ # Squared terms. for b = 1:NUM_BANDS E_ll_a[b, i] = SensitiveFloat{T}(length(BrightnessParams), 1, calculate_gradient, calculate_hessian) end E_ll_a[3, i].v[] = exp(2 * flux_loc[i] + 2 * flux_scale[i]) E_ll_a[4, i].v[] = exp(2 * color_mean[3, i] + 2 * color_var[3, i]) E_ll_a[5, i].v[] = exp(2 * color_mean[4, i] + 2 * color_var[4, i]) E_ll_a[2, i].v[] = exp(-2 * color_mean[2, i] + 2 * color_var[2, i]) E_ll_a[1, i].v[] = exp(-2 * color_mean[1, i] + 2 * color_var[1, i]) if calculate_gradient # Band 3, the reference band. E_ll_a[3, i].d[bids.flux_loc] = 2 * E_ll_a[3, i].v[] E_ll_a[3, i].d[bids.flux_scale] = 2 * E_ll_a[3, i].v[] if calculate_hessian for hess_ids in [(bids.flux_loc, bids.flux_loc), (bids.flux_loc, bids.flux_scale), (bids.flux_scale, bids.flux_scale)] set_hess!(E_ll_a[3, i], hess_ids..., 4.0 * E_ll_a[3, i].v[]) end end # Band 4 = band 3 * color 3. E_ll_a[4, i].d[bids.color_mean[3]] = E_ll_a[4, i].v[] * 2. E_ll_a[4, i].d[bids.color_var[3]] = E_ll_a[4, i].v[] * 2. if calculate_hessian for hess_ids in [(bids.color_mean[3], bids.color_mean[3]), (bids.color_mean[3], bids.color_var[3]), (bids.color_var[3], bids.color_var[3])] set_hess!(E_ll_a[4, i], hess_ids..., E_ll_a[4, i].v[] * 4.0) end end multiply_sfs!(E_ll_a[4, i], E_ll_a[3, i]) # Band 5 = band 4 * color 4. tmp4 = exp(2 * color_mean[4, i] + 2 * color_var[4, i]) E_ll_a[5, i].d[bids.color_mean[4]] = E_ll_a[5, i].v[] * 2. E_ll_a[5, i].d[bids.color_var[4]] = E_ll_a[5, i].v[] * 2. if calculate_hessian for hess_ids in [(bids.color_mean[4], bids.color_mean[4]), (bids.color_mean[4], bids.color_var[4]), (bids.color_var[4], bids.color_var[4])] set_hess!(E_ll_a[5, i], hess_ids..., E_ll_a[5, i].v[] * 4.0) end end multiply_sfs!(E_ll_a[5, i], E_ll_a[4, i]) # Band 2 = band 3 * color 2 tmp2 = exp(-2 * color_mean[2, i] + 2 * color_var[2, i]) E_ll_a[2, i].d[bids.color_mean[2]] = E_ll_a[2, i].v[] * -2. E_ll_a[2, i].d[bids.color_var[2]] = E_ll_a[2, i].v[] * 2. if calculate_hessian for hess_ids in [(bids.color_mean[2], bids.color_mean[2]), (bids.color_var[2], bids.color_var[2])] set_hess!(E_ll_a[2, i], hess_ids..., E_ll_a[2, i].v[] * 4.0) end set_hess!(E_ll_a[2, i], bids.color_mean[2], bids.color_var[2], E_ll_a[2, i].v[] * -4.0) end multiply_sfs!(E_ll_a[2, i], E_ll_a[3, i]) # Band 1 = band 2 * color 1 E_ll_a[1, i].d[bids.color_mean[1]] = E_ll_a[1, i].v[] * -2. E_ll_a[1, i].d[bids.color_var[1]] = E_ll_a[1, i].v[] * 2. if calculate_hessian for hess_ids in [(bids.color_mean[1], bids.color_mean[1]), (bids.color_var[1], bids.color_var[1])] set_hess!(E_ll_a[1, i], hess_ids..., E_ll_a[1, i].v[] * 4.0) end set_hess!(E_ll_a[1, i], bids.color_mean[1], bids.color_var[1], E_ll_a[1, i].v[] * -4.0) end multiply_sfs!(E_ll_a[1, i], E_ll_a[2, i]) else # Simply update the values if not calculating derivatives. E_ll_a[4, i].v[] *= E_ll_a[3, i].v[] E_ll_a[5, i].v[] *= E_ll_a[4, i].v[] E_ll_a[2, i].v[] *= E_ll_a[3, i].v[] E_ll_a[1, i].v[] *= E_ll_a[2, i].v[] end # calculate_gradient end SourceBrightness{T}(E_l_a, E_ll_a) end """ Load the source brightnesses for these model params. Each SourceBrightness object has information for all bands and object types. Returns: - An array of SourceBrightness objects for each object in 1:ea.S. Only sources in ea.active_sources will have derivative information. """ function load_source_brightnesses( ea::ElboArgs, vp::VariationalParams{T}; calculate_gradient::Bool=true, calculate_hessian::Bool=true) where {T<:Number} sbs = Vector{SourceBrightness{T}}(ea.S) for s in 1:ea.S this_deriv = (s in ea.active_sources) && calculate_gradient this_hess = (s in ea.active_sources) && calculate_hessian sbs[s] = SourceBrightness(vp[s]; calculate_gradient=this_deriv, calculate_hessian=this_hess) end sbs end
jeff-regier/Celeste.jl
src/deterministic_vi/source_brightness.jl
Julia
mit
10,351
/// <reference types="react-scripts" /> declare module "office-ui-fabric-react/lib/Modal" { const Modal: React.StatelessComponent<IModalProps>; }
azu/faao
src/react-app-env.d.ts
TypeScript
mit
150
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Mon Aug 31 23:15:49 CEST 2015 --> <title>IObjectUuidSameCheck (FailFast v.1.3)</title> <meta name="date" content="2015-08-31"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="IObjectUuidSameCheck (FailFast v.1.3)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/IObjectUuidSameCheck.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../starkcoder/failfast/checks/objects/uuids/IObjectUuidOutsideCheck.html" title="interface in starkcoder.failfast.checks.objects.uuids"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?starkcoder/failfast/checks/objects/uuids/IObjectUuidSameCheck.html" target="_top">Frames</a></li> <li><a href="IObjectUuidSameCheck.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">starkcoder.failfast.checks.objects.uuids</div> <h2 title="Interface IObjectUuidSameCheck" class="title">Interface IObjectUuidSameCheck</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Superinterfaces:</dt> <dd><a href="../../../../../starkcoder/failfast/checks/ICheck.html" title="interface in starkcoder.failfast.checks">ICheck</a></dd> </dl> <dl> <dt>All Known Subinterfaces:</dt> <dd><a href="../../../../../starkcoder/failfast/checks/IChecker.html" title="interface in starkcoder.failfast.checks">IChecker</a>, <a href="../../../../../starkcoder/failfast/checks/objects/IObjectChecker.html" title="interface in starkcoder.failfast.checks.objects">IObjectChecker</a>, <a href="../../../../../starkcoder/failfast/checks/objects/uuids/IObjectUuidChecker.html" title="interface in starkcoder.failfast.checks.objects.uuids">IObjectUuidChecker</a></dd> </dl> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../../starkcoder/failfast/checks/AChecker.html" title="class in starkcoder.failfast.checks">AChecker</a>, <a href="../../../../../starkcoder/failfast/checks/Checker.html" title="class in starkcoder.failfast.checks">Checker</a></dd> </dl> <hr> <br> <pre>public interface <span class="strong">IObjectUuidSameCheck</span> extends <a href="../../../../../starkcoder/failfast/checks/ICheck.html" title="interface in starkcoder.failfast.checks">ICheck</a></pre> <div class="block">Specifies a reference check for UUID.</div> <dl><dt><span class="strong">Author:</span></dt> <dd>Keld Oelykke</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../starkcoder/failfast/checks/objects/uuids/IObjectUuidSameCheck.html#isUuidSame(java.lang.Object, java.util.UUID, java.util.UUID)">isUuidSame</a></strong>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;caller, <a href="http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html?is-external=true" title="class or interface in java.util">UUID</a>&nbsp;referenceA, <a href="http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html?is-external=true" title="class or interface in java.util">UUID</a>&nbsp;referenceB)</code> <div class="block">Checks if the references are the same (using ==) or both nulls.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="isUuidSame(java.lang.Object, java.util.UUID, java.util.UUID)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>isUuidSame</h4> <pre>boolean&nbsp;isUuidSame(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;caller, <a href="http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html?is-external=true" title="class or interface in java.util">UUID</a>&nbsp;referenceA, <a href="http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html?is-external=true" title="class or interface in java.util">UUID</a>&nbsp;referenceB)</pre> <div class="block">Checks if the references are the same (using ==) or both nulls.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>caller</code> - end-user instance initiating the check</dd><dd><code>referenceA</code> - reference to check using == against reference B</dd><dd><code>referenceB</code> - argument to check using == of reference A</dd> <dt><span class="strong">Returns:</span></dt><dd>true, if references are the same (using ==) - including both nulls - otherwise false</dd> <dt><span class="strong">Throws:</span></dt> <dd><code><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html?is-external=true" title="class or interface in java.lang">IllegalArgumentException</a></code> - if caller is null</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/IObjectUuidSameCheck.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../starkcoder/failfast/checks/objects/uuids/IObjectUuidOutsideCheck.html" title="interface in starkcoder.failfast.checks.objects.uuids"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?starkcoder/failfast/checks/objects/uuids/IObjectUuidSameCheck.html" target="_top">Frames</a></li> <li><a href="IObjectUuidSameCheck.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><i>The MIT License (MIT) - Copyright &#169; 2014-2015 Keld Oelykke. All Rights Reserved.</i></small></p> </body> </html>
KeldOelykke/FailFast
Java/Web/war/releases/1.3/api/starkcoder/failfast/checks/objects/uuids/IObjectUuidSameCheck.html
HTML
mit
9,976
/* * The MIT License (MIT) * * Copyright (c) 2013 Zoltán Nyikos * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef REVIEWER_H #define REVIEWER_H #include "User.h" #include <string> class Reviewer: public User{ public: Reviewer(const std::string& name, const std::string& pass); virtual UserLevel getLevel() const; }; #endif
nyz93/advertapp
src/Reviewer.h
C
mit
1,380
/* This software module was originally developed by Apple Computer, Inc. in the course of development of MPEG-4. This software module is an implementation of a part of one or more MPEG-4 tools as specified by MPEG-4. ISO/IEC gives users of MPEG-4 free license to this software module or modifications thereof for use in hardware or software products claiming conformance to MPEG-4. Those intending to use this software module in hardware or software products are advised that its use may infringe existing patents. The original developer of this software module and his/her company, the subsequent editors and their companies, and ISO/IEC have no liability for use of this software module or modifications thereof in an implementation. Copyright is not released for non MPEG-4 conforming products. Apple Computer, Inc. retains full right to use the code for its own purpose, assign or donate the code to a third party and to inhibit third parties from using the code for non MPEG-4 conforming products. This copyright notice must be included in all copies or derivative works. Copyright (c) 1999. */ /* $Id: MovieFragmentAtom.c,v 1.1.1.1 2002/09/20 08:53:34 julien Exp $ */ #include "MP4Atoms.h" #include <stdlib.h> static void destroy( MP4AtomPtr s ) { MP4Err err; MP4MovieFragmentAtomPtr self; self = (MP4MovieFragmentAtomPtr) s; if ( self == NULL ) BAILWITHERROR( MP4BadParamErr ) DESTROY_ATOM_LIST_F( atomList ); (self->mfhd)->destroy( (MP4AtomPtr) (self->mfhd) ); if ( self->super ) self->super->destroy( s ); bail: TEST_RETURN( err ); return; } static MP4Err mdatMoved( struct MP4MovieAtom* s, u64 mdatBase, u64 mdatEnd, s32 mdatOffset ) { u32 trackCount; u32 i; MP4Err err; MP4MovieFragmentAtomPtr self; self = (MP4MovieFragmentAtomPtr) s; err = MP4NoErr; MP4GetListEntryCount( self->atomList, &trackCount ); for ( i = 0; i < trackCount; i++ ) { MP4TrackFragmentAtomPtr traf; err = MP4GetListEntry( self->atomList, i, (char**) &traf ); if (err) goto bail; if ( traf == NULL ) BAILWITHERROR( MP4InvalidMediaErr ); err = traf->mdatMoved( (struct MP4MediaInformationAtom *) traf, mdatBase, mdatEnd, mdatOffset ); if (err) goto bail; } bail: TEST_RETURN( err ); return err; } static MP4Err mergeFragments( struct MP4MovieFragmentAtom* self, MP4MovieAtomPtr moov ) { u32 trackCount; u32 i; MP4Err err; u64 base_offset; u32 traf_data_size; err = MP4NoErr; MP4GetListEntryCount( self->atomList, &trackCount ); base_offset = self->streamOffset; for ( i = 0; i < trackCount; i++ ) { MP4TrackFragmentAtomPtr traf; MP4TrackFragmentHeaderAtomPtr tfhd; MP4TrackExtendsAtomPtr trex; MP4MediaAtomPtr mdia; MP4Track trak; u64 mediaDuration, initialMediaDuration; u32 tfhd_flags; err = MP4GetListEntry( self->atomList, i, (char**) &traf ); if (err) goto bail; if ( traf == NULL ) BAILWITHERROR( MP4InvalidMediaErr ); tfhd = (MP4TrackFragmentHeaderAtomPtr) traf->tfhd; err = moov->getTrackExtendsAtom( moov, tfhd->trackID, (MP4AtomPtr*) &trex ); if (err) goto bail; traf->default_sample_description_index = trex->default_sample_description_index; traf->default_sample_duration = trex->default_sample_duration; traf->default_sample_size = trex->default_sample_size; traf->default_sample_flags = trex->default_sample_flags; tfhd_flags = tfhd->flags; if ((tfhd_flags & tfhd_sample_description_index_present)==0) tfhd->sample_description_index = trex->default_sample_description_index; if ((tfhd_flags & tfhd_default_sample_duration_present)==0) tfhd->default_sample_duration = trex->default_sample_duration; if ((tfhd_flags & tfhd_default_sample_size_present)==0) tfhd->default_sample_size = trex->default_sample_size; if ((tfhd_flags & tfhd_default_sample_flags_present)==0) tfhd->default_sample_flags = trex->default_sample_flags; if ((tfhd_flags & tfhd_base_data_offset_present)==0) tfhd->base_data_offset = base_offset; else base_offset = tfhd->base_data_offset; err = traf->calculateDataSize( traf, &traf_data_size ); if (err) goto bail; base_offset += traf_data_size; err = moov->getTrackMedia( moov, tfhd->trackID, (MP4AtomPtr*) &mdia ); if (err) goto bail; err = MP4GetMediaTrack( (MP4Media) mdia, &trak ); if (err) goto bail; err = MP4GetMediaDuration( (MP4Media) mdia, &initialMediaDuration ); if (err) goto bail; if ( (tfhd_flags & tfhd_duration_is_empty) ) /* BAILWITHERROR( MP4NotImplementedErr ) */ { /* if there is not already an edit list, and there is media, insert an edit covering the current track duration */ if ((initialMediaDuration>0) && (((MP4TrackAtomPtr) trak)->trackEditAtom == 0)) { err = MP4InsertMediaIntoTrack( trak, -1, 0, initialMediaDuration, 1 ); if (err) goto bail; } err = MP4InsertMediaIntoTrack( trak, -1, -1, tfhd->default_sample_duration, 1 ); if (err) goto bail; } else { err = MP4BeginMediaEdits( (MP4Media) mdia ); if (err) goto bail; err = traf->mergeRuns( traf, mdia ); err = MP4EndMediaEdits( (MP4Media) mdia ); if (err) goto bail; err = MP4GetMediaDuration( (MP4Media) mdia, &mediaDuration ); if (err) goto bail; if (((MP4TrackAtomPtr) trak)->trackEditAtom) { err = MP4InsertMediaIntoTrack( trak, -1, (s32) initialMediaDuration, mediaDuration-initialMediaDuration, 1 ); if (err) goto bail; } } } bail: TEST_RETURN( err ); return err; } static MP4Err serialize( struct MP4Atom* s, char* buffer ) { MP4Err err; MP4MovieFragmentAtomPtr self = (MP4MovieFragmentAtomPtr) s; err = MP4NoErr; err = MP4SerializeCommonBaseAtomFields( s, buffer ); if (err) goto bail; buffer += self->bytesWritten; SERIALIZE_ATOM( mfhd ); SERIALIZE_ATOM_LIST( atomList ); assert( self->bytesWritten == self->size ); bail: TEST_RETURN( err ); return err; } static MP4Err calculateSize( struct MP4Atom* s ) { MP4Err err; MP4MovieFragmentAtomPtr self = (MP4MovieFragmentAtomPtr) s; err = MP4NoErr; err = MP4CalculateBaseAtomFieldSize( s ); if (err) goto bail; ADD_ATOM_SIZE( mfhd ); ADD_ATOM_LIST_SIZE( atomList ); bail: TEST_RETURN( err ); return err; } static MP4Err calculateDuration( struct MP4MovieAtom* self ) { MP4Err err; err = MP4NoErr; if ( self == 0 ) BAILWITHERROR( MP4BadParamErr ); bail: TEST_RETURN( err ); return err; } static MP4Err addAtom( MP4MovieFragmentAtomPtr self, MP4AtomPtr atom ) { MP4Err err; err = MP4NoErr; if ( self == 0 ) BAILWITHERROR( MP4BadParamErr ); switch (atom->type) { case MP4MovieFragmentHeaderAtomType: self->mfhd = atom; break; case MP4TrackFragmentAtomType: err = MP4AddListEntry( atom, self->atomList ); break; default: BAILWITHERROR( MP4BadDataErr ) } bail: TEST_RETURN( err ); return err; } static MP4Err createFromInputStream( MP4AtomPtr s, MP4AtomPtr proto, MP4InputStreamPtr inputStream ) { PARSE_ATOM_LIST(MP4MovieFragmentAtom) bail: TEST_RETURN( err ); return err; } MP4Err MP4CreateMovieFragmentAtom( MP4MovieFragmentAtomPtr *outAtom ) { MP4Err err; MP4MovieFragmentAtomPtr self; self = (MP4MovieFragmentAtomPtr) calloc( 1, sizeof(MP4MovieFragmentAtom) ); TESTMALLOC( self ) err = MP4CreateBaseAtom( (MP4AtomPtr) self ); if ( err ) goto bail; self->type = MP4MovieFragmentAtomType; self->name = "movie fragment"; self->createFromInputStream = (cisfunc) createFromInputStream; self->destroy = destroy; err = MP4MakeLinkedList( &self->atomList ); if (err) goto bail; self->calculateSize = calculateSize; self->serialize = serialize; self->mdatMoved = mdatMoved; self->calculateDuration = calculateDuration; self->addAtom = addAtom; self->mergeFragments = mergeFragments; *outAtom = self; bail: TEST_RETURN( err ); return err; }
andresgonzalezfornell/TFM
lib/libisomediafile/src/MovieFragmentAtom.c
C
mit
7,783
#include "forms/transactioncontrol.h" #include "forms/graphicbutton.h" #include "forms/label.h" #include "forms/listbox.h" #include "forms/scrollbar.h" #include "forms/ui.h" #include "framework/data.h" #include "framework/framework.h" #include "framework/logger.h" #include "framework/renderer.h" #include "game/state/city/base.h" #include "game/state/city/building.h" #include "game/state/city/research.h" #include "game/state/city/vehicle.h" #include "game/state/city/vequipment.h" #include "game/state/gamestate.h" #include "game/state/rules/aequipmenttype.h" #include "game/state/rules/city/vammotype.h" #include "game/state/shared/organisation.h" #include "game/ui/general/messagebox.h" namespace OpenApoc { sp<Image> TransactionControl::bgLeft; sp<Image> TransactionControl::bgRight; sp<Image> TransactionControl::purchaseBoxIcon; sp<Image> TransactionControl::purchaseXComIcon; sp<Image> TransactionControl::purchaseArrow; sp<Image> TransactionControl::alienContainedDetain; sp<Image> TransactionControl::alienContainedKill; sp<Image> TransactionControl::scrollLeft; sp<Image> TransactionControl::scrollRight; sp<Image> TransactionControl::transactionShade; sp<BitmapFont> TransactionControl::labelFont; bool TransactionControl::resourcesInitialised = false; void TransactionControl::initResources() { bgLeft = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 45)); bgRight = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 46)); purchaseBoxIcon = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 47)); purchaseXComIcon = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 48)); purchaseArrow = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 52)); alienContainedDetain = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 75)); alienContainedKill = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 76)); scrollLeft = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 53)); scrollRight = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 54)); transactionShade = fw().data->loadImage("city/transaction-shade.png"); labelFont = ui().getFont("smalfont"); resourcesInitialised = true; } void TransactionControl::setScrollbarValues() { if (tradeState.getLeftIndex() == tradeState.getRightIndex()) { scrollBar->setMinimum(0); scrollBar->setMaximum(0); scrollBar->setValue(0); } else { scrollBar->setMinimum(0); scrollBar->setMaximum(tradeState.getLeftStock() + tradeState.getRightStock()); scrollBar->setValue(tradeState.getBalance()); } updateValues(); } void TransactionControl::setIndexLeft(int index) { tradeState.setLeftIndex(index); setScrollbarValues(); } void TransactionControl::setIndexRight(int index) { tradeState.setRightIndex(index); setScrollbarValues(); } void TransactionControl::updateValues() { if (scrollBar->getMaximum() != 0) { if (manufacturerHostile || manufacturerUnavailable) { int defaultRightStock = tradeState.getRightStock(); if ((tradeState.getLeftIndex() == ECONOMY_IDX && scrollBar->getValue() > defaultRightStock) || (tradeState.getRightIndex() == ECONOMY_IDX && scrollBar->getValue() < defaultRightStock)) { tradeState.cancelOrder(); scrollBar->setValue(tradeState.getBalance()); auto message_box = mksp<MessageBox>( manufacturerName, manufacturerHostile ? tr("Order canceled by the hostile manufacturer.") : tr("Manufacturer has no intact buildings in this city to " "deliver goods from."), MessageBox::ButtonOptions::Ok); fw().stageQueueCommand({StageCmd::Command::PUSH, message_box}); return; } } // TODO: remove linked if (tradeState.getBalance() != scrollBar->getValue()) { tradeState.setBalance(scrollBar->getValue()); if (linked) { for (auto &c : *linked) { if (auto c_sp = c.lock()) { c_sp->suspendUpdates = true; c_sp->scrollBar->setValue(scrollBar->getValue()); c_sp->updateValues(); c_sp->suspendUpdates = false; } } } if (!suspendUpdates) { this->pushFormEvent(FormEventType::ScrollBarChange, nullptr); } } } int curDeltaRight = tradeState.getLROrder(); int curDeltaLeft = -curDeltaRight; stockLeft->setText(format("%d", tradeState.getLeftStock(true))); stockRight->setText(format("%d", tradeState.getRightStock(true))); deltaLeft->setText(format("%s%d", curDeltaLeft > 0 ? "+" : "", curDeltaLeft)); deltaRight->setText(format("%s%d", curDeltaRight > 0 ? "+" : "", curDeltaRight)); deltaLeft->setVisible(tradeState.getLeftIndex() != ECONOMY_IDX && curDeltaLeft != 0); deltaRight->setVisible(tradeState.getRightIndex() != ECONOMY_IDX && curDeltaRight != 0); setDirty(); } void TransactionControl::link(sp<TransactionControl> c1, sp<TransactionControl> c2) { if (c1->linked && c2->linked) { LogError("Cannot link two already linked transaction controls!"); return; } if (!c2->linked) { if (!c1->linked) { c1->linked = mksp<std::list<wp<TransactionControl>>>(); c1->linked->emplace_back(c1); } c1->linked->emplace_back(c2); c2->linked = c1->linked; } if (!c1->linked && c2->linked) { c2->linked->emplace_back(c1); c1->linked = c2->linked; } // we assume c1 is older than c2, so we update c2 to match c1 c2->scrollBar->setValue(c1->scrollBar->getValue()); c2->updateValues(); } const sp<std::list<wp<TransactionControl>>> &TransactionControl::getLinked() const { return linked; } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<Agent> agent, int indexLeft, int indexRight) { // The agent or agent's vehicle should be on a base auto currentBuilding = agent->currentVehicle ? agent->currentVehicle->currentBuilding : agent->currentBuilding; if (!currentBuilding || !currentBuilding->base) { return nullptr; } std::vector<int> initialStock; // Fill out stock { initialStock.resize(9); // Stock of agents always zero on all bases except where it belongs int baseIndex = 0; for (auto &b : state.player_bases) { if (b.first == agent->homeBuilding->base.id) { initialStock[baseIndex] = 1; break; } baseIndex++; } } Type type; switch (agent->type->role) { case AgentType::Role::BioChemist: type = Type::BioChemist; break; case AgentType::Role::Engineer: type = Type::Engineer; break; case AgentType::Role::Physicist: type = Type::Physicist; break; case AgentType::Role::Soldier: type = Type::Soldier; break; default: LogError("Unknown type of agent %s.", agent.id); } int price = 0; int storeSpace = 0; bool isAmmo = false; bool isBio = false; bool isPerson = true; bool researched = true; auto manufacturer = agent->owner; bool manufacturerHostile = false; bool manufacturerUnavailable = false; return createControl(agent.id, type, agent->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<AEquipmentType> agentEquipmentType, int indexLeft, int indexRight) { bool isBio = agentEquipmentType->bioStorage; int price = 0; int storeSpace = agentEquipmentType->store_space; bool researched = isBio ? true : state.research.isComplete(agentEquipmentType); std::vector<int> initialStock; bool hasStock = false; // Fill out stock { initialStock.resize(9); int baseIndex = 0; for (auto &b : state.player_bases) { int divisor = (agentEquipmentType->type == AEquipmentType::Type::Ammo && !isBio) ? agentEquipmentType->max_ammo : 1; initialStock[baseIndex] = isBio ? b.second->inventoryBioEquipment[agentEquipmentType.id] : b.second->inventoryAgentEquipment[agentEquipmentType.id]; initialStock[baseIndex] = (initialStock[baseIndex] + divisor - 1) / divisor; if (initialStock[baseIndex] > 0) { hasStock = true; } baseIndex++; } } // Fill out economy data if (!agentEquipmentType->bioStorage) { bool economyUnavailable = true; if (state.economy.find(agentEquipmentType.id) != state.economy.end()) { auto &economy = state.economy[agentEquipmentType.id]; int week = state.gameTime.getWeek(); initialStock[ECONOMY_IDX] = economy.currentStock; price = economy.currentPrice; economyUnavailable = economy.weekAvailable == 0 || economy.weekAvailable > week || !researched; } if (!hasStock && economyUnavailable) { return nullptr; } } else if (!hasStock) { return nullptr; } auto manufacturer = agentEquipmentType->manufacturer; bool isAmmo = agentEquipmentType->type == AEquipmentType::Type::Ammo; bool isPerson = false; auto canBuy = isBio ? Organisation::PurchaseResult::OK : agentEquipmentType->manufacturer->canPurchaseFrom( state, state.current_base->building, false); bool manufacturerHostile = canBuy == Organisation::PurchaseResult::OrgHostile; bool manufacturerUnavailable = manufacturer != state.getPlayer() && canBuy == Organisation::PurchaseResult::OrgHasNoBuildings; return createControl(agentEquipmentType.id, isBio ? Type::AgentEquipmentBio : Type::AgentEquipmentCargo, agentEquipmentType->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<VEquipmentType> vehicleEquipmentType, int indexLeft, int indexRight) { int price = 0; int storeSpace = vehicleEquipmentType->store_space; bool researched = state.research.isComplete(vehicleEquipmentType); std::vector<int> initialStock; bool hasStock = false; // Fill out stock { initialStock.resize(9); int baseIndex = 0; for (auto &b : state.player_bases) { initialStock[baseIndex] = b.second->inventoryVehicleEquipment[vehicleEquipmentType.id]; if (initialStock[baseIndex] > 0) { hasStock = true; } baseIndex++; } } // Fill out economy data { bool economyUnavailable = true; if (state.economy.find(vehicleEquipmentType.id) != state.economy.end()) { auto &economy = state.economy[vehicleEquipmentType.id]; int week = state.gameTime.getWeek(); initialStock[ECONOMY_IDX] = economy.currentStock; price = economy.currentPrice; economyUnavailable = economy.weekAvailable == 0 || economy.weekAvailable > week || !researched; } if (!hasStock && economyUnavailable) { return nullptr; } } auto manufacturer = vehicleEquipmentType->manufacturer; bool isAmmo = false; bool isBio = false; bool isPerson = false; // Expecting all bases to be in one city auto canBuy = vehicleEquipmentType->manufacturer->canPurchaseFrom( state, state.current_base->building, false); bool manufacturerHostile = canBuy == Organisation::PurchaseResult::OrgHostile; bool manufacturerUnavailable = manufacturer != state.getPlayer() && canBuy == Organisation::PurchaseResult::OrgHasNoBuildings; return createControl(vehicleEquipmentType.id, Type::VehicleEquipment, vehicleEquipmentType->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<VAmmoType> vehicleAmmoType, int indexLeft, int indexRight) { int price = 0; int storeSpace = vehicleAmmoType->store_space; std::vector<int> initialStock; bool hasStock = false; // Fill out stock { initialStock.resize(9); int baseIndex = 0; for (auto &b : state.player_bases) { initialStock[baseIndex] = b.second->inventoryVehicleAmmo[vehicleAmmoType.id]; if (initialStock[baseIndex] > 0) { hasStock = true; } baseIndex++; } } // Fill out economy data { bool economyUnavailable = true; if (state.economy.find(vehicleAmmoType.id) != state.economy.end()) { auto &economy = state.economy[vehicleAmmoType.id]; int week = state.gameTime.getWeek(); initialStock[ECONOMY_IDX] = economy.currentStock; price = economy.currentPrice; economyUnavailable = economy.weekAvailable == 0 || economy.weekAvailable > week; } if (!hasStock && economyUnavailable) { return nullptr; } } auto manufacturer = vehicleAmmoType->manufacturer; bool isAmmo = true; bool isBio = false; bool isPerson = false; bool researched = true; // Expecting all bases to be in one city auto canBuy = vehicleAmmoType->manufacturer->canPurchaseFrom(state, state.current_base->building, false); bool manufacturerHostile = canBuy == Organisation::PurchaseResult::OrgHostile; bool manufacturerUnavailable = manufacturer != state.getPlayer() && canBuy == Organisation::PurchaseResult::OrgHasNoBuildings; return createControl(vehicleAmmoType.id, Type::VehicleAmmo, vehicleAmmoType->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<VehicleType> vehicleType, int indexLeft, int indexRight) { // No sense in transfer if (indexLeft != ECONOMY_IDX && indexRight != ECONOMY_IDX) { return nullptr; } int price = 0; int storeSpace = 0; std::vector<int> initialStock; // Fill out stock { initialStock.resize(9); // Stock of vehicle types always zero } // Fill out economy data { bool economyUnavailable = true; if (state.economy.find(vehicleType.id) != state.economy.end()) { auto &economy = state.economy[vehicleType.id]; int week = state.gameTime.getWeek(); initialStock[ECONOMY_IDX] = economy.currentStock; price = economy.currentPrice; economyUnavailable = economy.weekAvailable == 0 || economy.weekAvailable > week; } if (economyUnavailable) { return nullptr; } } auto manufacturer = vehicleType->manufacturer; bool isAmmo = false; bool isBio = false; bool isPerson = false; bool researched = true; // Expecting all bases to be in one city auto canBuy = vehicleType->manufacturer->canPurchaseFrom(state, state.current_base->building, true); bool manufacturerHostile = canBuy == Organisation::PurchaseResult::OrgHostile; bool manufacturerUnavailable = manufacturer != state.getPlayer() && canBuy == Organisation::PurchaseResult::OrgHasNoBuildings; return createControl(vehicleType.id, Type::VehicleType, vehicleType->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<Vehicle> vehicle, int indexLeft, int indexRight) { // Only parked on base vehicles can be sold if (!vehicle->currentBuilding || !vehicle->currentBuilding->base) { return nullptr; } int price = 0; int storeSpace = 0; std::vector<int> initialStock; // Fill out stock { initialStock.resize(9); // Stock of vehicle types always zero on all bases except where it belongs int baseIndex = 0; for (auto &b : state.player_bases) { if (b.first == vehicle->homeBuilding->base.id) { initialStock[baseIndex] = 1; break; } baseIndex++; } } // Fill out economy data { bool economyUnavailable = true; if (state.economy.find(vehicle->type.id) != state.economy.end()) { auto &economy = state.economy[vehicle->type.id]; int week = state.gameTime.getWeek(); price = economy.currentPrice; economyUnavailable = economy.weekAvailable == 0 || economy.weekAvailable > week; } if (economyUnavailable) { // Nothing, we can still sell it for parts or transfer! } } LogWarning("Vehicle type %s starting price %d", vehicle->type.id, price); // Add price of ammo and equipment for (auto &e : vehicle->equipment) { if (state.economy.find(e->type.id) != state.economy.end()) { price += state.economy[e->type.id].currentPrice; if (e->ammo > 0 && state.economy.find(e->type->ammo_type.id) != state.economy.end()) { price += e->ammo * state.economy[e->type->ammo_type.id].currentPrice; } LogWarning("Vehicle type %s price increased to %d after counting %s", vehicle->type.id, price, e->type.id); } } // Subtract price of default equipment for (auto &e : vehicle->type->initial_equipment_list) { if (state.economy.find(e.second.id) != state.economy.end()) { price -= state.economy[e.second.id].currentPrice; LogWarning("Vehicle type %s price decreased to %d after counting %s", vehicle->type.id, price, e.second.id); } } LogWarning("Vehicle type %s final price %d", vehicle->type.id, price); auto manufacturer = vehicle->type->manufacturer; bool isAmmo = false; bool isBio = false; bool isPerson = false; bool researched = true; bool manufacturerHostile = false; bool manufacturerUnavailable = false; return createControl(vehicle.id, Type::Vehicle, vehicle->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(const UString &id, Type type, const UString &name, StateRef<Organisation> manufacturer, bool isAmmo, bool isBio, bool isPerson, bool researched, bool manufacturerHostile, bool manufacturerUnavailable, int price, int storeSpace, std::vector<int> &initialStock, int indexLeft, int indexRight) { auto control = mksp<TransactionControl>(); control->itemId = id; control->itemType = type; control->manufacturer = manufacturer; control->isAmmo = isAmmo; control->isBio = isBio; control->isPerson = isPerson; control->researched = researched; control->manufacturerHostile = manufacturerHostile; control->manufacturerUnavailable = manufacturerUnavailable; control->storeSpace = storeSpace; control->tradeState.setInitialStock(std::forward<std::vector<int>>(initialStock)); control->tradeState.setLeftIndex(indexLeft); control->tradeState.setRightIndex(indexRight); // If we create a non-purchase control we never become one so clear the values if (isBio || !researched || (indexLeft != ECONOMY_IDX && indexRight != ECONOMY_IDX)) { control->manufacturerName = ""; control->price = 0; } else { control->manufacturerName = manufacturer->name; control->price = price; } // Setup vars control->Size = Vec2<int>{173 + 178 - 2, 47}; // Setup resources if (!resourcesInitialised) { initResources(); } // Add controls // Name const UString &labelName = researched ? tr(name) : tr("Alien Artifact"); if (labelName.length() > 0) { auto label = control->createChild<Label>(labelName, labelFont); label->Location = {isAmmo ? 32 : 11, 3}; label->Size = {256, 16}; label->TextHAlign = HorizontalAlignment::Left; label->TextVAlign = VerticalAlignment::Centre; } // Manufacturer if (control->manufacturerName.length() > 0) { auto label = control->createChild<Label>(tr(control->manufacturerName), labelFont); if (manufacturerHostile || manufacturerUnavailable) { label->Tint = {255, 50, 25}; } label->Location = {34, 3}; label->Size = {256, 16}; label->TextHAlign = HorizontalAlignment::Right; label->TextVAlign = VerticalAlignment::Centre; } // Price if (price != 0 && (indexLeft == ECONOMY_IDX || indexRight == ECONOMY_IDX)) { auto label = control->createChild<Label>(format("$%d", control->price), labelFont); label->Location = {290, 3}; label->Size = {47, 16}; label->TextHAlign = HorizontalAlignment::Right; label->TextVAlign = VerticalAlignment::Centre; } // Stock (values set in updateValues) control->stockLeft = control->createChild<Label>("", labelFont); control->stockLeft->Location = {11, 26}; control->stockLeft->Size = {32, 14}; control->stockLeft->TextHAlign = HorizontalAlignment::Right; control->stockLeft->TextVAlign = VerticalAlignment::Centre; control->stockRight = control->createChild<Label>("", labelFont); control->stockRight->Location = {303, 26}; control->stockRight->Size = {32, 14}; control->stockRight->TextHAlign = HorizontalAlignment::Right; control->stockRight->TextVAlign = VerticalAlignment::Centre; // Delta (values set in updateValues) control->deltaLeft = control->createChild<Label>("", labelFont); control->deltaLeft->Location = {50, 26}; control->deltaLeft->Size = {32, 14}; control->deltaLeft->TextHAlign = HorizontalAlignment::Right; control->deltaLeft->TextVAlign = VerticalAlignment::Centre; control->deltaRight = control->createChild<Label>("", labelFont); control->deltaRight->Location = {264, 26}; control->deltaRight->Size = {30, 14}; control->deltaRight->TextHAlign = HorizontalAlignment::Right; control->deltaRight->TextVAlign = VerticalAlignment::Centre; // ScrollBar control->scrollBar = control->createChild<ScrollBar>(); control->scrollBar->Location = {102, 24}; control->scrollBar->Size = {147, 20}; control->scrollBar->setMinimum(0); control->scrollBar->setMaximum(0); // ScrollBar buttons auto buttonScrollLeft = control->createChild<GraphicButton>(nullptr, scrollLeft); buttonScrollLeft->Size = scrollLeft->size; buttonScrollLeft->Location = {87, 24}; buttonScrollLeft->ScrollBarPrev = control->scrollBar; auto buttonScrollRight = control->createChild<GraphicButton>(nullptr, scrollRight); buttonScrollRight->Size = scrollRight->size; buttonScrollRight->Location = {247, 24}; buttonScrollRight->ScrollBarNext = control->scrollBar; // Callback control->setupCallbacks(); // Finally set the values control->setScrollbarValues(); return control; } void TransactionControl::setupCallbacks() { std::function<void(FormsEvent * e)> onScrollChange = [this](FormsEvent *) { if (!this->suspendUpdates) { this->updateValues(); } }; scrollBar->addCallback(FormEventType::ScrollBarChange, onScrollChange); } int TransactionControl::getCrewDelta(int index) const { return isPerson ? -tradeState.shipmentsTotal(index) : 0; } int TransactionControl::getCargoDelta(int index) const { return !isBio && !isPerson ? -tradeState.shipmentsTotal(index) * storeSpace : 0; } int TransactionControl::getBioDelta(int index) const { return isBio ? -tradeState.shipmentsTotal(index) * storeSpace : 0; } int TransactionControl::getPriceDelta() const { int delta = 0; for (int i = 0; i < 8; i++) { delta += tradeState.shipmentsTotal(i) * price; } return delta; } void TransactionControl::onRender() { Control::onRender(); static Vec2<int> bgLeftPos = {0, 2}; static Vec2<int> bgRightPos = {172, 2}; static Vec2<int> ammoPos = {4, 2}; static Vec2<int> iconLeftPos = {58, 24}; static Vec2<int> iconRightPos = {270, 24}; static Vec2<int> iconSize = {22, 20}; // Draw BG fw().renderer->draw(bgLeft, bgLeftPos); fw().renderer->draw(bgRight, bgRightPos); // Draw Ammo Arrow if (isAmmo) { fw().renderer->draw(purchaseArrow, ammoPos); } // Draw Icons if (!deltaLeft->isVisible()) { sp<Image> icon; if (isBio) { icon = tradeState.getLeftIndex() == ECONOMY_IDX ? alienContainedKill : alienContainedDetain; } else { icon = tradeState.getLeftIndex() == ECONOMY_IDX ? purchaseBoxIcon : purchaseXComIcon; } auto iconPos = iconLeftPos + (iconSize - (Vec2<int>)icon->size) / 2; fw().renderer->draw(icon, iconPos); } if (!deltaRight->isVisible()) { sp<Image> icon; if (isBio) { icon = tradeState.getRightIndex() == ECONOMY_IDX ? alienContainedKill : alienContainedDetain; } else { icon = tradeState.getRightIndex() == ECONOMY_IDX ? purchaseBoxIcon : purchaseXComIcon; } auto iconPos = iconRightPos + (iconSize - (Vec2<int>)icon->size) / 2; fw().renderer->draw(icon, iconPos); } } void TransactionControl::postRender() { Control::postRender(); // Draw shade if inactive static Vec2<int> shadePos = {0, 0}; if (tradeState.getLeftIndex() == tradeState.getRightIndex() || (tradeState.getLeftStock() == 0 && tradeState.getRightStock() == 0)) { fw().renderer->draw(transactionShade, shadePos); } } void TransactionControl::unloadResources() { bgLeft.reset(); bgRight.reset(); purchaseBoxIcon.reset(); purchaseXComIcon.reset(); purchaseArrow.reset(); alienContainedDetain.reset(); alienContainedKill.reset(); scrollLeft.reset(); scrollRight.reset(); transactionShade.reset(); Control::unloadResources(); } /** * Get the sum of shipment orders from the base (economy). * @param from - 0-7 for bases, 8 for economy * @param exclude - 0-7 for bases, 8 for economy, -1 don't exclude (by default) * @return - sum of shipment orders */ int TransactionControl::Trade::shipmentsFrom(const int from, const int exclude) const { int total = 0; if (shipments.find(from) != shipments.end()) { for (auto &s : shipments.at(from)) { if (s.first != exclude && s.second > 0) { total += s.second; } } } return total; } /** * Get total shipment orders from(+) and to(-) the base (economy). * @param baseIdx - 0-7 for bases, 8 for economy * @return - total sum of shipment orders */ int TransactionControl::Trade::shipmentsTotal(const int baseIdx) const { int total = 0; if (shipments.find(baseIdx) != shipments.end()) { for (auto &s : shipments.at(baseIdx)) { total += s.second; } } return total; } /** * Get shipment order. * @param from - 0-7 for bases, 8 for economy * @param to - 0-7 for bases, 8 for economy * @return - the shipment order */ int TransactionControl::Trade::getOrder(const int from, const int to) const { if (shipments.find(from) != shipments.end()) { auto &order = shipments.at(from); if (order.find(to) != order.end()) { return order.at(to); } } return 0; } /** * Cancel shipment order. * @param from - 0-7 for bases, 8 for economy * @param to - 0-7 for bases, 8 for economy */ void TransactionControl::Trade::cancelOrder(const int from, const int to) { if (shipments.find(from) != shipments.end()) { shipments.at(from).erase(to); if (shipments.at(from).empty()) shipments.erase(from); } if (shipments.find(to) != shipments.end()) { shipments.at(to).erase(from); if (shipments.at(to).empty()) shipments.erase(to); } } /** * Get current stock. * @param baseIdx - index of the base (economy) * @param oppositeIdx - index of the opposite base (economy) * @param currentStock - true for current, false for default (by default) * @return - the stock */ int TransactionControl::Trade::getStock(const int baseIdx, const int oppositeIdx, bool currentStock) const { return initialStock[baseIdx] - shipmentsFrom(baseIdx, oppositeIdx) - (currentStock ? getOrder(baseIdx, oppositeIdx) : 0); } /** * ScrollBar support. Set current value. * @param balance - scrollBar->getValue() * @return - order from left to right side */ int TransactionControl::Trade::setBalance(const int balance) { int orderLR = balance - getRightStock(); if (orderLR == 0) { cancelOrder(); } else { shipments[leftIdx][rightIdx] = orderLR; shipments[rightIdx][leftIdx] = -orderLR; } return orderLR; } }; // namespace OpenApoc
FranciscoDA/OpenApoc
forms/transactioncontrol.cpp
C++
mit
29,041
<?php namespace Upc\Cards\Bundle\CardsBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Upc\Cards\Bundle\CardsBundle\Entity\GroupCategory; use Symfony\Component\HttpFoundation\Request; /** * Description of CategoriaCrudController * * @author javier olivares */ class GroupCategoryCrudController extends Controller { /** * @Route("/", name="admin_gcategorias_list") * @Template("") */ public function listAction(Request $request) { $form = $this->createForm('gcategory_search', null); $form->handleRequest($request); $criteria = $form->getData() ? $form->getData() : array(); foreach ($criteria as $key => $value) { if (!$value) { unset($criteria[$key]); } } $em = $this->getDoctrine() ->getRepository('CardsBundle:GroupCategory'); $query = $em->findBy($criteria); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $this->get('request')->query->get('page', 1)/* page number */, 5/* limit per page */ ); return array( 'pagination' => $pagination, 'form' => $form->createView() ); } /** * @Route("/add", name="admin_gcategorias_add") * @Template("") */ public function newAction(Request $request) { $object = new GroupCategory(); $object->setCreatedAt( new \DateTime("now")); $form = $this->createForm('group_category', $object); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($object); $em->flush(); $this->get('session')->getFlashBag()->add( 'gcategoria', 'Registro grabado satisfactoriamente' ); $nextAction = $form->get('saveAndAdd')->isClicked() ? 'admin_gcategorias_add' : 'admin_gcategorias_list'; return $this->redirect($this->generateUrl($nextAction)); } return array( 'form' => $form->createView() ); } /** * @Route("/{pk}", name="admin_gcategorias_edit") * @Template("") */ public function editAction(Request $request, $pk) { $object = $this->getDoctrine()->getRepository('CardsBundle:GroupCategory')->find($pk); $form = $this->createForm('group_category', $object); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($object); $em->flush(); $this->get('session')->getFlashBag()->add( 'gcategoria', 'Registro modificado satisfactoriamente' ); $nextAction = $form->get('saveAndAdd')->isClicked() ? 'admin_gcategorias_add' : 'admin_gcategorias_list'; return $this->redirect($this->generateUrl($nextAction)); } return array( 'form' => $form->createView() ); } } ?>
devupc/cards
src/Upc/Cards/Bundle/CardsBundle/Controller/GroupCategoryCrudController.php
PHP
mit
3,369
var map; var infoWindow; // A variável markersData guarda a informação necessária a cada marcador // Para utilizar este código basta alterar a informação contida nesta variável var markersData = [ { lat: -3.741262, lng: -38.539389, nome: "Campus do Pici - Universidade Federal do Ceará", endereco:"Av. Mister Hull, s/n", telefone: "(85) 3366-9500" // não colocar virgula no último item de cada maracdor }, { lat: -3.780833, lng: -38.469656, nome: "Colosso Lake Lounge", endereco:"Rua Hermenegildo Sá Cavalcante, s/n", telefone: "(85) 98160-0088" // não colocar virgula no último item de cada maracdor } // não colocar vírgula no último marcador ]; function initialize() { var mapOptions = { center: new google.maps.LatLng(40.601203,-8.668173), zoom: 9, mapTypeId: 'roadmap', }; map = new google.maps.Map(document.getElementById('map-slackline'), mapOptions); // cria a nova Info Window com referência à variável infowindow // o conteúdo da Info Window será atribuído mais tarde infoWindow = new google.maps.InfoWindow(); // evento que fecha a infoWindow com click no mapa google.maps.event.addListener(map, 'click', function() { infoWindow.close(); }); // Chamada para a função que vai percorrer a informação // contida na variável markersData e criar os marcadores a mostrar no mapa displayMarkers(); } google.maps.event.addDomListener(window, 'load', initialize); // Esta função vai percorrer a informação contida na variável markersData // e cria os marcadores através da função createMarker function displayMarkers(){ // esta variável vai definir a área de mapa a abranger e o nível do zoom // de acordo com as posições dos marcadores var bounds = new google.maps.LatLngBounds(); // Loop que vai estruturar a informação contida em markersData // para que a função createMarker possa criar os marcadores for (var i = 0; i < markersData.length; i++){ var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng); var nome = markersData[i].nome; var endereco = markersData[i].endereco; var telefone = markersData[i].telefone; createMarker(latlng, nome, endereco, telefone); // Os valores de latitude e longitude do marcador são adicionados à // variável bounds bounds.extend(latlng); } // Depois de criados todos os marcadores // a API através da sua função fitBounds vai redefinir o nível do zoom // e consequentemente a área do mapa abrangida. map.fitBounds(bounds); } // Função que cria os marcadores e define o conteúdo de cada Info Window. function createMarker(latlng, nome, endereco, telefone){ var marker = new google.maps.Marker({ map: map, position: latlng, title: nome }); // Evento que dá instrução à API para estar alerta ao click no marcador. // Define o conteúdo e abre a Info Window. google.maps.event.addListener(marker, 'click', function() { // Variável que define a estrutura do HTML a inserir na Info Window. var iwContent = '<div id="iw_container">' + '<div class="iw_title">' + nome + '</div>' + '<div class="iw_content">' + endereco + '<br />' + telefone + '<br />'; // O conteúdo da variável iwContent é inserido na Info Window. infoWindow.setContent(iwContent); // A Info Window é aberta. infoWindow.open(map, marker); }); }
KatharineAmaral29/ArenaSports
js/mapslackline.js
JavaScript
mit
3,584
<?php require_once(APPPATH . 'views/header.php'); ?> <link rel="stylesheet" href="<?= base_url(); ?>assets/css/fullcalendar.css" /> <link rel="stylesheet" href="<?= base_url(); ?>css/mine.css" /> <style> .form-horizontal .controls { margin-left: 12px; } </style> <div class="page-content"> <div class="row-fluid"> <iframe id="frame" name="frame" frameborder="no" border="0" scrolling="no" height="750" width="450" class="span12" src="<?php echo base_url() . "index.php/management/"; ?>"> </iframe> <div class="row-fluid"> <div id="accordion2" class="accordion"> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseOne"> <div class="accordion-inner"> <div class="row-fluid"> <div class="span12"> <!--PAGE CONTENT BEGINS--> <form class="form-horizontal" > <div class="alert alert-block alert-info span6"> <div class="widget-main"> <input type="file" id="id-input-file-2" /> <input multiple="" type="file" id="id-input-file-3" /> <label> <input type="checkbox" name="file-format" id="id-file-format" /> <span class="lbl"> Allow only images</span> </label> </div> <div class="control-group"> <label class="control-label" for="form-field-username">First name</label> <div class="controls"> <input type="text" id="form-field-username" placeholder="First name" value="<?php echo 'name'; ?>" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-first">Last name</label> <div class="controls"> <input class="input-small" type="text" id="form-field-first" placeholder="First Name" /> <input class="input-small" type="text" id="form-field-last" placeholder="Othername" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-tags">Please enter your emails one by one</label> <div class="controls"> <label class="text-error">enter primary e-mail first</label> <input type="text" name="tags" id="form-field-tags" placeholder="info@gmail.com" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-tags">Please enter your contacts one by one</label> <div class="controls"> <label class="text-error">enter primary contact first</label> <input type="text" name="tags" id="form-field-tags" placeholder="+2567893213394" /> </div> </div></div> <div class="alert alert-block alert-info span6"> <div class="control-group"> <label class="control-label" for="form-field-sex">Sex</label> <div class="controls"> <select data-placeholder="Choose a sex..."> <option value="" /> <option value="male" />male <option value="female" />female </select> </div> </div> <div class="control-group"> <label class="control-label" for="id-date-picker-1">Date of Birth</label> <div class="controls"> <input class="date-picker" id="id-date-picker-1" type="text" data-date-format="dd-mm-yyyy" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-sex">Location</label> <div class="controls" id="locationField"> <input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text"></input> </div> </div> <div class="control-group"> <label class="control-label" for="id-date-picker-1">Country</label> <div class="controls"> <div class="controls" id="address"> <input id="country" type="text" /> <input class="field" id="street_number" type="hidden" disabled="true"></input> <input class="field" id="route"type="hidden" disabled="true"></input> <input class="field" id="locality" type="hidden" disabled="true"></input> <input class="field" type="hidden" id="administrative_area_level_1" disabled="true"></input> <input class="field" type="hidden" id="postal_code"></input> </div> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-pass1">New Password</label> <div class="controls"> <input type="password" id="form-field-pass1" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-pass2">Confirm Password</label> <div class="controls"> <input type="password" id="form-field-pass2" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div></div> </div><!--PAGE CONTENT ENDS--> </div><!--/.span--> </div><!--/.row-fluid--> <div class="accordion-group"> <div class="accordion-body collapse " id="collapseTwo"> <div class="accordion-inner"> <div class="widget-box"> <div class="widget-header header-color-blue"> <h5 class="bigger lighter"> <i class="icon-table"></i> Users and cohorts </h5> <div class="widget-toolbar widget-toolbar-light no-border"> <select id="simple-colorpicker-1" class="hide"> <option selected="" data-class="blue" value="#307ECC" />#307ECC <option data-class="blue2" value="#5090C1" />#5090C1 <option data-class="blue3" value="#6379AA" />#6379AA <option data-class="green" value="#82AF6F" />#82AF6F <option data-class="green2" value="#2E8965" />#2E8965 <option data-class="green3" value="#5FBC47" />#5FBC47 <option data-class="red" value="#E2755F" />#E2755F <option data-class="red2" value="#E04141" />#E04141 <option data-class="red3" value="#D15B47" />#D15B47 <option data-class="orange" value="#FFC657" />#FFC657 <option data-class="purple" value="#7E6EB0" />#7E6EB0 <option data-class="pink" value="#CE6F9E" />#CE6F9E <option data-class="dark" value="#404040" />#404040 <option data-class="grey" value="#848484" />#848484 <option data-class="default" value="#EEE" />#EEE </select> </div> </div> <div class="widget-body"> <div class="widget-main no-padding"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th> <i class="icon-user"></i> User </th> <th> <i>@</i> Email </th> <th class="hidden-480">Status</th> </tr> </thead> <tbody> <tr> <td class="">Alex</td> <td> <a href="#">alex@email.com</a> </td> <td class="hidden-480"> <span class="label label-warning">Pending</span> </td> </tr> <tr> <td class="">Fred</td> <td> <a href="#">fred@email.com</a> </td> <td class="hidden-480"> <span class="label label-success arrowed-in arrowed-in-right">Approved</span> </td> </tr> <tr> <td class="">Jack</td> <td> <a href="#">jack@email.com</a> </td> <td class="hidden-480"> <span class="label label-warning">Pending</span> </td> </tr> <tr> <td class="">John</td> <td> <a href="#">john@email.com</a> </td> <td class="hidden-480"> <span class="label label-inverse arrowed">Blocked</span> </td> </tr> <tr> <td class="">James</td> <td> <a href="#">james@email.com</a> </td> <td class="hidden-480"> <span class="label label-info arrowed-in arrowed-in-right">Online</span> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseTracks"> <div class="accordion-inner"> <form class="form-horizontal" > <div class="alert alert-block alert-info span6"> <div class="control-group"> <label class="control-label" for="form-field-username">Name</label> <div class="controls"> <input type="text" id="form-field-username" placeholder="" value="" /> </div> </div> <label for="form-field-8">Details</label> <textarea class="span12" id="form-field-8" placeholder="Default Text"></textarea> <div class="control-group"> <label class="control-label" for="id-date-picker-1">Date of Registration</label> <div class="controls"> <input class="date-picker" id="id-date-picker-1" type="text" data-date-format="dd-mm-yyyy" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div> </div> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseCohorts"> <div class="accordion-inner"> <form class="form-horizontal" > <div class="alert alert-block alert-info span6"> <div class="control-group"> <label class="control-label" for="form-field-username">Name</label> <div class="controls"> <input type="text" id="form-field-username" placeholder="" value="" /> </div> </div> <label for="form-field-8">Details</label> <textarea class="span12" id="form-field-8" placeholder="Default Text"></textarea> <div class="control-group"> <label class="control-label" for="id-date-picker-1">Date of Registration</label> <div class="controls"> <input class="date-picker" id="id-date-picker-1" type="text" data-date-format="dd-mm-yyyy" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div> </div> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseAdverts"> <div class="accordion-inner"> <form class="form-horizontal" > <div class="alert alert-block alert-info span6"> <div class="widget-main"> <input type="file" id="id-input-file-2" /> <input multiple="" type="file" id="id-input-file-3" /> <label> <input type="checkbox" name="file-format" id="id-file-format" /> <span class="lbl"> Allow only images</span> </label> </div> <div class="control-group"> <label class="control-label" for="form-field-username">Title</label> <div class="controls"> <input type="text" id="form-field-username" placeholder="" value="" /> </div> </div> <div class="control-group"> <label class="control-label" for="id-date-picker-1">Date of Display</label> <div class="controls"> <input class="date-picker" id="id-date-picker-1" type="text" data-date-format="dd-mm-yyyy" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div> </div> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseCountry"> <div class="accordion-inner"> <form class="form-horizontal" > <div class="alert alert-block alert-success span6"> <div class="control-group"> <label class="control-label" for="form-field-tags">Select the country flag</label> <div class="controls"> <input type="file" id="id-input-file-2" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-tags">Country name</label> <div class="controls"> <input type="text" name="tags" id="form-field-tags" placeholder="Uganda" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div> </div> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseUser"> <div class="accordion-inner"> <form class="form-horizontal" > <div class="alert alert-block alert-success span6"> <div class="control-group"> <label class="control-label" for="form-field-username">First name</label> <div class="controls"> <input type="text" id="form-field-username" placeholder="First name" value="<?php echo 'name'; ?>" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-first">Last name</label> <div class="controls"> <input class="input-small" type="text" id="form-field-first" placeholder="First Name" /> <input class="input-small" type="text" id="form-field-last" placeholder="Othername" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-tags">E-mail</label> <div class="controls"> <input type="text" name="tags" id="form-field-tags" placeholder="info@gmail.com" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-tags">Contacts</label> <div class="controls"> <input type="text" name="tags" id="form-field-tags" placeholder="+2567893213394" /> </div> </div></div> <div class="alert alert-block alert-info span6"> <div class="control-group"> <label class="control-label" for="form-field-sex">Location</label> <div class="controls" id="locationField"> <input id="autocomplete" placeholder="Select your country" type="text"></input> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-pass1">New Password</label> <div class="controls"> <input type="password" id="form-field-pass1" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-pass2">Confirm Password</label> <div class="controls"> <input type="password" id="form-field-pass2" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div><!--/span--> </div><!--/row--> </div><!--/.page-content--> <div class="ace-settings-container" id="ace-settings-container"> <div class="btn btn-app btn-mini btn-warning ace-settings-btn" id="ace-settings-btn"> <i class="icon-cog bigger-150"></i> </div> <div class="ace-settings-box" id="ace-settings-box"> <div> <div class="pull-left"> <select id="skin-colorpicker" class="hide"> <option data-class="default" value="#438EB9" />#438EB9 <option data-class="skin-1" value="#222A2D" />#222A2D <option data-class="skin-2" value="#C6487E" />#C6487E <option data-class="skin-3" value="#D0D0D0" />#D0D0D0 </select> </div> <span>&nbsp; Choose Skin</span> </div> <div> <input type="checkbox" class="ace-checkbox-2" id="ace-settings-header" /> <label class="lbl" for="ace-settings-header"> Fixed Header</label> </div> <div> <input type="checkbox" class="ace-checkbox-2" id="ace-settings-sidebar" /> <label class="lbl" for="ace-settings-sidebar"> Fixed Sidebar</label> </div> <div> <input type="checkbox" class="ace-checkbox-2" id="ace-settings-breadcrumbs" /> <label class="lbl" for="ace-settings-breadcrumbs"> Fixed Breadcrumbs</label> </div> <div> <input type="checkbox" class="ace-checkbox-2" id="ace-settings-rtl" /> <label class="lbl" for="ace-settings-rtl"> Right To Left (rtl)</label> </div> </div> </div><!--/#ace-settings-container--> </div><!--/.main-content--> <?php require_once(APPPATH . 'views/footer.php'); ?> <script type="text/javascript"> $(function () { $('#id-disable-check').on('click', function () { var inp = $('#form-input-readonly').get(0); if (inp.hasAttribute('disabled')) { inp.setAttribute('readonly', 'true'); inp.removeAttribute('disabled'); inp.value = "This text field is readonly!"; } else { inp.setAttribute('disabled', 'disabled'); inp.removeAttribute('readonly'); inp.value = "This text field is disabled!"; } }); $(".chzn-select").chosen(); $('[data-rel=tooltip]').tooltip({container: 'body'}); $('[data-rel=popover]').popover({container: 'body'}); $('textarea[class*=autosize]').autosize({append: "\n"}); $('textarea[class*=limited]').each(function () { var limit = parseInt($(this).attr('data-maxlength')) || 100; $(this).inputlimiter({ "limit": limit, remText: '%n character%s remaining...', limitText: 'max allowed : %n.' }); }); $.mask.definitions['~'] = '[+-]'; $('.input-mask-date').mask('99/99/9999'); $('.input-mask-phone').mask('(999) 999-9999'); $('.input-mask-eyescript').mask('~9.99 ~9.99 999'); $(".input-mask-product").mask("a*-999-a999", {placeholder: " ", completed: function () { alert("You typed the following: " + this.val()); }}); $("#input-size-slider").css('width', '200px').slider({ value: 1, range: "min", min: 1, max: 6, step: 1, slide: function (event, ui) { var sizing = ['', 'input-mini', 'input-small', 'input-medium', 'input-large', 'input-xlarge', 'input-xxlarge']; var val = parseInt(ui.value); $('#form-field-4').attr('class', sizing[val]).val('.' + sizing[val]); } }); $("#input-span-slider").slider({ value: 1, range: "min", min: 1, max: 11, step: 1, slide: function (event, ui) { var val = parseInt(ui.value); $('#form-field-5').attr('class', 'span' + val).val('.span' + val).next().attr('class', 'span' + (12 - val)).val('.span' + (12 - val)); } }); $("#slider-range").css('height', '200px').slider({ orientation: "vertical", range: true, min: 0, max: 100, values: [17, 67], slide: function (event, ui) { var val = ui.values[$(ui.handle).index() - 1] + ""; if (!ui.handle.firstChild) { $(ui.handle).append("<div class='tooltip right in' style='display:none;left:15px;top:-8px;'><div class='tooltip-arrow'></div><div class='tooltip-inner'></div></div>"); } $(ui.handle.firstChild).show().children().eq(1).text(val); } }).find('a').on('blur', function () { $(this.firstChild).hide(); }); $("#slider-range-max").slider({ range: "max", min: 1, max: 10, value: 2 }); $("#eq > span").css({width: '90%', 'float': 'left', margin: '15px'}).each(function () { // read initial values from markup and remove that var value = parseInt($(this).text(), 10); $(this).empty().slider({ value: value, range: "min", animate: true }); }); $('#id-input-file-1 , #id-input-file-2').ace_file_input({ no_file: 'No File ...', btn_choose: 'Choose', btn_change: 'Change', droppable: false, onchange: null, thumbnail: false //| true | large //whitelist:'gif|png|jpg|jpeg' //blacklist:'exe|php' //onchange:'' // }); $('#id-input-file-3').ace_file_input({ style: 'well', btn_choose: 'Drop files here or click to choose', btn_change: null, no_icon: 'icon-cloud-upload', droppable: true, thumbnail: 'small' //,icon_remove:null//set null, to hide remove/reset button /**,before_change:function(files, dropped) { //Check an example below //or examples/file-upload.html return true; }*/ /**,before_remove : function() { return true; }*/ , preview_error: function (filename, error_code) { //name of the file that failed //error_code values //1 = 'FILE_LOAD_FAILED', //2 = 'IMAGE_LOAD_FAILED', //3 = 'THUMBNAIL_FAILED' //alert(error_code); } }).on('change', function () { //console.log($(this).data('ace_input_files')); //console.log($(this).data('ace_input_method')); }); //dynamically change allowed formats by changing before_change callback function $('#id-file-format').removeAttr('checked').on('change', function () { var before_change var btn_choose var no_icon if (this.checked) { btn_choose = "Drop images here or click to choose"; no_icon = "icon-picture"; before_change = function (files, dropped) { var allowed_files = []; for (var i = 0; i < files.length; i++) { var file = files[i]; if (typeof file === "string") { //IE8 and browsers that don't support File Object if (!(/\.(jpe?g|png|gif|bmp)$/i).test(file)) return false; } else { var type = $.trim(file.type); if ((type.length > 0 && !(/^image\/(jpe?g|png|gif|bmp)$/i).test(type)) || (type.length == 0 && !(/\.(jpe?g|png|gif|bmp)$/i).test(file.name))//for android's default browser which gives an empty string for file.type ) continue;//not an image so don't keep this file } allowed_files.push(file); } if (allowed_files.length == 0) return false; return allowed_files; } } else { btn_choose = "Drop files here or click to choose"; no_icon = "icon-cloud-upload"; before_change = function (files, dropped) { return files; } } var file_input = $('#id-input-file-3'); file_input.ace_file_input('update_settings', {'before_change': before_change, 'btn_choose': btn_choose, 'no_icon': no_icon}) file_input.ace_file_input('reset_input'); }); $('#spinner1').ace_spinner({value: 0, min: 0, max: 200, step: 10, btn_up_class: 'btn-info', btn_down_class: 'btn-info'}) .on('change', function () { //alert(this.value) }); $('#spinner2').ace_spinner({value: 0, min: 0, max: 10000, step: 100, icon_up: 'icon-caret-up', icon_down: 'icon-caret-down'}); $('#spinner3').ace_spinner({value: 0, min: -100, max: 100, step: 10, icon_up: 'icon-plus', icon_down: 'icon-minus', btn_up_class: 'btn-success', btn_down_class: 'btn-danger'}); $('.date-picker').datepicker().next().on(ace.click_event, function () { $(this).prev().focus(); }); $('#id-date-range-picker-1').daterangepicker().prev().on(ace.click_event, function () { $(this).next().focus(); }); $('#timepicker1').timepicker({ minuteStep: 1, showSeconds: true, showMeridian: false }) $('#colorpicker1').colorpicker(); $('#simple-colorpicker-1').ace_colorpicker(); $(".knob").knob(); //we could just set the data-provide="tag" of the element inside HTML, but IE8 fails! var tag_input = $('#form-field-tags'); if (!(/msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase()))) tag_input.tag({placeholder: tag_input.attr('placeholder')}); else { //display a textarea for old IE, because it doesn't support this plugin or another one I tried! tag_input.after('<textarea id="' + tag_input.attr('id') + '" name="' + tag_input.attr('name') + '" rows="3">' + tag_input.val() + '</textarea>').remove(); //$('#form-field-tags').autosize({append: "\n"}); } ///////// $('#modal-form input[type=file]').ace_file_input({ style: 'well', btn_choose: 'Drop files here or click to choose', btn_change: null, no_icon: 'icon-cloud-upload', droppable: true, thumbnail: 'large' }) //chosen plugin inside a modal will have a zero width because the select element is originally hidden //and its width cannot be determined. //so we set the width after modal is show $('#modal-form').on('show', function () { $(this).find('.chzn-container').each(function () { $(this).find('a:first-child').css('width', '200px'); $(this).find('.chzn-drop').css('width', '210px'); $(this).find('.chzn-search input').css('width', '200px'); }); }) /** //or you can activate the chosen plugin after modal is shown //this way select element has a width now and chosen works as expected $('#modal-form').on('shown', function () { $(this).find('.modal-chosen').chosen(); }) */ }); </script>
WereDouglas/epitrack
application/views/management.php
PHP
mit
41,131
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; function _default() { return function ({ addUtilities, variants }) { addUtilities({ '.bg-clip-border': { 'background-clip': 'border-box' }, '.bg-clip-padding': { 'background-clip': 'padding-box' }, '.bg-clip-content': { 'background-clip': 'content-box' }, '.bg-clip-text': { 'background-clip': 'text' } }, variants('backgroundClip')); }; }
matryer/bitbar
xbarapp.com/node_modules/tailwindcss/lib/plugins/backgroundClip.js
JavaScript
mit
550
{% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}New Company Record{%endblock%} {% block container %} <div class="formbox" style="padding-top: 60px; padding-left: 15px;"> <form class="form" action="." method="POST"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary">{% if object %}Update{% else %}Create{% endif %}</button> </form> </div> {% endblock %}
mtheobaldo/crm
src/CRM/templates/CRM/company_form.html
HTML
mit
403
var gulp = require('gulp'); var karma = require('karma').server; var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var path = require('path'); var plumber = require('gulp-plumber'); var runSequence = require('run-sequence'); var jshint = require('gulp-jshint'); /** * File patterns **/ // Root directory var rootDirectory = path.resolve('./'); // Source directory for build process var sourceDirectory = path.join(rootDirectory, './src'); var sourceFiles = [ // Make sure module files are handled first path.join(sourceDirectory, '/**/*.module.js'), // Then add all JavaScript files path.join(sourceDirectory, '/**/*.js') ]; var lintFiles = [ 'gulpfile.js', // Karma configuration 'karma-*.conf.js' ].concat(sourceFiles); gulp.task('build', function() { gulp.src(sourceFiles) .pipe(plumber()) .pipe(concat('df-validator.js')) .pipe(gulp.dest('./dist/')) .pipe(uglify()) .pipe(rename('df-validator.min.js')) .pipe(gulp.dest('./dist')); }); /** * Process */ gulp.task('process-all', function (done) { runSequence(/*'jshint',*/ 'test-src', 'build', done); }); /** * Watch task */ gulp.task('watch', function () { // Watch JavaScript files gulp.watch(sourceFiles, ['process-all']); }); /** * Validate source JavaScript */ gulp.task('jshint', function () { return gulp.src(lintFiles) .pipe(plumber()) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); /** * Run test once and exit */ gulp.task('test-src', function (done) { karma.start({ configFile: __dirname + '/karma-src.conf.js', singleRun: true }, done); }); /** * Run test once and exit */ gulp.task('test-dist-concatenated', function (done) { karma.start({ configFile: __dirname + '/karma-dist-concatenated.conf.js', singleRun: true }, done); }); /** * Run test once and exit */ gulp.task('test-dist-minified', function (done) { karma.start({ configFile: __dirname + '/karma-dist-minified.conf.js', singleRun: true }, done); }); gulp.task('default', function () { runSequence('process-all', 'watch'); });
nikita-yaroshevich/df-validator
gulpfile.js
JavaScript
mit
2,192
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | Hooks | ------------------------------------------------------------------------- | This file lets you define "hooks" to extend CI without hacking the core | files. Please see the user guide for info: | | http://codeigniter.com/user_guide/general/hooks.html | */ $hook['pre_system'] = array( 'function' => 'auth_constants', 'filename' => 'auth_constants.php', 'filepath' => 'hooks' );
GazmanDevelopment/docman
application/config/hooks.php
PHP
mit
542
# frozen_string_literal: true module ProductMutationHelper def coerce_pricing_structure_input(input) return nil unless input value_field = case input[:pricing_strategy] when 'fixed' :fixed_value when 'scheduled_value' :scheduled_value end PricingStructure.new(pricing_strategy: input[:pricing_strategy], value: input[value_field]) end def create_or_update_variants(product, product_variants_fields) (product_variants_fields || []).each_with_index do |product_variant_fields, i| product_variant_attrs = product_variant_fields.merge(position: i + 1) variant_id = product_variant_attrs.delete(:id) product_variant_attrs[:override_pricing_structure] = coerce_pricing_structure_input(product_variant_fields[:override_pricing_structure]) if variant_id variant = product.product_variants.find { |v| v.id.to_s == variant_id } variant.update!(product_variant_attrs) else product.product_variants.create!(product_variant_attrs) end end end end
neinteractiveliterature/intercode
app/graphql/product_mutation_helper.rb
Ruby
mit
1,074
<html dir="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" /> <title>BinarizeFilter Constructor</title> <xml> </xml> <link rel="stylesheet" type="text/css" href="MSDN.css" /> </head> <body id="bodyID" class="dtBODY"> <div id="nsbanner"> <div id="bannerrow1"> <table class="bannerparthead" cellspacing="0"> <tr id="hdr"> <td class="runninghead">OCR PreProcessing Imagefilters, Imagesegmentation, OCR Image Creation and Feature Extraction</td> <td class="product"> </td> </tr> </table> </div> <div id="TitleRow"> <h1 class="dtH1">BinarizeFilter Constructor </h1> </div> </div> <div id="nstext"> <p> Defaultconstructor, does nothin' </p> <div class="syntax">public BinarizeFilter();</div> <h4 class="dtH4">See Also</h4> <p> <a href="OCRPreProcessing.BinarizeFilter.html">BinarizeFilter Class</a> | <a href="OCRPreProcessing.html">OCRPreProcessing Namespace</a></p> <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"> <param name="Keyword" value="BinarizeFilter class, constructor"> </param> </object> <hr /> <div id="footer"> <p> <a href="mailto:ocrPreProc@rene-schulte.info?subject=OCR%20PreProcessing%20Imagefilters,%20Imagesegmentation,%20OCR%20Image%20Creation%20and%20Feature%20Extraction%20Documentation%20Feedback:%20BinarizeFilter Constructor ">Send comments on this topic.</a> </p> <p> <a>(c) 2004 Rene Schulte and Torsten Baer</a> </p> <p> </p> </div> </div> </body> </html>
teichgraf/MuLaPeGASim
web/docs/OCR/OCRPreProcessing.BinarizeFilterConstructor.html
HTML
mit
1,888
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import "UIView.h" @class NSString, NSTimer, STRunCaloriesLabel, STRunDistanceLabel, STRunPaceLabel, STRunProgressView, STRunTimeLabel, SWRunWorkoutProxy, UIButton, UIImageView, UILabel; @interface STRunView : UIView { id <STRunViewDelegate> _delegate; SWRunWorkoutProxy *_workoutProxy; NSTimer *_subsecondTimer; NSTimer *_workoutInfoTimer; double _elapsedWorkoutTime; double _estimatedElapsedWorkoutTime; double _lastWorkoutNotificationTime; UIView *_rotationContainer; long long _orientation; int _interface; UIButton *_leftButton; UIButton *_rightButton; UIButton *_endWorkoutButton; UIButton *_previousTrackButton; UIButton *_nextTrackButton; UIImageView *_transportControlsDivider; STRunTimeLabel *_runTimeLabel; STRunDistanceLabel *_runDistanceLabel; STRunPaceLabel *_runPaceLabel; STRunCaloriesLabel *_runCaloriesLabel; UIView *_labelSeparator; UILabel *_nowPlayingSongLabel; STRunProgressView *_runProgressView; float _progressToGoal; NSTimer *_considerSeekTimer; long long _currentSeekDirection; NSString *_throttledWorkoutState; struct { unsigned int timerPaused:1; unsigned int shouldStartTimer:1; unsigned int isLockScreen:1; unsigned int animateForResumeEventsOnly:1; unsigned int canHighlightPowerSong:1; unsigned int validPaceReceived:1; unsigned int noMusic:1; unsigned int seekHandled:1; unsigned int seekAllowed:1; unsigned int needsNowPlayingLayout:1; unsigned int forceTimeExtrapolation:1; unsigned int goalCompleted:1; unsigned int useMetricDistance:1; unsigned int forceMetricForDistanceOnly:1; unsigned int throttleNextPauseResume:1; unsigned int shouldControlMusic:1; unsigned int unused:16; } _runFlagsBitfield; } @property(readonly, nonatomic) SWRunWorkoutProxy *workoutProxy; // @synthesize workoutProxy=_workoutProxy; @property(nonatomic) id <STRunViewDelegate> delegate; // @synthesize delegate=_delegate; @property(nonatomic) long long orientation; // @synthesize orientation=_orientation; @property(nonatomic) int interface; // @synthesize interface=_interface; - (void)_nowPlayingChanged:(id)arg1; - (void)_applicationWillResignActive:(id)arg1; - (void)_applicationResumed:(id)arg1; - (void)_applicationWillSuspend:(id)arg1; - (void)_playPowerSongEventFromRemote:(id)arg1; - (void)_startWorkoutEventFromRemote:(id)arg1; - (void)_workoutStateDidChange:(id)arg1; - (void)_empedSearchStateChanged:(id)arg1; - (id)_powersongLandscapeButtonDownImage; - (id)_powersongLandscapeButtonImage; - (id)_powersongButtonDownImage; - (id)_powersongButtonImage; - (id)_endWorkoutLandscapeButtonDownImage; - (id)_endWorkoutLandscapeButtonImage; - (id)_endWorkoutButtonDownImage; - (id)_endWorkoutButtonImage; - (id)_startWorkoutButtonImage; - (id)_startWorkoutEndColor; - (id)_startWorkoutStartColor; - (id)_flatGradientImageWithImage:(id)arg1 startColor:(id)arg2 startPoint:(struct CGPoint)arg3 endColor:(id)arg4 endPoint:(struct CGPoint)arg5; - (void)_stopUpdateTimers; - (void)_startUpdateTimers; - (id)_mainButtonStringForGoalType:(id)arg1; - (void)_configureButtonsForWorkout; - (void)_updateSubviewsForWorkoutData:(id)arg1; - (void)_workoutInfoTimerTick:(id)arg1; - (void)_subsecondTimerTick:(id)arg1; - (_Bool)_endSeekInDirection:(int)arg1; - (_Bool)_beginSeekInDirection:(int)arg1; - (void)_considerSeekTimerFired:(id)arg1; - (void)_endSeeking:(id)arg1; - (void)_beginConsiderSeeking:(id)arg1; - (void)_cancelConsiderSeeking:(id)arg1; - (void)_nextTrack; - (void)_previousTrack; - (void)_stop; - (void)_unthrottlePauseResume; - (void)_resumeWorkoutForResume:(_Bool)arg1; - (void)_resume; - (void)_pauseWorkoutForResume:(_Bool)arg1; - (void)_pause; - (void)_cancel; - (void)_start; - (void)_changeMusic; - (void)_updateProgressViewWithDictionary:(id)arg1; - (_Bool)_isLockedMusicInterface; - (void)selectPowerSong; - (void)resumeWorkout; - (void)_finishResumeEventsOnly; - (void)resumeEventsOnly; - (void)resume; - (void)suspend; @property(nonatomic) _Bool animateForResumeEventsOnly; @property(nonatomic) _Bool isLockScreen; - (void)updateOrientation; - (void)_layoutLabel:(id)arg1 inPosition:(int)arg2 isLandscape:(_Bool)arg3 isLockedMusicInterface:(_Bool)arg4 hasProgressView:(_Bool)arg5; - (void)_layoutCaloriesInPosition:(int)arg1 isLandscape:(_Bool)arg2 isLockedMusicInterface:(_Bool)arg3 hasProgressView:(_Bool)arg4; - (void)_layoutPaceInPosition:(int)arg1 isLandscape:(_Bool)arg2 isLockedMusicInterface:(_Bool)arg3 hasProgressView:(_Bool)arg4; - (void)_layoutRunDistanceInPosition:(int)arg1 isLandscape:(_Bool)arg2 isLockedMusicInterface:(_Bool)arg3 hasProgressView:(_Bool)arg4; - (void)_layoutRunTimeInPosition:(int)arg1 isLandscape:(_Bool)arg2 isLockedMusicInterface:(_Bool)arg3 hasProgressView:(_Bool)arg4; - (void)_layoutNowPlayingLabelForWorkoutType:(long long)arg1; - (void)_layoutSecondaryLabelsForWorkoutType:(long long)arg1; - (void)_layoutPrimaryLabelForWorkoutType:(long long)arg1; - (void)_layoutLabelsForWorkoutType:(long long)arg1 presetGoal:(id)arg2; - (void)_layoutMainButtonsForGoalType:(id)arg1; - (void)_layoutBottomButtons; - (void)layoutSubviews; - (void)didMoveToWindow; - (void)_applicationDidEnterBackgroundNotification:(id)arg1; - (void)_applicationDidBecomeActiveNotification:(id)arg1; - (void)dealloc; - (id)initWithFrame:(struct CGRect)arg1 workoutProxy:(id)arg2; - (id)initWithFrame:(struct CGRect)arg1; @end
matthewsot/CocoaSharp
Headers/PrivateFrameworks/SportsTrainer/STRunView.h
C
mit
5,667
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import <UIKit/UIStatusBarLegacyStyleAttributes.h> // Not exported @interface UIStatusBarAssistantEyesFreeStyleAttributes : UIStatusBarLegacyStyleAttributes { } - (double)glowAnimationDuration; - (id)backgroundImageName; - (_Bool)areTopCornersRounded; - (int)cornerStyle; @end
matthewsot/CocoaSharp
Headers/Frameworks/UIKit/UIStatusBarAssistantEyesFreeStyleAttributes.h
C
mit
423
/* * Copyright (c) 2003-2009 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme.curve; import java.io.IOException; import com.jme.math.Vector3f; import com.jme.scene.Controller; import com.jme.scene.Spatial; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; /** * <code>CurveController</code> defines a controller that moves a supplied * <code>Spatial</code> object along a curve. Attributes of the curve are set * such as the up vector (if not set, the spacial object will roll along the * curve), the orientation precision defines how accurate the orientation of the * spatial will be. * @author Mark Powell * @version $Id: CurveController.java 4131 2009-03-19 20:15:28Z blaine.dev $ */ public class CurveController extends Controller { private static final long serialVersionUID = 1L; private Spatial mover; private Curve curve; private Vector3f up; private float orientationPrecision = 0.1f; private float currentTime = 0.0f; private float deltaTime = 0.0f; private boolean cycleForward = true; private boolean autoRotation = false; /** * Constructor instantiates a new <code>CurveController</code> object. * The curve object that the controller operates on and the spatial object * that is moved is specified during construction. * @param curve the curve to operate on. * @param mover the spatial to move. */ public CurveController(Curve curve, Spatial mover) { this.curve = curve; this.mover = mover; setUpVector(new Vector3f(0,1,0)); setMinTime(0); setMaxTime(Float.MAX_VALUE); setRepeatType(Controller.RT_CLAMP); setSpeed(1.0f); } /** * Constructor instantiates a new <code>CurveController</code> object. * The curve object that the controller operates on and the spatial object * that is moved is specified during construction. The game time to * start and the game time to finish is also supplied. * @param curve the curve to operate on. * @param mover the spatial to move. * @param minTime the time to start the controller. * @param maxTime the time to end the controller. */ public CurveController( Curve curve, Spatial mover, float minTime, float maxTime) { this.curve = curve; this.mover = mover; setMinTime(minTime); setMaxTime(maxTime); setRepeatType(Controller.RT_CLAMP); } /** * * <code>setUpVector</code> sets the locking vector for the spatials up * vector. This prevents rolling along the curve and allows for a better * tracking. * @param up the vector to lock as the spatials up vector. */ public void setUpVector(Vector3f up) { this.up = up; } /** * * <code>setOrientationPrecision</code> sets a precision value for the * spatials orientation. The smaller the number the higher the precision. * By default 0.1 is used, and typically does not require changing. * @param value the precision value of the spatial's orientation. */ public void setOrientationPrecision(float value) { orientationPrecision = value; } /** * * <code>setAutoRotation</code> determines if the object assigned to * the controller will rotate with the curve or just following the * curve. * @param value true if the object is to rotate with the curve, false * otherwise. */ public void setAutoRotation(boolean value) { autoRotation = value; } /** * * <code>isAutoRotating</code> returns true if the object is rotating with * the curve and false if it is not. * @return true if the object is following the curve, false otherwise. */ public boolean isAutoRotating() { return autoRotation; } /** * <code>update</code> moves a spatial along the given curve for along a * time period. * @see com.jme.scene.Controller#update(float) */ public void update(float time) { if(mover == null || curve == null || up == null) { return; } currentTime += time * getSpeed(); if (currentTime >= getMinTime() && currentTime <= getMaxTime()) { if (getRepeatType() == RT_CLAMP) { deltaTime = currentTime - getMinTime(); mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( deltaTime, orientationPrecision, up)); } } else if (getRepeatType() == RT_WRAP) { deltaTime = (currentTime - getMinTime()) % 1.0f; if (deltaTime > 1) { currentTime = 0; deltaTime = 0; } mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( deltaTime, orientationPrecision, up)); } } else if (getRepeatType() == RT_CYCLE) { float prevTime = deltaTime; deltaTime = (currentTime - getMinTime()) % 1.0f; if (prevTime > deltaTime) { cycleForward = !cycleForward; } if (cycleForward) { mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( deltaTime, orientationPrecision, up)); } } else { mover.setLocalTranslation( curve.getPoint(1.0f - deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( 1.0f - deltaTime, orientationPrecision, up)); } } } else { return; } } } public void reset() { this.currentTime = 0; } public void write(JMEExporter e) throws IOException { super.write(e); OutputCapsule capsule = e.getCapsule(this); capsule.write(mover, "mover", null); capsule.write(curve, "Curve", null); capsule.write(up, "up", null); capsule.write(orientationPrecision, "orientationPrecision", 0.1f); capsule.write(cycleForward, "cycleForward", true); capsule.write(autoRotation, "autoRotation", false); } public void read(JMEImporter e) throws IOException { super.read(e); InputCapsule capsule = e.getCapsule(this); mover = (Spatial)capsule.readSavable("mover", null); curve = (Curve)capsule.readSavable("curve", null); up = (Vector3f)capsule.readSavable("up", null); orientationPrecision = capsule.readFloat("orientationPrecision", 0.1f); cycleForward = capsule.readBoolean("cycleForward", true); autoRotation = capsule.readBoolean("autoRotation", false); } }
accelazh/ThreeBodyProblem
lib/jME2_0_1-Stable/src/com/jme/curve/CurveController.java
Java
mit
9,311
# shellcheck disable=SC2148 # Defines transfer alias and provides easy command line file and folder sharing. # # source: https://gist.github.com/nl5887/a511f172d3fb3cd0e42d # # Authors: # Remco Verhoef <remco@dutchcoders.io> # transfer() { # check if curl is installed if ! curl --version >/dev/null 2>&1; then echo "Could not find curl." return 1 fi # check arguments if [ $# -eq 0 ]; then printf "No arguments specified. Usage:\necho transfer /tmp/test.md\ncat /tmp/test.md | transfer test.md" return 1 fi # get temporarily filename, output is written to this file show progress can be showed tmpfile=$(mktemp -t transferXXX) # upload stdin or file file=$1 if tty -s; then basefile=$(basename "$file" | sed -e 's/[^a-zA-Z0-9._-]/-/g') if [ ! -e "$file" ]; then echo "File $file doesn't exists." return 1 fi if [ -d "$file" ]; then # zip directory and transfer zipfile="$(mktemp -t transferXXX.zip)" # shellcheck disable=SC2086 cd "$(dirname $file)" && zip -r -q - "$(basename $file)" >>"$zipfile" curl --progress-bar --upload-file "$zipfile" "https://transfer.sh/$basefile.zip" >>"$tmpfile" rm -f "$zipfile" else # transfer file curl --progress-bar --upload-file "$file" "https://transfer.sh/$basefile" >>"$tmpfile" fi else # transfer pipe curl --progress-bar --upload-file "-" "https://transfer.sh/$file" >>"$tmpfile" fi # cat output link cat "$tmpfile" # cleanup rm -f "$tmpfile" }
niklas-heer/dotfiles
zsh/scripts/transfer.zsh
Shell
mit
1,469
--- layout: post title: "building machine learning system in python(0)" excerpt: "First Machine Learning" categories: articles tags: [python, machine learning] comments: true share: true --- ##Machine Learning 机器学习的目标就是通过给机器几个例子,教会机器处理任务。 ###本系列将交给你什么 这个系列是我学习building machine learning system in python的笔记和过程。它将提供一些广泛的学习算法(learning algorithm),以及使用它们的时候的注意事项。 我们知道一些机器学习的算法,比如SVM(support vector machines),NNS(nearest neighbor search)。但是事实上,我们大部分的时间都会花在下面: 1. 阅读我们的数据并且进行清洗 2. 探索并且理解我们输入的数据 3. 分析如何最好的把数据呈现给我们的学习算法 4. 选择正确的模型和学习算法 5. 正确地评估最后的表现。 ###Basic Numpy ```python import numpy ``` ```python numpy.version.full_version ``` '1.9.3' ```python from numpy import * ``` ```python import numpy as np ``` ```python a = np.array([0,1,2,3,4,5]) a ``` array([0, 1, 2, 3, 4, 5]) narray.ndim gives you the dimension of the array --- ```python a.ndim ``` narray.shape gives the tuple of arrary dimensions ---- ```python a.shape ``` (6,) ```python t = np.zeros((5,3,4)) t.shape ``` (5, 3, 4) ```python a ``` array([0, 1, 2, 3, 4, 5]) Transform a array to 2D matrix ---- ```python b = a.reshape((3,2)) b ``` array([[0, 1], [2, 3], [4, 5]]) ```python b.shape ``` (3, 2) ```python b.ndim ``` 2 ```python b[1][0] = 77 b ``` array([[ 0, 1], [77, 3], [ 4, 5]]) ```python a ``` array([ 0, 1, 77, 3, 4, 5]) It shows numpy avoids copies wherever possible ---- only if u use a copy() ```python c = a.reshape((3,2)).copy() c ``` array([[ 0, 1], [77, 3], [ 4, 5]]) ```python c[0][0]=-99 c ``` array([[-99, 1], [ 77, 3], [ 4, 5]]) ```python a ``` array([ 0, 1, 77, 3, 4, 5]) Another advantage of NumPy is that operation are propagated to individual elements --- ```python a * 2 ``` array([ 0, 2, 154, 6, 8, 10]) ```python a ** 2 ``` array([ 0, 1, 5929, 9, 16, 25]) ```python [1,2,3,4,5] ** 2 ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-46-2617e316bd48> in <module>() ----> 1 [1,2,3,4,5] ** 2 TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int' Indexing ---- ```python a ``` array([ 0, 1, 77, 3, 4, 5]) ```python a[np.array([2,3,4])] ``` array([77, 3, 4]) ```python a > 4 ``` array([False, False, True, False, False, True], dtype=bool) ```python a[a>4] ``` array([77, 5]) ```python a[a>4] = 4 a ``` array([0, 1, 4, 3, 4, 4]) clip会将所有的数值都缩在指定的区间中 ```python a.clip(0,4) ``` array([0, 1, 4, 3, 4, 4]) ```python a.clip(0,3) ``` array([0, 1, 3, 3, 3, 3]) Handling non-existing values --- ```python c = np.array([1, 2, np.NAN, 3, 4]) c ``` array([ 1., 2., nan, 3., 4.]) ```python np.isnan(c) ``` array([False, False, True, False, False], dtype=bool) ```python c[~np.isnan(c)] ``` array([ 1., 2., 3., 4.]) ```python np.mean(c[~np.isnan(c)]) ``` 2.5 Comparing Runtime behaviors ---- ```python import timeit ``` ```python normal_py_sec = timeit.timeit('sum(x*x for x in xrange(1000))', number = 10000) naive_py_sec = timeit.timeit('sum(na*na)', setup="import numpy as np; na=np.arange(1000)", number = 10000) good_np_sec = timeit.timeit('na.dot(na)', setup = "import numpy as np; na = np.arange(1000)", number = 10000) ``` ```python print normal_py_sec, naive_py_sec, good_np_sec ``` 1.04627522128 2.08086375548 0.0352430844598 ```python na = np.arange(1000) ``` ```python t = np.array([1,2,3,4]) ``` ```python t.dot([2,3,4,5]) # dot 是narray之间的乘法 ``` 40 Learning Scipy --- ```python import scipy, numpy ``` ```python scipy.dot is numpy.dot ``` True Scipy可以提供许多在NumPy的array之间的算法 Our first Machine Learning application ---- ```python import scipy as sp ``` ```python data = sp.genfromtxt("D:\Working Space\Machine Learning\source code\BuildingMachineLearningSystemsWithPython-first_edition\ch01\data\web_traffic.tsv", delimiter = "\t") ``` ```python data.shape ``` (743, 2) Preprocessing and cleaning the data --- ```python x = data[:, 0] y = data[:, 1] ``` ```python sp.sum(sp.isnan(y)) ``` 8 ~可以使得所有的布尔值反过来 ```python x = x[~sp.isnan(y)] y = y[~sp.isnan(y)] ``` ```python import matplotlib.pyplot as plt ``` ```python %matplotlib inline ``` ```python plt.scatter(x,y) plt.title("Web traffic over the last month") plt.xlabel("Time") plt.ylabel("Hits/hour") plt.xticks([w*7*24 for w in xrange(10)], ['week %i'%w for w in range(10)]) plt.autoscale(tight=True) plt.grid() ``` ![png](http://screenshot.net/qgk1jtk.jpg) Choosing the right model and learning algorithm ---- 现在我们已经有了一个对数据明确的印象了,接下来我们要做的是 * 找到数据背后的模型 * 用这个模型去找到将来这个web server需要拓展的时候,也就是突破我们的limit of 10000 per hour ## 在搭建我们的一个模型之前 每当我们建立模型的时候,总会出现一些approximation error。这样的误差会指导我们选择正确的模型。这里我们用squarred distance to real data来描述这个误差。 ```python def error(f, x, y): return sp.sum((f(x) - y)**2) ``` ### 假设模型是一根直线 我们假设模型是一根直线的话,唯一的挑战就是如何用直线得到最小的误差。 Scipy有个函数`polyfit()`可以帮助我们做这件事 ```python fp1, residuals, rank, sv, rcond = sp.polyfit(x, y, 1, full = True) ``` 这里我们用`full = True`得到了一些其他的额外信息,一般我们只需要斜率和截距, fp1中包含了我们的直线的参数 ```python fp1 ``` array([ 2.59619213, 989.02487106]) 所以我们的直线方程是 f(x) = 2.59619213 * x + 989.02487106 我们用`poly1d()`来建立一个模型方程 ```python f1 = sp.poly1d(fp1) ``` ```python error(f1, x, y) ``` 317389767.33977801 {% highlight python %} fx = sp.linspace(0, x[-1], 1000) plt.scatter(x,y) plt.title("Web traffic over the last month") plt.xlabel("Time") plt.ylabel("Hits/hour") plt.xticks([w*7*24 for w in xrange(10)], ['week %i'%w for w in range(10)]) plt.autoscale(tight=True) plt.grid() plt.plot(fx, f1(fx), 'b',linewidth = 2) plt.legend(["d=%i"% f1.order], loc = "upper left") {% endhighlight %} <matplotlib.legend.Legend at 0x10cc7f70> ![png](http://screenshot.net/25o2dhj.jpg) 接下来用点复杂的 --- {% highlight python %} f2p = sp.polyfit(x, y, 2) print f2p {% endhighlight %} [ 1.05322215e-02 -5.26545650e+00 1.97476082e+03] {% highlight python %} f2 = sp.poly1d(f2p) print error(f2, x, y) {% endhighlight %} 179983507.878 我们的这里函数是 f(x) = 0.0105322215 \* x \*\* 2 - 5.26545650 * x + 1974.76082 {% highlight python %} fx = sp.linspace(0, x[-1], 1000) plt.figure(figsize=[8,6]) plt.scatter(x,y,s=8,alpha=0.6) plt.title("Web traffic over the last month") plt.xlabel("Time") plt.ylabel("Hits/hour") plt.xticks([w*7*24 for w in xrange(10)], ['week %i'%w for w in range(10)]) plt.autoscale(tight=True) plt.grid() plt.plot(fx, f1(fx), 'b',linewidth = 2) plt.plot(fx, f2(fx), 'g', linewidth = 2) plt.legend(["d=%i"% f1.order], loc = "upper left") {% endhighlight %} <matplotlib.legend.Legend at 0x10b28b50> ![png](http://screenshot.net/qvj1yun.jpg) {% highlight python %} f3p = sp.polyfit(x,y,3) {% endhighlight %} {% highlight python %} f3 = sp.poly1d(f3p) print error(f3, x, y) {% endhighlight %} 139350144.032 {% highlight python %} f100p = sp.polyfit(x,y,100) f100 = sp.poly1d(f100p) {% endhighlight %} {% highlight python %} fx = sp.linspace(0, x[-1], 1000) plt.figure(figsize=[8,6]) plt.scatter(x,y,s=8,alpha=0.6) plt.title("Web traffic over the last month") plt.xlabel("Time") plt.ylabel("Hits/hour") plt.xticks([w*7*24 for w in xrange(10)], ['week %i'%w for w in range(10)]) plt.autoscale(tight=True) plt.grid() plt.plot(fx, f1(fx), 'b',linewidth = 2) plt.plot(fx, f2(fx), 'g', linewidth = 2) plt.plot(fx, f3(fx), color = '#94a0b6', linewidth = 2, linestyle = '--') plt.plot(fx, f100(fx), color = 'r', linewidth = 2) plt.legend(["d=%i"% f1.order], loc = "upper left") plt.legend(["d=%i"% f2.order], loc ="upper left") {% endhighlight %} <matplotlib.legend.Legend at 0x11e63990> ![png](http://screenshot.net/ynd0gfq.jpg) 然而当我们仔细看这幅图的时候,我们会开始想,这个模型真的表示了数据产生的过程吗? 我们发现我们提供的d越大,比如100,越来越容易出现摆动的表现,看起来,我们的模型好像有点太fit我们的data了。 也就是说它不仅捕捉到了trend,同时也捕捉到了noise。这样的表现我们称作overfitting ####到了现在我们有几个选择: * 选择其中一个多项式模型 * 换成另外一种更复杂的模型. * 重新考虑我们的data,然后重新开始。
ryanyuan42/ryanyuan42.github.io
_posts/2015-12-5-building machine learning system in python.md
Markdown
mit
9,738
using BizHawk.Common; namespace BizHawk.Emulation.Cores.Nintendo.NES { //AKA half of mapper 034 (the other half is AVE_NINA_001 which is entirely different..) public sealed class BxROM : NES.NESBoardBase { //configuration int prg_bank_mask_32k; int chr_bank_mask_8k; //state int prg_bank_32k; int chr_bank_8k; public override void SyncState(Serializer ser) { base.SyncState(ser); ser.Sync(nameof(prg_bank_32k), ref prg_bank_32k); ser.Sync(nameof(chr_bank_8k), ref chr_bank_8k); } public override bool Configure(NES.EDetectionOrigin origin) { switch (Cart.board_type) { case "AVE-NINA-07": // wally bear and the gang // it's not the NINA_001 but something entirely different; actually a colordreams with VRAM // this actually works AssertPrg(32,128); AssertChr(0,16); AssertWram(0); AssertVram(0,8); break; case "IREM-BNROM": //Mashou (J).nes case "NES-BNROM": //Deadly Towers (U) AssertPrg(128,256); AssertChr(0); AssertWram(0,8); AssertVram(8); break; default: return false; } prg_bank_mask_32k = Cart.prg_size / 32 - 1; chr_bank_mask_8k = Cart.chr_size / 8 - 1; SetMirrorType(Cart.pad_h, Cart.pad_v); return true; } public override byte ReadPRG(int addr) { addr |= (prg_bank_32k << 15); return ROM[addr]; } public override void WritePRG(int addr, byte value) { value = HandleNormalPRGConflict(addr, value); prg_bank_32k = value & prg_bank_mask_32k; chr_bank_8k = ((value >> 4) & 0xF) & chr_bank_mask_8k; } public override byte ReadPPU(int addr) { if (addr<0x2000) { if (VRAM != null) { return VRAM[addr]; } else { return VROM[addr | (chr_bank_8k << 13)]; } } else { return base.ReadPPU(addr); } } } }
ircluzar/RTC3
Real-Time Corruptor/BizHawk_RTC/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/BxROM.cs
C#
mit
1,817
/** * Created by quanpower on 14-8-20. */ var config = require('./../config'); var redis = require('./redis'); var _ = require('lodash'); function cacheDevice(device){ if(device){ var cloned = _.clone(device); redis.set('DEVICE_' + device.uuid, JSON.stringify(cloned),function(){ //console.log('cached', uuid); }); } } function noop(){} if(config.redis){ module.exports = cacheDevice; } else{ module.exports = noop; }
SmartLinkCloud/IOT-platform
lib/cacheDevice.js
JavaScript
mit
479
""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r
yavalvas/yav_com
build/matplotlib/lib/matplotlib/tight_bbox.py
Python
mit
2,604
// Copyright (c) 2014 Mark Dodwell. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #import <Cocoa/Cocoa.h> @interface MKSidebarLabel : NSTextField @end
mkdynamic/prototype
Source/MKSidebarLabel.h
C
mit
1,168
# Require any additional compass plugins here. require 'sass-globbing' # Set this to the root of your project when deployed: http_path = "/" css_dir = "_includes/css" sass_dir = "_includes/sass" images_dir = "assets/img" javascripts_dir = "assets/js" relative_assets = true # Compilation pour la prod : environment = :production output_style = :compressed # Compilation durant le dev : # environment = :development #output_style = :expanded # You can select your preferred output style here (can be overridden via the command line): # output_style = :expanded or :nested or :compact or :compressed # To enable relative paths to assets via compass helper functions. Uncomment: # relative_assets = true # To disable debugging comments that display the original location of your selectors. Uncomment: # line_comments = false # If you prefer the indented syntax, you might want to regenerate this # project again passing --syntax sass, or you can uncomment this: # preferred_syntax = :sass # and then run: # sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass
chipisan/blog
config.rb
Ruby
mit
1,100
/** * morningstar-base-charts * * Copyright © 2016 . All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import defaultClasses from "../config/classes.js"; import ChartBase from "./chartBase.js"; import { ChartUtils } from "../utils/utils.js"; /** * Horizontal Bar Chart Implementation * * @extends {ChartBase} */ class HorizontalBarChart extends ChartBase{ /** * Creates an instance of HorizontalBarChart. * * @param {any} options */ constructor(options) { super(options); } /** * @override */ render(options) { var axes = this.axes, yScale = axes.axis("y").scale(), xScale = axes.axis("x").scale(), data = this.data[0].values, chartArea = this.layer, barHeight = yScale.rangeBand(), barPadding = 6, hasNegative = ChartUtils.hasNegative(data), animation = (options && !options.animation) ? false : true;; var getClass = d => { if(hasNegative){ return d >= 0 ? "h-bar-positive" : "h-bar-negative"; } return "h-bar"; }; var draw = selection => { selection.attr("class", getClass) .attr("x", (d) => xScale(Math.min(0, d))) .attr("y", 6) .attr("transform", (d, i) => "translate(0," + i * barHeight + ")") .attr("width", d => animation ? 0 : Math.abs(xScale(d) - xScale(0)) ) .attr("height", barHeight - barPadding); return selection; }; var bar = chartArea.selectAll("rect").data(data); bar.call(draw) .enter().append("rect").call(draw); bar.exit().remove(); if (animation) { bar.transition().duration(300) .attr("width", d => Math.abs(xScale(d) - xScale(0))); } } /** * * * @param {any} index */ onMouseover(index) { this.canvas.svg.selectAll(`.${defaultClasses.CHART_GROUP}.${defaultClasses.FOCUS}-${index}`) .transition() .style("opacity", 0.5); } /** * * * @param {any} index */ onMouseout(index) { this.canvas.svg.selectAll(`.${defaultClasses.CHART_GROUP}.${defaultClasses.FOCUS}-${index}`) .transition() .style("opacity", 1); } /** * * * @param {any} data */ _formatData(data) { var xDomain = this.axes.axis("x").scale().domain(); this._categories = data.map(value => value.name); this.data = xDomain.map(function (series, i) { var item = { series }; item.values = data.map(value => { return { series: series, category: value.name, value: value.values[i], index: value.index }; }); return item; }); } } export default HorizontalBarChart;
jmconde/charts
src/js/charts/horizontal.js
JavaScript
mit
3,156
<?php namespace Wowo\NewsletterBundle\Newsletter\Placeholders; use Wowo\NewsletterBundle\Newsletter\Placeholders\Exception\InvalidPlaceholderMappingException; class PlaceholderProcessor implements PlaceholderProcessorInterface { protected $mapping; protected $referenceClass; protected $placeholder_delimiter_left = '{{'; protected $placeholder_delimiter_right = '}}'; protected $placeholder_regex = '#delim_lef\s*placeholder\s*delim_right#'; public function setMapping(array $mapping) { $this->mapping = $mapping; } public function setReferenceClass($referenceClass) { if (!class_exists($referenceClass)) { throw new \InvalidArgumentException(sprintf('Class %s doesn\'t exist!', $referenceClass)); } $this->referenceClass = $referenceClass; } public function process($object, $body) { if (null == $this->mapping) { throw new \BadMethodCallException('Placeholders mapping ain\'t configured yet'); } if (get_class($object) != $this->referenceClass) { throw new \InvalidArgumentException(sprintf('Object passed to method isn\'t an instance of referenceClass (%s != %s)', get_class($object), $this->referenceClass)); } $this->validatePlaceholders(); foreach ($this->mapping as $placeholder => $source) { $value = $this->getPlaceholderValue($object, $source); $body = $this->replacePlaceholder($placeholder, $value, $body); } return $body; } /** * Get value from object based on source (property or method). It claims that validation were done * * @param mixed $object * @param mixed $source * @access protected * @return void */ protected function getPlaceholderValue($object, $source) { $rc = new \ReflectionClass(get_class($object)); if ($rc->hasProperty($source)) { return $object->$source; } else { return call_user_func(array($object, $source)); } } protected function replacePlaceholder($placeholder, $value, $body) { $regex = str_replace( array('delim_lef', 'delim_right', 'placeholder'), array($this->placeholder_delimiter_left, $this->placeholder_delimiter_right, $placeholder), $this->placeholder_regex ); return preg_replace($regex, $value, $body); } /** * It looks firstly for properties, then for method (getter) * */ protected function validatePlaceholders() { $rc = new \ReflectionClass($this->referenceClass); foreach ($this->mapping as $placeholder => $source) { if ($rc->hasProperty($source)) { $rp = new \ReflectionProperty($this->referenceClass, $source); if (!$rp->isPublic()) { throw new InvalidPlaceholderMappingException( sprintf('A placeholder %s defines source %s as a property, but it isn\'t public visible', $placeholder, $source), InvalidPlaceholderMappingException::NON_PUBLIC_PROPERTY); } } elseif($rc->hasMethod($source)) { $rm = new \ReflectionMethod($this->referenceClass, $source); if (!$rm->isPublic()) { throw new InvalidPlaceholderMappingException( sprintf('A placeholder %s defines source %s as a method (getter), but it isn\'t public visible', $placeholder, $source), InvalidPlaceholderMappingException::NON_PUBLIC_METHOD); } } else { throw new InvalidPlaceholderMappingException( sprintf('Unable to map placeholder %s with source %s', $placeholder, $source), InvalidPlaceholderMappingException::UNABLE_TO_MAP); } } } }
mortenthorpe/gladturdev
vendor/wowo/wowo-newsletter-bundle/Wowo/NewsletterBundle/Newsletter/Placeholders/PlaceholderProcessor.php
PHP
mit
3,955
# -*- coding: utf-8 -*- r""" Bending of collimating mirror ----------------------------- Uses :mod:`shadow` backend. File: `\\examples\\withShadow\\03\\03_DCM_energy.py` Influence onto energy resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pictures after monochromator, :ref:`type 2 of global normalization<globalNorm>`. The nominal radius is 7.4 km. Watch the energy distribution when the bending radius is smaller or greater than the nominal one. +---------+---------+---------+---------+ | |VCMR1| | |VCMR2| | |VCMR3| | | +---------+---------+---------+ |VCMR4| | | |VCMR7| | |VCMR6| | |VCMR5| | | +---------+---------+---------+---------+ .. |VCMR1| image:: _images/03VCM_R0496453_norm2.* :scale: 35 % .. |VCMR2| image:: _images/03VCM_R0568297_norm2.* :scale: 35 % .. |VCMR3| image:: _images/03VCM_R0650537_norm2.* :scale: 35 % .. |VCMR4| image:: _images/03VCM_R0744680_norm2.* :scale: 35 % :align: middle .. |VCMR5| image:: _images/03VCM_R0852445_norm2.* :scale: 35 % .. |VCMR6| image:: _images/03VCM_R0975806_norm2.* :scale: 35 % .. |VCMR7| image:: _images/03VCM_R1117020_norm2.* :scale: 35 % Influence onto focusing ~~~~~~~~~~~~~~~~~~~~~~~ Pictures at the sample position, :ref:`type 1 of global normalization<globalNorm>` +----------+----------+----------+----------+ | |VCMRF1| | |VCMRF2| | |VCMRF3| | | +----------+----------+----------+ |VCMRF4| | | |VCMRF7| | |VCMRF6| | |VCMRF5| | | +----------+----------+----------+----------+ .. |VCMRF1| image:: _images/04VCM_R0496453_norm1.* :scale: 35 % .. |VCMRF2| image:: _images/04VCM_R0568297_norm1.* :scale: 35 % .. |VCMRF3| image:: _images/04VCM_R0650537_norm1.* :scale: 35 % .. |VCMRF4| image:: _images/04VCM_R0744680_norm1.* :scale: 35 % :align: middle .. |VCMRF5| image:: _images/04VCM_R0852445_norm1.* :scale: 35 % .. |VCMRF6| image:: _images/04VCM_R0975806_norm1.* :scale: 35 % .. |VCMRF7| image:: _images/04VCM_R1117020_norm1.* :scale: 35 % """ __author__ = "Konstantin Klementiev" __date__ = "1 Mar 2012" import sys sys.path.append(r"c:\Alba\Ray-tracing\with Python") import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.shadow as shadow def main(): plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def plot_generator(): for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png'] # plot1.persistentName = filename03 + '.pickle' # plot2.persistentName = filename04 + '.pickle' textToSet = 'collimating\nmirror\n$R =$ %.1f km' % (rmirr * 1e-5) textPanel1.set_text(textToSet) textPanel2.set_text(textToSet) yield def after(): # import subprocess # subprocess.call(["python", "05-VFM-bending.py"], # cwd='/home/kklementiev/Alba/Ray-tracing/with Python/05-VFM-bending') pass xrtr.run_ray_tracing( [plot1, plot2], repeats=640, updateEvery=2, energyRange=[5998, 6002], generator=plot_generator, threads=threads, globalNorm=True, afterScript=after, backend='shadow') #this is necessary to use multiprocessing in Windows, otherwise the new Python #contexts cannot be initialized: if __name__ == '__main__': main()
kklmn/xrt
examples/withShadow/04_06/04_dE_VCM_bending.py
Python
mit
4,894
// Copyright (c) 2011-2016 The Cryptonote developers // Copyright (c) 2014-2017 XDN-project developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include <string.h> #include <tuple> #include <boost/uuid/uuid.hpp> #include "Common/StringTools.h" namespace CryptoNote { typedef boost::uuids::uuid uuid; typedef boost::uuids::uuid net_connection_id; typedef uint64_t PeerIdType; #pragma pack (push, 1) struct NetworkAddress { uint32_t ip; uint32_t port; }; struct PeerlistEntry { NetworkAddress adr; PeerIdType id; uint64_t last_seen; }; struct connection_entry { NetworkAddress adr; PeerIdType id; bool is_income; }; #pragma pack(pop) inline bool operator < (const NetworkAddress& a, const NetworkAddress& b) { return std::tie(a.ip, a.port) < std::tie(b.ip, b.port); } inline bool operator == (const NetworkAddress& a, const NetworkAddress& b) { return memcmp(&a, &b, sizeof(a)) == 0; } inline std::ostream& operator << (std::ostream& s, const NetworkAddress& na) { return s << Common::ipAddressToString(na.ip) << ":" << std::to_string(na.port); } inline uint32_t hostToNetwork(uint32_t n) { return (n << 24) | (n & 0xff00) << 8 | (n & 0xff0000) >> 8 | (n >> 24); } inline uint32_t networkToHost(uint32_t n) { return hostToNetwork(n); // the same } }
xdn-project/digitalnote
src/P2p/P2pProtocolTypes.h
C
mit
1,478
Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'application#hello' root 'application#goodbye' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
tkakisu/rails_tutorial
chapter1/config/routes.rb
Ruby
mit
1,634
/** * Copyright (c) 2014-2015, CKSource - Frederico Knabben. All rights reserved. * Licensed under the terms of the MIT License (see LICENSE.md). */ ( function( QUnit, bender ) { var total = 0, failed = 0, passed = 0, ignored = 0, errors = 0, result = { success: true, errors: [] }; // prevent QUnit from starting QUnit.config.autostart = false; bender.removeListener( window, 'load', QUnit.load ); function start() { QUnit.testStart( function() { total++; } ); QUnit.testDone( function( details ) { details.success = result.success; details.error = result.errors.length ? result.errors.join( '\n' ) : undefined; details.duration = details.runtime; details.fullName = details.module + ' ' + details.name; bender.result( details ); if ( details.success ) { if ( details.ignored ) { ignored++; } else { passed++; } } else { failed++; errors++; } result.success = true; result.errors = []; } ); QUnit.done( function( details ) { details.duration = details.runtime; bender.next( { coverage: window.__coverage__, duration: details.runtime, passed: passed, failed: failed, errors: errors, ignored: ignored, total: total } ); } ); QUnit.log( function( details ) { // add detailed error message to test result if ( !details.result ) { result.success = false; result.errors.push( [ details.message, 'Expected: ' + details.expected, 'Actual: ' + details.actual, details.source ].join( '\n' ) ); } } ); // manually start the runner QUnit.load(); QUnit.start(); } function stopRunner() { QUnit.stop(); } function isSingle( name ) { return name === decodeURIComponent( window.location.hash.substr( 1 ) ); } var oldTest = QUnit.test; QUnit.test = function( name ) { var module = this.config.currentModule, fullName = module ? module + ' ' + name : name; if ( window.location.hash && window.location.hash !== '#child' && !isSingle( fullName ) ) { return; } oldTest.apply( this, arguments ); }; window.assert = bender.assert = QUnit.assert; bender.runner = QUnit; bender.start = start; bender.stopRunner = stopRunner; } )( window.QUnit || {}, bender );
benderjs/benderjs-qunit
lib/adapter.js
JavaScript
mit
2,277
<!doctype html> <html> <head> <script src="../bower_components/webcomponentsjs/webcomponents.js"></script> <link rel="import" href="../dist/metaroom-markup.html"> </head> <body> <meta-verse> <meta-style> #vrcollab-poster { frame-style: solid; frame-thickness: 2; frame-width: 0.3; frame-color: #F33; padding: 0.1; } #phong-meta-tsurface{ material-color: gold; material-type: phong; } meta-verse{ skybox-style: sun-sphere; } .pretty-pic{ material-color: red; } #that-pic{ material-color: blue; } .light-chocolate{ material-color: #8D6E63; tbottom-padding-top: 0.5; tbottom-padding-bottom: 0.3; } #left-wall{ material-color: #d3d3d3; } meta-tbottom{ material-color: #795548; } .chocolate{ material-color: #795548; } .styled-wall { material-color: #E0E0E0; } meta-table{ thickness: 0.1; } </meta-style> <meta-room width='30' height='15' length='20'> <!-- maybe we should make all the left wall and right wall to meta&#45;wall with left , right, top , floor alignement --> <meta-wall align='left' meta-style='material-color: #EEEEEE'> <meta-picture id='vrcollab-poster' src='img/VRcollab.png' width='6' length='3'></meta-picture> <meta-picture src='img/VRcollab.png' width='4' length='2'></meta-picture> <meta-board width='6' length='5'> <meta-picture src='img/VRcollab.png' width='3' length='2'></meta-picture> <meta-picture meta-style='frame-width: 0.5' src='img/VRcollab.png' width='3' length='2'></meta-picture> <meta-text width='3'>A place for you to build future VR websites collaboratively</meta-text> </meta-board> <meta-text width='1'>Yay!</meta-text> <meta-picture id="that-pic" class="pretty-pic" src='img/VRcollab.png' width='5' length='2'></meta-picture> </meta-wall> <meta-wall align='right' class='styled-wall'> <meta-picture meta-style='position: absolute; top: 10; left: 0' src='img/VRcollab.png' width='3' length='2'></meta-picture> <meta-picture meta-style='frame-width: 0.5' src='img/VRcollab.png' width='3' length='2'></meta-picture> <meta-html> <img src='img/VRcollab.png'/> A Place for you to build future VR websites collaboratively </meta-html> </meta-wall> <meta-wall align='front' class='styled-wall'> <meta-board width='3' length='3' meta-style='position: absolute; top: 0; left: 8'></meta-board> <meta-text width='3' length='2' meta-style='position: absolute; top: 3; left: 6'>Hello, Test!</meta-text> <meta-picture src='img/VRcollab.png' width='3' length='2'></meta-picture> </meta-wall> <meta-wall align='back' class='styled-wall'> <meta-picture src='img/VRcollab.png' width='3' length='2'></meta-picture> </meta-wall> <meta-wall align='ceiling' class='styled-wall'> <meta-picture src='img/VRcollab.png' width='3' length='2'></meta-picture> </meta-wall> <meta-floor class='styled-wall'> <meta-table class='light-chocolate' width='5' length='4' height='3'> <meta-tsurface class='light-chocolate'> <meta-tr> <meta-td> </meta-td> </meta-tr> </meta-tsurface> <meta-tbottom class='light-chocolate' align='left'></meta-tbottom> <meta-tbottom class='light-chocolate' align='right'></meta-tbottom> </meta-table> <meta-table class='light-chocolate' width='5' length='4' height='2' > <meta-tsurface class='chocolate'> <meta-item width='4' length='2' height='4' material-src='model/sydney/model_mesh.obj.mtl' geometry-src='model/sydney/model_mesh.obj' id='meta-item-on-floor'></meta-item> </meta-tsurface> <meta-tbottom class='chocolate' align='right'></meta-tbottom> <meta-tbottom align='left'> <meta-label>Contact US</meta-label> </meta-tbottom> </meta-table> <meta-table height='3' meta-style='tbottom-padding-top: 0.5'> <meta-tsurface class='chocolate'> <meta-picture src='img/VRcollab.png' width='3' length='2'></meta-picture> <meta-picture src='img/VRcollab.png' width='3' length='2'></meta-picture> <meta-picture src='img/VRcollab.png' width='2' length='2'></meta-picture> <meta-item width='4' length='2' height='4' material-src='model/sydney/model_mesh.obj.mtl' geometry-src='model/sydney/model_mesh.obj' id='meta-item-on-floor'></meta-item> <meta-picture src='img/VRcollab.png' width='3' length='2'></meta-picture> <meta-picture src='img/VRcollab.png' width='2' length='2'></meta-picture> <meta-picture src='img/VRcollab.png' width='2' length='2'></meta-picture> <meta-picture src='img/VRcollab.png' width='2' length='2'></meta-picture> <meta-picture src='img/VRcollab.png' width='2' length='2'></meta-picture> <meta-picture src='img/VRcollab.png' width='2' length='2'></meta-picture> <meta-picture src='img/VRcollab.png' width='2' length='2'></meta-picture> <meta-item width='2' length='2' height='4' material-src='model/pokka/model_mesh.obj.mtl' geometry-src='model/pokka/model_mesh.obj' id='meta-item-on-floor'></meta-item> <meta-picture src='img/VRcollab.png' width='2' length='2'></meta-picture> </meta-tsurface> <meta-tbottom class='chocolate' align='right'></meta-tbottom> <meta-tbottom align='left'> <meta-label>Contact US</meta-label> </meta-tbottom> </meta-table> <meta-table class='light-chocolate' width='5' length='4' height='3' meta-style='tbottom-padding: 0.5'> <meta-tsurface class='light-chocolate' id="phong-meta-tsurface"> <meta-picture src='img/VRcollab.png' width='3' length='2'></meta-picture> <meta-item width='2' length='2' height='4' material-src='model/pokka/model_mesh.obj.mtl' geometry-src='model/pokka/model_mesh.obj' id='meta-item-on-floor'></meta-item> </meta-tsurface> <meta-tbottom class='light-chocolate' align='left'></meta-tbottom> <meta-tbottom class='light-chocolate' align='right'></meta-tbottom> </meta-table> <meta-table class='light-chocolate' width='5' length='4' height='3' > <meta-tsurface class='light-chocolate' id="phong-meta-tsurface"> <meta-picture src='img/VRcollab.png' width='3' length='2'></meta-picture> <meta-item width='2' length='2' height='4' material-src='model/pokka/model_mesh.obj.mtl' geometry-src='model/pokka/model_mesh.obj' id='meta-item-on-floor'></meta-item> </meta-tsurface> <meta-tbottom class='light-chocolate' align='right'></meta-tbottom> <meta-tbottom class='light-chocolate' align='left'></meta-tbottom> </meta-table> <meta-table class='light-chocolate' width='5' length='4' height='4' meta-style='position: absolute; top: 0; left: 15; rotate-z:45'> <meta-tsurface class='light-chocolate' id="phong-meta-tsurface"> <meta-picture src='img/VRcollab.png' width='3' length='2' meta-style='position: absolute; top: 1; left: 0'></meta-picture> <meta-item width='2' length='2' height='4' material-src='model/pokka/model_mesh.obj.mtl' geometry-src='model/pokka/model_mesh.obj' id='meta-item-on-floor'></meta-item> </meta-tsurface> <meta-tbottom class='light-chocolate' align='right'></meta-tbottom> <meta-tbottom class='light-chocolate' align='left'></meta-tbottom> </meta-table> </meta-floor> </meta-room> </meta-verse> </body> </html>
cbas/MetaRoomMarkup
demo/metaroom-markup-standard-spec.html
HTML
mit
8,277
using System.Net; using FluentAssertions; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Links; public sealed class AtomicAbsoluteLinksTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>> { private const string HostPrefix = "http://localhost"; private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext; private readonly OperationsFakers _fakers = new(); public AtomicAbsoluteLinksTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext) { _testContext = testContext; testContext.UseController<OperationsController>(); // These routes need to be registered in ASP.NET for rendering links to resource/relationship endpoints. testContext.UseController<TextLanguagesController>(); testContext.UseController<RecordCompaniesController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddScoped(typeof(IResourceChangeTracker<>), typeof(NeverSameResourceChangeTracker<>)); }); } [Fact] public async Task Update_resource_with_side_effects_returns_absolute_links() { // Arrange TextLanguage existingLanguage = _fakers.TextLanguage.Generate(); RecordCompany existingCompany = _fakers.RecordCompany.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingLanguage, existingCompany); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new object[] { new { op = "update", data = new { type = "textLanguages", id = existingLanguage.StringId, attributes = new { } } }, new { op = "update", data = new { type = "recordCompanies", id = existingCompany.StringId, attributes = new { } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(2); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { string languageLink = $"{HostPrefix}/textLanguages/{existingLanguage.StringId}"; resource.ShouldNotBeNull(); resource.Links.ShouldNotBeNull(); resource.Links.Self.Should().Be(languageLink); resource.Relationships.ShouldContainKey("lyrics").With(value => { value.ShouldNotBeNull(); value.Links.ShouldNotBeNull(); value.Links.Self.Should().Be($"{languageLink}/relationships/lyrics"); value.Links.Related.Should().Be($"{languageLink}/lyrics"); }); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { string companyLink = $"{HostPrefix}/recordCompanies/{existingCompany.StringId}"; resource.ShouldNotBeNull(); resource.Links.ShouldNotBeNull(); resource.Links.Self.Should().Be(companyLink); resource.Relationships.ShouldContainKey("tracks").With(value => { value.ShouldNotBeNull(); value.Links.ShouldNotBeNull(); value.Links.Self.Should().Be($"{companyLink}/relationships/tracks"); value.Links.Related.Should().Be($"{companyLink}/tracks"); }); }); } [Fact] public async Task Update_resource_with_side_effects_and_missing_resource_controller_hides_links() { // Arrange Playlist existingPlaylist = _fakers.Playlist.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Playlists.Add(existingPlaylist); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new object[] { new { op = "update", data = new { type = "playlists", id = existingPlaylist.StringId, attributes = new { } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(1); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.ShouldNotBeNull(); resource.Links.Should().BeNull(); resource.Relationships.Should().BeNull(); }); } }
json-api-dotnet/JsonApiDotNetCore
test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Links/AtomicAbsoluteLinksTests.cs
C#
mit
5,903
<p> comp-1030 works! </p>
angular/angular-cli-stress-test
src/app/components/comp-1030/comp-1030.component.html
HTML
mit
28
--- layout: post title: ! 'The Universal Second Language: Why Everyone Should Learn Coding' category: Translation tags: whycoding learn keywords: whycoding learn description: 本文翻译自在线远程教育网站sololearn,阐述了编程思想在这个时代的重要性。我们来分享这么几个理由,让你花费数分钟去思考编程与了解它是如何在工作中甚至是在你的工作之余所产生的积极影响。 --- ## The Universal Second Language: Why Everyone Should Learn Coding ## 宇宙的第二语言:为什么每个人都应该学习写代码 ![start coding](http://schoolpot.qiniudn.com/start-coding.jpg) >译者注:在阅读本文之前需要提示的是写代码与编程是不同的概念,编程是一个更为广义的概念,意为:为解决一个问题而去创造出抽象化的解决方案。 A couple of years ago, when someone asked why he or she should learn programming, the answer was simple: To get a good job with a high salary. 几年前,当有人问到为什么他(她)该学习编程,答案是简单的,为了找一份高薪的工作。 During the 21st century, coding has become a core job skill. Computer skills are now essential, even if you’ve already got a non-technical job. 在21世纪期间,编程已经变成一个工作中的核心技能。电脑知识已经变得至关重要,既是你的工作和电脑技术无关。 In this post, we'd like to share just a few reasons to consider taking a few minutes of your time to explore the positive effects knowing how to code can have on your career - and on your life outside of work, as well. 在本文当中,我们来分享这么几个理由,让你花费数分钟去思考编程与了解它是如何在工作中甚至是在你的工作之余所产生的积极影响。 Gaining programming and coding skills will qualify you for dozens of new job opportunities, but besides that, it will enable you to... 获得编程和写代码的能力将会使你有资格获得更多工作机会但除此之外,它还会让你...... ######...Improve Problem-Solving Skills #####...提升你解决问题的能力 Even if you never become a professional software developer, you will benefit from knowing how to consider questions or issues as a coder would. You'll have the ability to understand and master technologies of all sorts and solve problems in almost any discipline. 尽管你从未成为过一个专业的软件开发者,你将会从如何像程序员一样去考虑一个问题或者事情中受益。你将会有能力在各个方面去理解并科学地规划事情、解决问题。 ######...Change Your Way of Thinking #####...改变你思考的方式 Steve Jobs once said, "Everybody in this country should learn how to program a computer, because it teaches you how to think." Programming is a component of computer science, which helps in the development of critical thinking skills. Having such skills is extremely useful when the need for processing and presenting information and thinking analytically arises. 乔布斯曾经说过,"在这个国家,每个人都应该学习如何去编程,因为它教会你如何去思考"。 编程是计算机科学的一部分,它有助于锻炼缜密的思维能力。 有这样的技能是非常有用的尤其是当处理和展示信息与具有分析性地思考(逻辑思考)的需求产生的时候。 ######...Create or Change Things #####...创造和改变事物 The act of programming almost feels like you're "acting God-like"! In other words, you're creating your own world, complete with all of the features you want. You can turn the blank text file into a working program, with nothing to limit you but your imagination. Doesn’t that sound completely amazing? 当你在编程的时候你甚至会觉得自己像神一样!换言之,你在创造一个属于你自己的世界,并为此完成所有你需要的功能。你可以把一个空文本文件变成一个可工作的程序,除了你的想象力以外没有任何东西可以限制你,这难道不是一件听起来完完全全令你觉得惊讶的事情吗? It's also great fun to see someone using your creation. Your ability to improve your life and the lives of your friends and family is limited only by your ideas once you can take full control of your computer. 让别人看到你的创造成果是非常有趣的一件事情,你用你的能力去改变你的生活,并且,你的朋友,家庭的生活亦因此而被你的创造所影响,然而这一切仅发生在你的电脑前。 ######...Stay Competitive #####...保持竞争力 Whether you want to give your career a boost, or you just think it's important to keep pace with the rest of the world, learning to code has never been more important or more accessible. 无论你是否想让你的事业获得帮助,或者你只是想平静地要一份稳定生活并遣度余生,学习写代码已经变得如此重要,面向大众。 Today's world is full of web services, and being familiar with computer science will help you stay competitive in the fast-growing digital economy. 在满是Web服务应用的今天,熟悉计算机科学将会帮助你在快速增长的数字化经济中保持竞争力。 Programming hasn't grown this popular "just because". There is a growing realization that knowing how to program is essential for everyone, and especially for the younger generation. 编程从来没有发展得如此想当然地受大众欢迎。越来越多的人意识到编程对每个人都是至关重要的,尤其是对于年轻的一代来说。 Early in 2015, President Obama asserted that making computer programming education a requirement in the public schools makes sense, and went on to further endorse the idea: 2015年的早些时候,总统奥巴马就宣称编程教学如同识字一样,应成为基础教育的一部分,并进一步说到: Learning computer skills will change the way we do just about everything. Don't just buy a new video game, make one. Don't just download the latest app, help design it. No one is born a computer scientist, but with a little hard work, just about anyone can become one. And don’t let anyone tell you that you can’t. 学习电脑技能将会改变我们做任何事的方式。我们能做的不只是购买一个新的电子游戏,而是做一个,不只是下载一个最新的应用,而是帮助并改进、设计它。没人是天生的计算机科学家,但是通过稍微的努力,每个人都将成为可能。切勿听旁人说你不能实现自己的目标。 The idea that everyone should learn coding, which is widely regarded as the new universal second language, is not about creating a nation of coders who will create the next Twitter or Facebook. It's about tapping into everyone’s creativity and developing the invaluable skill of being able to solve problems. 每个人都应该学习编程,它是公认的宇宙里新兴的第二语言,这并不是说,创造一个每个人都会创造出下一个Twitter或者Facebook的编程帝国. 这是在说,每个人的创造力与它培养出具有无可估量的价值的解决问题的技能 Even if you have no plans to become a software engineer, spend a few weeks or months learning to code. It will sharpen your ability to troubleshoot and solve all sorts of problems. 尽管你并不打算去称为一个软件工程师,花费数周或者数个月去学习写代码。它(适量学习写代码学习编程掌握编程思想)会提高你排错和解决所有问题的能力。 原文地址:[The Universal Second Language: Why Everyone Should Learn Coding](http://www.sololearn.com/Blog/15/the-universal-second-language-why-everyone-should-learn-coding/) ---From: Sololearn Translated by : Chrisheng
cygmris/cygmris.github.io
_posts/translation/2015-08-27-the_universal_second_language_why_everyone_should_learn_coding.md
Markdown
mit
7,764
#include "WebForm.h" WebForm::WebForm(void) :__pWeb(null), __phonegapCommand(null) { geolocation = null; device = null; accel = null; network = null; console = null; compass = null; contacts = null; } WebForm::~WebForm(void) { } bool WebForm::Initialize() { return true; } result WebForm::OnInitializing(void) { result r = E_SUCCESS; // TODO: Add your initialization code here r = CreateWebControl(); if (IsFailed(r)) { AppLog("CreateMainForm() has failed.\n"); goto CATCH; } __pWeb->LoadUrl("file:///Res/index.html"); //__pWeb->LoadUrl("file:///Res/mobile-spec/index.html"); return r; CATCH: return false; } result WebForm::OnTerminating(void) { result r = E_SUCCESS; // delete __phonegapCommand; // delete geolocation; // delete device; // delete accel; // delete network; // delete console; // delete compass; // delete contacts; // delete notification; // delete camera; return r; } void WebForm::OnActionPerformed(const Osp::Ui::Control& source, int actionId) { switch(actionId) { default: break; } } void WebForm::LaunchBrowser(const String& url) { ArrayList* pDataList = null; pDataList = new ArrayList(); pDataList->Construct(); String* pData = null; pData = new String(L"url:"); pData->Append(url); AppLogDebug("Launching Stock Browser with %S", pData->GetPointer()); pDataList->Add(*pData); AppControl* pAc = AppManager::FindAppControlN(APPCONTROL_BROWSER, ""); if(pAc) { pAc->Start(pDataList, null); delete pAc; } pDataList->RemoveAll(true); delete pDataList; } bool WebForm::OnLoadingRequested (const Osp::Base::String& url, WebNavigationType type) { AppLogDebug("URL REQUESTED %S", url.GetPointer()); if(url.StartsWith("gap://", 0)) { // __phonegapCommand = null; __phonegapCommand = new String(url); // FIXME: for some reason this does not work if we return true. Web freezes. // __pWeb->StopLoading(); // String* test; // test = __pWeb->EvaluateJavascriptN(L"'test'"); // AppLogDebug("String is %S", test->GetPointer()); // delete test; // return true; return false; } else if(url.StartsWith("http://", 0) || url.StartsWith("https://", 0)) { AppLogDebug("Non PhoneGap command. External URL. Launching WebBrowser"); LaunchBrowser(url); return false; } return false; } void WebForm::OnLoadingCompleted() { // Setting DeviceInfo to initialize PhoneGap (should be done only once) and firing onNativeReady event String* deviceInfo; deviceInfo = __pWeb->EvaluateJavascriptN(L"window.device.uuid"); if(deviceInfo->IsEmpty()) { device->SetDeviceInfo(); __pWeb->EvaluateJavascriptN("PhoneGap.onNativeReady.fire();"); } else { //AppLogDebug("DeviceInfo = %S;", deviceInfo->GetPointer()); } delete deviceInfo; // Analyzing PhoneGap command if(__phonegapCommand) { if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Geolocation", 0)) { geolocation->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Accelerometer", 0)) { accel->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Network", 0)) { network->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.DebugConsole", 0)) { console->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Compass", 0)) { compass->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Contacts", 0)) { contacts->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Notification", 0)) { notification->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Camera", 0)) { camera->Run(*__phonegapCommand); } // Tell the JS code that we got this command, and we're ready for another __pWeb->EvaluateJavascriptN(L"PhoneGap.queue.ready = true;"); delete __phonegapCommand; __phonegapCommand = null; } else { AppLogDebug("Non PhoneGap command completed"); } } result WebForm::CreateWebControl(void) { result r = E_SUCCESS; int screen_width = 0; int screen_height = 0; /*screen*/ r = SystemInfo::GetValue("ScreenWidth", screen_width); TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed"); r = SystemInfo::GetValue("ScreenHeight", screen_height); TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed"); /*Web*/ __pWeb = new Web(); r = __pWeb->Construct(Rectangle(0, 0, screen_width, screen_height - 38)); TryCatch(r == E_SUCCESS, ,"Web is not constructed\n "); r = this->AddControl(*__pWeb); TryCatch(r == E_SUCCESS, ,"Web is not attached\n "); __pWeb->SetLoadingListener(this); __pWeb->SetFocus(); if(__pWeb) { geolocation = new GeoLocation(__pWeb); device = new Device(__pWeb); accel = new Accelerometer(__pWeb); network = new Network(__pWeb); console = new DebugConsole(__pWeb); compass = new Compass(__pWeb); contacts = new Contacts(__pWeb); notification = new Notification(__pWeb); camera = new Kamera(__pWeb); } return r; CATCH: AppLog("Error = %s\n", GetErrorMessage(r)); return r; }
johnwargo/phonegap-essentials-code
chapter04/HelloWorld/src/WebForm.cpp
C++
mit
5,118
# Simple powershell (built-in to Win7/8/10) utility script # to compute sha256 (or md5, sha1 or sha512) of a file # # Usage: # C:\> powershell # PS .\Get-Hash filename.ext [sha|md5|sha256|sha512] # # May require: Control Panel/System/Admin/Windows Power Shell Modules, then: Set-Executionpolicy RemoteSigned # # Based on James Manning's and Mike Wilbur's get-hashes and get-sha256 MSDN scripts # param( [string] $file = $(throw "A filename is required. Usage: .\Get-Hash filename.ext [sha|md5|sha256|sha512]"), [string] $algorithm = 'sha256' ) $fileStream = [system.io.file]::openread((resolve-path $file)) $hasher = [System.Security.Cryptography.HashAlgorithm]::create($algorithm) $hash = $hasher.ComputeHash($fileStream) $fileStream.close() $fileStream.dispose() [system.bitconverter]::tostring($hash).ToLower().replace('-','')+" '"+$file+"' "+$algorithm+"`r`n"
Ianonn21/vm-utils
scripts/Get-Hash.ps1
PowerShell
mit
872
<!DOCTYPE html> <html lang='en' ng-app='app'> <head> <meta charset='utf-8'> <meta content='IE=edge' http-equiv='X-UA-Compatible'> <meta content='width=device-width, initial-scale=1.0' name='viewport'> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" media="all" rel="stylesheet" /> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" media="screen" rel="stylesheet" /> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"> <link href="bower_components/angular-ui-select/dist/select.css" media="screen" rel="stylesheet" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script> <script src="bower_components/underscore/underscore-min.js"></script> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/angular-sanitize/angular-sanitize.min.js"></script> <script src="bower_components/angular-translate/angular-translate.min.js"></script> <script src='bower_components/angular-ui-select/dist/select.js'></script> <script src="bower_components/tv4/tv4.js"></script> <script src="bower_components/objectpath/lib/ObjectPath.js"></script> <script src="bower_components/angular-schema-form/dist/schema-form.min.js"></script> <script src="bower_components/angular-schema-form/dist/bootstrap-decorator.min.js"></script> <script src="bower_components/angular-underscore.js"></script> <script src="ui-sortable.js"></script> <script src="schema-form-uiselect.js"></script> <script src="app.js"></script> <base href='/'> <style type="text/css" rel="stylesheet"> .short { width: 200px; } .ui-select-bootstrap > .ui-select-match > .caret { display: none; } .ui-state-highlight { display: inline-block; width: 50px; min-height: 100%; } </style> </head> <body ng-controller='SelectController'> <div class="box box-primary ng-cloak"> <div class="box-header"> <h3 class="box-title">{{$root.$state.current.data.label}} - {{model.name}}</h3> </div> <form name="roleForm" ng-submit="submitted(roleForm)"> <div class="box-body"> <div sf-schema="schema" sf-form="form" sf-model="model"></div> </div> <div class="box-footer"> <button type="submit" class="btn btn-primary btn-flat">{{ 'buttons.save' | translate }}</button> <a ui-sref="roles" class="btn btn-warning btn-flat pull-right">{{ 'buttons.cancel' | translate }}</a> </div> </form> </div> </div> </body> </html>
chengz/schema-form-uiselect
example.html
HTML
mit
2,793
<div class="container"> <form [formGroup]="form" (ngSubmit)="sendEmail()"> <div class="row"> <div class="column large-2 small-2"> <label for="subject" class="right">Получатели: <small *ngIf="selectedUsers?.length == 0"><i>не выбраны</i></small> </label> </div> <div class="column large-1 small-1"> <input class="button hollow" [ngClass]="{'button-signal': form?.controls['users'].hasError('noSelectedUsers') && !userSelecting}" type="button" value="+" (click)="toggleUserSelection()"> </div> <div class="column large-4 small-4" [hidden]="!userSelecting"> <select #userSelector multiple name="users" id="users" size="10"> <option *ngFor="let user of users" [value]="user.id">{{user.lastName}} {{user.firstName}} {{user.patronymic}} </option> </select> </div> <div class="column large-1 small-1" *ngIf="userSelecting"> <input class="button hollow" type="button" [ngClass]="{'button-signal': form?.controls['users'].hasError('noSelectedUsers') && userSelecting}" value=">>" (click)="addUsers(userSelector)"> </div> <div class="column large-4 small-4" *ngIf="!form?.controls['users'].hasError('noSelectedUsers') && userSelecting"> <ul class="list"> <li *ngFor="let user of selectedUsers" (click)="removeFromSelected(user)"> <span data-tooltip aria-haspopup="true" class="top" data-disable-hover="false" tabindex="2" title="Кликните, чтобы удалить"> {{user.lastName}} {{user.firstName}} {{user.patronymic}} </span> </li> </ul> </div> <div class="column large-3 small-3" *ngIf="form?.controls['users'].hasError('noSelectedUsers') && userSelecting"> <div class="callout alert"> Выберите получателя(ей) </div> </div> </div> <div class="row"> <div class="column large-2 small-2"> <label for="subject" class="right">Тема:</label> </div> <div class="column large-9 small-9"> <input id="subject" name="subject" type="text" [formControl]="form.controls['subject']"> </div> </div> <div class="row"> <div class="column large-offset-2 small-offset-2 medium-offset-2 large-10 medium-2 small-10"> <div class="button-group" id="control-panel"> <button class="button hollow background-button" type="button" data-toggle="backgroundColorDropdown">Bg </button> <div class="dropdown-pane" id="backgroundColorDropdown" data-dropdown data-auto-focus="true"> <input class="input-color" type="color" id="backgroundColor" name="backgroundColor" (change)="changeBackgroundColor()" [formControl]="form.controls['backgroundColor']"> </div> <label for="image" class="button hollow attach-button"><i class="fi-paperclip"></i></label> <input #image type="file" name="image" (change)="fileSelected(image)" id="image" class="show-for-sr" accept="image/jpeg"> <button class="button hollow" type="button" data-toggle="templateDropdown">T</button> <div class="dropdown-pane" id="templateDropdown" data-dropdown data-auto-focus="true"> <select name="template" id="template" [formControl]="form.controls['template']" (change)="changeTemplate()"> <option *ngFor="let t of templates" [value]="t.type"> {{templateNamesMessages.get(t.type)}} </option> </select> </div> </div> </div> </div> <div class="row"> <div class="column large-offset-2 small-offset-2 large-4 small-4"> <div class="attachment" *ngIf="file"> <span>{{file?.name}}</span> <button class="close" type="button" (click)="removeAttachment(image)"> <span aria-hidden="true">&times;</span> </button> </div> </div> </div> <div class="row"> <div class="column large-2 small-2"> <label for="textarea-body" class="right" *ngIf="!selectedTemplate.body">Текст:</label> <label for="div-body" class="right" *ngIf="selectedTemplate.body">Текст:</label> </div> <div class="column large-9 small-9"> <textarea id="textarea-body" name="body" [ngStyle]="{'background': selectedTemplate.backgroundColor}" [formControl]="form.controls['body']" cols="30" rows="20" *ngIf="!selectedTemplate.body"></textarea> <div #body id="div-body" [ngStyle]="{'background': selectedTemplate.backgroundColor}" class="email-body" [innerHTML]="selectedTemplate.body" *ngIf="selectedTemplate.body"></div> </div> </div> <div class="column large-11 medium-11 small-11"> <div class="button-right"> <input class="button" type="submit" [disabled]="!form.valid" value="Отправить"> </div> </div> </form> </div> <div class="reveal success" id="modalSizeError" data-reveal> <button class="close-button" type="button" data-close> <span aria-hidden="true">&times;</span> </button> <h5>Размер файла превышает допустимый (5 MB)</h5> </div> <div class="reveal success" id="modal" data-reveal> <button class="close-button" type="button" data-close> <span aria-hidden="true">&times;</span> </button> <div class="text center"> <span>Идёт отправка письма. Подождите </span> <div class="spinner" *ngIf="requestInProgress"> <spinner [size]="15" [tickness]="2"></spinner> </div> </div> <div class="text center"> <span *ngIf="success"><b>Письмо успешно отправлено</b></span> <span *ngIf="fail"><b>Произошёл сбой во время отправки письма. Письмо не было отправлено</b></span> </div> <input type="button" class="button center" value="ОК" data-close *ngIf="success || fail"> </div>
kirikzyusko1996/WarehouseAngular
src/app/components/email/email.component.html
HTML
mit
6,373
vectorectus ===========
wtdilab/vectorectus
README.md
Markdown
mit
23
import { flatArgs } from './Query'; import type { Entity } from '../binding'; import type { Filter } from './Filter'; import { JsonMap } from '../util'; import type { GeoPoint } from '../GeoPoint'; /** * The Condition interface defines all existing query filters */ export interface Condition<T extends Entity> { /** * An object that contains filter rules which will be merged with the current filters of this query * * @param conditions - Additional filters for this query * @return The resulting Query */ where(conditions: JsonMap): Filter<T>; /** * Adds a equal filter to the field. All other other filters on the field will be discarded * @param field The field to filter * @param value The value used to filter * @return The resulting Query */ equal(field: string, value: any): Filter<T> /** * Adds a not equal filter to the field * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/ne/ */ notEqual(field: string, value: any): Filter<T> /** * Adds a greater than filter to the field * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/gt/ */ greaterThan(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a greater than or equal to filter to the field * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/gte/ */ greaterThanOrEqualTo(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a less than filter to the field * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/lt/ */ lessThan(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a less than or equal to filter to the field * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/lte/ */ lessThanOrEqualTo(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a between filter to the field. This is a shorthand for an less than and greater than filter. * @param field The field to filter * @param greaterValue The field value must be greater than this value * @param lessValue The field value must be less than this value * @return The resulting Query */ between( field: string, greaterValue: number | string | Date | Entity, lessValue: number | string | Date | Entity ): Filter<T> /** * Adds a “in” filter to the field * * The field value must be equal to one of the given values. * * @param field The field to filter * @param args The field value or values to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/in/ */ in(field: string, ...args: any[]): Filter<T> /** * Adds an “in” filter to the field * * The field value must be equal to one of the given values. * * @param field The field to filter * @param args The field value or values to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/in/ */ in(field: string, ...args: any[]): Filter<T> /** * Adds a “not in” filter to the field * * The field value must not be equal to any of the given values. * * @param field The field to filter * @param args The field value or values to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/nin/ */ notIn(field: string, ...args: any[]): Filter<T> /** * Adds a “is null” filter to the field * * The field value must be null. * * @param field The field to filter * @return The resulting Query */ isNull(field: string): Filter<T> /** * Adds a “is not null” filter to the field * * The field value must not be null. * * @param field The field to filter * @return The resulting Query */ isNotNull(field: string): Filter<T> /** * Adds a contains all filter to the collection field * * The collection must contain all the given values. * * @param field The field to filter * @param args The field value or values to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/all/ */ containsAll(field: string, ...args: any[]): Filter<T> /** * Adds a modulo filter to the field * * The field value divided by divisor must be equal to the remainder. * * @param field The field to filter * @param divisor The divisor of the modulo filter * @param remainder The remainder of the modulo filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/mod/ */ mod(field: string, divisor: number, remainder: number): Filter<T> /** * Adds a regular expression filter to the field * * The field value must matches the regular expression. * <p>Note: Only anchored expressions (Expressions that starts with an ^) and the multiline flag are supported.</p> * * @param field The field to filter * @param regExp The regular expression of the filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/regex/ */ matches(field: string, regExp: string | RegExp): Filter<T> /** * Adds a size filter to the collection field * * The collection must have exactly size members. * * @param field The field to filter * @param size The collections size to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/size/ */ size(field: string, size: number): Filter<T> /** * Adds a geopoint based near filter to the GeoPoint field * * The GeoPoint must be within the maximum distance * to the given GeoPoint. Returns from nearest to farthest. * * @param field The field to filter * @param geoPoint The GeoPoint to filter * @param maxDistance Tha maximum distance to filter in meters * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/nearSphere/ */ near(field: string, geoPoint: GeoPoint, maxDistance: number): Filter<T> /** * Adds a GeoPoint based polygon filter to the GeoPoint field * * The GeoPoint must be contained within the given polygon. * * @param field The field to filter * @param geoPoints The geoPoints that describes the polygon of the filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/geoWithin/ */ withinPolygon(field: string, ...geoPoints: GeoPoint[] | GeoPoint[][]): Filter<T> /** * Adds a equal filter to the field * * All other other filters on the field will be discarded. * * @method * @param field The field to filter * @param value The value used to filter */ eq(field: string, value: any): Filter<T> /** * Adds a not equal filter to the field * * @method * @param field The field to filter * @param value The value used to filter * * @see http://docs.mongodb.org/manual/reference/operator/query/ne/ */ ne(field: string, value: any): Filter<T> /** * Adds a less than filter to the field * * Shorthand for {@link Condition#lessThan}. * * @method * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/lt/ */ lt(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a less than or equal to filter to the field * * Shorthand for {@link Condition#lessThanOrEqualTo}. * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/lte/ */ le(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a greater than filter to the field * * Shorthand for {@link Condition#greaterThan}. * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/gt/ */ gt(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a greater than or equal to filter to the field * * Shorthand for {@link Condition#greaterThanOrEqualTo}. * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/gte/ */ ge(field: string, value: number | string | Date | Entity): Filter<T> /** * The collection must contains one of the given values * * Adds a contains any filter to the collection field. * Alias for {@link Condition#in}. * * @param field The field to filter * @param args The field value or values to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/in/ */ containsAny(field: string, ...args: any[]): Filter<T> /** * Adds a filter to this query * * @param field * @param filter * @param value * @return The resulting Query */ addFilter(field: string | null, filter: string | null, value: any): Filter<T> } // eslint-disable-next-line @typescript-eslint/no-redeclare export const Condition: Partial<Condition<any>> = { where(this: Condition<any>, conditions) { return this.addFilter(null, null, conditions); }, equal(this: Condition<any>, field, value) { return this.addFilter(field, null, value); }, notEqual(this: Condition<any>, field, value) { return this.addFilter(field, '$ne', value); }, greaterThan(this: Condition<any>, field, value) { return this.addFilter(field, '$gt', value); }, greaterThanOrEqualTo(this: Condition<any>, field, value) { return this.addFilter(field, '$gte', value); }, lessThan(this: Condition<any>, field, value) { return this.addFilter(field, '$lt', value); }, lessThanOrEqualTo(this: Condition<any>, field, value) { return this.addFilter(field, '$lte', value); }, between(this: Condition<any>, field, greaterValue, lessValue) { return this .addFilter(field, '$gt', greaterValue) .addFilter(field, '$lt', lessValue); }, in(this: Condition<any>, field: string, ...args: any[]) { return this.addFilter(field, '$in', flatArgs(args)); }, notIn(this: Condition<any>, field, ...args: any[]) { return this.addFilter(field, '$nin', flatArgs(args)); }, isNull(this: Condition<any>, field) { return this.equal(field, null); }, isNotNull(this: Condition<any>, field) { return this.addFilter(field, '$exists', true) .addFilter(field, '$ne', null); }, containsAll(this: Condition<any>, field, ...args: any[]) { return this.addFilter(field, '$all', flatArgs(args)); }, mod(this: Condition<any>, field, divisor, remainder) { return this.addFilter(field, '$mod', [divisor, remainder]); }, matches(this: Condition<any>, field, regExp) { const reg = regExp instanceof RegExp ? regExp : new RegExp(regExp); if (reg.ignoreCase) { throw new Error('RegExp.ignoreCase flag is not supported.'); } if (reg.global) { throw new Error('RegExp.global flag is not supported.'); } if (reg.source.indexOf('^') !== 0) { throw new Error('regExp must be an anchored expression, i.e. it must be started with a ^.'); } const result = this.addFilter(field, '$regex', reg.source); if (reg.multiline) { result.addFilter(field, '$options', 'm'); } return result; }, size(this: Condition<any>, field, size) { return this.addFilter(field, '$size', size); }, near(this: Condition<any>, field, geoPoint, maxDistance) { return this.addFilter(field, '$nearSphere', { $geometry: { type: 'Point', coordinates: [geoPoint.longitude, geoPoint.latitude], }, $maxDistance: maxDistance, }); }, withinPolygon(this: Condition<any>, field, ...args: any[]) { const geoPoints = flatArgs(args); return this.addFilter(field, '$geoWithin', { $geometry: { type: 'Polygon', coordinates: [geoPoints.map((geoPoint) => [geoPoint.longitude, geoPoint.latitude])], }, }); }, }; // aliases Object.assign(Condition, { eq: Condition.equal, ne: Condition.notEqual, lt: Condition.lessThan, le: Condition.lessThanOrEqualTo, gt: Condition.greaterThan, ge: Condition.greaterThanOrEqualTo, containsAny: Condition.in, });
Baqend/js-sdk
lib/query/Condition.ts
TypeScript
mit
13,300
package googlechat import "time" // ChatMessage is message type from Pub/Sub events type ChatMessage struct { Type string `json:"type"` EventTime time.Time `json:"eventTime"` Token string `json:"token"` Message struct { Name string `json:"name"` Sender struct { Name string `json:"name"` DisplayName string `json:"displayName"` AvatarURL string `json:"avatarUrl"` Email string `json:"email"` Type string `json:"type"` } `json:"sender"` CreateTime time.Time `json:"createTime"` Text string `json:"text"` Thread struct { Name string `json:"name"` RetentionSettings struct { State string `json:"state"` } `json:"retentionSettings"` } `json:"thread"` Space struct { Name string `json:"name"` Type string `json:"type"` } `json:"space"` ArgumentText string `json:"argumentText"` } `json:"message"` User struct { Name string `json:"name"` DisplayName string `json:"displayName"` AvatarURL string `json:"avatarUrl"` Email string `json:"email"` Type string `json:"type"` } `json:"user"` Space struct { Name string `json:"name"` Type string `json:"type"` DisplayName string `json:"displayName"` } `json:"space"` ConfigCompleteRedirectURL string `json:"configCompleteRedirectUrl"` } // ReplyThread is a part of reply messages type ReplyThread struct { Name string `json:"name,omitempty"` } // ReplyMessage is partial hangouts format of messages used // For details see // https://developers.google.com/hangouts/chat/reference/rest/v1/spaces.messages#Message type ReplyMessage struct { Text string `json:"text"` Thread *ReplyThread `json:"thread,omitempty"` }
go-chat-bot/bot
google-chat/chat_msg.go
GO
mit
1,746
--- layout: post title: Serialization, class hierarchy and preserving sessions date: '2011-10-26T08:39:00.000-04:00' author: Bill Schneider tags: modified_time: '2011-10-26T08:39:37.739-04:00' blogger_id: tag:blogger.com,1999:blog-9159309.post-2352121751565864812 blogger_orig_url: http://wrschneider.blogspot.com/2011/10/serialization-and-class-hierarchy.html --- If you have a class that implements Serializable, superclass fields do NOT get serialized unless the parent class also explicitly implements Serializable. That bit me the other day with session-scoped objects and preserving sessions across restarts, using Glassfish 3.1.1. Glassfish will complain if any objects in session scope or their properties don't implement serializable, but if those objects extend some parent class, the parent class fields are silently ignored and end up being null on session restore. So the source of the problem wasn't immediately clear, like it would have been if individual session objects or properties within them weren't serializable.
wrschneider/wrschneider.github.io
_posts/2011-10-26-serialization-and-class-hierarchy.html
HTML
mit
1,041
/** * This is a "mini-app" that encapsulates router definitions. See more * at: http://expressjs.com/guide/routing.html (search for "express.Router") * */ var router = require('express').Router({ mergeParams: true }); module.exports = router; // Don't just use, but also export in case another module needs to use these as well. router.callbacks = require('./controllers/hello'); router.models = require('./models'); //-- For increased module encapsulation, you could also serve templates with module-local //-- paths, but using shared layouts and partials may become tricky / impossible //var hbs = require('hbs'); //app.set('views', __dirname + '/views'); //app.set('view engine', 'handlebars'); //app.engine('handlebars', hbs.__express); // Module's Routes. Please note this is actually under /hello, because module is attached under /hello router.get('/', router.callbacks.sayHello);
KalenAnson/nodebootstrap
lib/hello/hello.js
JavaScript
mit
903
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true config.action_mailer.default_url_options = { host: '127.0.0.1:3000' } end
kfrost32/AdventureAnswers
config/environments/development.rb
Ruby
mit
1,673
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Core; using Azure.ResourceManager.Network.Models; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager.Network { /// <summary> A class representing collection of PublicIPAddress and their operations over a ResourceGroup. </summary> public partial class PublicIPAddressContainer : ArmContainer { private readonly ClientDiagnostics _clientDiagnostics; private readonly PublicIPAddressesRestOperations _restClient; /// <summary> Initializes a new instance of the <see cref="PublicIPAddressContainer"/> class for mocking. </summary> protected PublicIPAddressContainer() { } /// <summary> Initializes a new instance of PublicIPAddressContainer class. </summary> /// <param name="parent"> The resource representing the parent resource. </param> internal PublicIPAddressContainer(ArmResource parent) : base(parent) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); _restClient = new PublicIPAddressesRestOperations(_clientDiagnostics, Pipeline, ClientOptions, Id.SubscriptionId, BaseUri); } /// <summary> Gets the valid resource type for this object. </summary> protected override ResourceType ValidResourceType => ResourceGroup.ResourceType; // Container level operations. /// <summary> Creates or updates a static or dynamic public IP address. </summary> /// <param name="publicIpAddressName"> The name of the public IP address. </param> /// <param name="parameters"> Parameters supplied to the create or update public IP address operation. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="publicIpAddressName"/> or <paramref name="parameters"/> is null. </exception> public virtual PublicIPAddressCreateOrUpdateOperation CreateOrUpdate(string publicIpAddressName, PublicIPAddressData parameters, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (publicIpAddressName == null) { throw new ArgumentNullException(nameof(publicIpAddressName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.CreateOrUpdate"); scope.Start(); try { var response = _restClient.CreateOrUpdate(Id.ResourceGroupName, publicIpAddressName, parameters, cancellationToken); var operation = new PublicIPAddressCreateOrUpdateOperation(Parent, _clientDiagnostics, Pipeline, _restClient.CreateCreateOrUpdateRequest(Id.ResourceGroupName, publicIpAddressName, parameters).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Creates or updates a static or dynamic public IP address. </summary> /// <param name="publicIpAddressName"> The name of the public IP address. </param> /// <param name="parameters"> Parameters supplied to the create or update public IP address operation. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="publicIpAddressName"/> or <paramref name="parameters"/> is null. </exception> public async virtual Task<PublicIPAddressCreateOrUpdateOperation> CreateOrUpdateAsync(string publicIpAddressName, PublicIPAddressData parameters, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (publicIpAddressName == null) { throw new ArgumentNullException(nameof(publicIpAddressName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.CreateOrUpdate"); scope.Start(); try { var response = await _restClient.CreateOrUpdateAsync(Id.ResourceGroupName, publicIpAddressName, parameters, cancellationToken).ConfigureAwait(false); var operation = new PublicIPAddressCreateOrUpdateOperation(Parent, _clientDiagnostics, Pipeline, _restClient.CreateCreateOrUpdateRequest(Id.ResourceGroupName, publicIpAddressName, parameters).Request, response); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets details for this resource from the service. </summary> /// <param name="publicIpAddressName"> The name of the public IP address. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> public virtual Response<PublicIPAddress> Get(string publicIpAddressName, string expand = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.Get"); scope.Start(); try { if (publicIpAddressName == null) { throw new ArgumentNullException(nameof(publicIpAddressName)); } var response = _restClient.Get(Id.ResourceGroupName, publicIpAddressName, expand, cancellationToken: cancellationToken); if (response.Value == null) throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse()); return Response.FromValue(new PublicIPAddress(Parent, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets details for this resource from the service. </summary> /// <param name="publicIpAddressName"> The name of the public IP address. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> public async virtual Task<Response<PublicIPAddress>> GetAsync(string publicIpAddressName, string expand = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.Get"); scope.Start(); try { if (publicIpAddressName == null) { throw new ArgumentNullException(nameof(publicIpAddressName)); } var response = await _restClient.GetAsync(Id.ResourceGroupName, publicIpAddressName, expand, cancellationToken: cancellationToken).ConfigureAwait(false); if (response.Value == null) throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false); return Response.FromValue(new PublicIPAddress(Parent, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="publicIpAddressName"> The name of the public IP address. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> public virtual Response<PublicIPAddress> GetIfExists(string publicIpAddressName, string expand = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.GetIfExists"); scope.Start(); try { if (publicIpAddressName == null) { throw new ArgumentNullException(nameof(publicIpAddressName)); } var response = _restClient.Get(Id.ResourceGroupName, publicIpAddressName, expand, cancellationToken: cancellationToken); return response.Value == null ? Response.FromValue<PublicIPAddress>(null, response.GetRawResponse()) : Response.FromValue(new PublicIPAddress(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="publicIpAddressName"> The name of the public IP address. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> public async virtual Task<Response<PublicIPAddress>> GetIfExistsAsync(string publicIpAddressName, string expand = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.GetIfExists"); scope.Start(); try { if (publicIpAddressName == null) { throw new ArgumentNullException(nameof(publicIpAddressName)); } var response = await _restClient.GetAsync(Id.ResourceGroupName, publicIpAddressName, expand, cancellationToken: cancellationToken).ConfigureAwait(false); return response.Value == null ? Response.FromValue<PublicIPAddress>(null, response.GetRawResponse()) : Response.FromValue(new PublicIPAddress(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="publicIpAddressName"> The name of the public IP address. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> public virtual Response<bool> CheckIfExists(string publicIpAddressName, string expand = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.CheckIfExists"); scope.Start(); try { if (publicIpAddressName == null) { throw new ArgumentNullException(nameof(publicIpAddressName)); } var response = GetIfExists(publicIpAddressName, expand, cancellationToken: cancellationToken); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="publicIpAddressName"> The name of the public IP address. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> public async virtual Task<Response<bool>> CheckIfExistsAsync(string publicIpAddressName, string expand = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.CheckIfExists"); scope.Start(); try { if (publicIpAddressName == null) { throw new ArgumentNullException(nameof(publicIpAddressName)); } var response = await GetIfExistsAsync(publicIpAddressName, expand, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets all public IP addresses in a resource group. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="PublicIPAddress" /> that may take multiple service requests to iterate over. </returns> public virtual Pageable<PublicIPAddress> GetAll(CancellationToken cancellationToken = default) { Page<PublicIPAddress> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.GetAll"); scope.Start(); try { var response = _restClient.GetAll(Id.ResourceGroupName, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new PublicIPAddress(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<PublicIPAddress> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.GetAll"); scope.Start(); try { var response = _restClient.GetAllNextPage(nextLink, Id.ResourceGroupName, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new PublicIPAddress(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Gets all public IP addresses in a resource group. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="PublicIPAddress" /> that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<PublicIPAddress> GetAllAsync(CancellationToken cancellationToken = default) { async Task<Page<PublicIPAddress>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.GetAll"); scope.Start(); try { var response = await _restClient.GetAllAsync(Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new PublicIPAddress(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<PublicIPAddress>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.GetAll"); scope.Start(); try { var response = await _restClient.GetAllNextPageAsync(nextLink, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new PublicIPAddress(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Filters the list of <see cref="PublicIPAddress" /> for this resource group represented as generic resources. </summary> /// <param name="nameFilter"> The filter used in this operation. </param> /// <param name="expand"> Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. </param> /// <param name="top"> The number of results to return. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> A collection of resource that may take multiple service requests to iterate over. </returns> public virtual Pageable<GenericResource> GetAllAsGenericResources(string nameFilter, string expand = null, int? top = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.GetAllAsGenericResources"); scope.Start(); try { var filters = new ResourceFilterCollection(PublicIPAddress.ResourceType); filters.SubstringFilter = nameFilter; return ResourceListOperations.GetAtContext(Parent as ResourceGroup, filters, expand, top, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Filters the list of <see cref="PublicIPAddress" /> for this resource group represented as generic resources. </summary> /// <param name="nameFilter"> The filter used in this operation. </param> /// <param name="expand"> Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. </param> /// <param name="top"> The number of results to return. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> An async collection of resource that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<GenericResource> GetAllAsGenericResourcesAsync(string nameFilter, string expand = null, int? top = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PublicIPAddressContainer.GetAllAsGenericResources"); scope.Start(); try { var filters = new ResourceFilterCollection(PublicIPAddress.ResourceType); filters.SubstringFilter = nameFilter; return ResourceListOperations.GetAtContextAsync(Parent as ResourceGroup, filters, expand, top, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } // Builders. // public ArmBuilder<ResourceIdentifier, PublicIPAddress, PublicIPAddressData> Construct() { } } }
AsrOneSdk/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/PublicIPAddressContainer.cs
C#
mit
21,480
# Contributing to Tesspathy We want to make contributing to this project as easy and transparent as possible. Hopefully this document makes the process for contributing clear and answers any questions you may have. If not, feel free to open an issue. ## Pull Requests We will be monitoring for pull requests. Before submitting a pull request, please make sure the following is done: 1. Fork the repo and create your branch from ```master```. 2. If you've added code that should be tested, add tests. 3. If you've changed APIs, update the documentation. 4. Ensure the test suite passes. ## Bugs ### Where to Find Known Issues We will be using GitHub Issues for our public bugs. We will keep a close eye on this and try to make it clear when we have an internal fix in progress. Before filing a new task, try to make sure your problem doesn't already exist. ### Reporting New Issues Please ensure your bug description is clear and has sufficient instructions to be able to reproduce the issue. The best way is to provide a reduced test case on jsFiddle or jsBin. ## Coding Style * 2 spaces for indentation (no tabs) * Prefer ```'``` over ```"``` * Use semicolons ## License By contributing to Tesspathy, you agree that your contributions will be licensed under its MIT license.
gree/tesspathy
CONTRIBUTING.md
Markdown
mit
1,290
import WebhookNotification, { LinkClick, LinkClickCount, MessageTrackingData, WebhookDelta, WebhookObjectAttributes, WebhookObjectData, } from '../src/models/webhook-notification'; import { WebhookTriggers } from '../src/models/webhook'; describe('Webhook Notification', () => { test('Should deserialize from JSON properly', done => { const webhookNotificationJSON = { deltas: [ { date: 1602623196, object: 'message', type: 'message.created', object_data: { namespace_id: 'aaz875kwuvxik6ku7pwkqp3ah', account_id: 'aaz875kwuvxik6ku7pwkqp3ah', object: 'message', attributes: { action: 'save_draft', job_status_id: 'abc1234', thread_id: '2u152dt4tnq9j61j8seg26ni6', received_date: 1602623166, }, id: '93mgpjynqqu5fohl2dvv6ray7', metadata: { sender_app_id: 64280, link_data: [ { url: 'https://nylas.com/', count: 1, }, ], timestamp: 1602623966, recents: [ { ip: '24.243.155.85', link_index: 0, id: 0, user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36', timestamp: 1602623980, }, ], message_id: '4utnziee7bu2ohak56wfxe39p', payload: 'Tracking enabled', }, }, }, ], }; const webhookNotification = new WebhookNotification().fromJSON( webhookNotificationJSON ); expect(webhookNotification.deltas.length).toBe(1); const webhookDelta = webhookNotification.deltas[0]; expect(webhookDelta instanceof WebhookDelta).toBe(true); expect(webhookDelta.date).toEqual(new Date(1602623196 * 1000)); expect(webhookDelta.object).toEqual('message'); expect(webhookDelta.type).toEqual(WebhookTriggers.MessageCreated); const webhookDeltaObjectData = webhookDelta.objectData; expect(webhookDeltaObjectData instanceof WebhookObjectData).toBe(true); expect(webhookDeltaObjectData.id).toEqual('93mgpjynqqu5fohl2dvv6ray7'); expect(webhookDeltaObjectData.accountId).toEqual( 'aaz875kwuvxik6ku7pwkqp3ah' ); expect(webhookDeltaObjectData.namespaceId).toEqual( 'aaz875kwuvxik6ku7pwkqp3ah' ); expect(webhookDeltaObjectData.object).toEqual('message'); const webhookDeltaObjectAttributes = webhookDeltaObjectData.objectAttributes; expect( webhookDeltaObjectAttributes instanceof WebhookObjectAttributes ).toBe(true); expect(webhookDeltaObjectAttributes.action).toEqual('save_draft'); expect(webhookDeltaObjectAttributes.jobStatusId).toEqual('abc1234'); expect(webhookDeltaObjectAttributes.threadId).toEqual( '2u152dt4tnq9j61j8seg26ni6' ); expect(webhookDeltaObjectAttributes.receivedDate).toEqual( new Date(1602623166 * 1000) ); const webhookMessageTrackingData = webhookDeltaObjectData.metadata; expect(webhookMessageTrackingData instanceof MessageTrackingData).toBe( true ); expect(webhookMessageTrackingData.messageId).toEqual( '4utnziee7bu2ohak56wfxe39p' ); expect(webhookMessageTrackingData.payload).toEqual('Tracking enabled'); expect(webhookMessageTrackingData.timestamp).toEqual( new Date(1602623966 * 1000) ); expect(webhookMessageTrackingData.senderAppId).toBe(64280); expect(webhookMessageTrackingData.linkData.length).toBe(1); expect(webhookMessageTrackingData.recents.length).toBe(1); const linkData = webhookMessageTrackingData.linkData[0]; expect(linkData instanceof LinkClickCount).toBe(true); expect(linkData.url).toEqual('https://nylas.com/'); expect(linkData.count).toBe(1); const recents = webhookMessageTrackingData.recents[0]; expect(recents instanceof LinkClick).toBe(true); expect(recents.id).toBe(0); expect(recents.ip).toEqual('24.243.155.85'); expect(recents.userAgent).toEqual( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36' ); expect(recents.timestamp).toEqual(new Date(1602623980 * 1000)); expect(recents.linkIndex).toBe(0); done(); }); });
nylas/nylas-nodejs
__tests__/webhook-notification-spec.js
JavaScript
mit
4,538
using HoloToolkit.Unity; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Networking; public class AuthorizationManager : Singleton<AuthorizationManager> { [SerializeField] private string clientId = "c4ced10f-ce0f-4155-b6f7-a4c40ffa410c"; private string clientSecret; [SerializeField] private string debugToken; private string accessToken; private string authorizationCode; const string learningLayersAuthorizationEndpoint = "https://api.learning-layers.eu/o/oauth2/authorize"; const string learningLayersTokenEndpoint = "https://api.learning-layers.eu/o/oauth2/token"; const string learningLayersUserInfoEndpoint = "https://api.learning-layers.eu/o/oauth2/userinfo"; const string scopes = "openid%20profile%20email"; const string gamrRedirectURI = "gamr://"; public string AccessToken { get { return accessToken; } } private void Start() { // skip the login by using the debug token if (Application.isEditor) { if (accessToken == null || accessToken == "") { accessToken = debugToken; AddAccessTokenToHeader(); RestManager.Instance.GET(learningLayersUserInfoEndpoint + "?access_token=" + accessToken, GetUserInfoForDebugToken); } } else // else: fetch the client secret { TextAsset secretAsset = (TextAsset)Resources.Load("values/client_secret"); clientSecret = secretAsset.text; } } private void GetUserInfoForDebugToken(UnityWebRequest req) { if (req.responseCode == 200) { string json = req.downloadHandler.text; Debug.Log(json); UserInfo info = JsonUtility.FromJson<UserInfo>(json); InformationManager.Instance.UserInfo = info; } else if (req.responseCode == 401) { Debug.LogError("Unauthorized: access token is wrong"); } } public void Login() { if (Application.isEditor) { SceneManager.LoadScene("Scene", LoadSceneMode.Single); return; } Application.OpenURL(learningLayersAuthorizationEndpoint + "?response_type=code&scope=" + scopes + "&client_id=" + clientId + "&redirect_uri=" + gamrRedirectURI); } public void Logout() { accessToken = ""; SceneManager.LoadScene("Login", LoadSceneMode.Single); } private void StartedByProtocol(Uri uri) { if (uri.Fragment != null) { char[] splitters = { '?', '&' }; string[] arguments = uri.AbsoluteUri.Split(splitters); foreach (string argument in arguments) { if (argument.StartsWith("code=")) { authorizationCode = argument.Replace("code=", ""); Debug.Log("authorizationCode: " + authorizationCode); // now exchange authorization code for access token RestManager.Instance.POST(learningLayersTokenEndpoint + "?code=" + authorizationCode + "&client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=" + gamrRedirectURI + "&grant_type=authorization_code", (req) => { string json = req.downloadHandler.text; Debug.Log("Token json: " + json); AuthorizationFlowAnswer answer = JsonUtility.FromJson<AuthorizationFlowAnswer>(json); if (!string.IsNullOrEmpty(answer.error)) { MessageBox.Show(answer.error_description, MessageBoxType.ERROR); } else { // extract access token and check it accessToken = answer.access_token; Debug.Log("The access token is " + accessToken); AddAccessTokenToHeader(); CheckAccessToken(); } } ); break; } } } } private void AddAccessTokenToHeader() { if (RestManager.Instance.StandardHeader.ContainsKey("access_token")) { RestManager.Instance.StandardHeader["access_token"] = accessToken; } else { RestManager.Instance.StandardHeader.Add("access_token", accessToken); } } private void CheckAccessToken() { RestManager.Instance.GET(learningLayersUserInfoEndpoint + "?access_token=" + accessToken, OnLogin); } private void OnLogin(UnityWebRequest result) { if (result.responseCode == 200) { string json = result.downloadHandler.text; Debug.Log(json); UserInfo info = JsonUtility.FromJson<UserInfo>(json); InformationManager.Instance.UserInfo = info; GamificationFramework.Instance.ValidateLogin(LoginValidated); } else { MessageBox.Show(LocalizationManager.Instance.ResolveString("Error while retrieving the user data. Login failed"), MessageBoxType.ERROR); } } private void LoginValidated(UnityWebRequest req) { if (req.responseCode == 200) { SceneManager.LoadScene("Scene", LoadSceneMode.Single); } else if (req.responseCode == 401) { MessageBox.Show(LocalizationManager.Instance.ResolveString("The login could not be validated"), MessageBoxType.ERROR); } else { MessageBox.Show(LocalizationManager.Instance.ResolveString("An error concerning the user data occured. The login failed.\nCode: ") + req.responseCode + "\n" + req.downloadHandler.text, MessageBoxType.ERROR); } } }
rwth-acis/GaMR
Frontend/GaMR/Assets/Scripts/Login/AuthorizationManager.cs
C#
mit
6,336
<!DOCTYPE html> <html ng-app="cookieDemo"> <head> <meta charset="utf-8"> <title>ch6</title> <link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css" /> <script type="text/javascript" src="../bower_components/angular/angular.min.js"></script> <script type="text/javascript" src="../bower_components/angular-cookies/angular-cookies.min.js"></script> <script type="text/javascript" src="cookieDemo.js"></script> </head> <body> <div ng-controller="mainCtrl"> <h1>Cookie 서비스 사용</h1> <p>test 키로 저장된값: {{value}}</p> <button ng-click="getValue()">쿠키 가져오기</button> <br/> <input type="text" ng-model="iValue"><button ng-click="putValue(iValue)">쿠키저장</button> </div> </body> </html>
sehoone/seed
app/beeer/cookieDemo.html
HTML
mit
796
/* * Copyright (C) 2011 ZXing authors * * 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. */ package com.longluo.demo.qrcode.zxing.client.android.encode; /** * Encapsulates some simple formatting logic, to aid refactoring in {@link ContactEncoder}. * * @author Sean Owen */ interface Formatter { /** * @param value value to format * @param index index of value in a list of values to be formatted * @return formatted value */ CharSequence format(CharSequence value, int index); }
longluo/AndroidDemo
app/src/main/java/com/longluo/demo/qrcode/zxing/client/android/encode/Formatter.java
Java
mit
1,015
require 'test_helper' class NoSchemaControllerTest < ActionController::TestCase def test_no_schema_always_validate # We send invalid value but it validates anyway because their is no schema. get :basic, format: 'json', param1: 51 assert_response :success assert !response.has_schema? end end
nicolasdespres/respect-rails
test/functional/no_schema_controller_test.rb
Ruby
mit
315
import deepFreeze from 'deep-freeze'; import { arrayToMap, mapKeysToArray } from './mapUtils'; describe('arrayToMap', () => { it('should create map from 2D array', () => { const a = [ ['key1', 'value1'], ['key2', 'value2'] ]; deepFreeze(a); const result = arrayToMap(a); expect(result.size).toBe(2); expect(result.get('key1')).toBe('value1'); expect(result.get('key2')).toBe('value2'); }); it('should create empty map from empty array', () => { const result = arrayToMap([]); expect(result.size).toBe(0); }); }); describe('mapKeysToArray', () => { it('should create array from map keys in order', () => { const map = new Map(); map.set('a', 'value1'); map.set('c', 'value2'); map.set('1', 'value3'); map.set('b', 'value4'); map.set('2', 'value5'); const result = mapKeysToArray(map); expect(result).toEqual(['a', 'c', '1', 'b', '2']); }); it('should create empty array from new map', () => { const map = new Map(); const result = mapKeysToArray(map); expect(result).toEqual([]); }); });
TrueWill/embracer
src/utils/mapUtils.test.js
JavaScript
mit
1,107
namespace SimShift.Data { public enum Ets2DataAuxilliary : int { CruiseControl = 0, Wipers = 1, ParkBrake = 2, MotorBrake = 3, ElectricEnabled = 4, EngineEnabled = 5, BlinkerLeftActive = 6, BlinkerRightActive = 7, BlinkerLeftOn = 8, BlinkerRightOn = 9, LightsParking = 10, LightsBeamLow = 11, LightsBeamHigh = 12, LightsAuxFront = 13, LightsAuxRoof = 14, LightsBeacon = 15, LightsBrake = 16, LightsReverse = 17, BatteryVoltageWarning = 18, AirPressureWarning = 19, AirPressureEmergency = 20, AdblueWarning = 21, OilPressureWarning = 22, WaterTemperatureWarning = 23, } }
zappybiby/SimShift
SimShift/SimShift/Data/Ets2DataAuxilliary.cs
C#
mit
797
###2015-12-20 ####objective-c * <img src='https://avatars3.githubusercontent.com/u/433320?v=3&s=40' height='20' width='20'>[ yulingtianxia / TBActionSheet ](https://github.com/yulingtianxia/TBActionSheet): A Custom Action Sheet * <img src='https://avatars3.githubusercontent.com/u/7830226?v=3&s=40' height='20' width='20'>[ zpz1237 / NirZhihuDaily2.0 ](https://github.com/zpz1237/NirZhihuDaily2.0): Swift精仿知乎日报iOS端 * <img src='https://avatars1.githubusercontent.com/u/1468993?v=3&s=40' height='20' width='20'>[ krzysztofzablocki / DetailsMatter ](https://github.com/krzysztofzablocki/DetailsMatter): * <img src='https://avatars1.githubusercontent.com/u/5310542?v=3&s=40' height='20' width='20'>[ Aufree / ESTMusicPlayer ](https://github.com/Aufree/ESTMusicPlayer): An elegant and simple iOS music player. * <img src='https://avatars1.githubusercontent.com/u/432536?v=3&s=40' height='20' width='20'>[ ReactiveCocoa / ReactiveCocoa ](https://github.com/ReactiveCocoa/ReactiveCocoa): Streams of values over time * <img src='https://avatars3.githubusercontent.com/u/1509815?v=3&s=40' height='20' width='20'>[ Guidebook / gbkui-button-progress-view ](https://github.com/Guidebook/gbkui-button-progress-view): Inspired by Apple’s download progress buttons in the app store * <img src='https://avatars1.githubusercontent.com/u/3631397?v=3&s=40' height='20' width='20'>[ exis-io / Exis ](https://github.com/exis-io/Exis): Exis client libraries, sample projects, and demos. * <img src='https://avatars1.githubusercontent.com/u/839283?v=3&s=40' height='20' width='20'>[ ibireme / YYKit ](https://github.com/ibireme/YYKit): A collection of iOS components. * <img src='https://avatars0.githubusercontent.com/u/4415086?v=3&s=40' height='20' width='20'>[ poboke / ActivatePowerMode ](https://github.com/poboke/ActivatePowerMode): ActivatePowerMode is a plugin for Xcode. This plugin will make your code powerful. * <img src='https://avatars2.githubusercontent.com/u/714?v=3&s=40' height='20' width='20'>[ postmates / PMKVObserver ](https://github.com/postmates/PMKVObserver): A type-safe Swift/ObjC KVO wrapper * <img src='https://avatars1.githubusercontent.com/u/839283?v=3&s=40' height='20' width='20'>[ ibireme / YYText ](https://github.com/ibireme/YYText): Powerful text framework for iOS to display and edit rich text. * <img src='https://avatars1.githubusercontent.com/u/627285?v=3&s=40' height='20' width='20'>[ alcatraz / Alcatraz ](https://github.com/alcatraz/Alcatraz): Package manager for Xcode * <img src='https://avatars3.githubusercontent.com/u/598870?v=3&s=40' height='20' width='20'>[ SnapKit / Masonry ](https://github.com/SnapKit/Masonry): Harness the power of AutoLayout NSLayoutConstraints with a simplified, chainable and expressive syntax. Supports iOS and OSX Auto Layout * <img src='https://avatars3.githubusercontent.com/u/7659?v=3&s=40' height='20' width='20'>[ AFNetworking / AFNetworking ](https://github.com/AFNetworking/AFNetworking): A delightful networking framework for iOS, OS X, watchOS, and tvOS. * <img src='https://avatars2.githubusercontent.com/u/1724674?v=3&s=40' height='20' width='20'>[ ViccAlexander / Chameleon ](https://github.com/ViccAlexander/Chameleon): Flat Color Framework for iOS (Obj-C & Swift) * <img src='https://avatars1.githubusercontent.com/u/565251?v=3&s=40' height='20' width='20'>[ facebook / AsyncDisplayKit ](https://github.com/facebook/AsyncDisplayKit): Smooth asynchronous user interfaces for iOS apps. * <img src='https://avatars0.githubusercontent.com/u/10654142?v=3&s=40' height='20' width='20'>[ Pluto-Y / iOS-Echarts ](https://github.com/Pluto-Y/iOS-Echarts): * <img src='https://avatars2.githubusercontent.com/u/627915?v=3&s=40' height='20' width='20'>[ git-up / GitUp ](https://github.com/git-up/GitUp): The Git interface you've been missing all your life has finally arrived. * <img src='' height='20' width='20'>[ Akateason / XTTableDatasourceDelegateSeparation ](https://github.com/Akateason/XTTableDatasourceDelegateSeparation): XTTableDatasourceDelegateSeparation * <img src='https://avatars3.githubusercontent.com/u/91322?v=3&s=40' height='20' width='20'>[ jdg / MBProgressHUD ](https://github.com/jdg/MBProgressHUD): MBProgressHUD + Customizations * <img src='https://avatars2.githubusercontent.com/u/3831495?v=3&s=40' height='20' width='20'>[ hackiftekhar / IQKeyboardManager ](https://github.com/hackiftekhar/IQKeyboardManager): Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. * <img src='https://avatars2.githubusercontent.com/u/10044430?v=3&s=40' height='20' width='20'>[ LeoiOS / LCTabBarController ](https://github.com/LeoiOS/LCTabBarController): A amazing and highly customized tabBarController! You could almost customize 100% of the properties with LCTabBarController! * <img src='https://avatars3.githubusercontent.com/u/1093321?v=3&s=40' height='20' width='20'>[ CEWendel / SWTableViewCell ](https://github.com/CEWendel/SWTableViewCell): An easy-to-use UITableViewCell subclass that implements a swippable content view which exposes utility buttons (similar to iOS 7 Mail Application) * <img src='https://avatars0.githubusercontent.com/u/605277?v=3&s=40' height='20' width='20'>[ uranusjr / macdown ](https://github.com/uranusjr/macdown): Open source Markdown editor for OS X. * <img src='https://avatars2.githubusercontent.com/u/68232?v=3&s=40' height='20' width='20'>[ rs / SDWebImage ](https://github.com/rs/SDWebImage): Asynchronous image downloader with cache support as a UIImageView category ####go * <img src='https://avatars2.githubusercontent.com/u/3039877?v=3&s=40' height='20' width='20'>[ google / git-appraise ](https://github.com/google/git-appraise): Distributed code review system for Git repos * <img src='https://avatars3.githubusercontent.com/u/1386065?v=3&s=40' height='20' width='20'>[ NYTimes / gizmo ](https://github.com/NYTimes/gizmo): A Microservice Toolkit from The New York Times * <img src='https://avatars1.githubusercontent.com/u/45629?v=3&s=40' height='20' width='20'>[ davidlazar / vuvuzela ](https://github.com/davidlazar/vuvuzela): Private messaging system that hides metadata * <img src='https://avatars1.githubusercontent.com/u/749551?v=3&s=40' height='20' width='20'>[ docker / containerd ](https://github.com/docker/containerd): Standalone Container Daemon * <img src='https://avatars3.githubusercontent.com/u/1445228?v=3&s=40' height='20' width='20'>[ jfrazelle / onion ](https://github.com/jfrazelle/onion): Tor networking plugin for docker containers. * <img src='https://avatars1.githubusercontent.com/u/5000654?v=3&s=40' height='20' width='20'>[ getlantern / lantern ](https://github.com/getlantern/lantern): Open Internet for everyone. Lantern is a free desktop application that delivers fast, reliable and secure access to the open Internet for users in censored regions. It uses a variety of techniques to stay unblocked, including P2P and domain fronting. Lantern relies on users in uncensored regions acting as access points to the open Internet. * <img src='https://avatars0.githubusercontent.com/u/14110142?v=3&s=40' height='20' width='20'>[ v2ray / v2ray-core ](https://github.com/v2ray/v2ray-core): Building blocks for developing proxy servers in golang. * <img src='https://avatars1.githubusercontent.com/u/62991?v=3&s=40' height='20' width='20'>[ Masterminds / glide ](https://github.com/Masterminds/glide): Vendor Package Management for Golang * <img src='https://avatars1.githubusercontent.com/u/749551?v=3&s=40' height='20' width='20'>[ docker / docker ](https://github.com/docker/docker): Docker - the open-source application container engine * <img src='https://avatars3.githubusercontent.com/u/394382?v=3&s=40' height='20' width='20'>[ spf13 / hugo ](https://github.com/spf13/hugo): A Fast and Flexible Static Site Generator built with love by spf13 in GoLang * <img src='https://avatars0.githubusercontent.com/u/1128849?v=3&s=40' height='20' width='20'>[ mholt / caddy ](https://github.com/mholt/caddy): Fast, cross-platform HTTP/2 web server with automatic HTTPS * <img src='https://avatars0.githubusercontent.com/u/2946214?v=3&s=40' height='20' width='20'>[ gogits / gogs ](https://github.com/gogits/gogs): Gogs (Go Git Service) is a painless self-hosted Git service. * <img src='https://avatars3.githubusercontent.com/u/31996?v=3&s=40' height='20' width='20'>[ avelino / awesome-go ](https://github.com/avelino/awesome-go): A curated list of awesome Go frameworks, libraries and software * <img src='https://avatars2.githubusercontent.com/u/114509?v=3&s=40' height='20' width='20'>[ go-kit / kit ](https://github.com/go-kit/kit): A standard library for microservices. * <img src='https://avatars3.githubusercontent.com/u/104030?v=3&s=40' height='20' width='20'>[ golang / go ](https://github.com/golang/go): The Go programming language * <img src='https://avatars1.githubusercontent.com/u/4566?v=3&s=40' height='20' width='20'>[ RobotsAndPencils / buford ](https://github.com/RobotsAndPencils/buford): A push notification delivery engine for the new HTTP/2 APNS service. * <img src='https://avatars2.githubusercontent.com/u/8446613?v=3&s=40' height='20' width='20'>[ golang / example ](https://github.com/golang/example): Go example projects * <img src='https://avatars0.githubusercontent.com/u/1366124?v=3&s=40' height='20' width='20'>[ otium / ytdl ](https://github.com/otium/ytdl): YouTube download library and CLI written in Go * <img src='https://avatars1.githubusercontent.com/u/993322?v=3&s=40' height='20' width='20'>[ go-ozzo / ozzo-dbx ](https://github.com/go-ozzo/ozzo-dbx): A Go package that enhances the standard database/sql package by providing powerful data retrieval methods as well as DB-agnostic query building capabilities. * <img src='https://avatars2.githubusercontent.com/u/1070920?v=3&s=40' height='20' width='20'>[ go-python / gopy ](https://github.com/go-python/gopy): gopy generates a CPython extension module from a go package. * <img src='https://avatars3.githubusercontent.com/u/1080370?v=3&s=40' height='20' width='20'>[ pingcap / tidb ](https://github.com/pingcap/tidb): TiDB is a distributed SQL database compatible with MySQL protocol * <img src='https://avatars0.githubusercontent.com/u/233907?v=3&s=40' height='20' width='20'>[ astaxie / beego ](https://github.com/astaxie/beego): beego is an open-source, high-performance web framework for the Go programming language. * <img src='https://avatars1.githubusercontent.com/u/283442?v=3&s=40' height='20' width='20'>[ valyala / fasthttp ](https://github.com/valyala/fasthttp): Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http * <img src='https://avatars2.githubusercontent.com/u/1299?v=3&s=40' height='20' width='20'>[ hashicorp / terraform ](https://github.com/hashicorp/terraform): Terraform is a tool for building, changing, and combining infrastructure safely and efficiently. * <img src='https://avatars0.githubusercontent.com/u/578256?v=3&s=40' height='20' width='20'>[ xenolf / lego ](https://github.com/xenolf/lego): Let's Encrypt client and ACME library written in Go ####javascript * <img src='https://avatars1.githubusercontent.com/u/985197?v=3&s=40' height='20' width='20'>[ FreeCodeCamp / FreeCodeCamp ](https://github.com/FreeCodeCamp/FreeCodeCamp): The http://FreeCodeCamp.com open source codebase and curriculum. Learn to code and help nonprofits. * <img src='https://avatars3.githubusercontent.com/u/810438?v=3&s=40' height='20' width='20'>[ heroku / react-refetch ](https://github.com/heroku/react-refetch): A simple, declarative, and composable way to fetch data for React components * <img src='https://avatars0.githubusercontent.com/u/2044842?v=3&s=40' height='20' width='20'>[ jlmakes / scrollreveal.js ](https://github.com/jlmakes/scrollreveal.js): Easy scroll animations for web and mobile browsers. * <img src='https://avatars1.githubusercontent.com/u/948896?v=3&s=40' height='20' width='20'>[ oneuijs / You-Dont-Need-jQuery ](https://github.com/oneuijs/You-Dont-Need-jQuery): Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript. * <img src='https://avatars2.githubusercontent.com/u/250480?v=3&s=40' height='20' width='20'>[ google / blockly ](https://github.com/google/blockly): The web-based visual programming editor. * <img src='https://avatars1.githubusercontent.com/u/203725?v=3&s=40' height='20' width='20'>[ aframevr / aframe ](https://github.com/aframevr/aframe): Building Blocks for the VR Web * <img src='https://avatars1.githubusercontent.com/u/729873?v=3&s=40' height='20' width='20'>[ howdyai / botkit ](https://github.com/howdyai/botkit): Botkit is a toolkit for making bot applications * <img src='https://avatars0.githubusercontent.com/u/6550035?v=3&s=40' height='20' width='20'>[ schollz / musicsaur ](https://github.com/schollz/musicsaur): Music synchronization using browsers and a Python server - great for LAN systems! * <img src='https://avatars3.githubusercontent.com/u/253398?v=3&s=40' height='20' width='20'>[ NARKOZ / hacker-scripts ](https://github.com/NARKOZ/hacker-scripts): Based on a true story * <img src='https://avatars0.githubusercontent.com/u/113087?v=3&s=40' height='20' width='20'>[ liferay / senna.js ](https://github.com/liferay/senna.js): A blazing-fast Single Page Application engine * <img src='https://avatars3.githubusercontent.com/u/173661?v=3&s=40' height='20' width='20'>[ WebAssembly / binaryen ](https://github.com/WebAssembly/binaryen): Compiler infrastructure and toolchain library for WebAssembly, in C++ * <img src='https://avatars3.githubusercontent.com/u/810438?v=3&s=40' height='20' width='20'>[ rackt / redux ](https://github.com/rackt/redux): Predictable state container for JavaScript apps * <img src='https://avatars0.githubusercontent.com/u/197597?v=3&s=40' height='20' width='20'>[ facebook / react-native ](https://github.com/facebook/react-native): A framework for building native apps with React. * <img src='https://avatars0.githubusercontent.com/u/6352327?v=3&s=40' height='20' width='20'>[ FormidableLabs / victory ](https://github.com/FormidableLabs/victory): A collection of composable React components for building interactive data visualizations * <img src='https://avatars0.githubusercontent.com/u/150330?v=3&s=40' height='20' width='20'>[ getify / You-Dont-Know-JS ](https://github.com/getify/You-Dont-Know-JS): A book series on JavaScript. @YDKJS on twitter. * <img src='https://avatars1.githubusercontent.com/u/16724?v=3&s=40' height='20' width='20'>[ meteor / meteor ](https://github.com/meteor/meteor): Meteor, the JavaScript App Platform * <img src='https://avatars3.githubusercontent.com/u/216296?v=3&s=40' height='20' width='20'>[ angular / angular.js ](https://github.com/angular/angular.js): HTML enhanced for web apps * <img src='https://avatars1.githubusercontent.com/u/406631?v=3&s=40' height='20' width='20'>[ buunguyen / octotree ](https://github.com/buunguyen/octotree): Code tree for GitHub and GitLab * <img src='https://avatars1.githubusercontent.com/u/499550?v=3&s=40' height='20' width='20'>[ vuejs / vue ](https://github.com/vuejs/vue): Simple yet powerful library for building modern web interfaces. * <img src='https://avatars3.githubusercontent.com/u/8445?v=3&s=40' height='20' width='20'>[ facebook / react ](https://github.com/facebook/react): A declarative, efficient, and flexible JavaScript library for building user interfaces. * <img src='https://avatars3.githubusercontent.com/u/6104558?v=3&s=40' height='20' width='20'>[ mohebifar / lebab ](https://github.com/mohebifar/lebab): Turn your ES5 code into readable ES6. It does the opposite of what Babel does. * <img src='https://avatars1.githubusercontent.com/u/339208?v=3&s=40' height='20' width='20'>[ airbnb / javascript ](https://github.com/airbnb/javascript): JavaScript Style Guide * <img src='https://avatars0.githubusercontent.com/u/23123?v=3&s=40' height='20' width='20'>[ Semantic-Org / Semantic-UI ](https://github.com/Semantic-Org/Semantic-UI): Semantic is a UI component framework based around useful principles from natural language. * <img src='https://avatars1.githubusercontent.com/u/80?v=3&s=40' height='20' width='20'>[ nodejs / node ](https://github.com/nodejs/node): Node.js JavaScript runtime * <img src='https://avatars0.githubusercontent.com/u/6236424?v=3&s=40' height='20' width='20'>[ samiskin / redux-electron-store ](https://github.com/samiskin/redux-electron-store): A redux implementation that synchronizes itself between Electron processes ####ruby * <img src='https://avatars2.githubusercontent.com/u/206662?v=3&s=40' height='20' width='20'>[ OpenHunting / openhunt ](https://github.com/OpenHunting/openhunt): discover new products, give feedback, help each other * <img src='https://avatars1.githubusercontent.com/u/1589480?v=3&s=40' height='20' width='20'>[ Homebrew / homebrew ](https://github.com/Homebrew/homebrew): The missing package manager for OS X. * <img src='https://avatars1.githubusercontent.com/u/3124?v=3&s=40' height='20' width='20'>[ rails / rails ](https://github.com/rails/rails): Ruby on Rails * <img src='https://avatars3.githubusercontent.com/u/3999?v=3&s=40' height='20' width='20'>[ github / scientist ](https://github.com/github/scientist): A Ruby library for carefully refactoring critical paths. * <img src='https://avatars2.githubusercontent.com/u/237985?v=3&s=40' height='20' width='20'>[ jekyll / jekyll ](https://github.com/jekyll/jekyll): Jekyll is a blog-aware, static site generator in Ruby * <img src='https://avatars2.githubusercontent.com/u/1529246?v=3&s=40' height='20' width='20'>[ codelittinc / slacked ](https://github.com/codelittinc/slacked): A simple and easy way to send notifications to Slack from your Ruby or Rails application. * <img src='https://avatars0.githubusercontent.com/u/29154?v=3&s=40' height='20' width='20'>[ cerebris / jsonapi-resources ](https://github.com/cerebris/jsonapi-resources): A resource-focused Rails library for developing JSON API compliant servers. * <img src='https://avatars0.githubusercontent.com/u/5382?v=3&s=40' height='20' width='20'>[ chriseidhof / pomotv ](https://github.com/chriseidhof/pomotv): * <img src='https://avatars3.githubusercontent.com/u/83390?v=3&s=40' height='20' width='20'>[ jondot / awesome-react-native ](https://github.com/jondot/awesome-react-native): An "awesome" type curated list of React Native components, news, tools, and learning material * <img src='https://avatars2.githubusercontent.com/u/4723115?v=3&s=40' height='20' width='20'>[ dkhamsing / awesome_bot ](https://github.com/dkhamsing/awesome_bot): Validate links in awesome projects * <img src='https://avatars1.githubusercontent.com/u/17579?v=3&s=40' height='20' width='20'>[ Thibaut / devdocs ](https://github.com/Thibaut/devdocs): API Documentation Browser * <img src='https://avatars1.githubusercontent.com/u/216339?v=3&s=40' height='20' width='20'>[ twbs / bootstrap-sass ](https://github.com/twbs/bootstrap-sass): Official Sass port of Bootstrap 2 and 3. * <img src='https://avatars1.githubusercontent.com/u/305940?v=3&s=40' height='20' width='20'>[ gitlabhq / gitlabhq ](https://github.com/gitlabhq/gitlabhq): GitLab is version control for your server * <img src='https://avatars0.githubusercontent.com/u/727482?v=3&s=40' height='20' width='20'>[ caskroom / homebrew-cask ](https://github.com/caskroom/homebrew-cask): A CLI workflow for the administration of Mac applications distributed as binaries * <img src='https://avatars2.githubusercontent.com/u/869950?v=3&s=40' height='20' width='20'>[ fastlane / fastlane ](https://github.com/fastlane/fastlane): Connect all iOS deployment tools into one streamlined workflow * <img src='https://avatars1.githubusercontent.com/u/83835?v=3&s=40' height='20' width='20'>[ cantino / huginn ](https://github.com/cantino/huginn): Build agents that monitor and act on your behalf. Your agents are standing by! * <img src='https://avatars2.githubusercontent.com/u/16700?v=3&s=40' height='20' width='20'>[ ruby / ruby ](https://github.com/ruby/ruby): The Ruby Programming Language * <img src='https://avatars1.githubusercontent.com/u/474794?v=3&s=40' height='20' width='20'>[ realm / jazzy ](https://github.com/realm/jazzy): Soulful docs for Swift & Objective-C * <img src='https://avatars1.githubusercontent.com/u/1153134?v=3&s=40' height='20' width='20'>[ muan / emoji-cli ](https://github.com/muan/emoji-cli): Emoji searcher but as a CLI app. * <img src='https://avatars2.githubusercontent.com/u/3356474?v=3&s=40' height='20' width='20'>[ skywinder / github-changelog-generator ](https://github.com/skywinder/github-changelog-generator): Automatically generate change log from your tags, issues, labels and pull requests on GitHub. * <img src='https://avatars0.githubusercontent.com/u/10308?v=3&s=40' height='20' width='20'>[ intridea / omniauth ](https://github.com/intridea/omniauth): OmniAuth is a flexible authentication system utilizing Rack middleware. * <img src='https://avatars1.githubusercontent.com/u/150632?v=3&s=40' height='20' width='20'>[ bundler / gemstash ](https://github.com/bundler/gemstash): * <img src='https://avatars2.githubusercontent.com/u/869950?v=3&s=40' height='20' width='20'>[ fastlane / match ](https://github.com/fastlane/match): Easily sync your certificates and profiles across your team using git * <img src='https://avatars3.githubusercontent.com/u/1926764?v=3&s=40' height='20' width='20'>[ rapid7 / metasploit-framework ](https://github.com/rapid7/metasploit-framework): Metasploit Framework * <img src='https://avatars3.githubusercontent.com/u/81859?v=3&s=40' height='20' width='20'>[ fgrehm / vagrant-cachier ](https://github.com/fgrehm/vagrant-cachier): Caffeine reducer
tzpBingo/github-trending
2015/2015-12-20.md
Markdown
mit
24,808
#!/bin/sh # CYBERWATCH SAS - 2016 # # Security fix for RHSA-2015:1686 # # Security announcement date: 2015-08-25 06:10:14 UTC # Script generation date: 2016-05-12 18:13:16 UTC # # Operating System: Red Hat 7 # Architecture: x86_64 # # Vulnerable packages fix on version: # - python-django.noarch:1.6.11-2.el7ost # - python-django-bash-completion.noarch:1.6.11-2.el7ost # - python-django-doc.noarch:1.6.11-2.el7ost # # Last versions recommanded by security team: # - python-django.noarch:1.8.4-1.el7 # - python-django-bash-completion.noarch:1.8.4-1.el7 # - python-django-doc.noarch:1.8.4-1.el7 # # CVE List: # - CVE-2015-5143 # # More details: # - https://www.cyberwatch.fr/vulnerabilites # # Licence: Released under The MIT License (MIT), See LICENSE FILE sudo yum install python-django.noarch-1.8.4 -y sudo yum install python-django-bash-completion.noarch-1.8.4 -y sudo yum install python-django-doc.noarch-1.8.4 -y
Cyberwatch/cbw-security-fixes
Red_Hat_7/x86_64/2015/RHSA-2015:1686.sh
Shell
mit
940
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>Akimages</title> </head> <body bgcolor="#CCCCCC"> <p></p> <p>Original</p> <img src="../../images/lenna256.jpg"/> <div id = "porID" style="relative; top:100px; left:100px;"> <canvas id="canvas1"></canvas> </div> <div id = "porID" style="relative; top:100px; left:100px;"> <canvas id="canvas2"></canvas> </div> <div id = "porOB" style="relative; top:100px; left:100px;"> <canvas id="canvas3"></canvas> <div id = "porOB" style="relative; top:100px; left:100px;"> <canvas id="canvas4"></canvas> </div> </body> </html> <script type="text/javascript" src="../../libs/build/compilated/akimage.js"> </script> <script type="text/javascript" src="js/AkPaddingZero.js"></script>
alefortvi/akimagejs
Demos/Modules/AkPaddingZero.html
HTML
mit
879
<h2>This is my home page</h2> <p>some text here</p>
OrifInformatique/ci_tuto
application/views/pages/home.php
PHP
mit
51
/** * */ package com.kant.datastructure.queues; import com.kant.sortingnsearching.MyUtil; /** * @author shaskant * */ public class GenerateBinaryNumbers1toN { /** * * @param n * @return * @throws OverFlowException * @throws UnderFlowException */ public String[] solve(int n) throws OverFlowException, UnderFlowException { String[] result = new String[n]; System.out.println("input # " + n); Queue<String> dequeue = new QueueListImplementation<String>(); dequeue.enQueue("1"); for (int count = 0; count < n; count++) { result[count] = dequeue.deQueue(); dequeue.enQueue(result[count]+"0"); dequeue.enQueue(result[count]+"1"); } return result; } /** * * @param args * @throws OverFlowException * @throws UnderFlowException */ public static void main(String[] args) throws OverFlowException, UnderFlowException { GenerateBinaryNumbers1toN prob = new GenerateBinaryNumbers1toN(); System.out.print("output # "); MyUtil.printArrayType(prob.solve(10)); } }
thekant/myCodeRepo
src/com/kant/datastructure/queues/GenerateBinaryNumbers1toN.java
Java
mit
1,022
// Binary-search solution for balance. // O(n * log (max coordinate / epsilon)) // David Garcia Soriano. #include <algorithm> #include <cstdio> #include <cmath> using namespace std; const int maxn = 50000; const double eps = 1e-11, infinity = 1e300; double px[maxn], py[maxn]; int n; bool possible(double d, double& px1, double& px2) { double x1 = -infinity, x2 = infinity; for (int i = 0; i < n; ++i) { if (d < py[i]) return false; double p = sqrt(d * d - py[i] * py[i]), a = px[i] - p, b = px[i] + p; x1 = max(x1, a); x2 = min(x2, b); if (x1 > x2) return false; } px1 = x1; px2 = x2; return true; } int main() { while (scanf("%i", &n) == 1 && n > 0) { double a, b = 0, x1, x2; for (int i = 0; i < n; ++i) { scanf("%lf%lf", &px[i], &py[i]); if (py[i] < 0) py[i] = -py[i]; b = max(b, py[i]); } if (b == 0) { if (n == 1) { printf("%.9lf %.9lf\n", px[0], .0); continue; } b = 1; } while (!possible(b, x1, x2)) b *= 2; a = b / 2; while (possible(a, x1, x2)) a /= 2; for (int i = 0; i < 100 && (b - a > eps || x2 - x1 > eps); ++i) { double m = (a + b) / 2; if (possible(m, x1, x2)) b = m; else a = m; } printf("%.9lf %.9lf\n", (x1 + x2) / 2, b); } return 0; }
Emunt/contest_problems
Java/PC2/Solutions/TrickTreat/balance.cpp
C++
mit
1,320
--- layout: post title: "Docker安装Mysql管理工具Phpmyadmin" tagline: "" description: "MySQL 和 MariaDB 的Web管理工具, 浏览器可以代替客户端了, 基本操作都够用了" date: '2017-12-27 13:09:08 +0800' category: docker tags: docker phpmyadmin mysql linux --- > {{ page.description }} # 拉取镜像 ```bash # 搜索镜像 $ docker search phpmyadmin NAME DESCRIPTION STARS OFFICIAL AUTOMATED phpmyadmin/phpmyadmin A web interface for MySQL and MariaDB. 441 [OK] nazarpc/phpmyadmin phpMyAdmin as Docker container, based on o... 56 [OK] ...... # 没有官方的镜像, 那就默认打星最多的 (默认标签:latest) $ docker pull phpmyadmin/phpmyadmin ``` # 初始化phpmyadmin容器 ```bash # 关联msyql容器初始化 $ docker run -d \ --name myadmin \ --link mysql:db \ -p 8080:80 \ phpmyadmin/phpmyadmin ``` **详解**: - `-d` - 以后台模式运行 - `--name myadmin` - 容器命名为 `myadmin`, 容器管理时用(启动/停止/重启/查看日志等) - `--link mysql:db` - 容器关联, 这里我们关联到之前创建的 `mysql` 容器, 别名这里设置为 `db` - `-p 8080:80` - 端口映射, 本地端口:容器端口, 访问: `http://ip:8080` - `phpmyadmin/phpmyadmin` - 要初始化的镜像名 # 关联独立的mysql服务器 ```bash # 比如阿里云的msyql服务器 $ docker run -d \ --name myadmin_aliyun \ -e PMA_HOST=xxx.mysql.rds.aliyuncs.com \ -e PMA_PORT=3xx6 \ -p 8081:80 \ phpmyadmin/phpmyadmin ``` **详解**: - `-e PMA_HOST=xxxx` - 环境变量: mysql服务器域名或IP地址 - `-e PMA_PORT=3xx6` - 环境变量: mysql端口 如果不想每次都输入账号密码的话, 可以设置 `PMA_USER` 和 `PMA_PASSWORD` 环境变量(注意场合), 更多环境变量可以看此镜像的文档 --- 参考: - [phpmyadmin/phpmyadmin 镜像文档](https://hub.docker.com/r/phpmyadmin/phpmyadmin/)
xu3352/xu3352.github.io
_posts/2017-12-27-install-phpmyadmin-with-docker.md
Markdown
mit
2,010
require 'log4r' module VagrantPlugins module G5K module Network class Nat def initialize(env, driver, oar_driver) @logger = Log4r::Logger.new("vagrant::network::nat") # command driver is unused @env = env @driver = driver @oar_driver = oar_driver @net = env[:machine].provider_config.net end def generate_net() fwd_ports = @net[:ports].map do |p| "hostfwd=tcp::#{p}" end.join(',') net = "-net nic,model=virtio -net user,#{fwd_ports}" @logger.debug("Generated net string : #{net}") return "NAT #{net}" end def check_state(job_id) return nil end def attach() # noop end def detach() # noop end def vm_ssh_info(vmid) # get forwarded port 22 ports = @net[:ports] ssh_fwd = ports.select{ |x| x.split(':')[1] == '22'}.first if ssh_fwd.nil? @env[:ui].error "SSH port 22 must be forwarded" raise Error "SSh port 22 isn't forwarded" end ssh_fwd = ssh_fwd.split('-:')[0] # get node hosting the vm job = @oar_driver.check_job(@env[:machine].id) ssh_info = { :host => job["assigned_network_address"].first, :port => ssh_fwd } @logger.debug(ssh_info) ssh_info end end end end end
msimonin/vagrant-g5k
lib/vagrant-g5k/network/nat.rb
Ruby
mit
1,523
<?php namespace Gitlab\Clients; class DeployKeyClient extends AbstractClient { /** * @param int $projectId * @return \Psr\Http\Message\ResponseInterface */ public function listDeployKeys($projectId) { return $this->getRequest(sprintf('projects/%u/keys', $projectId)); } /** * @param int $projectId * @param int $keyId * @return \Psr\Http\Message\ResponseInterface */ public function getDeployKey($projectId, $keyId) { return $this->getRequest(sprintf('projects/%u/keys/%u', $projectId, $keyId)); } /** * @param int $projectId * @param array|null $data * @return \Psr\Http\Message\ResponseInterface */ public function createDeployKey($projectId, array $data = null) { return $this->postRequest(sprintf('projects/%u/keys', $projectId), $data); } /** * @param int $projectId * @param int $keyId * @return \Psr\Http\Message\ResponseInterface */ public function deleteDeployKey($projectId, $keyId) { return $this->deleteRequest(sprintf('projects/%u/keys/%u', $projectId, $keyId)); } }
AlexKovalevych/gitlab-api
src/Clients/DeployKeyClient.php
PHP
mit
1,173
{% extends "layouts/_block_content.html" %} {% set page_title = "Account email change link expired " %} {% block main %} <h1 class="u-fs-xl">Your verification link has expired</h1> <div> <p> You will need to sign back into your account and <a href="{{ url_for('account_bp.resend_account_email_change_expired_token', token=token) }}">request another verification email</a>. </p> <p> <p>If you need help, please <a href="{{ url_for('contact_us_bp.contact_us') }}" rel="noopener">contact us</a>.</p> </p> </div> {% endblock main %}
ONSdigital/ras-frontstage
frontstage/templates/account/account-email-change-confirm-link-expired.html
HTML
mit
565
from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False)
compsoc-ssc/compsocssc
general/models.py
Python
mit
2,517
import complexism as cx import complexism.agentbased.statespace as ss import epidag as dag dbp = cx.read_dbp_script(cx.load_txt('../scripts/SIR_BN.txt')) pc = dag.quick_build_parameter_core(cx.load_txt('../scripts/pSIR.txt')) dc = dbp.generate_model('M1', **pc.get_samplers()) ag = ss.StSpAgent('Helen', dc['Sus'], pc) model = cx.SingleIndividualABM('M1', ag) model.add_observing_attribute('State') print(cx.simulate(model, None, 0, 10, 1))
TimeWz667/Kamanian
example/OOP/O2.4 SS, Single agent model.py
Python
mit
446
from __future__ import division, print_function from abc import ABCMeta, abstractmethod import matplotlib as mpl mpl.use('TkAgg') from matplotlib.ticker import MaxNLocator, Formatter, Locator from matplotlib.widgets import Slider, Button import matplotlib.patches as patches import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from tadtool.tad import GenomicRegion, sub_matrix_regions, sub_data_regions, \ data_array, insulation_index, sub_vector_regions, sub_regions, \ call_tads_insulation_index, directionality_index, call_tads_directionality_index, normalised_insulation_index import math import copy import numpy as np from bisect import bisect_left from future.utils import string_types try: import Tkinter as tk import tkFileDialog as filedialog except ImportError: import tkinter as tk from tkinter import filedialog class BasePlotter(object): __metaclass__ = ABCMeta def __init__(self, title): self._ax = None self.cax = None self.title = title @abstractmethod def _plot(self, region=None, **kwargs): raise NotImplementedError("Subclasses need to override _plot function") @abstractmethod def plot(self, region=None, **kwargs): raise NotImplementedError("Subclasses need to override plot function") @property def fig(self): return self._ax.figure @property def ax(self): if not self._ax: _, self._ax = plt.subplots() return self._ax @ax.setter def ax(self, value): self._ax = value class GenomeCoordFormatter(Formatter): """ Process axis tick labels to give nice representations of genomic coordinates """ def __init__(self, chromosome, display_scale=True): """ :param chromosome: :class:`~kaic.data.genomic.GenomicRegion` or string :param display_scale: Boolean Display distance scale at bottom right """ if isinstance(chromosome, GenomicRegion): self.chromosome = chromosome.chromosome else: self.chromosome = chromosome self.display_scale = display_scale def _format_val(self, x, prec_offset=0): if x == 0: oom_loc = 0 else: oom_loc = int(math.floor(math.log10(abs(x)))) view_range = self.axis.axes.get_xlim() oom_range = int(math.floor(math.log10(abs(view_range[1] - view_range[0])))) if oom_loc >= 3: return "{:.{prec}f}kb".format(x/1000, prec=max(0, 3 + prec_offset - oom_range)) return "{:.0f}b".format(x) def __call__(self, x, pos=None): """ Return label for tick at coordinate x. Relative position of ticks can be specified with pos. First tick gets chromosome name. """ s = self._format_val(x, prec_offset=1) if pos == 0 or x == 0: return "{}:{}".format(self.chromosome, s) return s def get_offset(self): """ Return information about the distances between tick bars and the size of the view window. Is called by matplotlib and displayed in lower right corner of plots. """ if not self.display_scale: return "" view_range = self.axis.axes.get_xlim() view_dist = abs(view_range[1] - view_range[0]) tick_dist = self.locs[2] - self.locs[1] minor_tick_dist = tick_dist/5 minor_tick_dist_str = self._format_val(minor_tick_dist, prec_offset=2) tick_dist_str = self._format_val(tick_dist, prec_offset=1) view_dist_str = self._format_val(view_dist) return "{}|{}|{}".format(minor_tick_dist_str, tick_dist_str, view_dist_str) class GenomeCoordLocator(MaxNLocator): """ Choose locations of genomic coordinate ticks on the plot axis. Behaves like default Matplotlib locator, except that it always places a tick at the start and the end of the window. """ def __call__(self): vmin, vmax = self.axis.get_view_interval() ticks = self.tick_values(vmin, vmax) # Make sure that first and last tick are the start # and the end of the genomic range plotted. If next # ticks are too close, remove them. ticks[0] = vmin ticks[-1] = vmax if ticks[1] - vmin < (vmax - vmin)/(self._nbins*3): ticks = np.delete(ticks, 1) if vmax - ticks[-2] < (vmax - vmin)/(self._nbins*3): ticks = np.delete(ticks, -2) return self.raise_if_exceeds(np.array(ticks)) class MinorGenomeCoordLocator(Locator): """ Choose locations of minor tick marks between major tick labels. Modification of the Matplotlib AutoMinorLocator, except that it uses the distance between 2nd and 3rd major mark as reference, instead of 2nd and 3rd. """ def __init__(self, n): self.ndivs = n def __call__(self): majorlocs = self.axis.get_majorticklocs() try: majorstep = majorlocs[2] - majorlocs[1] except IndexError: # Need at least two major ticks to find minor tick locations # TODO: Figure out a way to still be able to display minor # ticks without two major ticks visible. For now, just display # no ticks at all. majorstep = 0 if self.ndivs is None: if majorstep == 0: # TODO: Need a better way to figure out ndivs ndivs = 1 else: x = int(np.round(10 ** (np.log10(majorstep) % 1))) if x in [1, 5, 10]: ndivs = 5 else: ndivs = 4 else: ndivs = self.ndivs minorstep = majorstep / ndivs vmin, vmax = self.axis.get_view_interval() if vmin > vmax: vmin, vmax = vmax, vmin if len(majorlocs) > 0: t0 = majorlocs[1] tmin = ((vmin - t0) // minorstep + 1) * minorstep tmax = ((vmax - t0) // minorstep + 1) * minorstep locs = np.arange(tmin, tmax, minorstep) + t0 cond = np.abs((locs - t0) % majorstep) > minorstep / 10.0 locs = locs.compress(cond) else: locs = [] return self.raise_if_exceeds(np.array(locs)) class BasePlotter1D(BasePlotter): __metaclass__ = ABCMeta def __init__(self, title): BasePlotter.__init__(self, title=title) def plot(self, region=None, ax=None, **kwargs): if isinstance(region, string_types): region = GenomicRegion.from_string(region) if ax: self.ax = ax # set genome tick formatter self.ax.xaxis.set_major_formatter(GenomeCoordFormatter(region)) self.ax.xaxis.set_major_locator(GenomeCoordLocator(nbins=5)) self.ax.xaxis.set_minor_locator(MinorGenomeCoordLocator(n=5)) self.ax.set_title(self.title) self._plot(region, **kwargs) self.ax.set_xlim(region.start, region.end) return self.fig, self.ax def prepare_normalization(norm="lin", vmin=None, vmax=None): if isinstance(norm, mpl.colors.Normalize): norm.vmin = vmin norm.vmax = vmax return norm if norm == "log": return mpl.colors.LogNorm(vmin=vmin, vmax=vmax) elif norm == "lin": return mpl.colors.Normalize(vmin=vmin, vmax=vmax) else: raise ValueError("'{}'' not a valid normalization method.".format(norm)) class BasePlotterHic(object): __metaclass__ = ABCMeta def __init__(self, hic_matrix, regions=None, colormap='RdBu', norm="log", vmin=None, vmax=None, show_colorbar=True, blend_masked=False): if regions is None: for i in range(hic_matrix.shape[0]): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.regions = regions self.hic_matrix = hic_matrix self.colormap = copy.copy(mpl.cm.get_cmap(colormap)) if blend_masked: self.colormap.set_bad(self.colormap(0)) self._vmin = vmin self._vmax = vmax self.norm = prepare_normalization(norm=norm, vmin=vmin, vmax=vmax) self.colorbar = None self.slider = None self.show_colorbar = show_colorbar def add_colorbar(self, ax=None): ax = self.cax if ax is None else ax cmap_data = mpl.cm.ScalarMappable(norm=self.norm, cmap=self.colormap) cmap_data.set_array([self.vmin, self.vmax]) self.colorbar = plt.colorbar(cmap_data, cax=ax, orientation="vertical") @property def vmin(self): return self._vmin if self._vmin else np.nanmin(self.hic_matrix) @property def vmax(self): return self._vmax if self._vmax else np.nanmax(self.hic_matrix) class HicPlot(BasePlotter1D, BasePlotterHic): def __init__(self, hic_matrix, regions=None, title='', colormap='viridis', max_dist=None, norm="log", vmin=None, vmax=None, show_colorbar=True, blend_masked=False): BasePlotter1D.__init__(self, title=title) BasePlotterHic.__init__(self, hic_matrix, regions=regions, colormap=colormap, vmin=vmin, vmax=vmax, show_colorbar=show_colorbar, norm=norm, blend_masked=blend_masked) self.max_dist = max_dist self.hicmesh = None def _plot(self, region=None, cax=None): if region is None: raise ValueError("Cannot plot triangle plot for whole genome.") hm, sr = sub_matrix_regions(self.hic_matrix, self.regions, region) hm[np.tril_indices(hm.shape[0])] = np.nan # Remove part of matrix further away than max_dist if self.max_dist is not None: for i in range(hm.shape[0]): i_region = sr[i] for j in range(hm.shape[1]): j_region = sr[j] if j_region.start-i_region.end > self.max_dist: hm[i, j] = np.nan hm_masked = np.ma.MaskedArray(hm, mask=np.isnan(hm)) # prepare an array of the corner coordinates of the Hic-matrix # Distances have to be scaled by sqrt(2), because the diagonals of the bins # are sqrt(2)*len(bin_size) sqrt2 = math.sqrt(2) bin_coords = np.r_[[(x.start - 1) for x in sr], sr[-1].end]/sqrt2 X, Y = np.meshgrid(bin_coords, bin_coords) # rotatate coordinate matrix 45 degrees sin45 = math.sin(math.radians(45)) X_, Y_ = X*sin45 + Y*sin45, X*sin45 - Y*sin45 # shift x coords to correct start coordinate and center the diagonal directly on the # x-axis X_ -= X_[1, 0] - (sr[0].start - 1) Y_ -= .5*np.min(Y_) + .5*np.max(Y_) # create plot self.hicmesh = self.ax.pcolormesh(X_, Y_, hm_masked, cmap=self.colormap, norm=self.norm) # set limits and aspect ratio #self.ax.set_aspect(aspect="equal") ylim_max = 0.5*(region.end-region.start) if self.max_dist is not None and self.max_dist/2 < ylim_max: ylim_max = self.max_dist/2 self.ax.set_ylim(0, ylim_max) # remove y ticks self.ax.set_yticks([]) # hide background patch self.ax.patch.set_visible(False) if self.show_colorbar: self.add_colorbar(cax) def set_clim(self, vmin, vmax): self.hicmesh.set_clim(vmin=vmin, vmax=vmax) if self.colorbar is not None: self.colorbar.vmin = vmin self.colorbar.vmax = vmax self.colorbar.draw_all() class DataArrayPlot(BasePlotter1D): def __init__(self, data, window_sizes=None, regions=None, title='', midpoint=None, colormap='coolwarm_r', vmax=None, current_window_size=0, log_y=True): if regions is None: regions = [] for i in range(data.shape[1]): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.regions = regions BasePlotter1D.__init__(self, title=title) self.da = data if window_sizes is None: window_sizes = [] try: l = len(data) except TypeError: l = data.shape[0] for i in range(l): window_sizes.append(i) self.window_sizes = window_sizes self.colormap = colormap self.midpoint = midpoint self.mesh = None self.vmax = vmax self.window_size_line = None self.current_window_size = current_window_size self.log_y = log_y def _plot(self, region=None, cax=None): da_sub, regions_sub = sub_data_regions(self.da, self.regions, region) da_sub_masked = np.ma.MaskedArray(da_sub, mask=np.isnan(da_sub)) bin_coords = np.r_[[(x.start - 1) for x in regions_sub], regions_sub[-1].end] x, y = np.meshgrid(bin_coords, self.window_sizes) self.mesh = self.ax.pcolormesh(x, y, da_sub_masked, cmap=self.colormap, vmax=self.vmax) self.colorbar = plt.colorbar(self.mesh, cax=cax, orientation="vertical") self.window_size_line = self.ax.axhline(self.current_window_size, color='red') if self.log_y: self.ax.set_yscale("log") self.ax.set_ylim((np.nanmin(self.window_sizes), np.nanmax(self.window_sizes))) def set_clim(self, vmin, vmax): self.mesh.set_clim(vmin=vmin, vmax=vmax) if self.colorbar is not None: self.colorbar.vmin = vmin self.colorbar.vmax = vmax self.colorbar.draw_all() def update(self, window_size): self.window_size_line.set_ydata(window_size) class TADPlot(BasePlotter1D): def __init__(self, regions, title='', color='black'): BasePlotter1D.__init__(self, title=title) self.regions = regions self.color = color self.current_region = None def _plot(self, region=None, cax=None): self.current_region = region try: sr, start_ix, end_ix = sub_regions(self.regions, region) trans = self.ax.get_xaxis_transform() for r in sr: region_patch = patches.Rectangle( (r.start, .2), width=abs(r.end - r.start), height=.6, transform=trans, facecolor=self.color, edgecolor='white', linewidth=2. ) self.ax.add_patch(region_patch) except ValueError: pass self.ax.axis('off') def update(self, regions): self.regions = regions self.ax.cla() self.plot(region=self.current_region, ax=self.ax) class DataLinePlot(BasePlotter1D): def __init__(self, data, regions=None, title='', init_row=0, is_symmetric=False): BasePlotter1D.__init__(self, title=title) if regions is None: regions = [] for i in range(len(data)): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.init_row = init_row self.data = data self.sr = None self.da_sub = None self.regions = regions self.current_region = None self.line = None self.current_ix = init_row self.current_cutoff = None self.cutoff_line = None self.cutoff_line_mirror = None self.is_symmetric = is_symmetric def _new_region(self, region): self.current_region = region self.da_sub, self.sr = sub_data_regions(self.data, self.regions, region) def _plot(self, region=None, cax=None): self._new_region(region) bin_coords = [(x.start - 1) for x in self.sr] ds = self.da_sub[self.init_row] self.line, = self.ax.plot(bin_coords, ds) if not self.is_symmetric: self.current_cutoff = (self.ax.get_ylim()[1] - self.ax.get_ylim()[0]) / 2 + self.ax.get_ylim()[0] else: self.current_cutoff = self.ax.get_ylim()[1]/ 2 self.ax.axhline(0.0, linestyle='dashed', color='grey') self.cutoff_line = self.ax.axhline(self.current_cutoff, color='r') if self.is_symmetric: self.cutoff_line_mirror = self.ax.axhline(-1*self.current_cutoff, color='r') self.ax.set_ylim((np.nanmin(ds), np.nanmax(ds))) def update(self, ix=None, cutoff=None, region=None, update_canvas=True): if region is not None: self._new_region(region) if ix is not None and ix != self.current_ix: ds = self.da_sub[ix] self.current_ix = ix self.line.set_ydata(ds) self.ax.set_ylim((np.nanmin(ds), np.nanmax(ds))) if cutoff is None: if not self.is_symmetric: self.update(cutoff=(self.ax.get_ylim()[1]-self.ax.get_ylim()[0])/2 + self.ax.get_ylim()[0], update_canvas=False) else: self.update(cutoff=self.ax.get_ylim()[1] / 2, update_canvas=False) if update_canvas: self.fig.canvas.draw() if cutoff is not None and cutoff != self.current_cutoff: if self.is_symmetric: self.current_cutoff = abs(cutoff) else: self.current_cutoff = cutoff self.cutoff_line.set_ydata(self.current_cutoff) if self.is_symmetric: self.cutoff_line_mirror.set_ydata(-1*self.current_cutoff) if update_canvas: self.fig.canvas.draw() class TADtoolPlot(object): def __init__(self, hic_matrix, regions=None, data=None, window_sizes=None, norm='lin', max_dist=3000000, max_percentile=99.99, algorithm='insulation', matrix_colormap=None, data_colormap=None, log_data=True): self.hic_matrix = hic_matrix if regions is None: regions = [] for i in range(hic_matrix.shape[0]): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.regions = regions self.norm = norm self.fig = None self.max_dist = max_dist self.algorithm = algorithm self.svmax = None self.min_value = np.nanmin(self.hic_matrix[np.nonzero(self.hic_matrix)]) self.min_value_data = None self.hic_plot = None self.tad_plot = None self.data_plot = None self.line_plot = None self.sdata = None self.data_ax = None self.line_ax = None self.da = None self.ws = None self.current_window_size = None self.window_size_text = None self.tad_cutoff_text = None self.max_percentile = max_percentile self.tad_regions = None self.current_da_ix = None self.button_save_tads = None self.button_save_vector = None self.button_save_matrix = None self.log_data = log_data if algorithm == 'insulation': self.tad_algorithm = insulation_index self.tad_calling_algorithm = call_tads_insulation_index self.is_symmetric = False if matrix_colormap is None: self.matrix_colormap = LinearSegmentedColormap.from_list('myreds', ['white', 'red']) if data_colormap is None: self.data_plot_color = 'plasma' elif algorithm == 'ninsulation': self.tad_algorithm = normalised_insulation_index self.tad_calling_algorithm = call_tads_insulation_index self.is_symmetric = True if matrix_colormap is None: self.matrix_colormap = LinearSegmentedColormap.from_list('myreds', ['white', 'red']) if data_colormap is None: self.data_plot_color = LinearSegmentedColormap.from_list('myreds', ['blue', 'white', 'red']) elif algorithm == 'directionality': self.tad_algorithm = directionality_index self.tad_calling_algorithm = call_tads_directionality_index self.is_symmetric = True if matrix_colormap is None: self.matrix_colormap = LinearSegmentedColormap.from_list('myreds', ['white', 'red']) if data_colormap is None: self.data_plot_color = LinearSegmentedColormap.from_list('myreds', ['blue', 'white', 'red']) if data is None: self.da, self.ws = data_array(hic_matrix=self.hic_matrix, regions=self.regions, tad_method=self.tad_algorithm, window_sizes=window_sizes) else: self.da = data if window_sizes is None: raise ValueError("window_sizes parameter cannot be None when providing data!") self.ws = window_sizes def vmax_slider_update(self, val): self.hic_plot.set_clim(self.min_value, val) def data_slider_update(self, val): if self.is_symmetric: self.data_plot.set_clim(-1*val, val) else: self.data_plot.set_clim(self.min_value_data, val) def on_click_save_tads(self, event): tk.Tk().withdraw() # Close the root window save_path = filedialog.asksaveasfilename() if save_path is not None: with open(save_path, 'w') as o: for region in self.tad_regions: o.write("%s\t%d\t%d\n" % (region.chromosome, region.start-1, region.end)) def on_click_save_vector(self, event): tk.Tk().withdraw() # Close the root window save_path = filedialog.asksaveasfilename() if save_path is not None: da_sub = self.da[self.current_da_ix] with open(save_path, 'w') as o: for i, region in enumerate(self.regions): o.write("%s\t%d\t%d\t.\t%e\n" % (region.chromosome, region.start-1, region.end, da_sub[i])) def on_click_save_matrix(self, event): tk.Tk().withdraw() # Close the root window save_path = filedialog.asksaveasfilename() if save_path is not None: with open(save_path, 'w') as o: # write regions for i, region in enumerate(self.regions): o.write("%s:%d-%d" % (region.chromosome, region.start-1, region.end)) if i < len(self.regions)-1: o.write("\t") else: o.write("\n") # write matrix n_rows = self.da.shape[0] n_cols = self.da.shape[1] for i in range(n_rows): window_size = self.ws[i] o.write("%d\t" % window_size) for j in range(n_cols): o.write("%e" % self.da[i, j]) if j < n_cols-1: o.write("\t") else: o.write("\n") def plot(self, region=None): # set up plotting grid self.fig = plt.figure(figsize=(10, 10)) # main plots grid_size = (32, 15) hic_vmax_slider_ax = plt.subplot2grid(grid_size, (0, 0), colspan=13) hic_ax = plt.subplot2grid(grid_size, (1, 0), rowspan=9, colspan=13) hp_cax = plt.subplot2grid(grid_size, (1, 14), rowspan=9, colspan=1) tad_ax = plt.subplot2grid(grid_size, (10, 0), rowspan=1, colspan=13, sharex=hic_ax) line_ax = plt.subplot2grid(grid_size, (12, 0), rowspan=6, colspan=13, sharex=hic_ax) line_cax = plt.subplot2grid(grid_size, (12, 13), rowspan=6, colspan=2) data_vmax_slider_ax = plt.subplot2grid(grid_size, (19, 0), colspan=13) data_ax = plt.subplot2grid(grid_size, (20, 0), rowspan=9, colspan=13, sharex=hic_ax) da_cax = plt.subplot2grid(grid_size, (20, 14), rowspan=9, colspan=1) # buttons save_tads_ax = plt.subplot2grid(grid_size, (31, 0), rowspan=1, colspan=4) self.button_save_tads = Button(save_tads_ax, 'Save TADs') self.button_save_tads.on_clicked(self.on_click_save_tads) save_vector_ax = plt.subplot2grid(grid_size, (31, 5), rowspan=1, colspan=4) self.button_save_vector = Button(save_vector_ax, 'Save current values') self.button_save_vector.on_clicked(self.on_click_save_vector) save_matrix_ax = plt.subplot2grid(grid_size, (31, 10), rowspan=1, colspan=4) self.button_save_matrix = Button(save_matrix_ax, 'Save matrix') self.button_save_matrix.on_clicked(self.on_click_save_matrix) # add subplot content max_value = np.nanpercentile(self.hic_matrix, self.max_percentile) init_value = .2*max_value # HI-C VMAX SLIDER self.svmax = Slider(hic_vmax_slider_ax, 'vmax', self.min_value, max_value, valinit=init_value, color='grey') self.svmax.on_changed(self.vmax_slider_update) # HI-C self.hic_plot = HicPlot(self.hic_matrix, self.regions, max_dist=self.max_dist, norm=self.norm, vmax=init_value, vmin=self.min_value, colormap=self.matrix_colormap) self.hic_plot.plot(region, ax=hic_ax, cax=hp_cax) # generate data array self.min_value_data = np.nanmin(self.da[np.nonzero(self.da)]) max_value_data = np.nanpercentile(self.da, self.max_percentile) init_value_data = .5*max_value_data # LINE PLOT da_ix = int(self.da.shape[0]/2) self.current_da_ix = da_ix self.line_plot = DataLinePlot(self.da, regions=self.regions, init_row=da_ix, is_symmetric=self.is_symmetric) self.line_plot.plot(region, ax=line_ax) self.line_ax = line_ax # line info self.current_window_size = self.ws[da_ix] line_cax.text(.1, .8, 'Window size', fontweight='bold') self.window_size_text = line_cax.text(.3, .6, str(self.current_window_size)) line_cax.text(.1, .4, 'TAD cutoff', fontweight='bold') self.tad_cutoff_text = line_cax.text(.3, .2, "%.5f" % self.line_plot.current_cutoff) line_cax.axis('off') # TAD PLOT self.tad_regions = self.tad_calling_algorithm(self.da[da_ix], self.line_plot.current_cutoff, self.regions) self.tad_plot = TADPlot(self.tad_regions) self.tad_plot.plot(region=region, ax=tad_ax) # DATA ARRAY self.data_plot = DataArrayPlot(self.da, self.ws, self.regions, vmax=init_value_data, colormap=self.data_plot_color, current_window_size=self.ws[da_ix], log_y=self.log_data) self.data_plot.plot(region, ax=data_ax, cax=da_cax) # DATA ARRAY SLIDER if self.is_symmetric: self.sdata = Slider(data_vmax_slider_ax, 'vmax', 0.0, max_value_data, valinit=init_value_data, color='grey') else: self.sdata = Slider(data_vmax_slider_ax, 'vmax', self.min_value_data, max_value_data, valinit=init_value_data, color='grey') self.sdata.on_changed(self.data_slider_update) self.data_slider_update(init_value_data) # clean up hic_ax.xaxis.set_visible(False) line_ax.xaxis.set_visible(False) # enable hover self.data_ax = data_ax cid = self.fig.canvas.mpl_connect('button_press_event', self.on_click) return self.fig, (hic_vmax_slider_ax, hic_ax, line_ax, data_ax, hp_cax, da_cax) def on_click(self, event): if event.inaxes == self.data_ax or event.inaxes == self.line_ax: if event.inaxes == self.data_ax: ws_ix = bisect_left(self.ws, event.ydata) self.current_window_size = self.ws[ws_ix] self.current_da_ix = ws_ix self.data_plot.update(window_size=self.ws[ws_ix]) self.line_plot.update(ix=ws_ix, update_canvas=False) self.tad_cutoff_text.set_text("%.5f" % self.line_plot.current_cutoff) self.window_size_text.set_text(str(self.current_window_size)) elif event.inaxes == self.line_ax: if self.is_symmetric: self.line_plot.update(cutoff=abs(event.ydata), update_canvas=False) else: self.line_plot.update(cutoff=abs(event.ydata), update_canvas=False) self.tad_cutoff_text.set_text("%.5f" % self.line_plot.current_cutoff) # update TADs self.tad_regions = self.tad_calling_algorithm(self.da[self.current_da_ix], self.line_plot.current_cutoff, self.regions) self.tad_plot.update(self.tad_regions) self.fig.canvas.draw()
vaquerizaslab/tadtool
tadtool/plot.py
Python
mit
28,848
#define BOOST_TEST_NO_LIB #include <boost/test/auto_unit_test.hpp> #include "dormouse-engine/essentials/Formatter.hpp" using namespace dormouse_engine::essentials; namespace { BOOST_AUTO_TEST_SUITE(FormatterTestSuite); BOOST_AUTO_TEST_CASE(FormatsEmptyString) { std::string s; Formatter f(Formatter::FormatterChars('$', '{', '}', '\\')); Formatter::FormatList result; f.format(result, s); BOOST_CHECK(result.empty()); } BOOST_AUTO_TEST_CASE(FormatsNoSpecial) { std::string s = "No special characters here ({} is not special if no dollar sign before)"; Formatter f(Formatter::FormatterChars('$', '{', '}', '\\')); Formatter::FormatList result; f.format(result, s); BOOST_REQUIRE(result.size() == 1); BOOST_CHECK_EQUAL(result.front().function, '\0'); BOOST_CHECK_EQUAL(result.front().opts, s); } BOOST_AUTO_TEST_CASE(FormatsAllEscaped) { std::string s = "No special characters here (neither \\$f nor \\${opts}f is not special if \\$ is preceded by \\\\)"; std::string escaped = "No special characters here (neither $f nor ${opts}f is not special if $ is preceded by \\)"; Formatter f(Formatter::FormatterChars('$', '{', '}', '\\')); Formatter::FormatList result; f.format(result, s); BOOST_REQUIRE(result.size() == 1); BOOST_CHECK_EQUAL(result.front().function, '\0'); BOOST_CHECK_EQUAL(result.front().opts, escaped); } BOOST_AUTO_TEST_CASE(FormatsOnlySpecial) { std::string s = "%1%[opts]2%3"; Formatter f(Formatter::FormatterChars('%', '[', ']', '\\')); Formatter::FormatList result; f.format(result, s); BOOST_REQUIRE(result.size() == 3); Formatter::FormatList::iterator it = result.begin(); BOOST_CHECK_EQUAL(it->function, '1'); BOOST_CHECK_EQUAL(it->opts, ""); ++it; BOOST_CHECK_EQUAL(it->function, '2'); BOOST_CHECK_EQUAL(it->opts, "opts"); ++it; BOOST_CHECK_EQUAL(it->function, '3'); BOOST_CHECK_EQUAL(it->opts, ""); } BOOST_AUTO_TEST_CASE(FormatsMixed) { std::string s = "This is a mixed %s with opts %(012\\(\\)3)d and an escaped \\% char"; Formatter f(Formatter::FormatterChars('%', '(', ')', '\\')); Formatter::FormatList result; f.format(result, s); BOOST_REQUIRE(result.size() == 5); Formatter::FormatList::iterator it = result.begin(); BOOST_CHECK_EQUAL(it->function, '\0'); BOOST_CHECK_EQUAL(it->opts, "This is a mixed "); ++it; BOOST_CHECK_EQUAL(it->function, 's'); BOOST_CHECK_EQUAL(it->opts, ""); ++it; BOOST_CHECK_EQUAL(it->function, '\0'); BOOST_CHECK_EQUAL(it->opts, " with opts "); ++it; BOOST_CHECK_EQUAL(it->function, 'd'); BOOST_CHECK_EQUAL(it->opts, "012()3"); ++it; BOOST_CHECK_EQUAL(it->function, '\0'); BOOST_CHECK_EQUAL(it->opts, " and an escaped % char"); } BOOST_AUTO_TEST_CASE(ThrowsOnMissingFunction) { Formatter f(Formatter::FormatterChars('$', '{', '}', '\\')); Formatter::FormatList result; std::string s = "$"; BOOST_CHECK_THROW(f.format(result, s), FormatterError); s = "${}"; BOOST_CHECK_THROW(f.format(result, s), FormatterError); s = "$$a"; BOOST_CHECK_THROW(f.format(result, s), FormatterError); } BOOST_AUTO_TEST_CASE(ThrowsOnUnclosedOpts) { Formatter f(Formatter::FormatterChars('$', '{', '}', '\\')); Formatter::FormatList result; std::string s = "${opts$n"; BOOST_CHECK_THROW(f.format(result, s), FormatterError); } BOOST_AUTO_TEST_CASE(ThrowsOnExtraEscape) { Formatter f(Formatter::FormatterChars('$', '{', '}', '!')); Formatter::FormatList result; std::string s = "Just a text with an extra ! char"; BOOST_CHECK_THROW(f.format(result, s), FormatterError); s = "Text and format with escaped {: $!{"; BOOST_CHECK_THROW(f.format(result, s), FormatterError); } BOOST_AUTO_TEST_SUITE_END(); } // anonymous namespace
mikosz/dormouse-engine
src/foundation/essentials/src/test/c++/dormouse-engine/essentials/Formatter.cpp
C++
mit
3,664
<?php /** * Namesilo DNS Management * * @copyright Copyright (c) 2013, Phillips Data, Inc. * @license http://opensource.org/licenses/mit-license.php MIT License * @package namesilo.commands */ class NamesiloDomainsDns { /** * @var NamesiloApi */ private $api; /** * Sets the API to use for communication * * @param NamesiloApi $api The API to use for communication */ public function __construct(NamesiloApi $api) { $this->api = $api; } /** * Sets domain to use our default DNS servers. Required for free services * like Host record management, URL forwarding, email forwarding, dynamic * dns and other value added services. * * @param array $vars An array of input params including: * - SLD SLD of the DomainName * - TLD TLD of the DomainName * @return NamesiloResponse */ public function setDefault(array $vars) { return $this->api->submit("namesilo.domains.dns.setDefault", $vars); } /** * Sets domain to use custom DNS servers. NOTE: Services like URL forwarding, * Email forwarding, Dynamic DNS will not work for domains using custom * nameservers. * * https://www.namesilo.com/api_reference.php#changeNameServers */ public function setCustom(array $vars) { return $this->api->submit("changeNameServers", $vars); } /** * Gets a list of DNS servers associated with the requested domain. * * https://www.namesilo.com/api_reference.php#getDomainInfo */ public function getList(array $vars) { return $this->api->submit("getDomainInfo", $vars); } /** * Retrieves DNS host record settings for the requested domain. * * https://www.namesilo.com/api_reference.php#dnsListRecords */ public function getHosts(array $vars) { return $this->api->submit("dnsListRecords", $vars); } /** * Sets DNS host records settings for the requested domain. * * https://www.namesilo.com/api_reference.php#dnsAddRecord */ public function setHosts(array $vars) { return $this->api->submit("dnsAddRecord", $vars); } /** * Gets email forwarding settings for the requested domain. * * https://www.namesilo.com/api_reference.php#listEmailForwards */ public function getEmailForwarding(array $vars) { return $this->api->submit("listEmailForwards", $vars); } /** * Sets email forwarding for a domain name. * * https://www.namesilo.com/api_reference.php#configureEmailForward */ public function setEmailForwarding(array $vars) { return $this->api->submit("configureEmailForward", $vars); } } ?>
mrrsm/Blesta-Namesilo
apis/commands/domains_dns.php
PHP
mit
2,513
namespace Pioneer.Blog.Models { public class Contact { public int ContactId { get; set; } public string Email { get; set; } } }
PioneerCode/pioneer-blog
src/Pioneer.Blog/Models/Contact.cs
C#
mit
159
package com.baomidou.hibernateplus.spring.vo; import java.io.Serializable; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import com.baomidou.hibernateplus.entity.Convert; /** * <p> * Vdemo * </p> * * @author Caratacus * @date 2016-12-2 */ public class Vdemo extends Convert implements Serializable { protected Long id; private String demo1; private String demo2; private String demo3; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDemo1() { return demo1; } public void setDemo1(String demo1) { this.demo1 = demo1; } public String getDemo2() { return demo2; } public void setDemo2(String demo2) { this.demo2 = demo2; } public String getDemo3() { return demo3; } public void setDemo3(String demo3) { this.demo3 = demo3; } }
baomidou/hibernate-plus
hibernate-plus/src/test/java/com/baomidou/hibernateplus/spring/vo/Vdemo.java
Java
mit
1,066
import cProfile from pathlib import Path def main(args, results_dir: Path, scenario_dir: Path): try: scenario_dir.mkdir(parents=True) except FileExistsError: pass cProfile.runctx( 'from dmprsim.scenarios.python_profile import main;' 'main(args, results_dir, scenario_dir)', globals=globals(), locals=locals(), filename=str(results_dir / 'profile.pstats'), )
reisub-de/dmpr-simulator
dmprsim/analyze/profile_core.py
Python
mit
432
using System; using System.Collections.Generic; using System.Xml.Serialization; namespace Trafikverket.NET { /// <summary> /// Timetable information, represents a single train at a location /// </summary> public class TrainAnnouncement { /// <summary> /// Get ObjectType as string /// </summary> public static string ObjectTypeName { get { return "TrainAnnouncement"; } } /// <summary> /// Get or set unique id for the activity /// </summary> [XmlElement("ActivityId")] public string ActivityId { get; set; } /// <summary> /// Get or set type of activity, either "Ankomst" or "Angang" /// </summary> [XmlElement("ActivityType")] public string ActivityType { get; set; } /// <summary> /// Get or set if the activity is advertised in the time table /// </summary> [XmlElement("Advertised")] public bool Advertised { get; set; } /// <summary> /// Get or set advertised time in time table /// </summary> [XmlElement("AdvertisedTimeAtLocation")] public DateTime AdvertisedTimeAtLocation { get; set; } /// <summary> /// Get or set announced train number /// </summary> [XmlElement("AdvertisedTrainIdent")] public string AdvertisedTrainIdent { get; set; } /// <summary> /// Get or set booking information, e.g. "Vagn 4 obokad" /// </summary> [XmlElement("Booking")] public List<string> Booking { get; set; } /// <summary> /// Get or set if the activity is cancelled /// </summary> [XmlElement("Canceled")] public bool Canceled { get; set; } /// <summary> /// Get or set if this data post has been deleted /// </summary> [XmlElement("Deleted")] public bool Deleted { get; set; } /// <summary> /// Get or set possible deviation texts, e.g. "Buss ersätter" /// </summary> [XmlElement("Deviation")] public List<string> Deviation { get; set; } /// <summary> /// Get or set estimated time for arrival or departure /// </summary> [XmlElement("EstimatedTimeAtLocation")] public DateTime? EstimatedTimeAtLocation { get; set; } /// <summary> /// Get or set if the estimated time is preliminary /// </summary> [XmlElement("EstimatedTimeIsPreliminary")] public bool EstimatedTimeIsPreliminary { get; set; } /// <summary> /// Get or set from stations, sorted by order and priority to be displayed /// </summary> [XmlElement("FromLocation")] public List<string> FromLocation { get; set; } /// <summary> /// Get or set name of traffic information owner /// </summary> [XmlElement("InformationOwner")] public string InformationOwner { get; set; } /// <summary> /// Get or set signature for the station /// </summary> [XmlElement("LocationSignature")] public string LocationSignature { get; set; } /// <summary> /// Get or set url to traffic owners mobile website /// </summary> [XmlElement("MobileWebLink")] public string MobileWebLink { get; set; } /// <summary> /// Get or set modified time for this data post /// </summary> [XmlElement("ModifiedTime")] public DateTime Modified { get; set; } /// <summary> /// Get or set other announcement text, e.g. "Trevlig resa!", "Ingen påstigning", etc. /// </summary> [XmlElement("OtherInformation")] public List<string> OtherInformation { get; set; } /// <summary> /// Get or set description of the train, e.g. "Tågkompaniet", "SJ", "InterCity" etc. /// </summary> [XmlElement("ProductInformation")] public List<string> ProductInformation { get; set; } /// <summary> /// Get or set announced departure date /// </summary> [XmlElement("ScheduledDepartureDateTime")] public DateTime? ScheduledDeparture { get; set; } /// <summary> /// Get or set additional product information, e.g. "Bistro" etc. /// </summary> [XmlElement("Service")] public List<string> Service { get; set; } /// <summary> /// Get or set when train arrived or departed /// </summary> [XmlElement("TimeAtLocation")] public DateTimeOffset TimeAtLocation { get; set; } /// <summary> /// Get or set to locations, in order after priority in which to be displayed /// </summary> [XmlElement("ToLocation")] public List<string> ToLocation { get; set; } /// <summary> /// Get or set track at the station /// </summary> [XmlElement("TrackAtLocation")] public string TrackAtLocation { get; set; } /// <summary> /// Get or set train compisition, e.g. "Vagnsordning 7, 6, 5, 4, 2, 1" /// </summary> [XmlElement("TrainComposition")] public List<string> TrainComposition { get; set; } /// <summary> /// Get or set type of traffic, values "Tåg", "Direktbuss", "Extrabuss", "Ersättningsbuss", or "Taxi". /// </summary> [XmlElement("TypeOfTraffic")] public string TypeOfTraffic { get; set; } /// <summary> /// Get or set url to traffic owners website /// </summary> [XmlElement("WebLink")] public string WebLink { get; set; } } }
mrjfalk/Trafikverket.NET
src/Trafikverket.NET/Responses/DataModels/TrainAnnouncement.cs
C#
mit
5,935
<!DOCTYPE html> <html lang="ru" > <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="/static/img/favicon.ico" /> <title>Redmine 2.x обнуление пароля admin-a - Cyberflow</title> <meta name="author" content="Cyberflow" /> <meta name="description" content="Redmine 2.x обнуление пароля admin-a" /> <meta name="keywords" content="Redmine 2.x обнуление пароля admin-a, Cyberflow, notice" /> <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml"> <!-- syntax highlighting CSS --> <link rel="stylesheet" href="/static/css/syntax.css"> <!-- Bootstrap core CSS --> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <!-- Fonts --> <link href="//fonts.googleapis.com/css?family=Roboto+Condensed:400,300italic,300,400italic,700&amp;subset=latin,latin-ext" rel="stylesheet" type="text/css"> <!-- Custom CSS --> <link rel="stylesheet" href="/static/css/super-search.css"> <link rel="stylesheet" href="/static/css/main.css"> <!-- Google Analytics --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-31213444-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body> <div class="container"> <div class="col-sm-3"> <a href="/"><img id="about" src="https://www.gravatar.com/avatar/7ca36522be02d33e7d2f4ea209012ac3?s=68" alt="cyberflow_gravatar" height="75px" width="75px" /></a> <h1 class="author-name">Cyberflow</h1> <div id="about"> I am linux system administrator. </div> <hr /> <div class="search" id="js-search"> <input type="text" placeholder="(sitemap)~$ type to search" class="search__input form-control" id="js-search__input"> <ul class="search__results" id="js-search__results"></ul> </div> <hr /> <strong>Navigation</strong><br /> &raquo; <a href="/">Home</a> <br /> &raquo; <a class="about" href="/category/">Categories</a><br /> &raquo; <a class="about" href="/code/">Code</a><br /> &raquo; <a class="about" href="/feed.xml">XML Feed</a><br /> </div> <div class="col-sm-8 col-offset-1"> <h1>Redmine 2.x обнуление пароля admin-a</h1> <span class="time">13 Dec 2012</span> <span class="categories"> &raquo; <a href="/category/notice">notice</a> </span> <div class="content"> <div class="post"><p>Для обнуления пароля от пользователя admin в redmine 2.x выполните следующую команду из консоли находясь в директории с redmine</p> <figure class="highlight"><pre><code class="language-bash" data-lang="bash">ruby script/rails runner <span class="s1">'user = User.find(:first, :conditions =&gt; {:admin =&gt; true}) ; user.password, user.password_confirmation = "password"; user.save!'</span> <span class="nt">-e</span> production</code></pre></figure> </div> </div> <div class="panel-body"> <h4>Related Posts</h4> <ul> <li class="relatedPost"> <a href="https://cyberflow.net/2015/09/use-ssh-x-session-from-user-to-root.html" data-proofer-ignore>Пробрасывание X сессии от пользователя к root</a> (Categories: <a href="/category/notice">notice</a>, <a href="/category/linux">linux</a>) </li> <li class="relatedPost"> <a href="https://cyberflow.net/2013/05/logstash-rotate-logs-in-elasticsearch.html" data-proofer-ignore>logstash, ротация логов в elasticsearch</a> (Categories: <a href="/category/notice">notice</a>, <a href="/category/linux">linux</a>, <a href="/category/elasticsearch">elasticsearch</a>) </li> </ul> </div> <div class="PageNavigation"> <a class="prev" href="/2012/10/install-chef-solo-to-debian-6-squeeze.html">&laquo; Установка chef solo на debian 6 squeeze</a> <a class="next" href="/2013/02/how-to-install-nodejs-on-linux-deb-base.html">Установка node.js на Linux (deb base) &raquo;</a> </div> <div class="disqus-comments"> <div id="disqus_thread"></div> <script type="text/javascript"> /* <![CDATA[ */ var disqus_shortname = "cyberflowblog"; var disqus_identifier = "https://cyberflow.net_Redmine 2.x обнуление пароля admin-a"; var disqus_title = "Redmine 2.x обнуление пароля admin-a"; /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); /* ]]> */ </script> </div> <footer> &copy; Cyberflow - <a href="https://github.com/cyberflow">https://github.com/cyberflow</a> - Powered by Jekyll. </footer> </div><!-- end /.col-sm-8 --> </div><!-- end /.container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="/static/js/bootstrap.min.js"></script> <script src="/static/js/super-search.js"></script> </body> </html>
cyberflow/cyberflow.github.com
2012/12/redmine-2-admin-password-reset.html
HTML
mit
8,748
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Pasteurizer : Clickable { [SerializeField] private Transform positionMark; private Vector3 initial; [SerializeField] private GameObject milkObject; public override void OnStart() { base.OnStart(); initial = transform.position; } public void Show() { StartCoroutine(Coroutines.AnimatePosition(gameObject, positionMark.position, 20f)); } public void Hide() { StartCoroutine(Coroutines.AnimatePosition(gameObject, initial, 20f)); } public void MilkDragged() { GetComponent<Animator>().Play("barn_pasturiserWorking"); AkSoundEngine.PostEvent("PasturisingMachine", gameObject); } public void OnWorkingAnimationEnd() { milkObject.SetActive(true); } }
TeamTorchBear/Guzzlesaurus
Assets/Scripts/Barn/Pasteurizer.cs
C#
mit
872
<?php namespace Terion\PackageInstaller; use Illuminate\Filesystem\Filesystem; use Illuminate\Foundation\Application; use Symfony\Component\Finder\Finder; /** * Class ConfigUpdater * * @package Terion\PackageInstaller * @author Volodymyr Kornilov <mail@terion.name> * @license MIT http://opensource.org/licenses/MIT * @link http://terion.name */ class ConfigUpdater { /** * Path to config file. * * @var string */ protected $configFile; /** * Working environment. * * @var string */ protected $env; /** * Filesystem object. * * @var Filesystem */ protected $file; /** * Default quote type. * * @var string */ protected $defaultQuoteType = "'"; /** * Default separator between config items. * * @var string */ protected $defaultSeparator = ",\r\n "; /** * @var Application */ private $app; /** * @param Filesystem $filesystem * @param Application $app */ public function __construct(Filesystem $filesystem, Application $app) { $this->app = $app; $this->env = $this->app->environment(); $this->file = $filesystem; $this->configFile = $this->app['path'] . '/config/app.php'; /* Adding environment-specific packages has some nuances See: https://github.com/laravel/framework/issues/1603 https://github.com/barryvdh/laravel-debugbar/issues/86 https://github.com/laravel/framework/issues/3327 So at the moment this is at stage of TODO if ($this->env === 'production') { $this->configFile = $this->app['path'] . '/config/app.php'; } else { $this->configFile = $this->app['path'] . '/config/' . $this->env . '/app.php'; if (!$this->file->exists($this->configFile)) { $this->file->copy(__DIR__ . '/app.config.stub', $this->configFile); } } */ } /** * List installed service providers. * * @return mixed */ public function getServiceProviders() { $cfg = $this->file->getRequire($this->configFile); return array_get($cfg, 'providers'); } /** * List installed facades. * * @return mixed */ public function getAliases() { $cfg = $this->file->getRequire($this->configFile); return array_get($cfg, 'aliases'); } /** * Add specified provider. * * @param $provider */ public function addProvider($provider) { if (!in_array($provider, $this->getServiceProviders())) { $quote = $this->getQuoteType('providers'); $separator = $this->getArrayItemsSeparator('providers'); $anchor = $this->getInsertPoint('providers'); $insert = $separator . $quote . $provider . $quote . ','; $this->write($insert, $anchor); } } /** * Detect quote type used in selected config item (providers, aliases). * * @param $item * * @return string */ protected function getQuoteType($item) { $bounds = $this->getConfigItemBounds($item); if (!$bounds[0] or !$bounds[1]) { return $this->defaultQuoteType; } $file = $this->getFileContents(); $substr = substr($file, $bounds[0], $bounds[1] - $bounds[0] + 1); return substr_count($substr, '"') > substr_count($substr, "'") ? '"' : "'"; } /** * Get bite bounds of selected config item (providers, aliases) in file. * * @param $item * * @return array */ protected function getConfigItemBounds($item) { $file = $this->getFileContents(); if (!$file) { return [null, null]; } $searchStart = '/[\'"]' . $item . '[\'"]/'; preg_match($searchStart, $file, $matchStart, PREG_OFFSET_CAPTURE); $start = array_get(reset($matchStart), 1); $end = $start + 1; // search for array closing that is not commented $match = [')', ']']; for ($i = $start; $i <= strlen($file); ++$i) { $char = $file[$i]; if (in_array($char, $match)) { if (!$this->isCharInComment($file, $i)) { $end = $i; break; } } } return [$start, $end]; } /** * Detect config items separator used in selected config item (providers, aliases). * * @param $item * * @return string */ protected function getArrayItemsSeparator($item) { $cfg = $this->file->getRequire($this->configFile); if (!$cfg) { return $this->defaultSeparator; } $file = $this->getFileContents(); $arr = array_get($cfg, $item); $lastItem = end($arr); $preLastItem = prev($arr); if (!$lastItem or !$preLastItem) { return $this->defaultSeparator; } preg_match('/\,/', $file, $matchStart, PREG_OFFSET_CAPTURE, strpos($file, $preLastItem)); $start = array_get(reset($matchStart), 1); $searchEnd = preg_match('/[\'"]/', $file, $matchEnd, PREG_OFFSET_CAPTURE, $start); $end = array_get(reset($matchEnd), 1); $separator = substr($file, $start, $end - $start); // remove comments $separator = preg_replace('/\/\/.*/ui', '', $separator); $separator = preg_replace('/#.*/ui', '', $separator); $separator = preg_replace('/\/\*(.*)\*\//ui', '', $separator); return $separator; } /** * Detect point where to insert new data for selected config item (providers, aliases). * * @param $for * * @return array */ protected function getInsertPoint($for) { $bound = $this->getConfigItemBounds($for); $file = $this->getFileContents(); $match = ['\'', '"', ',']; $matches = []; for ($i = $bound[0]; $i <= $bound[1]; ++$i) { $char = $file[$i]; if (in_array($char, $match)) { if (!$this->isCharInComment($file, $i)) { $matches[] = ['position' => $i + 1, 'symbol' => $char]; } } } return end($matches); } /** * Detect is character at specified position is inside of a comment * * @param $haystack * @param $charPosition * * @return bool */ protected function isCharInComment($haystack, $charPosition) { // check for line comment for ($c = $charPosition; $c > 0; --$c) { if ($haystack[$c] === PHP_EOL) { break; } elseif ($haystack[$c] === '#' or ($haystack[$c] === '/' and ($haystack[$c + 1] === '/' or $haystack[$c - 1] === '/')) ) { return true; } } // check for block comment $openingsCount = 0; $closingsCount = 0; for ($c = $charPosition; $c > 0; --$c) { if ($haystack[$c] === '*' and $haystack[$c - 1] === '/') { ++$openingsCount; } if ($haystack[$c] === '/' and $haystack[$c - 1] === '*') { ++$closingsCount; } } if ($openingsCount !== $closingsCount) { return true; } return false; } /** * Write new data to config file for selected config item (providers, aliases). * * @param $text * @param $anchor */ protected function write($text, $anchor) { $this->backup(); $file = $this->getFileContents(); if ($anchor['symbol'] === ',') { $text = ltrim($text, ','); } $file = substr_replace($file, $text, $anchor['position'], 0); $this->file->put($this->configFile, $file); $this->cleanup(); } /** * Backup config file */ protected function backup() { $from = $this->configFile; $pathinfo = pathinfo($from); $to = $pathinfo['dirname'] . DIRECTORY_SEPARATOR . $pathinfo['filename'] . '.bak.php'; $this->file->copy($from, $to); } /** * Cleanup backup */ protected function cleanup() { $pathinfo = pathinfo($this->configFile); $backup = $pathinfo['dirname'] . DIRECTORY_SEPARATOR . $pathinfo['filename'] . '.bak.php'; $this->file->delete($backup); } /** * Add specified facade. * * @param $alias * @param $facade */ public function addAlias($alias, $facade) { if ($facadeCurrent = array_get($this->getAliases(), $alias)) { if ($facadeCurrent === $facade) { return; } $this->commentOut($alias, 'aliases'); } $quote = $this->getQuoteType('aliases'); $separator = $this->getArrayItemsSeparator('aliases'); $anchor = $this->getInsertPoint('aliases'); $insert = $separator . $quote . $alias . $quote . ' => ' . $quote . $facade . $quote . ','; $this->write($insert, $anchor); } /** * Comment item * * @param $search * @param $from */ protected function commentOut($search, $from) { $bounds = $this->getConfigItemBounds($from); $file = $this->getFileContents(); $cutted = substr($file, 0, $bounds[1]); preg_match_all( '/[\'"]' . preg_quote($search) . '[\'"]/', $cutted, $matchFacade, PREG_OFFSET_CAPTURE | PREG_SET_ORDER ); foreach ($matchFacade as $match) { if (!$this->isCharInComment($cutted, $match[0][1])) { $commentFrom = $match[0][1]; $comma = strpos($cutted, ',', $commentFrom); while ($this->isCharInComment($cutted, $comma)) { $comma = strpos($cutted, ',', $comma); } $commentTill = $comma + 1; $this->write('*/', ['position' => $commentTill, 'symbol' => '']); $this->write('/*', ['position' => $commentFrom, 'symbol' => '']); } } } /** * Get contents of config file * * @return string */ protected function getFileContents() { return $this->file->get($this->configFile); } }
terion-name/package-installer
src/Terion/PackageInstaller/ConfigUpdater.php
PHP
mit
10,543
require('./node') require('./console')
Jam3/hihat
lib/prelude/node-console.js
JavaScript
mit
39
/* * Author: Brendan Le Foll <brendan.le.foll@intel.com> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var m = require("mraa") console.log("mraa version: " + m.getVersion()); var x = new m.Gpio(8) x.dir(m.DIR_OUT) x.write(1)
rwaldron/mraa
examples/javascript/example.js
JavaScript
mit
1,305
<?php $view->extend('EmVistaBundle::base.html.php'); ?> <?php $view['slots']->start('body') ?> <div class="container"> <form method="post" action="<?php echo $view['router']->generate('submissao_iniciar') ?>"> <div class="row"> <div class="col-sm-12"> <h3>Termos de uso</h3> <p class="text-info">Antes de continuar, é necessário que leia e concorde com os termos de uso do cultura crowdfunding.</p> </div> </div> <div class="row"> <div class="col-sm-12" style="height: 300px;overflow: auto; "> <?php echo $termosUso->getTermoUso(); ?> </div> </div> <div class="form-actions" style="text-align: center"> <button type="submit" class="btn btn-success">Li e concordo com os termos acima.</button> </div> </form> </div> <?php $view['slots']->stop(); ?>
brunonm/emvista
src/EmVista/EmVistaBundle/Resources/views/Submissao/termosUso.html.php
PHP
mit
920
<# .SYNOPSIS Gets reader mode. .DESCRIPTION Gets the reader mode for all readers or the reader mode for a single reader if a panel id and reader id is specified. If the result returns null, try the parameter "-Verbose" to get more details. .EXAMPLE Get-ReaderMode .LINK https://github.com/erwindevreugd/PSDataConduIT .EXTERNALHELP PSDataConduIT-help.xml #> function Get-ReaderMode { [CmdletBinding()] param ( [Parameter( Position = 0, Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = 'The name of the server where the DataConduIT service is running or localhost.')] [string] $Server = $Script:Server, [Parameter( Position = 1, Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = 'The credentials used to authenticate the user to the DataConduIT service.')] [PSCredential] $Credential = $Script:Credential, [Parameter( Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = 'The panel id parameter.')] [int] $PanelID, [Parameter( Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = 'The reader id parameter.')] [int] $ReaderID ) process { $parameters = @{ Server = $Server; } if ($Credential -ne $null) { $parameters.Add("Credential", $Credential) } if (($panels = Get-Panel @parameters -PanelID $PanelID) -eq $null) { Write-Verbose -Message ("No panels found") return } foreach ($panel in $panels) { # Update panel hardware status so we can get the current reader mode $panel | Invoke-UpdateHardwareStatus } if (($readers = Get-Reader @parameters -PanelID $PanelID -ReaderID $ReaderID) -eq $null) { Write-Verbose -Message ("No readers found") return } foreach ($reader in $readers) { $mode = MapEnum ([ReaderMode].AsType()) $reader.GetReaderMode.Invoke().Mode Write-Verbose -Message ("Reader '$($reader.Name)' on Panel '$($panel.Name)' reader mode is '$($mode)'") New-Object PSObject -Property @{ PanelID = $reader.PanelID; ReaderID = $reader.ReaderID; Name = $reader.Name; Mode = $mode; } | Add-ObjectType -TypeName "DataConduIT.LnlReaderMode" } } }
erwindevreugd/PSDataConduIT
PSDataConduIT/Public/Get-ReaderMode.ps1
PowerShell
mit
2,699
package main import ( "flag" "fmt" "github.com/ammario/fastpass" ) func cmdGet(fp *fastpass.FastPass) { search := flag.Arg(0) if len(flag.Args()) != 1 { usage() } results := fp.Entries.SortByName() if search != "" { results = fp.Entries.SortByBestMatch(search) } if len(results) == 0 { fail("no results found") } e := results[0] e.Stats.Hit() if len(results) > 1 { fmt.Printf("similar: ") for i, r := range results[1:] { //show a maximum of five suggestions if i > 5 { break } fmt.Printf("%v ", r.Name) } fmt.Printf("\n") } copyPassword(e) }
ammario/fastpass
cmd/fp/cmd_get.go
GO
mit
599
from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context)
vault/bugit
viewer/views.py
Python
mit
3,804
import {Component, OnInit} from '@angular/core'; @Component({ selector: 'sqap-about', templateUrl: './about.component.html', styleUrls: ['./about.component.scss'] }) export class AboutComponent implements OnInit { constructor() { } ngOnInit() { console.log('hello `About` component'); } }
MarcinMilewski/sqap
sqap-ui/src/main/frontend/app/about/about.component.ts
TypeScript
mit
311
<?php /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2012 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez <andres@phalconphp.com> | | Eduar Carvajal <eduar@phalconphp.com> | | Nikita Vershinin <endeveit@gmail.com> | +------------------------------------------------------------------------+ */ namespace Phalcon\Error; class Error { /** * @var array */ protected $_attributes; /** * Class constructor sets the attributes. * * @param array $options */ public function __construct(array $options = array()) { $defaults = array( 'type' => -1, 'message' => 'No error message', 'file' => '', 'line' => '', 'exception' => null, 'isException' => false, 'isError' => false, ); $options = array_merge($defaults, $options); foreach ($options as $option => $value) { $this->_attributes[$option] = $value; } } /** * Magic method to retrieve the attributes. * * @param string $method * @param array $args * @return mixed */ public function __call($method, $args) { return isset($this->_attributes[$method]) ? $this->_attributes[$method] : null; } }
le51/foundation
app/library/Phalcon/Error/Error.php
PHP
mit
2,269
-- PCT19H. NONRELATIVES BY HOUSEHOLD TYPE (HISPANIC OR LATINO) -- designed to work with the IRE Census bulk data exports -- see http://census.ire.org/data/bulkdata.html CREATE TABLE ire_pct19h ( geoid VARCHAR(11) NOT NULL, sumlev VARCHAR(3) NOT NULL, state VARCHAR(2) NOT NULL, county VARCHAR(3), cbsa VARCHAR(5), csa VARCHAR(3), necta VARCHAR(5), cnecta VARCHAR(3), name VARCHAR(90) NOT NULL, pop100 INTEGER NOT NULL, hu100 INTEGER NOT NULL, pop100_2000 INTEGER, hu100_2000 INTEGER, pct019h001 INTEGER, pct019h001_2000 INTEGER, pct019h002 INTEGER, pct019h002_2000 INTEGER, pct019h003 INTEGER, pct019h003_2000 INTEGER, pct019h004 INTEGER, pct019h004_2000 INTEGER, pct019h005 INTEGER, pct019h005_2000 INTEGER, pct019h006 INTEGER, pct019h006_2000 INTEGER, pct019h007 INTEGER, pct019h007_2000 INTEGER, pct019h008 INTEGER, pct019h008_2000 INTEGER, pct019h009 INTEGER, pct019h009_2000 INTEGER, pct019h010 INTEGER, pct019h010_2000 INTEGER, pct019h011 INTEGER, pct019h011_2000 INTEGER, PRIMARY KEY (geoid) );
ireapps/census
tools/sql/ire_export/ire_PCT19H.sql
SQL
mit
1,073
import classnames from 'classnames'; import cloneDeep from 'lodash/cloneDeep'; import React from 'react'; import { HTMLFieldProps, connectField, filterDOMProps, joinName, useField, } from 'uniforms'; export type ListAddFieldProps = HTMLFieldProps< unknown, HTMLSpanElement, { initialCount?: number } >; function ListAdd({ disabled, initialCount, name, readOnly, value, ...props }: ListAddFieldProps) { const nameParts = joinName(null, name); const parentName = joinName(nameParts.slice(0, -1)); const parent = useField< { initialCount?: number; maxCount?: number }, unknown[] >(parentName, { initialCount }, { absoluteName: true })[0]; const limitNotReached = !disabled && !(parent.maxCount! <= parent.value!.length); function onAction(event: React.KeyboardEvent | React.MouseEvent) { if ( limitNotReached && !readOnly && (!('key' in event) || event.key === 'Enter') ) { parent.onChange(parent.value!.concat([cloneDeep(value)])); } } return ( <i {...filterDOMProps(props)} className={classnames( 'ui', props.className, limitNotReached ? 'link' : 'disabled', 'fitted add icon', )} onClick={onAction} onKeyDown={onAction} role="button" tabIndex={0} /> ); } export default connectField<ListAddFieldProps>(ListAdd, { initialValue: false, kind: 'leaf', });
vazco/uniforms
packages/uniforms-semantic/src/ListAddField.tsx
TypeScript
mit
1,438
<link rel="import" href="../color.html"> <dom-module id="material-required-field"> <template> <style> [part="label"] { display: block; position: absolute; top: 8px; font-size: 1em; line-height: 1; height: 20px; margin-bottom: -4px; white-space: nowrap; overflow-x: hidden; text-overflow: ellipsis; color: var(--material-secondary-text-color); transform-origin: 0 75%; transform: scale(0.75); } :host([required]) [part="label"]::after { content: " *"; color: inherit; } :host([invalid]) [part="label"] { color: var(--material-error-text-color); } [part="error-message"] { font-size: .75em; line-height: 1; color: var(--material-error-text-color); margin-top: 6px; } :host(:not([invalid])) [part="error-message"] { margin-top: 0; max-height: 0; overflow: hidden; } :host([invalid]) [part="error-message"] { animation: reveal 0.2s; } @keyframes reveal { 0% { opacity: 0; } } </style> </template> </dom-module>
StarcounterSamples/People
src/People/wwwroot/sys/vaadin-material-styles/mixins/required-field.html
HTML
mit
1,228
--- layout: article title: “Nancy Grows Up,” the Media Age, and the Historian’s Craft authors: - schmidt-michael excerpt: > Historians have mostly relied on the printed page to communicate their work. But what about sound? Michael Schmidt looks to the alternate aural history of the twentieth century and unearths beautiful experiments in sonic storytelling. permalink: /issues/2013/7/nancy-grows-up-the-media-age-and-the-historians-craft supernotes: /issues/1/3/schmidt-history_through_sound.json toc: 18 volume: 1 number: 3 audio: true --- <div class="inline-image"> <a class="fancybox" href="/images/issues/1/3/large-Schmidt1.jpg"> <img src="/images/issues/1/3/medium-Schmidt1.jpg" alt="" /> </a> <p class="caption"> <span class="credit">Benjamin Breen, 2013, based on a photograph of Tony Schwartz in the 1950s</span> </p> </div> <h3>The Challenge of “Nancy Grows Up”</h3> <!-- 1 --> <div class="paragraph-pack"><p id="paragraph-1"> It begins with anxious crying. The plaintive sound only lasts a few moments before the screams drop into a slightly lower register and transform into a calm murmur. The sound repeats, then breaks into the rudiments of language. It sings—or tries—and falters. A man helps, playing a game with a familiar rhyme: “Jack and Jill went up the … to fetch a pail of … Jack fell down and broke his … and Jill came tumbling …” </p></div> <!-- 2 --> <div class="paragraph-pack"><p id="paragraph-2"> She fills in the appropriate words and, as she does, we suddenly meet her. </p></div> <!-- 3 --> <div class="paragraph-pack"><p id="paragraph-3"> For the remaining minute and forty-two seconds we hear and follow Nancy. We listen to her development as a person through a variety of situations: she wishes her father a happy birthday, she lists what she wants for Christmas (“a puppy and a whistle and a horn and a hat and a dress and a ballerina costume”), she explains how to housetrain a dog, and she expresses her feelings about the Russians sending the dog Laika into space. All the while Nancy’s voice grows increasingly distinct, speaks longer, takes on and sheds accents, and uses increasingly sophisticated vocabulary. Finally, the recording ends, but it does so just as we witness what seems like a personal milestone. Nancy becomes silent just after we see the door open on her developing sexuality. In the last and longest of the voices, after updating us on what she has been doing at school, she sighs and confesses, “and I’ve been discovering boys.” </p></div> <div class="inline-audio"><a href="/audio/issue-1-3/Nancy.mp3" class="sm2_button">“Nancy Grows Up”</a><p class="label">“Nancy Grows Up”</p></div> <!-- 4 --> <div class="paragraph-pack"><p id="paragraph-4"> Recorded over the course of the 1950s and the early 1960s, “Nancy Grows Up” gives us a beautiful and stimulating portrait of growth. It is an audio montage; Tony Schwartz, its creator, continuously taped his niece from her first month of life to the age of thirteen and, later, spliced together pieces chronologically. Schwartz likened what he did to time-lapse photography: it condenses the story of thirteen years, as Schwartz said, in less than two and a half minutes. </p></div> <!-- 5 --> <div class="paragraph-pack"><p id="paragraph-5"> “Nancy Grows Up” is more than a simple novelty piece. Poetic and expository, it reveals a type of storytelling that has an enigmatic intelligibility. Offering a biographical history of development, “Nancy” narrates the phases and stages of a young girl’s early life. It does so quite successfully and evocatively and achieves a rich unspoken analysis in its juxtaposition of different voices, words, and timbre. </p></div> <!-- 6 --> <div class="paragraph-pack"><p id="paragraph-6"> Confronted with the possibilities of communication in “Nancy,” one can’t help but ask, “why have historians neglected sound?” Despite more than a century and a half of ongoing media revolutions, historians—especially professional academic historians—have largely worked within a self-imposed textual ghetto. Why have historians restricted themselves to <em>written</em> histories? Why only the monograph and journal article after the advent of the photo essay, the LP record, the radio show, documentary film, and animation short? </p></div> <!-- 7 --> <div class="paragraph-pack"><p id="paragraph-7"> There do seem to be substantial reasons for why we have continued to rely almost exclusively on text. It is beyond the scope of this piece to attempt to give a comprehensive explanation of this phenomenon, but a few things come immediately to mind. Text’s capacity to transmit large masses of information, for example, is attractive. The monograph and article also parallel and allow the exact reproduction of what has been most historians’ primary source: written documents. Furthermore, the footnote, the <em>sine qua non</em> of historical scholarship and the linguistic technology for and symbol of the discipline’s seriousness and rigor, appears almost inextricably grounded in the text. </p></div> <!-- 8 --> <div class="paragraph-pack"><p id="paragraph-8"> Beginning to rethink the footnote outside the page only seemed possible recently. Internet-based publications have shown that digital footnotes can reference sources in more direct ways, offer more detail and information, and, possibly, shift the function of the footnote altogether. The blog maintained by <em>The Appendix</em>, for example, uses hyperlink footnotes to immediately show the content of a source or acquaint the reader with information about an obscure person or organization. </p></div> <!-- 9 --> <div class="paragraph-pack"><p id="paragraph-9"> Text has served historians well, but it is useful to ask if we have missed whole modes of analysis and presentation with such a consistently narrow range of media. How, for example, has the primacy of text and the page shaped how we understand and judge historical scholarship as a whole? Hayden White famously asserted that historical interpretation is shaped by the plot structures of particular kinds of stories—the romance, the tragedy, the comedy, and the satire—but we can go one step further: history as a discipline has also been fundamentally structured by its medium. The way we conceive of the work of history and, thus, the field in which history can be told and debated are intimately intertwined with and determined by the advantages and limitations of the written word. </p></div> <!-- 10 --> <div class="paragraph-pack"><p id="paragraph-10"> There is nothing essential linking history and text. Historians can and should embrace other media in the production of history. Fortunately, there are considerable guideposts for a journey into new media; our neglect has not been for a lack of evidence of the unique and intriguing capabilities of other media. </p></div> <!-- 11 --> <div class="paragraph-pack"><p id="paragraph-11"> The use and exploration of sound and sound technology offer clear examples of this. “Nancy Grows Up” was not an isolated piece; it was part of a large, rich history of thinking about and through sound in the twentieth century. Even a brief account of sound technology shows that there is a considerable body of work in other media that historians could learn from and draw on. </p></div> <!-- 12 --> <div class="paragraph-pack"><p id="paragraph-12"> Looking at some of the ideas and practices surrounding “Nancy” illuminates some of the ways non-historians have sought to engage sound narrative and documentation. </p></div> <hr class="special" /> <h3>Telling with Sound: A Very Short History</h3> <div class="inline-image"> <a class="fancybox" href="/images/issues/1/3/large-Schmidt2.jpg"> <img src="/images/issues/1/3/medium-Schmidt2.jpg" alt="" /> </a> <p class="caption"> The cover of Tony Schwartz’s 1959 LP, <em><a href="http://www.discogs.com/Tony-Schwartz-Dwight-Weist-The-New-York-Taxi-Driver/release/3755900">The New York Taxi Driver</a></em>. <span class="credit">Folkways Records</span> </p> </div> <!-- 13 --> <div class="paragraph-pack"><p id="paragraph-13"> From the late 1920s until the early 1950s, American radio drama, comedies, and soap operas pioneered new ways of conveying stories and ideas through voice and other auditory material. These shows worked out, in the words of radio scholar Susan Douglas, a mode of “story listening.” Although primarily a source of entertainment, Orson Welles’s 1938 famous Mercury Theater production of <a href="http://www.youtube.com/watch?v=Xs0K4ApWl4g"><em>War of the Worlds</em></a>—and the consequent panic that a Martian invasion was under way—demonstrates the immense power and effect that audio stories could wield. Welles’s ability to create hysteria and horror in his listeners was a direct consequence of his “media sense”—his talent at adapting storytelling to his artistic vehicle. </p></div> <!-- 14 --> <div class="paragraph-pack"><p id="paragraph-14"> Across the pond, intellectuals quickly used the young technology as material for modernist experimentation. During the late 1920s and early 1930s, German artists sought to create a radio-specific art form, i.e., an artistic genre that would reveal and marshal radio’s unique characteristics. The intriguing possibilities of the ether attracted a number of artists from outside the musical or theatrical world; established writers like Alfred Döblin and future film directors like Max Ophüls and Billy Wilder produced <em>Hörbilder</em> (literally, listening pictures) and <em>Hörspiele</em> (listening plays). In 1930, the avant-garde director Walter Ruttmann produced the following: </p></div> <div class="inline-audio"><a href="/audio/issue-1-3/Ruttmann.mp3" class="sm2_button">Walter Ruttmann, <em>Wochenende</em>, (1930)</a><p class="label">Walter Ruttmann, <em>Wochenende</em>, (1930)</p></div> <!-- 15 --> <div class="paragraph-pack"><p id="paragraph-15"> A film soundtrack without the accompanying picture, <em>Wochenende</em> is the story of a weekend. Ruttmann had spent much of the previous decade making “Absolute Film,” abstract films which attempted to capture the essential qualities of the filmic medium. With <em>Wochenende</em>, he tried to do the same with sound. Working with new sound film technology, he isolated the soundtrack and built a narrative using a montage of noises, identifiable sounds, and speech-fragments. </p></div> <!-- 16 --> <div class="paragraph-pack"><p id="paragraph-16"> Germans were not the only Europeans playing with the open possibilities of radio form. Around the same time, Lance Sieveking attempted his own experiments in “wireless imagination” at the BBC and Italian Futurists like Fillipo Marinetti produced music and theater for fascist radio. </p></div> <!-- 17 --> <div class="paragraph-pack"><p id="paragraph-17"> Others, like Paul Daharme, Sir Oliver Lodge, and Rudolf Arnheim, wrote and theorized about the possibilities of the disembodied auditory content of radio during the interwar period. For many, the ethereal and mysterious qualities of radio could foster outlandish hopes and fantasies. Daharme and Lodge, for example, believed that the ether granted access to new psychological and metaphysical spaces. Daharme, a French advertiser and experimental radio practitioner, believed that broadcasting could reach directly into the unconscious and radio works could provoke a psychoactive space in which individuals would encounter their own theater of the mind. Lodge, a pioneer in radio technology and revered British scientist, argued that the ether comingled with the realm of the dead and that broadcasting could be used as a spiritualist tool to communicate with lost love ones. </p></div> <!-- 18 --> <div class="paragraph-pack"><p id="paragraph-18"> Arnheim stayed a bit closer to the ground. Like Daharme and Lodge, however, he was also fascinated by radio’s ability to detach sound from image. After years thinking about images as a film critic, he wrote <em>Radio: The Art of Sound</em>. In it he pondered the power of isolated sounds and the audio-specific methods through which radio could tell stories. </p></div> <!-- 19 --> <div class="paragraph-pack"><p id="paragraph-19"> The ether was not only used for fiction and modernist abstraction, however. Radio journalists also produced documentary news programs. By the late 1930s, broadcast journalism had supplanted newspapers for immediate news coverage in the United States, and most Americans on the home front experienced World War II on a day-to-day basis through listening. Radio journalism employed all sorts of sounds—location noises, sound effects, monologues, and dialogues—in order to move audiences between “informational listening” (taking in facts) and “dimensional listening” (where, for example, “people were compelled to conjure up maps, topographies, street scenes in London after a bombing”). </p></div> <!-- 20 --> <div class="paragraph-pack"><p id="paragraph-20"> After their introduction in 1948, long playing records provided new materials and resources to explore the story-telling and documentary capabilities of sound. In addition to being repeatable, LPs had a distinct advantage over radio: their multi-faceted presentation format. Record producers and designers could use the non-aural parts of the LP—the label, cover, photos, and liner notes—to guide the listener’s perceptions and stoke their imagination. Ever the brilliant pioneer, Schwartz made a number of innovative narrative and representational <a href="http://www.loc.gov/rr/record/schwartzrecordings.html">experimental recordings</a> for Folkway Records, including <em>An Actual Story in Sound of a Dog’s Life</em>, <em>New York 19</em>, <em>Nueva York: A Tape Documentary of Puerto Rican New Yorkers</em>, and <em>The World in My Mailbox</em>. </p></div> <div class="inline-image"> <a class="fancybox" href="/images/issues/1/3/large-Schmidt3.jpg"> <img src="/images/issues/1/3/medium-Schmidt3.jpg" alt="cover of a dog’s life" /> </a> <p class="caption"> The cover of <em>An Actual Story in Sound of a Dog’s Life</em>, 1958. <span class="credit">Folkways Records</span> </p> </div> <!-- 21 --> <div class="paragraph-pack"><p id="paragraph-21"> “Nancy” was an intersection of techniques developed in radio and on LP. Originally produced for Schwartz’s show <em>Around New York</em> on New York Public Radio, he reworked and released it more than once on record. First appearing as “History of a Voice” in 1962 on <em>You’re Stepping on My Shadow: “Sound Stories” of NYC,</em> he re-presented it as “Nancy” on <em>Records the Sounds of Children</em> in 1970. Although utilizing the same base recordings, they told their story a bit differently: “History” utilizes voice-over narration like a radio news piece while “Nancy” edits together sounds in a way similar to Ruttmann. Both were packaged with a cover and notes. </p></div> <!-- 22 --> <div class="paragraph-pack"><p id="paragraph-22"> During the period that Schwartz released “History” and “Nancy,” other LP projects approached history more directly. In the early 1960s, for example, Time-Life released <em>The Sounds of History</em>, a twelve-volume set of records that intertwined short explanations of events, readings of documents and literature, recordings, and contemporary music to evoke sonic portraits of important eras in the history of the United States. Later in the decade, torch singer and Batman star Eartha Kitt helped record narrative biographies of important African Americans in the two-volume set <em>Black Pioneers in American History</em>. </p></div> <!-- 23 --> <div class="paragraph-pack"><p id="paragraph-23"> The largest engagement with telling history on records during the period occurred, not surprisingly, in the sphere of music. Some did it within music itself—ambitious albums like Duke Ellington’s <em>Black, Brown, and Beige</em> or the Kinks’ <em>Arthur (Or the Rise and Fall of the British Empire)</em> attempt to paint large historical shifts through suite-like musical assemblages. Others used records to present the history of music through documents; record companies, for example, offered overviews of musical genres by collecting together and chronologically ordering recordings. These projects could become quite ambitious—the most cursory and expansive collection of this sort, the 1962 record collection <em>2,000 Years of Music</em>, tried to capture “a concise history of the development of music from the earliest times through the 18th century” on four LP sides. </p></div> <hr class="special" /> <h3>“Nancy” and the New Work of History</h3> <!-- 24 --> <div class="paragraph-pack"><p id="paragraph-24"> This is a just sketch, but it gives us a sense of the wide range of work that has been done exploring the narrative and communication possibilities of sound technology before the digital age. They demonstrate the ample resources and precedents to which historians might turn and build on if we wished to expand beyond paper and the PDF. Despite this extensive engagement with sound as a narrative medium, however, these experiments and treatises have largely taken place outside the historical discipline. Sound creators and thinkers have remained outliers and outsiders. </p></div> <!-- 25 --> <div class="paragraph-pack"><p id="paragraph-25"> This non-engagement with sound seems surprising, given the significant place that speech plays in the profession. Historians have taught through lectures for centuries, and conference presentations have become an expected part of membership in the profession. These forms of audio scholarship have not been engaged as ‘works’ of history, however, unless published in journals or in edited volumes. It is quite possible that universities’ insistence on written scholarship as the litmus test for academic success has played a crucial role in the centrality of the text within history. </p></div> <!-- 26 --> <div class="paragraph-pack"><p id="paragraph-26"> But what might sonic forms of historical scholarship look and sound like? How can historians marshal these forms to tell history? This question remains largely unanswered at the moment, and this openness is full of exciting possibilities. </p></div> <!-- 27 --> <div class="paragraph-pack"><p id="paragraph-27"> Listening to “Nancy” once again in another context may give us some hints, however. Let’s listen to the final segment of it, along with something a little more: </p></div> <div class="inline-audio"><a href="/audio/issue-1-3/Radiolab.mp3" class="sm2_button">Radiolab, “Time”, (2007)</a><p class="label">Radiolab, “Time”, (2007)</p></div> <!-- 28 --> <div class="paragraph-pack"><p id="paragraph-28"> In 2007, “Nancy” was used in its entirety in the <em>Radiolab</em> episode “<a href="http://www.radiolab.org/2007/may/29/">Time</a>.” <em>Radiolab</em> and other public radio programs like <em>This American Life</em> have built on the foundations of sonic thinking and experimentation outlined above and embodied by Schwartz and “Nancy.” These programs remain most Americans’ contact (if they have any at all) with the legacy and form of these sonic experiments. Although it is not strictly concerned with history, <em>Radiolab</em> consistently employs sophisticated ideas, arguments, and narratives from current historical scholarship. The discussion of time employed as part of their discussion of “Nancy,” for example, is indebted to cultural histories of the standardization of time like Wolfgang Schivelbusch’s <a href="http://isites.harvard.edu/fs/docs/icb.topic837305.files/OReilly_Schivelbusch.htm"><em>The Railway Journey</em></a>. </p></div> <!-- 29 --> <div class="paragraph-pack"><p id="paragraph-29"> Radio and sound recordings are not the only vehicles that we historians have excluded. The other media that seem most obvious for us to embrace—television and film—have also been pushed beyond the disciplinary pale. Ken Burns’s documentaries and the History Channel, for example, are seldom considered part of the scholarly conversation and are often seen as non-specialist intrusions into “serious history,” despite their formative impact on the popular imagination of the past. Incursions by historians into other types of media—like the film version of Natalie Zemon Davis’s <a href="http://www.imdb.com/title/tt0084589/"><em>The Return of Martin Guerre</em></a> or Niall Ferguson’s multi-episode version of <a href="http://www.pbs.org/wnet/ascentofmoney/"><em>The Ascent of Money</em></a>—have been relatively rare and are often conducted or spearheaded by people not considered part of the scholarly community. </p></div> <!-- 30 --> <div class="paragraph-pack"><p id="paragraph-30"> The main point is not that all historians need to begin making sound documentaries, but that there are rich resources outside the text that we have neglected. Sound recording is but one device. Indeed, my own experience within the classroom has demonstrated that historians are increasingly moving towards multi-media presentations within teaching—using music on Youtube, photographs, blogs, and film footage—both to expand the range of sources and to try to engage students through the media that are the most familiar to them. Scholarship should follow suit. The increasing move towards the digitalization of academic work—as PDFs or online books—is an incredible opportunity to begin to rethink the historical work. At the same time, it could allow us to dialogue with audiences that are receptive to Errol Morris’s documentaries and podcasts of <em>Fresh Air</em> but who find academic monographs tedious or difficult to approach. </p></div> <!-- 31 --> <div class="paragraph-pack"><p id="paragraph-31"> If we accept Walter Benjamin’s argument that perception and communication are historical and formed by their social and technological contexts, then historians are lagging behind. Creating scholarship has long required that historians learn the art of writing; there is no reason that the historian’s craft could not begin to include a fluency in other technologies and media. If, as historians, we took such a turn, we could open up new horizons for historical scholarship and begin to speak a language more attuned to a larger public. </p></div> <!-- 32 --> <div class="paragraph-pack"><p id="paragraph-32" class="alternate-voice"> <strong>Editor’s Note:</strong> For a related exploration of ‘sonic forms of historical scholarship’ see Amber Abbas’s “<a href="/issues/2013/7/for-the-sound-of-her-voice">For the Sound of Her Voice</a>” elsewhere in this issue. </p></div>
theappendix/theappendix-jekyll-source
_posts/issue-1-3/2013-09-03-schmidt-nancy.html
HTML
mit
22,889
import * as Lint from 'tslint'; import * as ts from 'typescript'; const RULE_FAILURE = `Undecorated class defines fields with Angular decorators. Undecorated ` + `classes with Angular fields cannot be extended in Ivy since no definition is generated. ` + `Add a "@Directive" decorator to fix this.`; /** * Rule that doesn't allow undecorated class declarations with fields using Angular * decorators. */ export class Rule extends Lint.Rules.TypedRule { applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] { return this.applyWithWalker( new Walker(sourceFile, this.getOptions(), program.getTypeChecker())); } } class Walker extends Lint.RuleWalker { constructor( sourceFile: ts.SourceFile, options: Lint.IOptions, private _typeChecker: ts.TypeChecker) { super(sourceFile, options); } visitClassDeclaration(node: ts.ClassDeclaration) { if (this._hasAngularDecorator(node)) { return; } for (let member of node.members) { if (member.decorators && this._hasAngularDecorator(member)) { this.addFailureAtNode(node, RULE_FAILURE); return; } } } /** Checks if the specified node has an Angular decorator. */ private _hasAngularDecorator(node: ts.Node): boolean { return !!node.decorators && node.decorators.some(d => { if (!ts.isCallExpression(d.expression) || !ts.isIdentifier(d.expression.expression)) { return false; } const moduleImport = this._getModuleImportOfIdentifier(d.expression.expression); return moduleImport ? moduleImport.startsWith('@angular/core') : false; }); } /** Gets the module import of the given identifier if imported. */ private _getModuleImportOfIdentifier(node: ts.Identifier): string | null { const symbol = this._typeChecker.getSymbolAtLocation(node); if (!symbol || !symbol.declarations || !symbol.declarations.length) { return null; } const decl = symbol.declarations[0]; if (!ts.isImportSpecifier(decl)) { return null; } const importDecl = decl.parent.parent.parent; const moduleSpecifier = importDecl.moduleSpecifier; return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : null; } }
trimox/angular-mdc-web
tools/tslint-rules/noUndecoratedClassWithNgFieldsRule.ts
TypeScript
mit
2,257
/*! fingoCarousel.js © heoyunjee, 2016 */ function(global, $){ 'use strict'; /** * width: carousel width * height: carousel height * margin: tabpanel margin * count: how many tabpanels will move when you click button * col: how many columns in carousel mask * row: how many rows in carousel mask * infinite: infinite carousel or not(true or false) * index: index of active tabpanel */ // Default Options var defaults = { 'width': 1240, 'height': 390, 'margin': 0, 'count': 1, 'col': 1, 'row': 1, 'infinite': false, 'index': 0 }; // Constructor Function var Carousel = function(widget, options) { // Public this.$widget = $(widget); this.settings = $.extend({}, defaults, options); this.carousel_infinite = false; this.carousel_row = 0; this.carousel_width = 0; this.carousel_height = 0; this.carousel_count = 0; this.carousel_col = 0; this.carousel_content_margin = 0; this.active_index = 0; this.carousel_one_tab = 0; this.carousel_content_width = 0; this.carousel_content_height= 0; this.$carousel = null; this.$carousel_headline = null; this.$carousel_tablist = null; this.$carousel_tabs = null; this.$carousel_button_group = null; this.$carousel_mask = null; this.$carousel_tabpanels = null; this.$carousel_tabpanel_imgs = null; this.$carousel_tabpanel_content_videos = null; this.start_tabpanel_index = 0; // 초기 설정 this.init(); // 이벤트 연결 this.events(); }; // Prototype Object Carousel.prototype = { 'init': function() { var $this = this; var $widget = this.$widget; // 캐러셀 내부 구성 요소 참조 this.$carousel = $widget; this.$carousel_headline = this.$carousel.children(':header:first'); this.$carousel_tablist = this.$carousel.children('ul').wrap('<div/>').parent(); this.$carousel_tabs = this.$carousel_tablist.find('a'); this.$carousel_tabpanels = this.$carousel.children().find('figure'); this.$carousel_content = this.$carousel_tabpanels.children().parent(); this.$carousel_tabpanel_imgs = this.$carousel.children().last().find('img').not('.icon'); this.$carousel_tabpanel_content_videos = this.$carousel.children().last().find('iframe'); this.setResponsive(); this.carousel_width = this.settings.width; this.carousel_height = this.settings.height; this.carousel_infinite = this.settings.infinite; this.carousel_row = this.settings.row; this.carousel_count = this.settings.count; this.carousel_col = this.settings.col; this.carousel_content_margin = this.settings.margin; this.start_tabpanel_index = this.settings.index; // 동적으로 캐러셀 구조 생성/추가 this.createPrevNextButtons(); this.createCarouselMask(); // 역할별 스타일링 되는 클래스 설정 this.settingClass(); this.settingSliding(); }, 'createPrevNextButtons': function() { var button_group = ['<div>', '<button type="button"></button>', '<button type="button"></button>', '</div>'].join(''); this.$carousel_button_group = $(button_group).insertAfter( this.$carousel_tablist ); }, 'createCarouselMask': function() { this.$carousel_tabpanels.parent().closest('div').wrap('<div/>'); this.$carousel_mask = this.$carousel.children().last(); }, 'settingClass': function() { this.$carousel.addClass('ui-carousel'); this.$carousel_headline.addClass('ui-carousel-headline'); this.$carousel_tablist.addClass('ui-carousel-tablist'); this.$carousel_tabs.addClass('ui-carousel-tab'); this.$carousel_button_group.addClass('ui-carousel-button-group'); this.$carousel_button_group.children().first().addClass('ui-carousel-prev-button'); this.$carousel_button_group.children().last().addClass('ui-carousel-next-button'); this.$carousel_tabpanels.addClass('ui-carousel-tabpanel'); this.$carousel_tabpanels.parent().closest('div').addClass('ui-carousel-tabpanel-wrapper'); this.$carousel_mask.addClass('ui-carousel-mask'); this.$carousel_tabpanel_imgs.addClass('ui-carousel-image'); this.$carousel_tabpanel_content_videos.addClass('ui-carousel-video'); if(this.carousel_row === 2) { var j = 1; var j2 = 1; for(var i = 0, l = this.$carousel_tabpanels.length; i < l; i++) { if(i%2===1){ this.$carousel_tabpanels.eq(i).addClass('top-2'); this.$carousel_tabpanels.eq(i).addClass('left-' + j); j++; } else { this.$carousel_tabpanels.eq(i).addClass('top-1'); this.$carousel_tabpanels.eq(i).addClass('left-' + j2); j2++; } } } }, 'settingSliding': function() { var $carousel = this.$carousel; var $tabpanel = this.$carousel_tabpanels; var $tabpanel_wrapper = $tabpanel.parent(); var $carousel_mask = this.$carousel_mask; var carousel_tabpannel_width = ($carousel_mask.width() - (this.carousel_col - 1) * this.carousel_content_margin) / this.carousel_col; this.carousel_content_width = this.$carousel_tabpanel_imgs.eq(0).width(); // carousel 높이 설정 $carousel.height(this.carousel_height); // Set carousel tabpanel(div or img) size and margin if(this.settings.col === 1) { $tabpanel.width($carousel.width()); } else { $tabpanel .width(this.carousel_content_width) .css('margin-right', this.carousel_content_margin); } // Set carousel tabpanel wrapper width $tabpanel_wrapper.width(($tabpanel.width() + this.carousel_content_margin) * ($tabpanel.length + 1)); // Set carousel one tab mask width this.carousel_one_tab = ($tabpanel.width() + this.carousel_content_margin) * this.carousel_count; if(this.start_tabpanel_index !== 0) { for(var i = 0, l = this.start_tabpanel_index + 1; i < l; i++) { this.$carousel_tabpanels.last().parent().prepend(this.$carousel_tabpanels.eq($tabpanel.length - (i + 1))); } } // Carousel 상태 초기화 if(this.carousel_infinite === true) { // tabpanel active 상태 초기화 this.$carousel_tabpanels.eq(this.active_index).radioClass('active'); // tabpanel wrapper 위치 초기화 $tabpanel_wrapper.css('left', -this.carousel_one_tab); } else if(this.carousel_col !== 1){ // Infinite Carousel이 아닐때 // prevBtn 비활성화 this.prevBtnDisable(); } // 인디케이터 active 상태 초기화 this.$carousel_tabs.eq(this.active_index).parent().radioClass('active'); }, 'prevBtnActive': function() { this.$carousel.find('.ui-carousel-prev-button') .attr('aria-disabled', 'false') .css({'opacity': 1, 'display': 'block'}); }, 'prevBtnDisable': function() { this.$carousel.find('.ui-carousel-prev-button') .attr('aria-disabled', 'true') .css({'opacity': 0, 'display': 'none'}); }, 'events': function() { var widget = this; var $carousel = widget.$carousel; var $tabs = widget.$carousel_tabs; var $buttons = widget.$carousel_button_group.children(); // buttons event $buttons.on('click', function() { if ( this.className === 'ui-carousel-prev-button' ) { widget.prevPanel(); } else { widget.nextPanel(); } }); // tabs event $.each($tabs, function(index) { var $tab = $tabs.eq(index); $tab.on('click', $.proxy(widget.viewTabpanel, widget, index, null)); }); }, 'setActiveIndex': function(index) { // 활성화된 인덱스를 사용자가 클릭한 인덱스로 변경 this.active_index = index; // tab 최대 개수 var carousel_tabs_max = (this.$carousel_tabpanels.length / (this.carousel_count * this.carousel_row)) - 1; // 한 마스크 안에 패널이 다 채워지지 않을 경우 if((this.$carousel_tabpanels.length % (this.carousel_count * this.carousel_row)) !== 0) { carousel_tabs_max = carousel_tabs_max + 1; } // 처음 또는 마지막 인덱스에 해당할 경우 마지막 또는 처음으로 변경하는 조건 처리 if ( this.active_index < 0 ) { this.active_index = carousel_tabs_max; } if ( this.active_index > carousel_tabs_max ) { this.active_index = 0; } return this.active_index; }, 'nextPanel': function() { if(!this.$carousel_tabpanels.parent().is(':animated')) { var active_index = this.setActiveIndex(this.active_index + 1); this.viewTabpanel(active_index, 'next'); } }, 'prevPanel': function() { if(!this.$carousel_tabpanels.parent().is(':animated')) { var active_index = this.setActiveIndex(this.active_index - 1); this.viewTabpanel(active_index, 'prev'); } }, 'viewTabpanel': function(index, btn, e) { // 사용자가 클릭을 하는 행위가 발생하면 이벤트 객체를 받기 때문에 // 조건 확인을 통해 브라우저의 기본 동작 차단 if (e) { e.preventDefault(); } this.active_index = index; var $carousel_wrapper = this.$carousel_tabpanels.eq(index).parent(); var one_width = this.carousel_one_tab; // Infinite Carousel if(this.carousel_infinite === true) { // index에 해당되는 탭패널 활성화 this.$carousel_tabpanels.eq(index).radioClass('active'); // next 버튼 눌렀을때 if(btn === 'next') { $carousel_wrapper.stop().animate({ 'left': -one_width * 2 }, 500, 'easeOutExpo', function() { $carousel_wrapper.append($carousel_wrapper.children().first()); $carousel_wrapper.css('left', -one_width); this.animating = false; }); // prev 버튼 눌렀을때 } else if(btn === 'prev') { $carousel_wrapper.stop().animate({ 'left': 0 }, 500, 'easeOutExpo', function() { $carousel_wrapper.prepend($carousel_wrapper.children().last()); $carousel_wrapper.css('left', -one_width); }); } } else if(this.carousel_infinite === false) { if(this.carousel_col !== 1) { if(index === 0) { this.prevBtnDisable(); } else { this.prevBtnActive(); } } $carousel_wrapper.stop().animate({ 'left': index * -this.carousel_one_tab }, 600, 'easeOutExpo'); } // 인디케이터 라디오클래스 활성화 this.$carousel_tabs.eq(index).parent().radioClass('active'); }, 'setResponsive': function() { if(global.innerWidth <= 750) { this.settings.width = this.settings.width.mobile || this.settings.width; this.settings.height = this.settings.height.mobile || this.settings.height; this.settings.margin = this.settings.margin.mobile || this.settings.margin; this.settings.count = this.settings.count.mobile || this.settings.count; this.settings.col = this.settings.col.mobile || this.settings.col; this.settings.row = this.settings.row.mobile || this.settings.row; if(this.settings.infinite.mobile !== undefined) { this.settings.infinite = this.settings.infinite.mobile; } this.settings.index = 0; } else if(global.innerWidth <= 1024) { this.settings.width = this.settings.width.tablet || this.settings.width; this.settings.height = this.settings.height.tablet || this.settings.height; this.settings.margin = this.settings.margin.tablet || this.settings.margin; this.settings.count = this.settings.count.tablet || this.settings.count; this.settings.col = this.settings.col.tablet || this.settings.col; this.settings.row = this.settings.row.tablet || this.settings.row; if(this.settings.infinite.tablet !== undefined) { this.settings.infinite = this.settings.infinite.tablet; } this.settings.index = this.settings.index.tablet || this.settings.index; } else { this.settings.width = this.settings.width.desktop || this.settings.width; this.settings.height = this.settings.height.desktop || this.settings.height; this.settings.margin = this.settings.margin.desktop || this.settings.margin; this.settings.count = this.settings.count.desktop || this.settings.count; this.settings.col = this.settings.col.desktop || this.settings.col; this.settings.row = this.settings.row.desktop || this.settings.row; if(this.settings.infinite.desktop !== undefined) { this.settings.infinite = this.settings.infinite.desktop; } this.settings.index = this.settings.index.desktop || this.settings.index; } } }; // jQuery Plugin $.fn.fingoCarousel = function(options){ var $collection = this; // jQuery {} return $.each($collection, function(idx){ var $this = $collection.eq(idx); var _instance = new Carousel( this, options ); // 컴포넌트 화 $this.data('fingoCarousel', _instance); }); }; })(this, this.jQuery);
ooyunjee/fingoCarousel
fingo.carousel.js
JavaScript
mit
13,831
/* * ============================================================================= * * Filename: cqi_pool.c * * Description: connection queue item pool. * * Created: 10/18/2012 07:56:53 PM * * Author: Fu Haiping (forhappy), haipingf@gmail.com * Company: ICT ( Institute Of Computing Technology, CAS ) * * ============================================================================= */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include "cqi_pool.h" /** returns a fresh connection queue item. */ connection_queue_item_t * cqi_pool_get_item(cqi_pool_t *pool) { int i = 0, ret = 0; connection_queue_item_t *newpool = NULL; connection_queue_item_t *item = NULL; ret = pthread_mutex_lock(&(pool->lock)); if (ret != 0) { LOG_ERROR(("pthread_mutex_lock() failed.")); return NULL; } if (pool->curr != NULL) { item = pool->curr; pool->curr = item->next; } if (NULL == item) { if (pool->allocs == ITEMS_MAX_ALLOC){ ret = pthread_mutex_unlock(&(pool->lock)); if (ret != 0) { LOG_ERROR(("pthread_mutex_unlock() failed.")); return NULL; } LOG_ERROR(("connection item pool allocated too many times.")); return NULL; } /* allocate a bunch of items at once to reduce fragmentation */ newpool = (connection_queue_item_t *) malloc( sizeof(connection_queue_item_t) * ITEMS_PER_ALLOC); if (NULL == newpool) { LOG_ERROR(("cqi_pool_get_item() failed due to out of memory.")); return NULL; } else { memset(newpool, 0, sizeof(connection_queue_item_t) * (ITEMS_PER_ALLOC)); for (i = 1; i < ITEMS_PER_ALLOC; i++) newpool[i - 1].next = &newpool[i]; newpool[ITEMS_PER_ALLOC - 1].next = NULL; pool->memo[pool->allocs++] = newpool; pool->curr = newpool; item = pool->curr; pool->curr = item->next; pool->size += ITEMS_PER_ALLOC; } } ret = pthread_mutex_unlock(&(pool->lock)); if (ret != 0) { LOG_ERROR(("pthread_mutex_unlock() failed.")); return NULL; } return item; } /** return a connection queue item pool. */ cqi_pool_t * cqi_pool_new(void) { int i = 0, ret = 0; cqi_pool_t *pool = NULL; pool = (cqi_pool_t *) malloc(sizeof(cqi_pool_t)); if (pool == NULL) { exit(-1); } ret = pthread_mutex_init(&(pool->lock), NULL); if (ret != 0) { LOG_ERROR(("pthread_mutex_init() failed.")); return NULL; } pool->pool = (connection_queue_item_t *) malloc(sizeof(connection_queue_item_t) * INITIAL_CQI_POOL_SIZE); if (pool->pool == NULL) { LOG_ERROR(("cqi_pool_new() failed due to out of memory.")); return NULL; } else { pool->curr = pool->pool; pool->size = INITIAL_CQI_POOL_SIZE; pool->allocs = 0; memset(pool->memo, 0, sizeof(connection_queue_item_t *) * ITEMS_MAX_ALLOC); for (i = 1; i < INITIAL_CQI_POOL_SIZE; i++) (pool->pool)[i - 1].next= &(pool->pool)[i]; (pool->pool)[INITIAL_CQI_POOL_SIZE - 1].next = NULL; } return pool; } /* * release a connection queue item back to the pool. */ void cqi_pool_release_item(cqi_pool_t *pool, connection_queue_item_t *item) { int index = -1, ret = 0; ret = pthread_mutex_lock(&(pool->lock)); if (ret != 0) LOG_ERROR(("pthread_mutex_lock() failed.")); item->next = pool->curr; pool->curr = item; ret = pthread_mutex_unlock(&(pool->lock)); if (ret != 0) LOG_ERROR(("pthread_mutex_unlock() failed.")); } /** free a connection queue item pool. */ void cqi_pool_free(cqi_pool_t *pool) { int i = 0; if (pool != NULL) { pthread_mutex_destroy(&(pool->lock)); if (pool->pool != NULL) { free(pool->pool); pool->pool = NULL; } for (i = 0; i < pool->allocs; i++) { free(pool->memo[i]); } free(pool); } } #ifdef LLDB_CQI_POOL_TEST #define WORKER_THREAD_SIZE 64 void * worker_thread(void *arg) { cqi_pool_t *pool = (cqi_pool_t *)arg; connection_queue_item_t *item = cqi_pool_get_item(pool); if (item != NULL) { item->sfd = pthread_self(); item->active_flag = pthread_self(); sleep(1); cqi_pool_release_item(pool, item); } } cqi_pool_t *pool = NULL; int main() { pool = cqi_pool_new(); connection_queue_item_t *curr = NULL; pthread_t thead[WORKER_THREAD_SIZE]; log_set_debug_level(LLDB_LOG_LEVEL_DEBUG); for (int i = 0; i < WORKER_THREAD_SIZE; i++) { pthread_create(&thead[i], NULL, worker_thread, pool); } for (int i = 0; i < WORKER_THREAD_SIZE; i++) { pthread_join(thead[i], NULL); } printf("pool size: %d\n", pool->size); cqi_pool_free(pool); } #endif // LLDB_CQI_POOL_TEST
forhappy/LLDB
src/server/cqi_pool.c
C
mit
4,584
<?php use \SeedDataInterface as SeedDataInterface; abstract class BaseSeedData implements SeedDataInterface{ public function markMigration(){ $data = []; $data['class_name'] = get_called_class(); $seedMigration = SeedMigrationModel::createObject($data,SeedMigrationModel::$attributes); SeedMigrationModel::getMapper()->setModel($seedMigration)->save(); } }
poupouxios/custom-light-mvc
db/seed-data/BaseSeedData.php
PHP
mit
403
class upnp_soaprequest { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = upnp_soaprequest;
mrpapercut/wscript
testfiles/COMobjects/JSclasses/UPnP.SOAPRequest.js
JavaScript
mit
569
module.exports = { schedule_inputError: "Not all required inputs are present in the request", reminder_newscheduleSuccess: "A new mail has been successfully saved and scheduled", schedule_ShdlError: "The scheduleAt should be a timestamp (like : 1411820580000) and should be in the future", gbl_oops: "Oops something went wrong", gbl_success: "success" };
karankohli13/sendgrid-scheduler
messages/messages.js
JavaScript
mit
375
package xsmeral.semnet.sink; import java.util.Properties; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.sail.SailRepository; import org.openrdf.sail.rdbms.RdbmsStore; /** * Factory of {@link RdbmsStore} repositories. * <br /> * Takes parameters corresponding to RdbmsStore {@linkplain RdbmsStore#RdbmsStore(java.lang.String, java.lang.String, java.lang.String, java.lang.String) constructor}: * <ul> * <li><code>driver</code> - FQN of JDBC driver</li> * <li><code>url</code> - JDBC URL</li> * <li><code>user</code> - DB user name</li> * <li><code>password</code> - DB password</li> * </ul> * @author Ron Šmeral (xsmeral@fi.muni.cz) */ public class RdbmsStoreFactory extends RepositoryFactory { @Override public void initialize() throws RepositoryException { Properties props = getProperties(); String jdbcDriver = props.getProperty("driver"); String url = props.getProperty("url"); String user = props.getProperty("user"); String pwd = props.getProperty("password"); if (jdbcDriver == null || url == null || user == null || pwd == null) { throw new RepositoryException("Invalid parameters for repository"); } else { Repository repo = new SailRepository(new RdbmsStore(jdbcDriver, url, user, pwd)); repo.initialize(); setRepository(repo); } } }
rsmeral/semnet
SemNet/src/xsmeral/semnet/sink/RdbmsStoreFactory.java
Java
mit
1,465
#pragma once #include "base/Ref.h" #include "math/vec3.h" #include "math/mat4.h" #include "math/quat.h" #include "base/component/BaseComponent.h" #include "base/Vector.h" class Transform : public BaseComponent { public: Transform(GameObject* owner = nullptr); virtual ~Transform(); public: virtual void Update(float dt); Vector<Transform*>& getChildren(); public: Vec3& getPosition() { return _position; } void setPosition(const Vec3& pos); Vec3& getScale() { return _scale; } void setScale(const Vec3& scale); void setScale(float scale); Quat& getRotation() { return _rotation; } void setRotation(const Quat& rot); Vec3& getLocalPosition() { return _localPosition; } void setLocalPosition(const Vec3& pos); Vec3& getLocalScale() { return _localScale; } void setLocalScale(const Vec3& scale); Quat& getLocalRotation() { return _localRotation; } void setLocalRotation(const Quat& rot); Transform* getParent() { return _parent; } void setParent(Transform* parent); const Mat4& apply(); protected: Vec3 _position, _localPosition; Vec3 _scale, _localScale; Quat _rotation, _localRotation; Mat4 _modleMatrix; Transform* _parent; Vector<Transform*> _children; protected: bool _transformDirty = true; bool _transformLocalDirty = false; };
lyzardiar/BWEngine
frameworks/base/component/Transform.h
C
mit
1,331
package com.test.SERVICE; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.test.DAO.IMercaderiaDAO; import com.test.BEAN.Mercaderia; @Service public class MercaderiaService implements IMercaderiaService{ @Autowired private IMercaderiaDAO mercaderiaDAO; @Override public List<Mercaderia> getAllMercaderia() { return mercaderiaDAO.getAllMercaderia(); } @Override public Mercaderia getMercaderiaById(int mercaderiaId) { Mercaderia merc = mercaderiaDAO.getMercaderiaById(mercaderiaId); return merc; } @Override public boolean createMercaderia(Mercaderia mercaderia) { if (mercaderiaDAO.mercaderiaExists(mercaderia.getNombre())) { return false; } else { mercaderiaDAO.createMercaderia(mercaderia); return true; } } @Override public void updateMercaderia(Mercaderia mercaderia) { // TODO Auto-generated method stub mercaderiaDAO.updateMercaderia(mercaderia); } }
renzopalmieri/demomercaderia
spring-boot-2/src/main/java/com/test/SERVICE/MercaderiaService.java
Java
mit
1,116