text
stringlengths
2
1.04M
meta
dict
#region Foreign-License #endregion using System; namespace Tcl.Lang { /* * This class implements the built-in "error" command in Tcl. */ class ErrorCmd : ICommand { public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv) { if (argv.Length < 2 || argv.Length > 4) { throw new TclNumArgsException(interp, 1, argv, "message ?errorInfo? ?errorCode?"); } if (argv.Length >= 3) { string errorInfo = argv[2].ToString(); if (!errorInfo.Equals("")) { interp.AddErrorInfo(errorInfo); interp._errAlreadyLogged = true; } } if (argv.Length == 4) { interp.SetErrorCode(argv[3]); } interp.SetResult(argv[1]); throw new TclException(TCL.CompletionCode.ERROR); } } // end ErrorCmd }
{ "content_hash": "1d5b0473d6a3343a073099327bc8aef7", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 98, "avg_line_length": 24.302325581395348, "alnum_prop": 0.46411483253588515, "repo_name": "BclEx/GpuStructs", "id": "795fc03f2dadb5628f5e1e70748421242f5b6cf9", "size": "1330", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Tcl.net/Lang+Commands/ErrorCmd.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Bison", "bytes": "45727" }, { "name": "C", "bytes": "3784724" }, { "name": "C#", "bytes": "5110307" }, { "name": "C++", "bytes": "970081" }, { "name": "Cuda", "bytes": "9043036" }, { "name": "Objective-C", "bytes": "2166" }, { "name": "PowerShell", "bytes": "31854" }, { "name": "Shell", "bytes": "73" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AccessIO { /// <summary> /// Establishes a relationship between object type and corresponding file extensión /// </summary> public class ObjectTypeExtension { public ObjectType ObjectType {get; set; } public FileExtensions FileExtension { get; set; } public ContainerNames Container { get; private set; } public ObjectTypeExtension(ContainerNames container, ObjectType objectType, FileExtensions fileExtension) { Container = container; ObjectType = objectType; FileExtension = fileExtension; } } }
{ "content_hash": "a483e0d79cd3aa29b11573f8bd31ac46", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 115, "avg_line_length": 31.545454545454547, "alnum_prop": 0.6815561959654178, "repo_name": "funkysi1701/MSAccessSVN", "id": "3404ba784e387cb2d7b5a9a5ac9cecbaa1ed17ff", "size": "697", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "trunk/AccessIO/Metadata/ObjectTypeExtension.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "234597" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- // Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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. --> <config id="sharpdx-mediafoundation-all" xmlns="urn:SharpGen.Config"> <depends>sharpdx-core</depends> <depends>sharpdx-mediafoundation</depends> <ifndef name="DIRECTX11_1"> <depends>sharpdx-direct3d9</depends> </ifndef> <file>Mapping-core.xml</file> <ifndef name="DIRECTX11_1"> <depends>sharpdx-mediafoundation-directx</depends> <depends>sharpdx-mediafoundation-opm</depends> <file>DirectX\Mapping.xml</file> <file>OPM\Mapping.xml</file> </ifndef> <ifndef name="W8CORE"> <depends>sharpdx-mediafoundation-dsp</depends> <file>Dsp\Mapping.xml</file> </ifndef> </config>
{ "content_hash": "2c10c2f08986d7e2dfe411ec84641fbd", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 80, "avg_line_length": 40.84090909090909, "alnum_prop": 0.7373400111296605, "repo_name": "TigerKO/SharpDX", "id": "9ed3578e90141b0234f7a7dadcb9e5095c98fcfc", "size": "1797", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Source/SharpDX.MediaFoundation/Mapping.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6082576" }, { "name": "C#", "bytes": "11202840" }, { "name": "C++", "bytes": "3915964" }, { "name": "CSS", "bytes": "10347" }, { "name": "FLUX", "bytes": "79643" }, { "name": "Objective-C", "bytes": "130591" }, { "name": "PowerShell", "bytes": "2255" }, { "name": "Shell", "bytes": "4638" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- You may freely edit this file. See commented blocks below for --> <!-- some examples of how to customize the build. --> <!-- (If you delete it and reopen the project it will be recreated.) --> <!-- By default, only the Clean and Build commands use this build script. --> <!-- Commands such as Run, Debug, and Test only use this build script if --> <!-- the Compile on Save feature is turned off for the project. --> <!-- You can turn off the Compile on Save (or Deploy on Save) setting --> <!-- in the project's Project Properties dialog box.--> <project name="unab-erp-core-rrhh" default="default" basedir="."> <description>Builds, tests, and runs the project unab-erp-core-rrhh.</description> <import file="nbproject/build-impl.xml"/> <!-- There exist several targets which are by default empty and which can be used for execution of your tasks. These targets are usually executed before and after some main targets. They are: -pre-init: called before initialization of project properties -post-init: called after initialization of project properties -pre-compile: called before javac compilation -post-compile: called after javac compilation -pre-compile-single: called before javac compilation of single file -post-compile-single: called after javac compilation of single file -pre-compile-test: called before javac compilation of JUnit tests -post-compile-test: called after javac compilation of JUnit tests -pre-compile-test-single: called before javac compilation of single JUnit test -post-compile-test-single: called after javac compilation of single JUunit test -pre-jar: called before JAR building -post-jar: called after JAR building -post-clean: called after cleaning build products (Targets beginning with '-' are not intended to be called on their own.) Example of inserting an obfuscator after compilation could look like this: <target name="-post-compile"> <obfuscate> <fileset dir="${build.classes.dir}"/> </obfuscate> </target> For list of available properties check the imported nbproject/build-impl.xml file. Another way to customize the build is by overriding existing main targets. The targets of interest are: -init-macrodef-javac: defines macro for javac compilation -init-macrodef-junit: defines macro for junit execution -init-macrodef-debug: defines macro for class debugging -init-macrodef-java: defines macro for class execution -do-jar: JAR building run: execution of project -javadoc-build: Javadoc generation test-report: JUnit report generation An example of overriding the target for project execution could look like this: <target name="run" depends="unab-erp-core-rrhh-impl.jar"> <exec dir="bin" executable="launcher.exe"> <arg file="${dist.jar}"/> </exec> </target> Notice that the overridden target depends on the jar target and not only on the compile target as the regular run target does. Again, for a list of available properties which you can use, check the target you are overriding in the nbproject/build-impl.xml file. --> </project>
{ "content_hash": "bb5e9ac81bcec9ee1f60434065f71498", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 86, "avg_line_length": 48.84931506849315, "alnum_prop": 0.6539540100953449, "repo_name": "mcastillob/ERP-UNAB-", "id": "c2e9d96e39147719a1f446cac94b7a6aef378efb", "size": "3566", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "unab-erp-core-rrhh/build.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "212853" } ], "symlink_target": "" }
package br.com.fametro.wine.repository.helper.venda; import java.time.LocalDateTime; import java.time.LocalTime; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.sql.JoinType; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import br.com.fametro.wine.model.TipoPessoa; import br.com.fametro.wine.model.Venda; import br.com.fametro.wine.repository.filter.VendaFilter; public class VendasImpl implements VendasQueries { @PersistenceContext private EntityManager manager; @Transactional(readOnly = true) @Override public Venda buscarComItens(Long codigo) { Criteria criteria = manager.unwrap(Session.class).createCriteria(Venda.class); criteria.createAlias("itens", "i", JoinType.LEFT_OUTER_JOIN); criteria.add(Restrictions.eq("codigo", codigo)); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return (Venda) criteria.uniqueResult(); } @SuppressWarnings("unchecked") @Transactional(readOnly = true) @Override public Page<Venda> filtrar(VendaFilter filtro, Pageable pageable) { Criteria criteria = manager.unwrap(Session.class).createCriteria(Venda.class); //paginacaoUtil.preparar(criteria, pageable); adicionarFiltro(filtro, criteria); return new PageImpl<>(criteria.list(), pageable, total(filtro)); } private Long total(VendaFilter filtro) { Criteria criteria = manager.unwrap(Session.class).createCriteria(Venda.class); adicionarFiltro(filtro, criteria); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); } private void adicionarFiltro(VendaFilter filtro, Criteria criteria) { criteria.createAlias("cliente", "c"); if (filtro != null) { if (!StringUtils.isEmpty(filtro.getCodigo())) { criteria.add(Restrictions.eq("codigo", filtro.getCodigo())); } if (filtro.getStatus() != null) { criteria.add(Restrictions.eq("status", filtro.getStatus())); } if (filtro.getDesde() != null) { LocalDateTime desde = LocalDateTime.of(filtro.getDesde(), LocalTime.of(0, 0)); criteria.add(Restrictions.ge("dataCriacao", desde)); } if (filtro.getAte() != null) { LocalDateTime ate = LocalDateTime.of(filtro.getAte(), LocalTime.of(23, 59)); criteria.add(Restrictions.le("dataCriacao", ate)); } if (filtro.getValorMinimo() != null) { criteria.add(Restrictions.ge("valorTotal", filtro.getValorMinimo())); } if (filtro.getValorMaximo() != null) { criteria.add(Restrictions.le("valorTotal", filtro.getValorMaximo())); } if (!StringUtils.isEmpty(filtro.getNomeCliente())) { criteria.add(Restrictions.ilike("c.nome", filtro.getNomeCliente(), MatchMode.ANYWHERE)); } if (!StringUtils.isEmpty(filtro.getCpfOuCnpjCliente())) { criteria.add(Restrictions.eq("c.cpfOuCnpj", TipoPessoa.removerFormatacao(filtro.getCpfOuCnpjCliente()))); } } } }
{ "content_hash": "083743f0cb754755abf38cf387ad88ae", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 109, "avg_line_length": 33.06, "alnum_prop": 0.7453115547489413, "repo_name": "EliasMG/wine", "id": "04703e914dccecc7a4c99dc460f62672cf09d814", "size": "3306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/br/com/fametro/wine/repository/helper/venda/VendasImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5006" }, { "name": "HTML", "bytes": "52631" }, { "name": "Java", "bytes": "76278" }, { "name": "JavaScript", "bytes": "16968" } ], "symlink_target": "" }
/** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. * * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html */ /*************************************************************************************************** * BROWSER POLYFILLS */ import 'core-js/client/core.min.js' /** IE9, IE10 and IE11 requires all of the following polyfills. **/ import 'core-js/es6/symbol'; import 'core-js/es6/object'; import 'core-js/es6/function'; import 'core-js/es6/parse-int'; import 'core-js/es6/parse-float'; import 'core-js/es6/number'; import 'core-js/es6/math'; import 'core-js/es6/string'; import 'core-js/es6/date'; import 'core-js/es6/array'; import 'core-js/es6/regexp'; import 'core-js/es6/map'; import 'core-js/es6/weak-map'; import 'core-js/es6/set'; /** IE10 and IE11 requires the following for NgClass support on SVG elements */ // import 'classlist.js'; // Run `npm install --save classlist.js`. /** Evergreen browsers require these. **/ import 'core-js/es6/reflect'; import 'core-js/es7/reflect'; /** * Required to support Web Animations `@angular/animation`. * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation **/ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. /*************************************************************************************************** * Zone JS is required by Angular itself. */ import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */ /** * Date, currency, decimal and percent pipes. * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 */ // import 'intl'; // Run `npm install --save intl`. /** * Need to import at least one locale-data with intl. */ // import 'intl/locale-data/jsonp/en';
{ "content_hash": "d426768d8373853e3eac32eec6c7ca35", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 100, "avg_line_length": 33.445945945945944, "alnum_prop": 0.6181818181818182, "repo_name": "scorzy/IdleAnt", "id": "c4cc3fc377841bf68dd7ac1f486b4f589eb25a78", "size": "2475", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/polyfills.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "34964" }, { "name": "JavaScript", "bytes": "33922" }, { "name": "SCSS", "bytes": "3522" }, { "name": "TypeScript", "bytes": "228981" } ], "symlink_target": "" }
/* * grafeas.proto * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: version not set * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.ImageDerived; import java.io.IOException; /** * Details of an image occurrence. */ @ApiModel(description = "Details of an image occurrence.") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-08-22T18:45:44.983-04:00") public class V1beta1imageDetails { @SerializedName("derived_image") private ImageDerived derivedImage = null; public V1beta1imageDetails derivedImage(ImageDerived derivedImage) { this.derivedImage = derivedImage; return this; } /** * Required. Immutable. The child image derived from the base image. * @return derivedImage **/ @ApiModelProperty(value = "Required. Immutable. The child image derived from the base image.") public ImageDerived getDerivedImage() { return derivedImage; } public void setDerivedImage(ImageDerived derivedImage) { this.derivedImage = derivedImage; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } V1beta1imageDetails v1beta1imageDetails = (V1beta1imageDetails) o; return Objects.equals(this.derivedImage, v1beta1imageDetails.derivedImage); } @Override public int hashCode() { return Objects.hash(derivedImage); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class V1beta1imageDetails {\n"); sb.append(" derivedImage: ").append(toIndentedString(derivedImage)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
{ "content_hash": "f7f55dfe4bef0187af51548f7367ac4d", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 125, "avg_line_length": 27.572916666666668, "alnum_prop": 0.7117491499811107, "repo_name": "grafeas/client-java", "id": "e93fc74c9b2f29abb1506c62f7dcf6ea8a54df10", "size": "2647", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "0.1.0/src/main/java/io/swagger/client/model/V1beta1imageDetails.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1026154" }, { "name": "Scala", "bytes": "1687" }, { "name": "Shell", "bytes": "3686" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <CustomField xmlns="http://soap.sforce.com/2006/04/metadata"> <fullName>CustomerPriority__c</fullName> <externalId>false</externalId> <label>Customer Priority</label> <required>false</required> <trackFeedHistory>false</trackFeedHistory> <type>Picklist</type> <valueSet> <valueSetDefinition> <sorted>false</sorted> <value> <fullName>High</fullName> <default>false</default> <label>High</label> </value> <value> <fullName>Low</fullName> <default>false</default> <label>Low</label> </value> <value> <fullName>Medium</fullName> <default>false</default> <label>Medium</label> </value> </valueSetDefinition> </valueSet> </CustomField>
{ "content_hash": "a20c6a138b42d5d51d4a45048191eb3f", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 61, "avg_line_length": 32.55172413793103, "alnum_prop": 0.5296610169491526, "repo_name": "nileshndethe/SFDX-Labs", "id": "d95b75c9fb284121cf888cf528d6387fc661d922", "size": "944", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "geolocation/force-app/main/default/objects/Account/fields/CustomerPriority__c.field-meta.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Apex", "bytes": "9764" }, { "name": "CSS", "bytes": "5549" }, { "name": "JavaScript", "bytes": "22442" } ], "symlink_target": "" }
<?php // src/Timesheet/Bundle/HrBundle/Form/Type/PhotoType.php namespace Timesheet\Bundle\HrBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\NotBlank; use Doctrine\ORM\EntityRepository; class PhotoType extends AbstractType { private $userid; private $name; private $notes; public function __construct($userid, $name, $notes) { $this->userid = $userid; $this->name = $name; $this->notes = $notes; } public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->setAttribute('enctype', 'multipart/form-data') ->add('id', 'hidden', array( 'data'=>$this->userid )) ->add('name', 'text', array( 'label'=>'Name:', 'required'=>true, 'data'=>$this->name )) ->add('file', 'file', array( 'label'=>'Photo file:', 'required'=>true, 'data'=>null )) ->add('notes', 'textarea', array( 'label'=>'Notes:', 'required'=>false, 'attr'=>array( 'rows'=>3, 'cols'=>70 ), 'data'=>$this->notes )) ->add('submit', 'submit', array( 'label'=>'Upload', 'attr'=>array('class'=>'submitButton') )) ->add('cancel', 'button', array( 'label'=>'Cancel', 'attr'=>array('formnovalidate'=>true), // 'validation_groups'=>false )); } public function getName() { return 'photo'; } public function setDefaultOptions(OptionsResolverInterface $resolver) { } }
{ "content_hash": "afa4fccddd38398cdffc603e0160647a", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 76, "avg_line_length": 24.2987012987013, "alnum_prop": 0.589524318546232, "repo_name": "inczei/timesheet", "id": "2a17fbebb7a7a1e4de9c102d549b8f19ec1e2df1", "size": "1871", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Timesheet/Bundle/HrBundle/Form/Type/PhotoType.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2907" }, { "name": "CSS", "bytes": "60892" }, { "name": "HTML", "bytes": "219446" }, { "name": "JavaScript", "bytes": "775039" }, { "name": "PHP", "bytes": "1129588" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; namespace _03.EmployeesWithFormView { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { } } }
{ "content_hash": "15a886c440c46bcad7f2e83d68f46e59", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 68, "avg_line_length": 21.125, "alnum_prop": 0.7130177514792899, "repo_name": "kalinalazarova1/TelerikAcademy", "id": "b96dcbf88fdc9ae5b203f8fcb4beac74e53ac74e", "size": "340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Programming/10. ASP.NET WebForms/05.DataBinding/03.EmployeesWithFormView/Global.asax.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "243036" }, { "name": "C#", "bytes": "3102941" }, { "name": "CSS", "bytes": "100159" }, { "name": "JavaScript", "bytes": "4504076" }, { "name": "Pascal", "bytes": "24705" }, { "name": "PowerShell", "bytes": "1717597" }, { "name": "Puppet", "bytes": "3970" }, { "name": "Smalltalk", "bytes": "62944" }, { "name": "TypeScript", "bytes": "5342" }, { "name": "XSLT", "bytes": "4523" } ], "symlink_target": "" }
<?php namespace Skybot; use Skybot\Main; use Skybot\Message\Chat; use Skybot\Message\Direct; use Skybot\Message\Reply; use Skybot\User; interface DriverInterface { function __construct(\Monolog\Logger $log); function initialize($params = array()); function refuseCalls(); function getRecentChats(); function getMissedChats(); function getRecentMessagesForChat($chatid, Main $skybot); function isContact($name); function getContacts(); function getMessageProperties(Chat $chatmsg); function getUserProperty($contactname, $property); function getChatProperty($chatid, $property); function sendDirectMessage(Direct $dm); function sendReply(Reply $reply); function createChatWith(User $user); function markSeen(Chat $chatmsg); }
{ "content_hash": "585896b313a5bac77af85f58d926afd9", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 58, "avg_line_length": 24.866666666666667, "alnum_prop": 0.7761394101876675, "repo_name": "mor10am/skybot", "id": "b429918efac46e3f275e1d26b47474b07437e0a7", "size": "957", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Skybot/DriverInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "49221" } ], "symlink_target": "" }
<?php class m110325_070148_add_kampus_table extends CDbMigration { public function safeUp() { $this->createTable('kampus',array( 'id' => 'pk', 'nama' => 'string NOT NULL', 'alamat' => 'string', 'created' => 'datetime NOT NULL', 'modified' => 'datetime NOT NULL', ),'engine=innoDB'); $this->addColumn('mahasiswa','kampusId','integer'); $this->addForeignKey('mahasiswa_kampusId','mahasiswa','kampusId','kampus','id'); } public function safeDown() { $this->dropForeignKey('mahasiswa_kampusId','mahasiswa'); $this->dropColumn('mahasiswa','kampusId'); $this->dropTable('kampus'); } }
{ "content_hash": "0251da9760d1dfded2a100181e870430", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 82, "avg_line_length": 23.76923076923077, "alnum_prop": 0.6504854368932039, "repo_name": "ata/kkn", "id": "b217140247d2ad03deca90a8d1bdbd2727a49c72", "size": "618", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "protected/migrations/m110325_070148_add_kampus_table.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "188073" }, { "name": "PHP", "bytes": "10026459" }, { "name": "Perl", "bytes": "35924" }, { "name": "Shell", "bytes": "6149" } ], "symlink_target": "" }
#pragma once #include <cstdint> #include <functional> #include <memory> #include <string> #include <vector> #include "envoy/config/metrics/v3/stats.pb.h" #include "envoy/stats/tag_extractor.h" #include "envoy/stats/tag_producer.h" #include "common/common/hash.h" #include "common/common/utility.h" #include "common/config/well_known_names.h" #include "common/protobuf/protobuf.h" #include "absl/container/flat_hash_map.h" #include "absl/container/node_hash_set.h" #include "absl/strings/string_view.h" namespace Envoy { namespace Stats { /** * Organizes a collection of TagExtractors so that stat-names can be processed without * iterating through all extractors. */ class TagProducerImpl : public TagProducer { public: TagProducerImpl(const envoy::config::metrics::v3::StatsConfig& config); TagProducerImpl() = default; /** * Take a metric name and a vector then add proper tags into the vector and * return an extracted metric name. * @param metric_name std::string a name of Stats::Metric (Counter, Gauge, Histogram). * @param tags std::vector a set of Stats::Tag. */ std::string produceTags(absl::string_view metric_name, TagVector& tags) const override; private: friend class DefaultTagRegexTester; /** * Adds a TagExtractor to the collection of tags, tracking prefixes to help make * produceTags run efficiently by trying only extractors that have a chance to match. * @param extractor TagExtractorPtr the extractor to add. */ void addExtractor(TagExtractorPtr extractor); /** * Adds all default extractors matching the specified tag name. In this model, * more than one TagExtractor can be used to generate a given tag. The default * extractors are specified in common/config/well_known_names.cc. * @param name absl::string_view the extractor to add. * @return int the number of matching extractors. */ int addExtractorsMatching(absl::string_view name); /** * Roughly estimate the size of the vectors. * @param config const envoy::config::metrics::v2::StatsConfig& the config. */ void reserveResources(const envoy::config::metrics::v3::StatsConfig& config); /** * Adds all default extractors from well_known_names.cc into the * collection. Returns a set of names of all default extractors * into a string-set for dup-detection against new stat names * specified in the configuration. * @param config const envoy::config::metrics::v2::StatsConfig& the config. * @return names absl::node_hash_set<std::string> the set of names to populate */ absl::node_hash_set<std::string> addDefaultExtractors(const envoy::config::metrics::v3::StatsConfig& config); /** * Iterates over every tag extractor that might possibly match stat_name, calling * callback f for each one. This is broken out this way to reduce code redundancy * during testing, where we want to verify that extraction is order-independent. * The possibly-matching-extractors list is computed by: * 1. Finding the first '.' separated token in stat_name. * 2. Collecting the TagExtractors whose regexes have that same prefix "^prefix\\." * 3. Collecting also the TagExtractors whose regexes don't start with any prefix. * In the future, we may also do substring searches in some cases. * See DefaultTagRegexTester::produceTagsReverse in test/common/stats/stats_impl_test.cc. * * @param stat_name const std::string& the stat name. * @param f std::function<void(const TagExtractorPtr&)> function to call for each extractor. */ void forEachExtractorMatching(absl::string_view stat_name, std::function<void(const TagExtractorPtr&)> f) const; std::vector<TagExtractorPtr> tag_extractors_without_prefix_; // Maps a prefix word extracted out of a regex to a vector of TagExtractors. Note that // the storage for the prefix string is owned by the TagExtractor, which, depending on // implementation, may need make a copy of the prefix. absl::flat_hash_map<absl::string_view, std::vector<TagExtractorPtr>> tag_extractor_prefix_map_; TagVector default_tags_; }; } // namespace Stats } // namespace Envoy
{ "content_hash": "c17bee0a425ae239cdeb0fb078d8d2b9", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 97, "avg_line_length": 39.714285714285715, "alnum_prop": 0.7292565947242207, "repo_name": "envoyproxy/envoy-wasm", "id": "093d4021389b8f39340f9b5c8ae82a4b7ea3f9d2", "size": "4170", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/common/stats/tag_producer_impl.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "34272" }, { "name": "C++", "bytes": "18917650" }, { "name": "Dockerfile", "bytes": "245" }, { "name": "Emacs Lisp", "bytes": "966" }, { "name": "Go", "bytes": "695" }, { "name": "JavaScript", "bytes": "1760" }, { "name": "Makefile", "bytes": "1985" }, { "name": "PowerShell", "bytes": "5725" }, { "name": "PureBasic", "bytes": "472" }, { "name": "Python", "bytes": "392412" }, { "name": "Rust", "bytes": "3471" }, { "name": "Shell", "bytes": "115198" }, { "name": "Starlark", "bytes": "1134460" }, { "name": "Thrift", "bytes": "748" } ], "symlink_target": "" }
/** * Portfolio plugin DB installation */ CREATE TABLE IF NOT EXISTS `cot_folio` ( `item_id` int(10) unsigned NOT NULL auto_increment, `item_userid` int(11) NOT NULL, `item_date` int(11) NOT NULL, `item_update` int(11) NOT NULL, `item_parser` VARCHAR(64) NOT NULL DEFAULT '', `item_cat` varchar(255) collate utf8_unicode_ci NOT NULL, `item_title` varchar(255) collate utf8_unicode_ci NOT NULL, `item_alias` varchar(255) collate utf8_unicode_ci NOT NULL, `item_desc` varchar(255) collate utf8_unicode_ci default NULL, `item_keywords` varchar(255) collate utf8_unicode_ci default NULL, `item_metatitle` varchar(255) collate utf8_unicode_ci default NULL, `item_metadesc` varchar(255) collate utf8_unicode_ci default NULL, `item_text` MEDIUMTEXT collate utf8_unicode_ci NOT NULL, `item_cost` float(16,2) NOT NULL, `item_count` int(11) NOT NULL, `item_sort` int(11) NOT NULL, `item_state` tinyint(4) NOT NULL, `item_country` varchar(3) collate utf8_unicode_ci NOT NULL, `item_region` INT( 11 ) NOT NULL DEFAULT '0', `item_city` INT( 11 ) NOT NULL DEFAULT '0', PRIMARY KEY (`item_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
{ "content_hash": "437e27bec11e10ae581e45ba3375e122", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 69, "avg_line_length": 43.96296296296296, "alnum_prop": 0.7101937657961247, "repo_name": "Velm14/dribascorp", "id": "0406ea33653318c3e1b0f7a326f31fb15dcfebbf", "size": "1187", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/folio/setup/folio.install.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "125" }, { "name": "CSS", "bytes": "104664" }, { "name": "HTML", "bytes": "7932" }, { "name": "JavaScript", "bytes": "93545" }, { "name": "PHP", "bytes": "3379214" }, { "name": "Smarty", "bytes": "544125" } ], "symlink_target": "" }
// MainActivity.java // Manages your favorite Twitter searches for easy // access and display in the device's web browser package com.deitel.twittersearches; import java.util.ArrayList; import java.util.Collections; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; public class MainActivity extends Activity { // name of SharedPreferences XML file that stores the saved searches private static final String SEARCHES = "searches"; private EditText queryEditText; // EditText where user enters a query private EditText tagEditText; // EditText where user tags a query private SharedPreferences savedSearches; // user's favorite searches private ArrayList<String> tags; // list of tags for saved searches private RecyclerView recyclerView; private SearchesAdapter adapter; // called when MainActivity is first created @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get references to the EditTexts queryEditText = (EditText) findViewById(R.id.queryEditText); tagEditText = (EditText) findViewById(R.id.tagEditText); // get the SharedPreferences containing the user's saved searches savedSearches = getSharedPreferences(SEARCHES, MODE_PRIVATE); // store the saved tags in an ArrayList then sort them tags = new ArrayList<String>(savedSearches.getAll().keySet()); Collections.sort(tags, String.CASE_INSENSITIVE_ORDER); recyclerView = (RecyclerView) findViewById(R.id.list); // create ArrayAdapter and use it to bind tags to the ListView adapter = new SearchesAdapter(); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); // register listener to save a new or edited search ImageButton saveButton = (ImageButton) findViewById(R.id.saveButton); saveButton.setOnClickListener(saveButtonListener); } // end method onCreate // saveButtonListener saves a tag-query pair into SharedPreferences public OnClickListener saveButtonListener = new OnClickListener() { @Override public void onClick(View v) { // create tag if neither queryEditText nor tagEditText is empty if (queryEditText.getText().length() > 0 && tagEditText.getText().length() > 0) { addTaggedSearch(queryEditText.getText().toString(), tagEditText.getText().toString()); queryEditText.setText(""); // clear queryEditText tagEditText.setText(""); // clear tagEditText ((InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow( tagEditText.getWindowToken(), 0); } else // display message asking user to provide a query and a tag { // create a new AlertDialog Builder AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // set dialog's message to display builder.setMessage(R.string.missingMessage); // provide an OK button that simply dismisses the dialog builder.setPositiveButton(R.string.OK, null); // create AlertDialog from the AlertDialog.Builder AlertDialog errorDialog = builder.create(); errorDialog.show(); // display the modal dialog } } // end method onClick }; // end OnClickListener anonymous inner class // add new search to the save file, then refresh all Buttons private void addTaggedSearch(String query, String tag) { // get a SharedPreferences.Editor to store new tag/query pair SharedPreferences.Editor preferencesEditor = savedSearches.edit(); preferencesEditor.putString(tag, query); // store current search preferencesEditor.apply(); // store the updated preferences // if tag is new, add to and sort tags, then display updated list if (!tags.contains(tag)) { tags.add(tag); // add new tag Collections.sort(tags, String.CASE_INSENSITIVE_ORDER); adapter.notifyDataSetChanged(); // rebind tags to ListView } } // itemClickListener launches a web browser to display search results OnClickListener itemClickListener = new OnClickListener() { @Override public void onClick(View v) { // get query string and create a URL representing the search String tag = ((TextView) v.findViewById(R.id.textView)).getText().toString(); String urlString = getString(R.string.searchURL) + Uri.encode(savedSearches.getString(tag, ""), "UTF-8"); // create an Intent to launch a web browser Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString)); startActivity(webIntent); // launches web browser to view results } }; // end itemClickListener declaration // itemLongClickListener displays a dialog allowing the user to delete // or edit a saved search View.OnLongClickListener itemLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // get the tag that the user long touched final String tag = ((TextView) v.findViewById(R.id.textView)).getText().toString(); // create a new AlertDialog AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // set the AlertDialog's title builder.setTitle( getString(R.string.shareEditDeleteTitle, tag)); // set list of items to display in dialog builder.setItems(R.array.dialog_items, new DialogInterface.OnClickListener() { // responds to user touch by sharing, editing or // deleting a saved search @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // share shareSearch(tag); break; case 1: // edit // set EditTexts to match chosen tag and query tagEditText.setText(tag); queryEditText.setText( savedSearches.getString(tag, "")); break; case 2: // delete deleteSearch(tag); break; } } } // end DialogInterface.OnClickListener ); // end call to builder.setItems // set the AlertDialog's negative Button builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { // called when the "Cancel" Button is clicked public void onClick(DialogInterface dialog, int id) { dialog.cancel(); // dismiss the AlertDialog } } ); // end call to setNegativeButton builder.create().show(); // display the AlertDialog return true; } }; // end OnItemLongClickListener declaration // allows user to choose an app for sharing a saved search's URL private void shareSearch(String tag) { // create the URL representing the search String urlString = getString(R.string.searchURL) + Uri.encode(savedSearches.getString(tag, ""), "UTF-8"); // create Intent to share urlString Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shareSubject)); shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.shareMessage, urlString)); shareIntent.setType("text/plain"); // display apps that can share text startActivity(Intent.createChooser(shareIntent, getString(R.string.shareSearch))); } // deletes a search after the user confirms the delete operation private void deleteSearch(final String tag) { // create a new AlertDialog AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(this); // set the AlertDialog's message confirmBuilder.setMessage( getString(R.string.confirmMessage, tag)); // set the AlertDialog's negative Button confirmBuilder.setNegativeButton( getString(R.string.cancel), new DialogInterface.OnClickListener() { // called when "Cancel" Button is clicked public void onClick(DialogInterface dialog, int id) { dialog.cancel(); // dismiss dialog } } ); // end call to setNegativeButton // set the AlertDialog's positive Button confirmBuilder.setPositiveButton(getString(R.string.delete), new DialogInterface.OnClickListener() { // called when "Cancel" Button is clicked public void onClick(DialogInterface dialog, int id) { tags.remove(tag); // remove tag from tags // get SharedPreferences.Editor to remove saved search SharedPreferences.Editor preferencesEditor = savedSearches.edit(); preferencesEditor.remove(tag); // remove search preferencesEditor.apply(); // saves the changes // rebind tags ArrayList to ListView to show updated list adapter.notifyDataSetChanged(); } } // end OnClickListener ); // end call to setPositiveButton confirmBuilder.create().show(); // display AlertDialog } // end method deleteSearch // Create the basic adapter extending from RecyclerView.Adapter // Note that we specify the custom ViewHolder which gives us access to our views public class SearchesAdapter extends RecyclerView.Adapter<ViewHolder> { // Usually involves inflating a layout from XML and returning the holder @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); // Inflate the custom layout View contactView = inflater.inflate(R.layout.list_item, parent, false); contactView.setOnClickListener(itemClickListener); contactView.setOnLongClickListener(itemLongClickListener); // Return a new holder instance ViewHolder viewHolder = new ViewHolder(contactView); return viewHolder; } // Involves populating data into the item through holder @Override public void onBindViewHolder(ViewHolder viewHolder, int position) { // Get the data model based on position String search = tags.get(position); // Set item views based on the data model TextView textView = viewHolder.textView; textView.setText(search); } // Return the total count of items @Override public int getItemCount() { return tags.size(); } } // Provide a direct reference to each of the views within a data item // Used to cache the views within the item layout for fast access public static class ViewHolder extends RecyclerView.ViewHolder { // Your holder should contain a member variable // for any view that will be set as you render a row public TextView textView; // We also create a constructor that accepts the entire item row // and does the view lookups to find each subview public ViewHolder(View itemView) { // Stores the itemView in a public final member variable that can be used // to access the context from any ViewHolder instance. super(itemView); textView = (TextView) itemView.findViewById(R.id.textView); } } } // end class MainActivity
{ "content_hash": "55e3e9b29fdd25e3845a4876d9e2ca89", "timestamp": "", "source": "github", "line_count": 339, "max_line_length": 95, "avg_line_length": 39.78171091445428, "alnum_prop": 0.6284294824262198, "repo_name": "dwa012/CSCI4669-Fall15-Android", "id": "a4a5871b779c22166272f9c9f11c2bd71ac05dd6", "size": "14550", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Book Example Code/Android Studio/TwitterSearches/app/src/main/java/com/deitel/twittersearches/MainActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "398573" } ], "symlink_target": "" }
from misc.utils import * # NOTE # - single underscore indicates protected; double underscore indicates private # - can treat var as an arbitrary object and make the value True/False # - this does limit the possible variables created to a finite, specified set though # - contains is automatically generated # None => anything # False => not present/off HASH_DICT = '__hash_dict' class Substate(DictPrintObject, Mapping): def __init__(self, values): HashObject.__init__(self) self.__dict__[HASH_DICT] = values def variables(self): return set(self.__dict__[HASH_DICT].keys()) def includes(self, other): return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state def __getitem__(self, var): return self.get(var) def __iter__(self): return self.__dict__[HASH_DICT].items() def __len__(self): return len(self.__dict__[HASH_DICT]) def __str__(self): return 'SS' + str_args(self.__dict__[HASH_DICT]) class State(Substate): def __init__(self, values): super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False}) def __getitem__(self, var): if var not in self.__dict__[HASH_DICT]: return False return self.__dict__[HASH_DICT][var] def substate(self, variables): return Substate({var: self[var] for var in variables}) def __call__(self, variables): return self.substate(variables) # NOTE - the condition order determines the order in which conditions are processed class PartialState(SinglePrintObject): #__slots__ = ('conditions',) def __init__(self, conditions): HashObject.__init__(self) self.conditions = tuple(conditions) def __contains__(self, state): return all(state in condition for condition in self.conditions) def __iter__(self): for condition in self.conditions: yield condition def __len__(self): return len(self.conditions)
{ "content_hash": "9317d52e67fa4d649cfa0f26274028d9", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 109, "avg_line_length": 35.851851851851855, "alnum_prop": 0.6745867768595041, "repo_name": "caelan/pyplanners", "id": "307d07d3749cf08f65079000a8236e0e4b5fd254", "size": "1936", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "planner/states.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "253138" } ], "symlink_target": "" }
@interface JavaxJmdnsImplConstantsDNSOptionCode () { @public NSString *_externalName_; jint _index_; } @end J2OBJC_FIELD_SETTER(JavaxJmdnsImplConstantsDNSOptionCode, _externalName_, NSString *) __attribute__((unused)) static void JavaxJmdnsImplConstantsDNSOptionCode_initWithNSString_withInt_withNSString_withInt_(JavaxJmdnsImplConstantsDNSOptionCode *self, NSString *name, jint index, NSString *__name, jint __ordinal); __attribute__((unused)) static JavaxJmdnsImplConstantsDNSOptionCode *new_JavaxJmdnsImplConstantsDNSOptionCode_initWithNSString_withInt_withNSString_withInt_(NSString *name, jint index, NSString *__name, jint __ordinal) NS_RETURNS_RETAINED; J2OBJC_INITIALIZED_DEFN(JavaxJmdnsImplConstantsDNSOptionCode) JavaxJmdnsImplConstantsDNSOptionCode *JavaxJmdnsImplConstantsDNSOptionCode_values_[5]; @implementation JavaxJmdnsImplConstantsDNSOptionCode - (NSString *)externalName { return _externalName_; } - (jint)indexValue { return _index_; } + (JavaxJmdnsImplConstantsDNSOptionCode *)resultCodeForFlagsWithInt:(jint)optioncode { return JavaxJmdnsImplConstantsDNSOptionCode_resultCodeForFlagsWithInt_(optioncode); } - (NSString *)description { return JreStrcat("$$I", [self name], @" index ", [self indexValue]); } + (IOSObjectArray *)values { return JavaxJmdnsImplConstantsDNSOptionCode_values(); } + (JavaxJmdnsImplConstantsDNSOptionCode *)valueOfWithNSString:(NSString *)name { return JavaxJmdnsImplConstantsDNSOptionCode_valueOfWithNSString_(name); } - (id)copyWithZone:(NSZone *)zone { return self; } + (const J2ObjcClassInfo *)__metadata { static J2ObjcMethodInfo methods[] = { { NULL, "LNSString;", 0x1, -1, -1, -1, -1, -1, -1 }, { NULL, "I", 0x1, -1, -1, -1, -1, -1, -1 }, { NULL, "LJavaxJmdnsImplConstantsDNSOptionCode;", 0x9, 0, 1, -1, -1, -1, -1 }, { NULL, "LNSString;", 0x1, 2, -1, -1, -1, -1, -1 }, { NULL, "[LJavaxJmdnsImplConstantsDNSOptionCode;", 0x9, -1, -1, -1, -1, -1, -1 }, { NULL, "LJavaxJmdnsImplConstantsDNSOptionCode;", 0x9, 3, 4, -1, -1, -1, -1 }, }; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wobjc-multiple-method-names" methods[0].selector = @selector(externalName); methods[1].selector = @selector(indexValue); methods[2].selector = @selector(resultCodeForFlagsWithInt:); methods[3].selector = @selector(description); methods[4].selector = @selector(values); methods[5].selector = @selector(valueOfWithNSString:); #pragma clang diagnostic pop static const J2ObjcFieldInfo fields[] = { { "Unknown", "LJavaxJmdnsImplConstantsDNSOptionCode;", .constantValue.asLong = 0, 0x4019, -1, 5, -1, -1 }, { "LLQ", "LJavaxJmdnsImplConstantsDNSOptionCode;", .constantValue.asLong = 0, 0x4019, -1, 6, -1, -1 }, { "UL", "LJavaxJmdnsImplConstantsDNSOptionCode;", .constantValue.asLong = 0, 0x4019, -1, 7, -1, -1 }, { "NSID", "LJavaxJmdnsImplConstantsDNSOptionCode;", .constantValue.asLong = 0, 0x4019, -1, 8, -1, -1 }, { "Owner", "LJavaxJmdnsImplConstantsDNSOptionCode;", .constantValue.asLong = 0, 0x4019, -1, 9, -1, -1 }, { "_externalName_", "LNSString;", .constantValue.asLong = 0, 0x12, -1, -1, -1, -1 }, { "_index_", "I", .constantValue.asLong = 0, 0x12, -1, -1, -1, -1 }, }; static const void *ptrTable[] = { "resultCodeForFlags", "I", "toString", "valueOf", "LNSString;", &JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, Unknown), &JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, LLQ), &JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, UL), &JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, NSID), &JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, Owner), "Ljava/lang/Enum<Ljavax/jmdns/impl/constants/DNSOptionCode;>;" }; static const J2ObjcClassInfo _JavaxJmdnsImplConstantsDNSOptionCode = { "DNSOptionCode", "javax.jmdns.impl.constants", ptrTable, methods, fields, 7, 0x4011, 6, 7, -1, -1, -1, 10, -1 }; return &_JavaxJmdnsImplConstantsDNSOptionCode; } + (void)initialize { if (self == [JavaxJmdnsImplConstantsDNSOptionCode class]) { JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, Unknown) = new_JavaxJmdnsImplConstantsDNSOptionCode_initWithNSString_withInt_withNSString_withInt_(@"Unknown", 65535, @"Unknown", 0); JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, LLQ) = new_JavaxJmdnsImplConstantsDNSOptionCode_initWithNSString_withInt_withNSString_withInt_(@"LLQ", 1, @"LLQ", 1); JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, UL) = new_JavaxJmdnsImplConstantsDNSOptionCode_initWithNSString_withInt_withNSString_withInt_(@"UL", 2, @"UL", 2); JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, NSID) = new_JavaxJmdnsImplConstantsDNSOptionCode_initWithNSString_withInt_withNSString_withInt_(@"NSID", 3, @"NSID", 3); JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, Owner) = new_JavaxJmdnsImplConstantsDNSOptionCode_initWithNSString_withInt_withNSString_withInt_(@"Owner", 4, @"Owner", 4); J2OBJC_SET_INITIALIZED(JavaxJmdnsImplConstantsDNSOptionCode) } } @end void JavaxJmdnsImplConstantsDNSOptionCode_initWithNSString_withInt_withNSString_withInt_(JavaxJmdnsImplConstantsDNSOptionCode *self, NSString *name, jint index, NSString *__name, jint __ordinal) { JavaLangEnum_initWithNSString_withInt_(self, __name, __ordinal); self->_externalName_ = name; self->_index_ = index; } JavaxJmdnsImplConstantsDNSOptionCode *new_JavaxJmdnsImplConstantsDNSOptionCode_initWithNSString_withInt_withNSString_withInt_(NSString *name, jint index, NSString *__name, jint __ordinal) { J2OBJC_NEW_IMPL(JavaxJmdnsImplConstantsDNSOptionCode, initWithNSString_withInt_withNSString_withInt_, name, index, __name, __ordinal) } JavaxJmdnsImplConstantsDNSOptionCode *JavaxJmdnsImplConstantsDNSOptionCode_resultCodeForFlagsWithInt_(jint optioncode) { JavaxJmdnsImplConstantsDNSOptionCode_initialize(); jint maskedIndex = optioncode; { IOSObjectArray *a__ = JavaxJmdnsImplConstantsDNSOptionCode_values(); JavaxJmdnsImplConstantsDNSOptionCode * const *b__ = ((IOSObjectArray *) nil_chk(a__))->buffer_; JavaxJmdnsImplConstantsDNSOptionCode * const *e__ = b__ + a__->size_; while (b__ < e__) { JavaxJmdnsImplConstantsDNSOptionCode *aCode = *b__++; if (((JavaxJmdnsImplConstantsDNSOptionCode *) nil_chk(aCode))->_index_ == maskedIndex) return aCode; } } return JreEnum(JavaxJmdnsImplConstantsDNSOptionCode, Unknown); } IOSObjectArray *JavaxJmdnsImplConstantsDNSOptionCode_values() { JavaxJmdnsImplConstantsDNSOptionCode_initialize(); return [IOSObjectArray arrayWithObjects:JavaxJmdnsImplConstantsDNSOptionCode_values_ count:5 type:JavaxJmdnsImplConstantsDNSOptionCode_class_()]; } JavaxJmdnsImplConstantsDNSOptionCode *JavaxJmdnsImplConstantsDNSOptionCode_valueOfWithNSString_(NSString *name) { JavaxJmdnsImplConstantsDNSOptionCode_initialize(); for (int i = 0; i < 5; i++) { JavaxJmdnsImplConstantsDNSOptionCode *e = JavaxJmdnsImplConstantsDNSOptionCode_values_[i]; if ([name isEqual:[e name]]) { return e; } } @throw create_JavaLangIllegalArgumentException_initWithNSString_(name); return nil; } JavaxJmdnsImplConstantsDNSOptionCode *JavaxJmdnsImplConstantsDNSOptionCode_fromOrdinal(NSUInteger ordinal) { JavaxJmdnsImplConstantsDNSOptionCode_initialize(); if (ordinal >= 5) { return nil; } return JavaxJmdnsImplConstantsDNSOptionCode_values_[ordinal]; } J2OBJC_CLASS_TYPE_LITERAL_SOURCE(JavaxJmdnsImplConstantsDNSOptionCode)
{ "content_hash": "e4d7416772fbaf8f467c6a969ce3919e", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 436, "avg_line_length": 51.19444444444444, "alnum_prop": 0.7540694519804666, "repo_name": "kebernet/erigo", "id": "a07592bbd0db8b3b8bf5b54efac5ac1c51a44770", "size": "7752", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ios/app/Erigo/javax/jmdns/impl/constants/DNSOptionCode.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "13326" }, { "name": "Java", "bytes": "361122" }, { "name": "Objective-C", "bytes": "18622052" }, { "name": "Shell", "bytes": "34226" }, { "name": "Swift", "bytes": "4013" } ], "symlink_target": "" }
package io.linuxserver.davos.transfer.ftp.client; import io.linuxserver.davos.transfer.ftp.TransferProtocol; public class ClientFactory { public Client getClient(TransferProtocol protocol) { if (protocol.equals(TransferProtocol.SFTP)) return new SFTPClient(); if (protocol.equals(TransferProtocol.FTPS)) return new FTPSClient(); return new FTPClient(); } }
{ "content_hash": "4a2d38fbd915da64e5e1e02088c333bf", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 58, "avg_line_length": 26.058823529411764, "alnum_prop": 0.654627539503386, "repo_name": "linuxserver/davos", "id": "01e8ea9f3b190630cae1336c30e46efb4181065e", "size": "443", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/linuxserver/davos/transfer/ftp/client/ClientFactory.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1018" }, { "name": "Gherkin", "bytes": "3040" }, { "name": "HTML", "bytes": "58400" }, { "name": "Java", "bytes": "293069" }, { "name": "JavaScript", "bytes": "15601" } ], "symlink_target": "" }
describe('WalkontableColumnStrategy', function () { var source; var fakeWalkontableInstance = { getSetting : function(){} }; function allCells25(i) { if (source[i] !== void 0) { return 25; } } //STRATEGY none it("default - cell sizes should be 25", function () { source = [0, 1, 2, 5, 6, 7, 8, 9, 10]; var strategy = new WalkontableColumnStrategy(fakeWalkontableInstance, 100, allCells25, 'none'); strategy.stretch(); expect(strategy.getSize(0)).toEqual(25); expect(strategy.getSize(1)).toEqual(25); expect(strategy.getSize(2)).toEqual(25); expect(strategy.getSize(3)).toEqual(25); expect(strategy.cellCount).toEqual(4); }); //STRATEGY none - unlimited width it("default - should show all cells if containerSize is Infinity", function () { source = [0, 1, 2, 5, 6, 7, 8, 9, 10]; var strategy = new WalkontableColumnStrategy(fakeWalkontableInstance, Infinity, allCells25, 'none'); strategy.stretch(); expect(strategy.cellCount).toEqual(source.length); }); //STRATEGY all it("all - should show 4 cells and stretch their size to 28", function () { source = [0, 1, 2, 3, 4]; var strategy = new WalkontableColumnStrategy(fakeWalkontableInstance, 140, allCells25, 'all'); strategy.stretch(); expect(strategy.getSize(0)).toEqual(28); expect(strategy.getSize(1)).toEqual(28); expect(strategy.getSize(2)).toEqual(28); expect(strategy.getSize(3)).toEqual(28); expect(strategy.getSize(4)).toEqual(28); expect(strategy.cellCount).toEqual(5); }); it("all - should show 4 cells and stretch their size to 28 (except last one which is stretched to remaining 29)", function () { source = [0, 1, 2, 3, 4]; var strategy = new WalkontableColumnStrategy(fakeWalkontableInstance, 141, allCells25, 'all'); strategy.stretch(); expect(strategy.getSize(0)).toEqual(28); expect(strategy.getSize(1)).toEqual(28); expect(strategy.getSize(2)).toEqual(28); expect(strategy.getSize(3)).toEqual(28); expect(strategy.getSize(4)).toEqual(29); expect(strategy.cellCount).toEqual(5); }); it("all - should not strech if not all cells are fully visible", function () { source = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var strategy = new WalkontableColumnStrategy(fakeWalkontableInstance, 140, allCells25, 'all'); strategy.stretch(); expect(strategy.getSize(0)).toEqual(25); expect(strategy.getSize(1)).toEqual(25); expect(strategy.getSize(2)).toEqual(25); expect(strategy.getSize(3)).toEqual(25); expect(strategy.getSize(4)).toEqual(25); expect(strategy.getSize(5)).toEqual(25); //actually visible size of last column is 15 but here goes full value expect(strategy.cellCount).toEqual(6); }); //STRATEGY last it("last - should show 4 cells and stretch last one to 41", function () { source = [0, 1, 2, 3, 4]; var strategy = new WalkontableColumnStrategy(fakeWalkontableInstance, 141, allCells25, 'last'); strategy.stretch(); expect(strategy.getSize(0)).toEqual(25); expect(strategy.getSize(1)).toEqual(25); expect(strategy.getSize(2)).toEqual(25); expect(strategy.getSize(3)).toEqual(25); expect(strategy.getSize(4)).toEqual(41); expect(strategy.cellCount).toEqual(5); }); it("last - should not strech if not all cells are fully visible", function () { source = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var strategy = new WalkontableColumnStrategy(fakeWalkontableInstance, 140, allCells25, 'last'); strategy.stretch(); expect(strategy.getSize(0)).toEqual(25); expect(strategy.getSize(1)).toEqual(25); expect(strategy.getSize(2)).toEqual(25); expect(strategy.getSize(3)).toEqual(25); expect(strategy.getSize(4)).toEqual(25); expect(strategy.getSize(5)).toEqual(25); //actually visible size of last column is 15 but here goes full value expect(strategy.cellCount).toEqual(6); }); //getSize it("getSize should return cell size at given index", function () { source = [0, 1, 2, 3, 4]; var strategy = new WalkontableColumnStrategy(fakeWalkontableInstance, 141, allCells25, 'last'); strategy.stretch(); expect(strategy.getSize(0)).toEqual(25); expect(strategy.getSize(1)).toEqual(25); expect(strategy.getSize(2)).toEqual(25); expect(strategy.getSize(3)).toEqual(25); expect(strategy.getSize(4)).toEqual(41); expect(strategy.cellCount).toEqual(5); }); });
{ "content_hash": "f7c6316f3fff20f3c1b57d8e65be5f13", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 129, "avg_line_length": 39.767857142857146, "alnum_prop": 0.6755725190839694, "repo_name": "digitaltech/handsontable", "id": "1847769dde430cd8f918ad24851d480546d9b777", "size": "4454", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/3rdparty/walkontable/test/jasmine/spec/columnStrategy.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "114040" }, { "name": "JavaScript", "bytes": "3973111" }, { "name": "PHP", "bytes": "6780" } ], "symlink_target": "" }
@implementation ClutchAB + (ClutchAB *)setupWithKey:(NSString *)appKey rpcURL:(NSString *)rpcURL { static ClutchAB *_sharedClient = nil; static dispatch_once_t oncePredicate; dispatch_once(&oncePredicate, ^{ _sharedClient = [[self alloc] init]; [_sharedClient setAppKey:appKey]; [_sharedClient setRpcURL:rpcURL]; [_sharedClient setupFakeGUID]; [[NSNotificationCenter defaultCenter] addObserver:_sharedClient selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:_sharedClient selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:_sharedClient selector:@selector(applicationDidFinishLaunching:) name:UIApplicationDidFinishLaunchingNotification object:nil]; }); return _sharedClient; } - (void)_sendABLogs { ClutchAPIClient *apiClient = [ClutchAPIClient sharedClientForKey:_appKey rpcURL:_rpcURL]; ClutchStats *statsClient = [ClutchStats sharedClient]; NSArray *logs = [statsClient getABLogs]; if([logs count] == 0) { return; } NSTimeInterval lastTimestamp = [[[logs lastObject] objectForKey:@"ts"] doubleValue]; NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:logs, @"logs", _fakeGUID, @"guid", nil]; [apiClient callMethod:@"send_ab_logs" withParams:params success:^(id object) { if([[(NSDictionary *)object objectForKey:@"status"] isEqualToString:@"ok"]) { [statsClient deleteABLogs:lastTimestamp]; } else { NSLog(@"Failed to actually download the Clutch AB metadata from the server.\n"); } } failure:^(NSData *data, NSError *error) { NSLog(@"Failed to connect to the Clutch server to get AB metadata. %@\n", error); }]; } - (void)_downloadABMetadata { ClutchAPIClient *apiClient = [ClutchAPIClient sharedClientForKey:_appKey rpcURL:_rpcURL]; NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:_fakeGUID, @"guid", nil]; [apiClient callMethod:@"get_ab_metadata" withParams:params success:^(id object) { NSDictionary *metadata = [(NSDictionary *)object objectForKey:@"metadata"]; NSString *errorString1; NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:metadata format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorString1]; NSString *abPlist = [NSString stringWithFormat:@"%@/Library/Caches/__clutchab.plist", NSHomeDirectory()]; if(plistData) { [plistData writeToFile:abPlist atomically:YES]; } else { NSLog(@"(Clutch) Error writing out AB plist: %@\n", errorString1); } if(errorString1) { [errorString1 release]; } } failure:^(NSData *data, NSError *error) { NSLog(@"Failed to connect to the Clutch server to send AB logs. %@\n", error); }]; } - (void)applicationDidBecomeActive:(UIApplication *)application { if(_appKey == nil) { return; } [self _sendABLogs]; [self _downloadABMetadata]; } - (void)applicationDidEnterBackground:(UIApplication *)application { if(_appKey == nil) { return; } [self _sendABLogs]; } - (void)applicationDidFinishLaunching:(UIApplication *)application { if(_appKey == nil) { return; } [self _sendABLogs]; [self _downloadABMetadata]; } + (NSDictionary *)getLatestMetadata { // TODO: Cache NSString *abPlist = [NSString stringWithFormat:@"%@/Library/Caches/__clutchab.plist", NSHomeDirectory()]; if([[NSFileManager defaultManager] fileExistsAtPath:abPlist]) { return [NSDictionary dictionaryWithContentsOfFile:abPlist]; } else { return [NSDictionary dictionary]; } } + (int)weightedChoice:(NSArray *)weights { double total = 0; int winner = 0; for(int i = 0; i < [weights count]; ++i) { NSNumber *weight = [weights objectAtIndex:i]; total += [weight doubleValue]; double rnd = (double)arc4random() / ARC4RANDOM_MAX; if(rnd * total < [weight doubleValue]) { winner = i; } } double shouldTestRnd = (double)arc4random() / ARC4RANDOM_MAX; if(shouldTestRnd <= total) { return winner; } return -1; } + (int)cachedChoiceForTestNamed:(NSString *)name weights:(NSArray *)weights { ClutchStats *statsClient = [ClutchStats sharedClient]; int resp = [statsClient getCachedChoice:name]; if(resp == -1) { resp = [ClutchAB weightedChoice:weights]; [statsClient setCachedChoice:name choice:resp]; } return resp; } + (void)testWithName:(NSString *)name data:(void(^)(NSDictionary *testData))dataCallbackBlock { NSDictionary *metaMeta = [ClutchAB getLatestMetadata]; if([metaMeta count] == 0) { return; } NSDictionary *meta = [metaMeta objectForKey:name]; if(meta == nil) { [[ClutchStats sharedClient] testFailure:name type:@"no-meta-name"]; [[ClutchStats sharedClient] setNumChoices:0 forTest:name hasData:true]; return; } NSArray *weights = [meta objectForKey:@"weights"]; NSArray *allData = [meta objectForKey:@"data"]; if(allData == nil || weights == nil) { [[ClutchStats sharedClient] testFailure:name type:@"no-data"]; return; } if([weights count] == 0) { return; } int choice = [ClutchAB cachedChoiceForTestNamed:name weights:weights]; [[ClutchStats sharedClient] testChosen:name choice:choice numChoices:[weights count]]; if(choice == -1) { return; } NSDictionary *data = [allData objectAtIndex:choice]; dataCallbackBlock(data); } + (void)testWithName:(NSString *)name blocks:(NSArray *)blocks { NSDictionary *metaMeta = [ClutchAB getLatestMetadata]; if([metaMeta count] == 0) { return; } NSDictionary *meta = [metaMeta objectForKey:name]; NSArray *weights = [meta objectForKey:@"weights"]; if(meta == nil || weights == nil) { if(meta == nil) { [[ClutchStats sharedClient] testFailure:name type:@"no-meta-name"]; } else if(weights == nil) { [[ClutchStats sharedClient] testFailure:name type:@"no-weights"]; } [[ClutchStats sharedClient] setNumChoices:[blocks count] forTest:name hasData:false]; return; } int choice = [ClutchAB cachedChoiceForTestNamed:name weights:weights]; [[ClutchStats sharedClient] testChosen:name choice:choice numChoices:[blocks count]]; if(choice == -1) { return; } void(^complete)(void) = [blocks objectAtIndex:choice]; complete(); } + (void)testWithName:(NSString *)name A:(void(^)(void))blockA B:(void(^)(void))blockB { NSArray *blocks = [NSArray arrayWithObjects: [[blockA copy] autorelease], [[blockB copy] autorelease], nil]; [ClutchAB testWithName:name blocks:blocks]; } + (void)testWithName:(NSString *)name A:(void(^)(void))blockA B:(void(^)(void))blockB C:(void(^)(void))blockC { NSArray *blocks = [NSArray arrayWithObjects: [[blockA copy] autorelease], [[blockB copy] autorelease], [[blockC copy] autorelease], nil]; [ClutchAB testWithName:name blocks:blocks]; } + (void)testWithName:(NSString *)name A:(void(^)(void))blockA B:(void(^)(void))blockB C:(void(^)(void))blockC D:(void(^)(void))blockD { NSArray *blocks = [NSArray arrayWithObjects: [[blockA copy] autorelease], [[blockB copy] autorelease], [[blockC copy] autorelease], [[blockD copy] autorelease], nil]; [ClutchAB testWithName:name blocks:blocks]; } + (void)testWithName:(NSString *)name A:(void(^)(void))blockA B:(void(^)(void))blockB C:(void(^)(void))blockC D:(void(^)(void))blockD E:(void(^)(void))blockE { NSArray *blocks = [NSArray arrayWithObjects: [[blockA copy] autorelease], [[blockB copy] autorelease], [[blockC copy] autorelease], [[blockD copy] autorelease], [[blockE copy] autorelease], nil]; [ClutchAB testWithName:name blocks:blocks]; } + (void)testWithName:(NSString *)name A:(void(^)(void))blockA B:(void(^)(void))blockB C:(void(^)(void))blockC D:(void(^)(void))blockD E:(void(^)(void))blockE F:(void(^)(void))blockF { NSArray *blocks = [NSArray arrayWithObjects: [[blockA copy] autorelease], [[blockB copy] autorelease], [[blockC copy] autorelease], [[blockD copy] autorelease], [[blockE copy] autorelease], [[blockF copy] autorelease], nil]; [ClutchAB testWithName:name blocks:blocks]; } + (void)testWithName:(NSString *)name A:(void(^)(void))blockA B:(void(^)(void))blockB C:(void(^)(void))blockC D:(void(^)(void))blockD E:(void(^)(void))blockE F:(void(^)(void))blockF G:(void(^)(void))blockG { NSArray *blocks = [NSArray arrayWithObjects: [[blockA copy] autorelease], [[blockB copy] autorelease], [[blockC copy] autorelease], [[blockD copy] autorelease], [[blockE copy] autorelease], [[blockF copy] autorelease], [[blockG copy] autorelease], nil]; [ClutchAB testWithName:name blocks:blocks]; } + (void)testWithName:(NSString *)name A:(void(^)(void))blockA B:(void(^)(void))blockB C:(void(^)(void))blockC D:(void(^)(void))blockD E:(void(^)(void))blockE F:(void(^)(void))blockF G:(void(^)(void))blockG H:(void(^)(void))blockH { NSArray *blocks = [NSArray arrayWithObjects: [[blockA copy] autorelease], [[blockB copy] autorelease], [[blockC copy] autorelease], [[blockD copy] autorelease], [[blockE copy] autorelease], [[blockF copy] autorelease], [[blockG copy] autorelease], [[blockH copy] autorelease], nil]; [ClutchAB testWithName:name blocks:blocks]; } + (void)testWithName:(NSString *)name A:(void(^)(void))blockA B:(void(^)(void))blockB C:(void(^)(void))blockC D:(void(^)(void))blockD E:(void(^)(void))blockE F:(void(^)(void))blockF G:(void(^)(void))blockG H:(void(^)(void))blockH I:(void(^)(void))blockI { NSArray *blocks = [NSArray arrayWithObjects: [[blockA copy] autorelease], [[blockB copy] autorelease], [[blockC copy] autorelease], [[blockD copy] autorelease], [[blockE copy] autorelease], [[blockF copy] autorelease], [[blockG copy] autorelease], [[blockH copy] autorelease], [[blockI copy] autorelease], nil]; [ClutchAB testWithName:name blocks:blocks]; } + (void)testWithName:(NSString *)name A:(void(^)(void))blockA B:(void(^)(void))blockB C:(void(^)(void))blockC D:(void(^)(void))blockD E:(void(^)(void))blockE F:(void(^)(void))blockF G:(void(^)(void))blockG H:(void(^)(void))blockH I:(void(^)(void))blockI J:(void(^)(void))blockJ { NSArray *blocks = [NSArray arrayWithObjects: [[blockA copy] autorelease], [[blockB copy] autorelease], [[blockC copy] autorelease], [[blockD copy] autorelease], [[blockE copy] autorelease], [[blockF copy] autorelease], [[blockG copy] autorelease], [[blockH copy] autorelease], [[blockI copy] autorelease], [[blockJ copy] autorelease], nil]; [ClutchAB testWithName:name blocks:blocks]; } + (void)goalReached:(NSString *)name { [[ClutchStats sharedClient] goalReached:name]; } + (UIColor *)colorFromHex:(NSString *)hex { NSString *correctedHex = nil; if([hex hasPrefix:@"#"]) { correctedHex = [hex substringFromIndex:1]; } else { correctedHex = hex; } if([correctedHex length] == 3) { correctedHex = [NSString stringWithFormat:@"%C%C%C%C%C%C", [correctedHex characterAtIndex:0], [correctedHex characterAtIndex:0], [correctedHex characterAtIndex:1], [correctedHex characterAtIndex:1], [correctedHex characterAtIndex:2], [correctedHex characterAtIndex:2] ]; } unsigned int hexVal; NSScanner *scanner = [NSScanner scannerWithString:correctedHex]; [scanner scanHexInt:&hexVal]; if([correctedHex length] == 6) { return [UIColor colorWithRed:((hexVal & 0xFF0000) >> 16)/255.0 green:((hexVal & 0xFF00) >> 8)/255.0 blue:(hexVal & 0xFF)/255.0 alpha:1]; } else if([correctedHex length] == 8) { return [UIColor colorWithRed:((hexVal & 0xFF000000) >> 24)/255.0 green:((hexVal & 0x00FF0000) >> 16)/255.0 blue:((hexVal & 0x0000FF00) >> 8)/255.0 alpha:(hexVal & 0x000000FF)/255.0]; } else { NSLog(@"Invalid color hex string: '%@'. Using black instead.\n", hex); return [UIColor blackColor]; } } #pragma mark - Misc - (void)setFakeGUID:(NSString *)fakeGUID { [fakeGUID retain]; [_fakeGUID release]; _fakeGUID = fakeGUID; } - (void)setupFakeGUID { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [self setFakeGUID:[defaults objectForKey:@"fakeUUID"]]; if(_fakeGUID == nil) { [self setFakeGUID:[ClutchUtils getUUID]]; [defaults setValue:_fakeGUID forKey:@"fakeUUID"]; [defaults synchronize]; } } #pragma mark - Setters - (void)setAppKey:(NSString *)appKey { [appKey retain]; [_appKey release]; _appKey = appKey; } - (void)setRpcURL:(NSString *)rpcURL { [rpcURL retain]; [_rpcURL release]; _rpcURL = rpcURL; } @end
{ "content_hash": "a3108900fb53bb17e20fa5de14de4f7b", "timestamp": "", "source": "github", "line_count": 424, "max_line_length": 114, "avg_line_length": 38.464622641509436, "alnum_prop": 0.5317922619412594, "repo_name": "clutchio/clutchios", "id": "ea7555673deb6ff4e92f426da3a6dcecf87c57d4", "size": "16957", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Clutch/ClutchAB.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5063" }, { "name": "Objective-C", "bytes": "369056" } ], "symlink_target": "" }
@implementation NSArray_HLSExtensionsTestCase #pragma mark Tests - (void)testRotation { NSArray *array = @[@"1", @"2", @"3"]; NSArray *leftArray = [array arrayByLeftRotatingNumberOfObjects:2]; NSArray *expectedLeftArray = @[@"3", @"1", @"2"]; GHAssertTrue([leftArray isEqualToArray:expectedLeftArray], nil); NSArray *rightArray = [array arrayByRightRotatingNumberOfObjects:2]; NSArray *expectedRightArray = @[@"2", @"3", @"1"]; GHAssertTrue([rightArray isEqualToArray:expectedRightArray], nil); } - (void)testSafeInsert { NSMutableArray *array = [NSMutableArray array]; [array safelyAddObject:nil]; GHAssertEquals([array count], (NSUInteger)0, nil); } @end
{ "content_hash": "d1d2d7d9049147dc82a21d77e0c3db66", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 72, "avg_line_length": 28.44, "alnum_prop": 0.6877637130801688, "repo_name": "cbdr/CoconutKit", "id": "0a0e9f3663bd7c0162cfb0ca11050c0ef39e9e1e", "size": "919", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CoconutKit-demo/Tests/Sources/Core/NSArray+HLSExtensionsTestCase.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2913" }, { "name": "C++", "bytes": "1748" }, { "name": "HTML", "bytes": "10759" }, { "name": "Makefile", "bytes": "175" }, { "name": "Objective-C", "bytes": "1730631" }, { "name": "Ruby", "bytes": "4207" }, { "name": "Shell", "bytes": "1762" } ], "symlink_target": "" }
module Opsworks module Deploy VERSION = "0.0.6" end end
{ "content_hash": "e3610b3d6cfdf57c583f2fb5ce7b1d2b", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 21, "avg_line_length": 12.8, "alnum_prop": 0.65625, "repo_name": "hayesgm/opsworks-deploy", "id": "3f18bec0d781f52eb173e25df188dd6b955ba137", "size": "64", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/opsworks/deploy/version.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "10000" } ], "symlink_target": "" }
(function(env) { "use strict"; env.ddg_spice_bike_sharing_indego_phl = function(api_result) { if (!api_result || !api_result.features) { return Spice.failed('bike_sharing_indego_phl'); } DDG.require(['moment.js', 'maps'], function() { moment.locale('en', { relativeTime: { past: "%s ago", s: "1 sec", ss: "%d sec", m: "1 min", mm: "%d min", h: "1 hour", hh: "%d hours", d: "1 day", dd: "%d days", M: "1 month", MM: "%d months", y: "1 year", yy: "%d years" } }); Spice.add({ id: 'bike_sharing_indego_phl', name: 'Bike Sharing', meta: { sourceName: 'Ride Indego', sourceUrl: 'http://www.rideindego.com/stations/', itemType: 'Bike Stations', pinIcon: 'ddgsi-circle', pinIconSelected: 'ddgsi-star' }, data: api_result.features, normalize: function(item) { if (item.geometry.length < 2 || item.geometry.length > 2 || item.properties.kioskPublicStatus !== 'Active') { return null; } return { title: item.properties.name, name: item.properties.name, lat: (item.geometry.coordinates[1]).toString(), lon: (item.geometry.coordinates[0]).toString(), docksAvailable: item.properties.docksAvailable, bikesAvailable: item.properties.bikesAvailable }; }, model: 'Place', view: 'Places', templates: { group: "text", detail: false, item_detail: false, options: { footer: Spice.bike_sharing_indego_phl.footer }, variants: { tile: 'narrow', tileTitle: "3line" }, elClass: { tileTitle: "tx--14" } }, sort_fields: { distance: function(a, b) { return a.distanceToReference - b.distanceToReference; } }, sort_default: 'distance' }); }); } }(this));
{ "content_hash": "d80e5d59bc8df09881655c4b2fd7c2d4", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 133, "avg_line_length": 39.21518987341772, "alnum_prop": 0.3337637185280826, "repo_name": "GrandpaCardigan/zeroclickinfo-spice", "id": "60fe4bf341bf6dcbe0917235673c3f2118274405", "size": "3098", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "share/spice/bike_sharing/indego_phl/bike_sharing_indego_phl.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "93829" }, { "name": "HTML", "bytes": "75910" }, { "name": "JavaScript", "bytes": "573094" }, { "name": "Perl", "bytes": "495375" }, { "name": "Perl6", "bytes": "12858" }, { "name": "Python", "bytes": "3695" } ], "symlink_target": "" }
/* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 License: none (public domain) */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; }
{ "content_hash": "84a63a011bdea8d8bee75a7e63b42cc8", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 48, "avg_line_length": 26.846153846153847, "alnum_prop": 0.660458452722063, "repo_name": "Maffsie/WerePaste", "id": "ac5cacdc08aa04c5b4d43cf4b83adc6071de0b58", "size": "698", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/reset.css", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "5957" }, { "name": "Perl", "bytes": "6001" }, { "name": "Shell", "bytes": "707" } ], "symlink_target": "" }
@interface RoomViewController : ViewController <UIPickerViewDataSource,UIPickerViewDelegate> { NSString *room_type; } @property (strong, nonatomic) IBOutlet UIPickerView *picker_cuarto; @property (strong, nonatomic) NSMutableArray *arrayC; @end
{ "content_hash": "4fe376527bb389dc466aedb5c24cf7fd", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 92, "avg_line_length": 25.2, "alnum_prop": 0.7936507936507936, "repo_name": "SeminarioInvestigacion/Horizon-Suites", "id": "818025112d774746555ca0d04e2a6e01f51286ac", "size": "440", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "HorizonSuites/HorizonSuites/RoomViewController.h", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Objective-C", "bytes": "31962" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Biblthca Lichenol. 71: 96 (1998) #### Original name Phaeocalicium fuegensis Tibell ### Remarks null
{ "content_hash": "bf87e2d109bda7980cbd2bc4eb51fe54", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 32, "avg_line_length": 12.538461538461538, "alnum_prop": 0.7239263803680982, "repo_name": "mdoering/backbone", "id": "3aff352ae1c11c0857f2efd90a3771abb3a50390", "size": "217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Eurotiomycetes/Mycocaliciales/Mycocaliciaceae/Phaeocalicium/Phaeocalicium fuegensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Imports ESRI.ArcGIS.Mobile.MapActions Imports ESRI.ArcGIS.Mobile Imports ESRI.ArcGIS.Mobile.MobileServices Imports ESRI.ArcGIS.Mobile.Geometries Imports System.Windows.Forms Imports System Imports System.Drawing Imports MobileControls.EditControl Imports MobileControls Imports Esri.ArcGISTemplates Public Class CreateFeaturesMapAction Inherits Esri.ArcGIS.Mobile.MapActions.MapAction Private WithEvents m_cboCreateLayers As ComboBox Private m_LongString As String = " " Public Event RaiseMessage(ByVal Message As String) 'Private m_RadioOnTwo As Boolean = True 'Private m_FLay As FeatureLayer Private m_btn As Button 'Ink Collector 'Edit panel to capture redlines attributes Private WithEvents m_EditPanel As MobileControls.EditControl Private m_mousePosition As Coordinate ' stores current mouse position Private m_coordinates As CoordinateCollection ' stores all coordinates used in drawing the measure line Private m_lineColor As Color = Color.Red Private m_LayerName As String 'Private m_DoubleTapToFinish As Boolean = False 'Private m_PointAtTapOnly As Boolean = False Private m_SketchMode As String Private m_ShowCombo As Boolean = True Private m_lineWidth As Integer = 5 Public Event checkGPS() Private m_GPSVal As GPSLocationDetails Private m_Fnt As System.Drawing.Font Private m_FntSize As Single Private m_DT As FeatureDataTable #Region "Public Methods" Public Sub New() MyBase.New() m_coordinates = New CoordinateCollection() End Sub Public Function addMapButton(Optional ByVal TopX As Integer = -1, Optional ByVal TopY As Integer = -1) As Boolean Try 'Create and add the button to toggle the redline map action If m_btn Is Nothing Then 'Create a new button m_btn = New Button With m_btn 'Set the buttons look and feel .BackColor = System.Drawing.SystemColors.Info .BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch .FlatAppearance.BorderSize = 0 .FlatStyle = System.Windows.Forms.FlatStyle.Flat .BackgroundImage = My.Resources.Pen .Name = "btnRedline" .Size = New System.Drawing.Size(50, 50) .UseVisualStyleBackColor = False 'Locate the button TopX = MyBase.Map.Width - 80 TopY = 85 .Location = New System.Drawing.Point(TopX, TopY) 'Add the handler for relocating the button AddHandler MyBase.Map.Resize, AddressOf resize 'Add a handler for the click event AddHandler .MouseClick, AddressOf InkBtnClick End With If m_cboCreateLayers Is Nothing Then m_cboCreateLayers = New ComboBox m_cboCreateLayers.Visible = False m_cboCreateLayers.ForeColor = Drawing.Color.White m_cboCreateLayers.BackColor = Drawing.Color.DarkBlue m_cboCreateLayers.DropDownStyle = ComboBoxStyle.DropDownList ' m_cboCreateLayers.DropDownHeight = 300 m_cboCreateLayers.Font = m_Fnt m_cboCreateLayers.Width = 200 m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) ' AddHandler m_cboCreateLayers.SelectedIndexChanged, AddressOf m_cboCreateLayers_SelectedIndexChanged ' AddHandler m_cboCreateLayers.MouseDoubleClick, AddressOf m_cboCreateLayers_MouseDoubleClick 'Locate it to the left of the button and add to the map MyBase.Map.Controls.Add(m_cboCreateLayers) End If 'Add the button to the map MyBase.Map.Controls.Add(m_btn) End If Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return False End Try Return True End Function Public Function InitControl(ByVal container As Control, Optional ByVal LayerName As String = "") As Boolean Try Single.TryParse(GlobalsFunctions.appConfig.ApplicationSettings.FontSize, m_FntSize) If Not IsNumeric(m_FntSize) Then m_FntSize = 10 ElseIf m_FntSize = 0 Then m_FntSize = 10 End If m_Fnt = New System.Drawing.Font("Microsoft Sans Serif", m_FntSize, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 0) ''Get the redline layer 'Dim pMblLay As Esri.ArcGIS.Mobile.MobileServices.MobileCacheMapLayer 'pMblLay = CType(Map.MapLayers(m_LayerName), MobileCacheMapLayer) ''Return if it was not found 'If pMblLay Is Nothing Then ' MyBase.Map.Controls.Remove(m_btn) ' Return False 'End If addMapButton() 'Create the form is not already created If m_EditPanel Is Nothing Then 'Create a new edit control m_EditPanel = New MobileControls.EditControl(MyBase.Map, Nothing) 'Fill the containter m_EditPanel.Dock = DockStyle.Fill 'Tell the panel to draw the geometry m_EditPanel.DrawGeo = False m_EditPanel.Height = container.Parent.Height 'Clear the controls on the cotainer container.Controls.Clear() 'Add the edit panel container.Dock = DockStyle.Fill container.Controls.Add(m_EditPanel) container.Refresh() container.Update() m_EditPanel.ResumeLayout(True) m_EditPanel.Refresh() m_EditPanel.Update() 'Create a new row on the panel End If ''Set the layer to a global 'pMblLay.Visible = True 'm_FLay = CType(pMblLay.Layer, FeatureLayer) 'If m_FLay Is Nothing Then ' MyBase.Map.Controls.Remove(m_btn) ' Return False 'End If LoadCreateLayers() If m_cboCreateLayers.Items.Count > 0 Then setDataTable(m_cboCreateLayers.Text) End If 'Create a new row SetNewRow() setCurrentLayer() Return True Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Function #End Region #Region "Private Methods" Private Sub setCurrentLayer() Dim pCurConfgi As MobileConfigClass.MobileConfigMobileMapConfigCreateFeaturePanelLayersLayer = m_cboCreateLayers.SelectedItem m_SketchMode = m_cboCreateLayers.SelectedValue If m_SketchMode.ToUpper = "Freehand".ToUpper Then m_EditPanel.GPSButtonVisible = False Else m_EditPanel.GPSButtonVisible = True End If If pCurConfgi.SketchColor <> "" Then m_lineColor = System.Drawing.Color.FromArgb(Int32.Parse(pCurConfgi.SketchColor.Replace("#", ""), Globalization.NumberStyles.HexNumber)) End If End Sub Private Sub setDataTable(ByVal LayerName As String) Try 'Gets a datatable from a feature layer Dim pFl As Esri.ArcGIS.Mobile.MobileServices.FeatureLayer = GlobalsFunctions.GetFeatureLayer(LayerName, MyBase.Map) If pFl Is Nothing Then Return m_DT = pFl.GetDataTable() pFl = Nothing Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub Private Sub SetNewRow() If m_DT IsNot Nothing Then 'Create a new row Dim pDR As DataRow = m_DT.NewRow m_EditPanel.CurrentRecord = CType(pDR, FeatureDataRow) End If End Sub 'Private Sub SetNewRow() ' Try ' 'If the redline layer was not set, return ' If m_FLay Is Nothing Then Return ' 'if the form is not initilize, then exit ' If m_EditPanel Is Nothing Then Return ' 'Get a table from the layer ' Dim pDT As FeatureDataTable = m_FLay.GetDataTable() ' 'Create a new row and assign it to the edit form ' m_EditPanel.CurrentRecord = pDT.NewRow ' 'Cleanup ' pDT = Nothing ' Catch ex As Exception ' Dim st As New StackTrace ' MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) ' st = Nothing ' Return ' End Try 'End Sub Private Sub LoadCreateLayers() Try m_LongString = "" 'Load the inspection types to the inspection dropdown If m_cboCreateLayers Is Nothing Then Return RemoveHandler m_cboCreateLayers.SelectedIndexChanged, AddressOf m_cboCreateLayers_SelectedIndexChanged For Each createLay In GlobalsFunctions.appConfig.CreateFeaturePanel.Layers.Layer If createLay.Name.Length > m_LongString.Length Then m_LongString = createLay.Name End If Next m_cboCreateLayers.DataSource = GlobalsFunctions.appConfig.CreateFeaturePanel.Layers.Layer m_cboCreateLayers.DisplayMember = "Name" m_cboCreateLayers.ValueMember = "EditTool" If GlobalsFunctions.appConfig.CreateFeaturePanel.Layers.Layer.Count = 1 Then m_cboCreateLayers.Visible = False m_ShowCombo = False End If AddHandler m_cboCreateLayers.SelectedIndexChanged, AddressOf m_cboCreateLayers_SelectedIndexChanged Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub #End Region #Region "Events" Private Sub m_cboCreateLayers_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.DropDown Dim g As Graphics = m_cboCreateLayers.CreateGraphics For i = 0 To 5 ' m_layCBO.Width = m_layCBO.Width + 40 ' m_cboCreateLayers.Height = m_cboCreateLayers.Height + 5 Dim pFnt As System.Drawing.Font = New System.Drawing.Font(m_cboCreateLayers.Font.Name, m_cboCreateLayers.Font.Size + i, System.Drawing.FontStyle.Bold) m_cboCreateLayers.Width = g.MeasureString(m_LongString, pFnt).Width + 50 m_cboCreateLayers.Font = pFnt m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) Next g.Dispose() g = Nothing ' End If End Sub Private Sub m_cboCreateLayers_DropDownClosed(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.DropDownClosed Dim g As Graphics = m_cboCreateLayers.CreateGraphics m_cboCreateLayers.Width = g.MeasureString(m_cboCreateLayers.Text, m_Fnt).Width + 50 m_cboCreateLayers.Font = m_Fnt m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) g.Dispose() g = Nothing End Sub Private Sub m_cboCreateLayers_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.Enter End Sub Private Sub m_cboCreateLayers_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles m_cboCreateLayers.MouseClick End Sub Private Sub m_cboCreateLayers_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.SelectedIndexChanged setDataTable(m_cboCreateLayers.Text) 'Create a new row SetNewRow() setCurrentLayer() End Sub Private Sub GPSCreateFinished() Try 'Convert the stoke to a mobile geo Dim pGeo As Geometry = Nothing If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon And m_coordinates.Count > 2 Then pGeo = New Polygon(m_coordinates.Clone) ElseIf m_DT.FeatureLayer.GeometryType = GeometryType.Polyline And m_coordinates.Count >= 2 Then pGeo = New Polyline(m_coordinates.Clone) Else Return End If ' 'If there is not shape, prompt the user and exit If pGeo Is Nothing Then Map.Invalidate() 'delete the strokes Return End If Try 'Try to set the geometry from the stroke to the edit panel m_EditPanel.Geometry = pGeo 'Cleanup pGeo = Nothing Catch ex As Exception 'Capture a invalid geometry 'delete the strokes m_coordinates.Clear() 'Prompt the user Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing 'Clean up and return pGeo = Nothing Map.Invalidate() Return End Try 'The geometry was save to the edit panel, delete the strokes 'm_coordinates.Clear() 'refresh the map ' Map.Refresh() Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Private Sub CreateFinished() Try 'Convert the stoke to a mobile geo Dim pGeo As Geometry = Nothing If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then pGeo = New Polygon(m_coordinates) m_coordinates.Clear() ElseIf m_DT.FeatureLayer.GeometryType = GeometryType.Polyline Then pGeo = New Polyline(m_coordinates) m_coordinates.Clear() Else 'delete the strokes m_coordinates.Clear() Return End If ' 'If there is not shape, prompt the user and exit If pGeo Is Nothing Then Map.Invalidate() 'delete the strokes m_coordinates.Clear() Return End If Try 'Try to set the geometry from the stroke to the edit panel m_EditPanel.Geometry = pGeo 'Cleanup pGeo = Nothing Catch ex As Exception 'Capture a invalid geometry 'delete the strokes m_coordinates.Clear() 'Prompt the user Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing 'Clean up and return pGeo = Nothing Map.Invalidate() Return End Try 'The geometry was save to the edit panel, delete the strokes m_coordinates.Clear() 'refresh the map Map.Refresh() Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Private Sub MouseDoubleClick(ByVal sender As Object, ByVal e As MapMouseEventArgs) 'If UCase(m_SketchMode) <> UCase("FreeHand") And ActionInProgress Then ' CreateFinished() ' m_coordinates = New CoordinateCollection() ' Map.Invalidate() ' MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) ' ' signal to other mapactions that the action is completed ' ActionInProgress = False 'End If 'If m_DoubleTapToFinish = True Then ' RedlineFinished() ' m_coordinates = New CoordinateCollection() ' Map.Invalidate() ' MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) ' ' signal to other mapactions that the action is completed ' ActionInProgress = False 'ElseIf m_DoubleTapToFinish = False And m_PointAtTapOnly = True Then ' RedlineFinished() ' m_coordinates = New CoordinateCollection() ' Map.Invalidate() ' MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) ' ' signal to other mapactions that the action is completed ' ActionInProgress = False 'End If End Sub Protected Overrides Sub OnMapMouseUp(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs) MyBase.OnMapMouseUp(e) If UCase(m_SketchMode) = UCase("FreeHand") And ActionInProgress Then CreateFinished() m_coordinates = New CoordinateCollection() Map.Invalidate() MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) ' signal to other mapactions that the action is completed ActionInProgress = False ElseIf ActionInProgress Then GPSCreateFinished() End If End Sub Protected Overrides Sub OnMapMouseMove(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs) 'MyBase.OnMapMouseMove(e) m_mousePosition = e.MapCoordinate If (m_coordinates.Count < 1) Then Return End If If UCase(m_SketchMode).ToUpper = UCase("FreeHand").ToUpper Then If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then If (m_coordinates.Count < 2) Then Return End If m_coordinates.Insert(m_coordinates.Count - 1, m_mousePosition) Else m_coordinates.Add(m_mousePosition) End If If (Map IsNot Nothing) Then Map.Invalidate() End If End If End Sub Protected Overrides Sub OnMapMouseDown(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs) ' MyBase.OnMapMouseDown(e) Map.Focus() If (e.MapCoordinate Is Nothing) Then Return End If 'If ActionInProgress And m_PointAtTapOnly = True Then ' m_coordinates.Insert(m_coordinates.Count - 1, m_mousePosition) ' If (Map IsNot Nothing) Then ' Map.Invalidate() ' End If 'ElseIf ActionInProgress And m_DoubleTapToFinish = False Then ' ActionInProgress = False ' RedlineFinished() ' MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) 'Else ' signal to other mapactions that the action is executing ActionInProgress = True If (m_coordinates.Count = 0) Then m_coordinates.Add(e.MapCoordinate) If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then m_coordinates.Add(e.MapCoordinate) End If If (Map IsNot Nothing) Then Map.Invalidate() End If 'ElseIf (m_coordinates.Count = 2) Then ' If (m_measureMethod = EsriMeasureMethod.MultiPoint) Then ' m_coordinates.Insert(1, e.MapCoordinate) ' End If 'ElseIf (m_measureMethod = EsriMeasureMethod.MultiPoint) Then ' m_coordinates.Insert(m_coordinates.Count - 1, e.MapCoordinate) Else If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then m_coordinates.Insert(m_coordinates.Count - 1, m_mousePosition) Else m_coordinates.Add(m_mousePosition) End If 'm_coordinates.Add(m_mousePosition) If (Map IsNot Nothing) Then Map.Invalidate() End If End If End Sub Private Sub MapPaint(ByVal sender As Object, ByVal e As Esri.ArcGIS.Mobile.MapPaintEventArgs) If m_coordinates.Count = 0 Then Return If m_coordinates.Count = 1 Then e.Display.DrawPoint(New Pen(m_lineColor, m_lineWidth), New SolidBrush(m_lineColor), 1, m_coordinates(0)) Return End If If m_coordinates.Count = 2 Then If m_coordinates(0).EquivalentTo(m_coordinates(1)) Then e.Display.DrawPoint(New Pen(m_lineColor, m_lineWidth), New SolidBrush(m_lineColor), 1, m_coordinates(0)) Return End If End If Dim g As Graphics = e.Graphics 'If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then ' If m_coordinates.Count > 3 Then ' e.Display.DrawPolygon(New Pen(m_lineColor, m_lineWidth), Nothing, m_coordinates) ' End If 'ElseIf m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then e.Display.DrawPolyline(New Pen(m_lineColor, m_lineWidth), m_coordinates) 'End If End Sub Protected Overrides Sub OnActiveChanged(ByVal active As Boolean) If active Then AddHandler Map.MouseDoubleClick, AddressOf MouseDoubleClick AddHandler Map.KeyUp, AddressOf MapKeyUp AddHandler Map.KeyDown, AddressOf MapKeyDown AddHandler Map.Paint, AddressOf MapPaint MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) Else RemoveHandler Map.MouseDoubleClick, AddressOf MouseDoubleClick RemoveHandler Map.KeyUp, AddressOf MapKeyUp RemoveHandler Map.KeyDown, AddressOf MapKeyDown RemoveHandler Map.Paint, AddressOf MapPaint MyBase.Map.Cursor = Cursors.Default m_coordinates = New CoordinateCollection() Map.Invalidate() ' signal to other mapactions that the action is completed ActionInProgress = False End If MyBase.OnActiveChanged(active) End Sub Private Sub MapKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) MyBase.OnMapKeyDown(e) If e.KeyValue = 27 Then m_coordinates.Clear() Map.Invalidate() ActionInProgress = False Return End If End Sub Private Sub MapKeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) MyBase.OnMapKeyUp(e) End Sub Private Sub resize() Try 'Relocate the button If m_btn IsNot Nothing And MyBase.Map IsNot Nothing Then m_btn.Location = New System.Drawing.Point(MyBase.Map.Width - 80, 85) End If m_cboCreateLayers.Width = 200 m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub Private Sub CreateFeaturesMapAction_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed Try 'Remove the button from the map If m_btn IsNot Nothing Then If m_btn.Parent IsNot Nothing Then m_btn.Parent.Controls.Remove(m_btn) End If End If 'Release the other objects If m_EditPanel IsNot Nothing Then m_EditPanel.Dispose() End If m_EditPanel = Nothing Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Private Sub CreateFeaturesMapAction_StatusChanged(ByVal sender As Object, ByVal e As Esri.ArcGIS.Mobile.MapActions.MapActionStatusChangedEventArgs) Handles Me.StatusChanged Try 'Check the map actions status If e.StatusId = Esri.ArcGIS.Mobile.MapActions.MapAction.Activated Then 'If the button has been created, update the buttons image If m_btn IsNot Nothing Then m_btn.BackgroundImage = My.Resources.penDown m_cboCreateLayers.Visible = m_ShowCombo End If ElseIf e.StatusId = Esri.ArcGIS.Mobile.MapActions.MapAction.Deactivated Then 'If the button has been created, update the buttons image If m_btn IsNot Nothing Then m_btn.BackgroundImage = My.Resources.Pen m_cboCreateLayers.Visible = False End If End If Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Public Sub InkBtnClick(ByVal sender As Object, ByVal e As MouseEventArgs) Try 'Release or assign the map action If MyBase.Map.CurrentMapAction Is Me Then MyBase.Map.CurrentMapAction = Nothing Else MyBase.Map.CurrentMapAction = Me End If Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub #End Region Public Property GPSLocation() As GPSLocationDetails Get Return m_GPSVal End Get Set(ByVal value As GPSLocationDetails) m_GPSVal = value End Set End Property Private Sub m_EditPanel_CheckGPS() Handles m_EditPanel.CheckGPS RaiseEvent checkGPS() If (m_GPSVal IsNot Nothing) Then ' MsgBox("") If m_GPSVal.SpatialReference.FactoryCode <> Map.SpatialReference.FactoryCode Then m_coordinates.Add(Map.SpatialReference.FromGps(m_GPSVal.Coordinate)) 'Me.Geometry = New Esri.ArcGIS.Mobile.Geometries.Point(m_Map.SpatialReference.FromDegreeMinuteSecond(m_GPSVal.LongitudeToDegreeMinutesSeconds), m_Map.SpatialReference.FromDegreeMinuteSecond(m_GPSVal.LatitudeToDegreeMinutesSeconds)) 'Me.Geometry = m_GPSVal() Else m_coordinates.Add(m_GPSVal.Coordinate) End If GPSCreateFinished() Map.Invalidate() End If 'm_EditPanel.GPSLocation = m_GPSVal End Sub Private Sub m_EditPanel_RaiseMessage(ByVal Message As String) Handles m_EditPanel.RaiseMessage RaiseEvent RaiseMessage(Message) End Sub Private Sub m_EditPanel_RecordClear() Handles m_EditPanel.RecordClear m_coordinates.Clear() End Sub Private Sub m_EditPanel_RecordSaved(ByVal LayerName As String, ByVal pGeo As Esri.ArcGIS.Mobile.Geometries.Geometry, ByVal OID As Integer) Handles m_EditPanel.RecordSaved m_coordinates.Clear() ' MsgBox("Record Saved", MsgBoxStyle.Information) RaiseEvent RaiseMessage(GlobalsFunctions.appConfig.EditControlOptions.UIComponents.SavedMessage) End Sub End Class
{ "content_hash": "dd031b9732b6c3d9cd86df63b76c3963", "timestamp": "", "source": "github", "line_count": 829, "max_line_length": 247, "avg_line_length": 35.32689987937274, "alnum_prop": 0.6001843884449908, "repo_name": "Esri/water-utility-mobile-map", "id": "c3ea98e64f87a10ae787f0a9349f22ef1e13c48c", "size": "29288", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Redline_Control/CreateFeaturesControl.vb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "298" }, { "name": "C#", "bytes": "305392" }, { "name": "Visual Basic", "bytes": "3366475" } ], "symlink_target": "" }
using Domain.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Text; namespace Project.Domain.Identity { public static class IdentityExtensionService { public static void EnsureRolesCreated(IServiceProvider serviceProvider) { var context = serviceProvider.GetRequiredService<UtilitiesContext>(); var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); if (context == null || roleManager == null) { throw new InvalidCastException(); } foreach (var role in Roles.All) { if (!roleManager.RoleExistsAsync(role.ToUpper()).Result) { roleManager.CreateAsync(new IdentityRole() { Name = role }); } } context.SaveChanges(); } } }
{ "content_hash": "cbd61fac05a4819238292f83fbbab12e", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 94, "avg_line_length": 31.84375, "alnum_prop": 0.619234543670265, "repo_name": "AlexanderAnishchik/Core-Angular4-Template", "id": "42c1ad5a255788accd9d0259d340e65f8e588ca8", "size": "1021", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core/Project.DataAccess/Identity/IdentityExtensionService.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "47041" }, { "name": "CSS", "bytes": "1371" }, { "name": "HTML", "bytes": "4261" }, { "name": "JavaScript", "bytes": "8198" }, { "name": "Smalltalk", "bytes": "308" }, { "name": "TypeScript", "bytes": "8405" } ], "symlink_target": "" }
Warden::Strategies.add(:password) do def subdomain ActionDispatch::Http::URL.extract_subdomains(request.host, 1) end def valid? subdomain.present? && params["user"] end def authenticate! return fail! unless account = Subscriber::Account.find_by(subdomain: subdomain) return fail! unless user = account.users.find_by(email: params["user"]["email"]) return fail! unless user.authenticate(params["user"]["password"]) success! user end end
{ "content_hash": "e5653aeb6e87a2e4869b40372cc315a1", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 84, "avg_line_length": 25.105263157894736, "alnum_prop": 0.7023060796645703, "repo_name": "rocknrollMarc/subsciption_engine", "id": "c487b8860fa457b7fe0d29f26f553725a7da519a", "size": "477", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/initializers/warden/strategies/password.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2134" }, { "name": "JavaScript", "bytes": "2080" }, { "name": "Ruby", "bytes": "44481" } ], "symlink_target": "" }
package com.alixander.nutrihawk; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import org.joda.time.LocalDate; import android.app.ActionBar; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.text.Spannable; import android.text.SpannableString; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class FoodCategoryFragment extends ListFragment { public static final String EXTRA_FOOD_CATEGORY_ID = "com.example.nutrihawk.food_category_id"; private String foodCategoryName; private HashMap<String, VitaminSet> vitaminSources; private HashMap<String, MineralSet> mineralSources; private ArrayList<Button> all_buttons; private ArrayList<String> foods; private ArrayList<String> logged_foods; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setHasOptionsMenu(true); all_buttons = new ArrayList<Button>(); logged_foods = new ArrayList<String>(); foods = new ArrayList<String>(); foodCategoryName = getActivity().getIntent().getStringExtra(EXTRA_FOOD_CATEGORY_ID).toUpperCase(); vitaminSources = Information.get(getActivity()).getVitaminSources(); mineralSources = Information.get(getActivity()).getMineralSources(); populate(); StatusItemAdapter adapter = new StatusItemAdapter(foods); setListAdapter(adapter); } // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // super.onCreateOptionsMenu(menu, inflater); // inflater.inflate(R.menu.food_menu, menu); // } private void populate() { if (foodCategoryName.equals("FRUITS")) { String[] food_list = {"apple", "avocado", "banana", "blackberries", "blueberries", "boysenberries", "cantaloupe", "cherries", "cranberries", "dates", "grapefruit", "grapes", "kiwi", "lemon", "limes", "lychees", "mangos", "nectarines", "olives", "oranges", "papayas", "passionfruit", "peaches", "pears", "pineapple", "plums", "pomegranates", "raisins", "raspberries", "starfruit", "strawberries", "tomatoes", "watermelon"}; populateButtons(food_list); } else if (foodCategoryName.equals("VEGGIES")) { String[] food_list = {"artichokes", "asparagus", "bamboo", "beets", "bok choy", "broccoli", "brussels sprouts", "butternut squash", "cabbage", "carrots", "cauliflower", "celeriac", "celery", "chinese brocolli", "chinese cabbage", "corn", "cucumber", "daikon", "eggplant", "fennel", "french beans", "green peppers", "yambean (jicama)", "kale", "leeks", "lima beans", "mushrooms", "okra", "onions", "parsnips", "peas", "potatoes", "pumpkin", "radishes", "rapini", "spinach", "seaweed", "zucchini", "winter squash", "sweet potatoes", "swiss chard", "taro", "turnips"}; populateButtons(food_list); } else if (foodCategoryName.equals("NUTS")) { String[] food_list = {"almonds", "cashews", "chestnuts", "coconut", "hazelnuts", "macadamias", "peanuts", "pecans", "pine nuts", "pistachios", "pumpkin seeds", "sesame seeds", "sunflower seeds", "walnuts"}; populateButtons(food_list); } else if (foodCategoryName.equals("GRAINS")) { String[] food_list = {"amaranth", "barley", "buckwheat", "millet", "oats", "quinoa", "brown rice", "wild rice", "rye", "spelt", "white rice"}; populateButtons(food_list); } else if (foodCategoryName.equals("MEATS")) { String[] food_list = {"beef kidney", "beef liver", "beef lung", "beef pancreas", "beef spleen", "beef tongue", "bologna", "beef tenderloin", "cubed steak", "ground beef", "beef ribs", "beef briskets", "beef sirloin", "roast beef", "chicken breast", "chicken drumstick", "chicken leg", "light meat chicken", "chicken thigh", "chicken wing", "chicken nuggets", "dark meat chicken", "carp fish", "cod fish", "catfish", "bass fish", "anchovy", "caviar", "eel", "halibut", "haddock", "herring", "mackerel", "pike", "pollock", "salmon", "sardine", "sea bass", "seatrout", "swordfish", "trout", "tuna", "perch", "lamb", "bacon", "sausage", "ham", "pork patties", "pork (composite)", "ground pork", "turkey (dark)", "turkey breast", "turkey (light)", "turkey bacon", "veal", "duck breast", "duck leg", "ground turkey"}; populateButtons(food_list); } else if (foodCategoryName.equals("DAIRY")) { String[] food_list = {"milk", "butter", "cheddar cheese", "cottage cheese", "cream cheese", "gouda cheese", "goat cheese", "feta cheese", "mozzarella cheese", "parmesan cheese", "provolone cheese", "swiss cheese", "yogurt", "frozen yogurt", "sour cream"}; populateButtons(food_list); } else if (foodCategoryName.equals("OTHER")) { String[] food_list = {"soymilk", "soybeans", "eggs"}; populateButtons(food_list); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_food_category, parent, false); ActionBar ab = getActivity().getActionBar(); SpannableString s = new SpannableString(foodCategoryName); s.setSpan(new TypeSpan(getActivity(), "mensch-bold.ttf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ab.setTitle(s); Button log_button = (Button) v.findViewById(R.id.log_items_button); final Activity activity = getActivity(); log_button.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (logged_foods.size() != 0) { logFoods(); Toast.makeText(getActivity(), "Nutrients logged!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), "Not Saved", Toast.LENGTH_SHORT).show(); } activity.finish(); } }); return v; } private void logFoods() { LocalDate now = new LocalDate(); ArrayList<Nutrient> currentNutrients = Information.get(getActivity()).getNutrients(); for (String newFood : logged_foods) { VitaminSet foodVitamins = vitaminSources.get(newFood); MineralSet foodMinerals = mineralSources.get(newFood); for (Nutrient n : currentNutrients) { if (foodVitamins.getVitaminAmount().containsKey(n.toString().toUpperCase()) && foodVitamins.getVitaminAmount().get(n.toString().toUpperCase()) != 0) { n.addAmount(foodVitamins.getVitaminAmount().get(n.toString().toUpperCase()), now); n.addSource(newFood); } else if (foodMinerals.getMineralAmount().containsKey(n.toString().toUpperCase()) && foodMinerals.getMineralAmount().get(n.toString().toUpperCase()) != 0) { n.addAmount(foodMinerals.getMineralAmount().get(n.toString().toUpperCase()), now); n.addSource(newFood); } else { } } } Information.get(getActivity()).setNutrients(currentNutrients); } public void onListItemClick(ListView l, View v, int position, long id) { String newFood = ((StatusItemAdapter)getListAdapter()).getItem(position).toUpperCase(); CheckBox food_checkbox = (CheckBox)v.findViewById(R.id.food_checked); if (!food_checkbox.isChecked()) { food_checkbox.setChecked(true); logged_foods.add(newFood); } else { food_checkbox.setChecked(false); logged_foods.remove(newFood); } } @Override public void onResume() { super.onResume(); ((StatusItemAdapter)getListAdapter()).notifyDataSetChanged(); } private class StatusItemAdapter extends ArrayAdapter<String> { public StatusItemAdapter(ArrayList<String> foods) { super(getActivity(), 0, foods); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate(R.layout.list_foods, null); } final String food = SpecificNutrientFragment.capitalizeAllFirstLetters(getItem(position)); TextView food_name_section = (TextView)convertView.findViewById(R.id.food_name); food_name_section.setText(food); CheckBox food_checked = (CheckBox)convertView.findViewById(R.id.food_checked); food_checked.setChecked(logged_foods.contains(food.toUpperCase())); food_checked.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { logged_foods.add(food.toUpperCase()); } else { logged_foods.remove(food.toUpperCase()); } } }); return convertView; } } private void populateButtons(String[] food_list) { for (int i = 0; i < food_list.length; i++) { foods.add(food_list[i]); } Collections.sort(foods); } }
{ "content_hash": "2f0e2b986f1a7cf9f247a05e7207fd8f", "timestamp": "", "source": "github", "line_count": 192, "max_line_length": 814, "avg_line_length": 45.875, "alnum_prop": 0.7020890099909174, "repo_name": "alixander/NutriHawk", "id": "aca9503154c953fb3950f9a456df0e1975b57668", "size": "8808", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/alixander/nutrihawk/FoodCategoryFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "98255" }, { "name": "Python", "bytes": "3388" } ], "symlink_target": "" }
.contentViewerOverview { background: rgb(23, 23, 23); border: 1px solid black; border-radius: 0; box-shadow: none; } .contentViewerSingle, .contentViewerEdit { background: rgb(23, 23, 23); padding: 5px; border: 1px solid black; } .contentViewerSingleInnerWrapper, .contentViewerEditInnerWrapper { border: 1px solid black; background: rgb(12, 12, 12); padding: 5px; } .contentPreview { border-radius: 0; } .gray { background: rgb(12, 12, 12); border: 1px solid black; } .gray2 { background: rgb(15, 15, 15); border: 1px solid black; } .contentViewerEdit .title, .contentViewerRemove .title, .contentViewerSingle .title, .contentViewerOverview .title { font-size: 14px; font-weight: bold; } .contentViewerSingle .title, .contentViewerOverview .titleOverview { float: left; padding: 10px; padding-bottom: 15px; font-size: 16px; font-weight: bold; } .contentViewerEdit .title { font-size: 16px; font-weight: bold; padding: 5px; padding-bottom: 7px; } .contentViewerSingle .admin { margin-top: 12px; margin-right: 5px; } .contentViewerOverview .admin { margin-top: 12px; padding-right: 10px; } .contentViewerSingle .admin .title { padding: 0; padding-top: 3px; padding-right: 10px; } .contentViewerSingle .admin .buttons { position: relative; top: -2px; } .contentViewerSingle .admin form { display: inline; } .contentViewerSingle .admin .title, .contentViewerSingle .admin .buttons { display: inline; font-size: 12px; } .contentViewerOverview .admin p, .contentViewerSingle .admin p { font-style: normal; } .contentViewerSingle .date, .contentViewerOverview .date { font-style: italic; font-size: 12px; } .contentViewerSingle .show, .contentViewerOverview .show { font-size: 12px; }
{ "content_hash": "ae2f221de74295ff460c01a0d83d7e0d", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 115, "avg_line_length": 15.818181818181818, "alnum_prop": 0.7235632183908046, "repo_name": "Rasmusa91/Appelicious", "id": "e5df04de4ce45cbab85ea37c99a2ab9d4c9b5e8b", "size": "1740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webroot/css/themes/project/news.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22829" }, { "name": "JavaScript", "bytes": "142" }, { "name": "PHP", "bytes": "1293724" } ], "symlink_target": "" }
<!-- Unsafe sample input : get the UserData field of $_SESSION sanitize : use of the function htmlentities. Sanitizes the query but has a high chance to produce unexpected results File : use of untrusted data in a property value (CSS) --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <style> <?php $tainted = $_SESSION['UserData']; $tainted = htmlentities($tainted, ENT_QUOTES); //flaw echo "body { color :". $tainted ." ; }" ; ?> </style> </script> </head> <body> <h1>Hello World!</h1> </body> </html>
{ "content_hash": "dc4a7ee1c628699997629ad9381acede", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 116, "avg_line_length": 23.416666666666668, "alnum_prop": 0.7530249110320285, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "1fdf0577fcaa29f32a2db3c5f171af32b9685913", "size": "1405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XSS/CWE_79/unsafe/CWE_79__SESSION__func_htmlentities__Use_untrusted_data_propertyValue_CSS-property_Value.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
import visible from '../../src/js/spies/visible.directive'; describe('visible', () => { let rootScope, scope, window, parentElement, element, api, scrollContainerController, template = ` <div spy-fake-scroller> <p spy-visible="visible"></p> </div> `; beforeEach(angular.mock.module('spy.spies.visible')); beforeEach(angular.mock.module('spy.utils.clientRect')); beforeEach(() => { scrollContainerController = { registerSpy: sinon.spy(), getScrollContainer: sinon.spy(() => parentElement[0]) }; }); beforeEach(angular.mock.inject(($compile, $rootScope, $timeout, $window) => { parentElement = angular.element(template); parentElement.data('$spyScrollContainerController', scrollContainerController); rootScope = $rootScope; scope = $rootScope.$new(); $compile(parentElement)(scope); element = parentElement.children(); window = $window; api = scrollContainerController.registerSpy.args[0][0]; })); it('should be defined', () => { visible.should.be.defined; }); it('should be an angular module', () => { visible.name.should.equal('spy.spies.visible'); }); it('should get the scrollContainer DOM element', () => { scrollContainerController.getScrollContainer.should.have.been.called; }); it('should register itself to the parent scrollContainer directive', () => { scrollContainerController.registerSpy.should.have.been.called; }); it('should update his position on link', () => { scrollContainerController.registerSpy.should.have.been.called; }); describe('api', () => { describe('update', () => { it('should be a function', () => { api.update.should.be.a('function'); }); it('should check if item is fully visible', () => { document.body.appendChild(element[0]); element.css({ height: '100px', width: '300px', display: 'block', position: 'absolute', top: 0, left: 0, margin: 0, padding: 0 }); api.updateClientRect(); sinon.spy(api, 'setInView'); api.update({ top: 0, left: 0, width: 1000, height: 1000 }); api.setInView.should.have.been.calledWith(true); }); it('should check if item is fully hidden', () => { document.body.appendChild(element[0]); element.css({ height: '100px', width: '300px', display: 'block', position: 'absolute', left: 0, margin: 0, top: '1001px', padding: 0 }); api.updateClientRect(); sinon.spy(api, 'setInView'); api.update({ top: 0, left: 0, width: 1000, height: 1000 }); api.setInView.should.have.been.calledWith(false); }); it('should not change status if in between', () => { document.body.appendChild(element[0]); element.css({ height: '1000px', width: '300px', display: 'block', position: 'absolute', left: 0, margin: 0, top: '500px', padding: 0 }); api.updateClientRect(); sinon.spy(api, 'setInView'); api.update({ top: 0, left: 0, width: 1000, height: 1000 }); api.setInView.should.not.have.been.called; }); }); describe('updateClientRect', () => { it('should be a function', () => { api.updateClientRect.should.be.a('function'); }); it('should update the rect object calling getBoundingClientRect', () => { let updateRect = sinon.spy(element[0], 'getBoundingClientRect'); api.updateClientRect(); updateRect.should.have.been.called; }); }); describe('getRect', () => { it('should be a function', () => { api.getRect.should.be.a('function'); }); it('should be a function', () => { api.getRect.should.be.a('function'); }); }); describe('setInView', () => { beforeEach(() => { document.body.appendChild(element[0]); api.updateClientRect(); }); afterEach(() => { document.body.removeChild(element[0]); }); it('should be a function', () => { api.setInView.should.be.a('function'); }); it('should set visible to true', () => { api.setInView(true); scope.$apply(); scope.visible.should.be.true; }); it('should set visible to false', () => { api.setInView(false); scope.$apply(); scope.visible.should.be.false; }); it('should call evalAsync id visible value changes', () => { let spyEval = sinon.spy(scope, '$evalAsync'); scope.visible = true; scope.$apply(); api.setInView(false); scope.$apply(); spyEval.should.have.been.called; }); it('should set visible to false', () => { let spyEval = sinon.spy(scope, '$evalAsync'); scope.visible = false; scope.$apply(); api.setInView(false); scope.$apply(); spyEval.should.not.have.been.called; }); }); }); });
{ "content_hash": "41e75da6cd56d43abbaed005447c52a8", "timestamp": "", "source": "github", "line_count": 202, "max_line_length": 87, "avg_line_length": 32.272277227722775, "alnum_prop": 0.4422457432121491, "repo_name": "flea89/angular-spy", "id": "310e8e16e6a35684daf6d710e62984bdb4702f11", "size": "6519", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/scroll-spy/visible.directive.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2020" }, { "name": "JavaScript", "bytes": "39064" } ], "symlink_target": "" }
<?php if (!defined('BASEPATH')) exit('Acesso Direto não permitido'); class Cadastro_model extends CI_Model { public function __construct() { parent::__construct(); if (!$this->session->userdata('session_id') || !$this->session->userdata('logado')) { redirect("login"); } $this->load->model("access_model", "access"); } function geraSenha($tamanho = 7, $maiusculas = true, $numeros = true, $simbolos = TRUE) { $lmin = 'abcdefghijklmnopqrstuvwxyz'; $lmai = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $num = '1234567890'; $simb = '!@#$%*-'; $retorno = ''; $caracteres = ''; $caracteres .= $lmin; if ($maiusculas) {$caracteres .= $lmai;} if ($numeros) {$caracteres .= $num;} if ($simbolos) {$caracteres .= $simb;} $len = strlen($caracteres); for ($n = 1; $n <= $tamanho; $n++) { $rand = mt_rand(1, $len); $retorno .= $caracteres[$rand - 1]; } return $retorno; } public function ListaAssociacao() { $this->db ->select("idASSOCIACAO, nome_completo") ->from("associacoes") ->order_by("nome_completo", "ASC"); return $this->db->get()->result(); } public function ListaProfessor($id) { $this->db ->select('p.idPROFESSOR, p.nome') ->from('professores p') ->join('professor_associacao pa', 'p.idPROFESSOR = pa.idPROFESSOR', 'inner') ->where('pa.idASSOCIACAO', $id) ->where('p.nome is not null'); return $this->db->get()->result(); } public function GravarUsuario($dados) { $this->db->trans_start(); $this->db->insert('usuarios', $dados['USUARIOS']); $dados['DADOS']['IDUSUARIO'] = $this->db->insert_id(); $this->db->insert('dados', $dados['DADOS']); $this->db->trans_complete(); if ($this->db->trans_status() === FALSE) { return NULL; } else { $this->db ->select('IDUSUARIO') ->from('usuarios') ->where('EMAIL', $dados['USUARIOS']['email']); return $this->db->get()->result(); } } public function RollBack($email) { $this->db ->select('idusuario') ->from('usuarios') ->where('email', $email); $id = $this->db->get()->result(); $tabelas = array('usuarios', 'dados'); $this->db ->where('idusuario', $id[0]->idusuario) ->delete($tabelas); } public function AtivaUsuario($email) { $ativo = array('ativo' => 1); $this->db ->where('email', $email) ->update('usuarios', $ativo); } public function VerificaEmail($email) { $this->db ->select('email') ->from('usuarios') ->where('email', $email); $result = $this->db->get()->result(); $r = count($result) == 0 ? 'OK' : 'ER'; return $r; } public function GravaEmailProfessor($email, $senha, $nome = 'aaa') { $dados['usuario'] = $nome; $dados['senha'] = hash('sha512', $senha); $dados['tipo'] = '2'; $dados['ativo'] = '1'; $dados['email'] = $email; $dados['MUDAR_SENHA'] = 0; $dados['primeiroAcesso'] = 1; return $this->db->insert('usuarios', $dados); } public function DeletaEmailProfessor($email) { $this->db->delete('usuarios', 'email = ' . "'$email'"); } public function DeletarEmail($email) { $this->db->delete('usuarios', $email); } public function FinalizaCadastroProfessor($dados) { $this->db->trans_start(); $this->db ->where('email', $dados->usuario->email) ->update('usuarios', $dados->usuario); $this->db ->select('idusuario') ->from('usuarios') ->where('email', $dados->usuario->email); $idUsuario = $this->db->get()->result(); $this->db ->select('COUNT(*)', TRUE) ->from('professores') ->where('usuario_idusuario', $idUsuario[0]->idusuario); $temProf = $this->db->get()->result(); $dados->dados->usuario_idusuario = $idUsuario[0]->idusuario; if(intval($temProf) > 0){ $this->db ->where('usuario_idusuario', $dados->dados->usuario_idusuario) ->update('professores', $dados->dados); }else{ $this->db->insert('professores', $dados->dados); } $this->db->trans_complete(); if ($this->db->trans_status() === FALSE) { return FALSE; } return TRUE; } public function RecuperaIdProfessorUsuario($email) { $this->db ->where('email', $email) ->from('usuarios') ->select('idusuario'); return $id = $this->db->get()->result(); } public function RecuperaIdProfessor($id) { $this->db ->select('idPROFESSOR') ->from('professores') ->where('usuario_idusuario', $id); return $this->db->get()->result(); } public function GravarDadosAssociacao($dados) { $this->db->trans_start(); $this->db->insert('associacoes', $dados); $this->db->trans_complete(); if ($this->db->trans_status() === FALSE) { return FALSE; } $this->db->trans_start(); $this->db ->select('a.idassociacao, a.idProfessor') ->from('associacoes a') ->join('professores p', 'p.usuario_idusuario = a.idusuario', 'INNER') ->where('email', $dados['EMAIL']) ->where('nome_completo', $dados['NOME_COMPLETO']) ->where('end', $dados['END']); $id = $this->db->get()->result(); $ins['idPROFESSOR'] = $id[0]->idProfessor; $ins['idASSOCIACAO'] = $id[0]->idassociacao; $this->db->insert('professor_associacao', $ins); $this->db->trans_complete(); if ($this->db->trans_status() === FALSE) { return FALSE; } return TRUE; } public function ExcluirAssociacao($idAssociacao) { $this->db->trans_start(); $this->db ->where('idASSOCIACAO', $idAssociacao) ->delete('associacoes'); $this->db->trans_complete(); if ($this->db->trans_status()) { return TRUE; } else { return FALSE; } } public function BloquearAssociacao($idAssociacao) { $this->db->trans_start(); $dados = ['bloqueado' => 1]; $this->db ->where('idASSOCIACAO', $idAssociacao) ->update('associacoes', $dados); $this->db->trans_complete(); if ($this->db->trans_status()) { return TRUE; } else { return FALSE; } } public function DesbloquearAssociacao($idAssociacao) { $this->db->trans_start(); $dados = ['bloqueado' => 0]; $this->db ->where('idASSOCIACAO', $idAssociacao) ->update('associacoes', $dados); $this->db->trans_complete(); if ($this->db->trans_status()) { return TRUE; } else { return FALSE; } } public function AlterarSenha($dados, $codUsuario) { $this->db ->where('idUSUARIO', $codUsuario) ->update('usuarios', $dados); $resp = $this->db->affected_rows(); return $resp; } public function ListarAssociacaoProfessor($idUsusario) { $this->db ->select('idAssociacao, nome_completo') ->from('associacoes') ->where('idusuario', $idUsusario); return $this->db->get()->result(); } public function RetornarDadosAssociacao($idAssociacao) { $this->db ->select('idASSOCIACAO, NOME_COMPLETO, END, BAIRRO, NUMERO, CIDADE, UF, COMPLEMENTO, CEP, FONE, EMAIL, NOME_ABR') ->from('associacoes') ->where('idASSOCIACAO', $idAssociacao); return $this->db->get()->result(); } public function EsqueciSenha($email, $dados) { $this->db ->where('email', $email) ->update('usuarios', $dados); $resp = $this->db->affected_rows(); return $resp; } public function RetornarDadosAssocProf($idAssociacao) { $this->db ->select('a.idASSOCIACAO, a.NOME_COMPLETO, p.nome, pt.titulo') ->from('associacoes a') ->join('professores p', 'p.usuario_idusuario = a.idusuario', 'INNER') ->join('professor_titulos pt', 'pt.id = p.titulo') ->where('a.idASSOCIACAO', $idAssociacao) ->where('a.responsavel', 1); return $this->db->get()->result(); } public function RetornarDadosInstrutores($idAssociacao) { $this->db ->select('p.nome, u.EMAIL, u.ATIVO, u.idUSUARIO') ->from('professores p') ->join('professor_associacao pa', 'p.idPROFESSOR = pa.idPROFESSOR', 'INNER') ->join('associacoes a', 'a.idASSOCIACAO = pa.idASSOCIACAO', 'INNER') ->join('usuarios u', 'u.idUSUARIO = p.USUARIO_idUSUARIO', 'INNER') ->where('a.idASSOCIACAO', $idAssociacao) ->where('p.responsavel', 0); return $this->db->get()->result(); } public function BloquearUsuario($idUsuario) { $this->db->trans_start(); $dados = ['ATIVO' => 0]; $this->db ->where('idUSUARIO', $idUsuario) ->update('usuarios', $dados); $this->db->trans_complete(); if ($this->db->trans_status()) { return TRUE; } else { return FALSE; } } public function DesbloquearUsuario($idUsuario) { $this->db->trans_start(); $dados = ['ATIVO' => 1]; $this->db ->where('idUSUARIO', $idUsuario) ->update('usuarios', $dados); $this->db->trans_complete(); if ($this->db->trans_status()) { return TRUE; } else { return FALSE; } } public function RetornaIdUsuario($email) { $this->db ->select('idUSUARIO') ->from('usuarios') ->where('email', $email); return $this->db->get()->result(); } public function GravarInstrutorAssociacao($idAssociacao, $idUsusario) { $this->db->trans_start(); $dadosProfessor = [ 'USUARIO_idUSUARIO' => $idUsusario, 'responsavel' => 0 ]; $this->db->insert('professores', $dadosProfessor); $idProfessor = $this->db->insert_id(); $dadosAssociacao = [ 'idPROFESSOR' => $idProfessor, 'idASSOCIACAO' => $idAssociacao ]; $this->db->insert('professor_associacao', $dadosAssociacao); $this->db->trans_complete(); if ($this->db->trans_status()) { return TRUE; } else { return FALSE; } } public function ListarEmails() { $this->db ->select("usuario, email, primeiroAcesso") ->from("usuarios") ->where("tipo", "2") ->order_by("email"); return $this->db->get()->result(); } public function NumeroProfessorCadastrados() { $this->db ->select('count(idProfessor)`numero`', FALSE) ->from('professores') ->where('nome is not null', NULL, FALSE); return $this->db->get()->result(); } public function NumeroAssociacoes() { $this->db ->select('count(idAssociacao)`numero`') ->from('associacoes') ->where('bloqueado', 0); return $this->db->get()->result(); } public function GetTitulos() { $this->db ->select("IdTitulosProfessor, Descricao") ->from("TitulosProfessor") ->where("Ativo", 1); return $this->db->get()->result(); } public function GetDadosProfessor($idProfessor) { $this->db ->select('nome, dt_nasc, sexo, fone, titulo') ->from('professores') ->where('usuario_idusuario', $idProfessor); return $this->db->get()->result(); } }
{ "content_hash": "1cb2cde7dd08c31fb8f8ee8636558566", "timestamp": "", "source": "github", "line_count": 415, "max_line_length": 129, "avg_line_length": 31.096385542168676, "alnum_prop": 0.48725300271212707, "repo_name": "Deividson007/Sis", "id": "0c763a125bdc23d506e83a6733784d479f44d82a", "size": "12906", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/models/cadastro/cadastro_model.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "243" }, { "name": "CSS", "bytes": "274262" }, { "name": "HTML", "bytes": "1368710" }, { "name": "JavaScript", "bytes": "57562" }, { "name": "PHP", "bytes": "6595944" }, { "name": "PLpgSQL", "bytes": "3937" }, { "name": "Shell", "bytes": "4440" } ], "symlink_target": "" }
import { Injectable, Inject, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { ISourceResponse } from './source.interfaces' import { IReleaseResponse } from '../releases/release.interfaces'; @Injectable() export class SourceService { constructor(private client: HttpClient, @Inject('BASE_URL') private baseUrl: string) { } public get(queryString: string): Observable<ISourceResponse> { let apiRoute = this.baseUrl + 'api/sources/' + (queryString || ""); return this.client.get<ISourceResponse>(apiRoute); } public getSource(sourceId: number, queryString: string): Observable<ISourceResponse> { let apiRoute = this.baseUrl + 'api/source/' + sourceId + (queryString || ""); console.log(apiRoute); return this.client.get<ISourceResponse>(apiRoute); } public getSourceReleases(sourceId: number, queryString: string): Observable<IReleaseResponse> { let apiRoute = this.baseUrl + 'api/sourceReleases/' + sourceId + (queryString || ""); console.log(apiRoute); return this.client.get<IReleaseResponse>(apiRoute); } }
{ "content_hash": "cc993e55f0fd4749016b02bb85ce8191", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 97, "avg_line_length": 32.68571428571428, "alnum_prop": 0.7106643356643356, "repo_name": "rcapel/FRED-API-Toolkit", "id": "b8d9753a436276be86df26ef784e38a369ebd91f", "size": "1144", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Version 2.0/Consumers/Angular-1/Angular-1/ClientApp/src/fredapi/sources/source.service.ts", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "104" }, { "name": "Batchfile", "bytes": "168" }, { "name": "C#", "bytes": "349456" }, { "name": "CSS", "bytes": "667" }, { "name": "HTML", "bytes": "132792" }, { "name": "JavaScript", "bytes": "37861" }, { "name": "TypeScript", "bytes": "214960" } ], "symlink_target": "" }
/* jshint eqeqeq:false */ /* global af: false */ if (!window.af || typeof(af) !== "function") { /** * This is our master af object that everything is built upon. * $ is a pointer to this object * @title appframework * @param {Window} window The global window object * @api private */ var af = (function(window) { "use strict"; var nundefined, document = window.document, emptyArray = [], slice = emptyArray.slice, classCache = {}, eventHandlers = [], _eventID = 1, jsonPHandlers = [], _jsonPID = 1, fragmentRE = /<(\w+)[^>]*>/, classSelectorRE = /^\.([\w-]+)$/, tagSelectorRE = /^[\w-]+$/, _attrCache = {}, _propCache = {}, /** * CSS Properties that can be expressed as a number (w/o 'px') * @type {Object} */ cssNumber = { "columncount": true, "fontweight": true, "lineheight": true, "column-count": true, "font-weight": true, "line-height": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "z-index": true, "zoom": true }, isWin8 = (typeof(MSApp) === "object"); /** * internal function used for $().css - checks to see if it is a number and the css property * needs "px" added to it * @param {string} prop * @param {string|number} val * @return {boolean} * @api private */ function _addPx(prop, val) { return (typeof(val) === "number") && !cssNumber[prop.toLowerCase()] ? val + "px" : val; } /** * internal function to use domfragments for insertion * * @param {$afm} afm An appframework object * @param {Element} container * @param {boolean=} insert Default: false (append) * @api private */ function _insertFragments(afm, container, insert) { var frag = document.createDocumentFragment(); if (insert) { for (var j = afm.length - 1; j >= 0; j--) { frag.insertBefore(afm[j], frag.firstChild); } container.insertBefore(frag, container.firstChild); } else { for (var k = 0; k < afm.length; k++) frag.appendChild(afm[k]); container.appendChild(frag); } frag = null; } /** * Internal function to test if a class name fits in a regular expression * @param {String} name to search against * @return {Boolean} * @api private */ function classRE(name) { return name in classCache ? classCache[name] : (classCache[name] = new RegExp("(^|\\s)" + name + "(\\s|$)")); } /** * Internal function that returns a array of unique elements * @param {Array} arr array to compare against * @return {Array} array of unique elements * @api private */ function unique(arr) { for (var i = 0; i < arr.length; i++) { if (arr.indexOf(arr[i]) !== i) { arr.splice(i, 1); i--; } } return arr; } /** * Given a set of nodes, it returns them as an array. Used to find * siblings of an element * @param {Nodelist} nodes Node list to search * @param {Object=} element [optional] objects to find siblings off of * @return {Array} array of siblings * @api private */ function siblings(nodes, element) { var elems = []; if (nodes == nundefined) return elems; for (; nodes; nodes = nodes.nextSibling) { if (nodes.nodeType === 1 && nodes !== element) { elems.push(nodes); } } return elems; } /** * This is the internal appframework object that gets extended and added on to it * This is also the start of our query selector engine * @param {String|Element|Object|Array} toSelect selector * @param {String|Element|Object|undefined} what Context * @typedef {Object} $afm * @api private */ var $afm = function(toSelect, what) { this.length = 0; if (!toSelect) { return this; } else if (toSelect instanceof $afm && what == nundefined) { return toSelect; } else if (af.isFunction(toSelect)) { return af(document).ready(toSelect); } else if (af.isArray(toSelect) && toSelect.length != nundefined) { //Passing in an array or object for (var i = 0; i < toSelect.length; i++) this[this.length++] = toSelect[i]; return this; } else if (af.isObject(toSelect) && af.isObject(what)) { //var tmp=$("span"); $("p").find(tmp); if (toSelect.length == nundefined) { if (toSelect.parentNode == what) this[this.length++] = toSelect; } else { for (var j = 0; j < toSelect.length; j++) if (toSelect[j].parentNode == what) this[this.length++] = toSelect[j]; } return this; } else if (af.isObject(toSelect) && what == nundefined) { //Single object this[this.length++] = toSelect; return this; } else if (what !== nundefined) { if (what instanceof $afm) { return what.find(toSelect); } } else { what = document; } return this.selector(toSelect, what); }; /** * This calls the $afm function * @title $() * @param {(string|Element|Object)=} selector * @param {(string|Element|Object)=} what Context * @return {$afm} an appframework object */ var $ = function(selector, what) { return new $afm(selector, what); }; /** * this is the engine for "all" and is only exposed internally * @param {string|Element|Object|Array} selector * @param {string|Element|Object|undefined} what Context * @return {$afm} an appframework object * @api private */ function _selectorAll(selector, what) { try { return what.querySelectorAll(selector); } catch (e) { return []; } } /** * this is the query selector engine for elements * @param {String} selector * @param {String|Element|Object|undefined} what [optional] Context * @api private */ function _selector(selector, what) { /*jshint validthis:true*/ selector = selector.trim(); if (selector[0] === "#" && selector.indexOf(".") === -1 &&selector.indexOf(",") === -1 && selector.indexOf(" ") === -1 && selector.indexOf(">") === -1) { if (what === document) _shimNodes(what.getElementById(selector.replace("#", "")), this); else _shimNodes(_selectorAll(selector, what), this); } else if ((selector[0] === "<" && selector[selector.length - 1] === ">") || (selector.indexOf("<") !== -1 && selector.indexOf(">") !== -1)) //html { var tmp = document.createElement("div"); if (isWin8) { MSApp.execUnsafeLocalFunction(function() { tmp.innerHTML = selector.trim(); }); } else tmp.innerHTML = selector.trim(); _shimNodes(tmp.childNodes, this); } else { _shimNodes((_selectorAll(selector, what)), this); } return this; } function _shimNodes(nodes, obj) { if (!nodes) return; if (nodes.nodeType) { obj[obj.length++] = nodes; return; } for (var i = 0, iz = nodes.length; i < iz; i++) obj[obj.length++] = nodes[i]; } /** * Checks to see if the parameter is a $afm object ``` var foo=$("#header"); $.is$(foo); ``` * @param {*} obj * @return {boolean} * @title $.is$(param) */ $.is$ = function(obj) { return (obj instanceof $afm); }; /** * Map takes in elements and executes a callback function on each and returns a collection ``` $.map([1,2],function(ind){return ind+1}); ``` * @param {Array|Object} elements * @param {Function} callback * @return {array} array with elements * @title $.map(elements,callback) */ $.map = function(elements, callback) { var value, values = [], i, key; if ($.isArray(elements)){ for (i = 0; i < elements.length; i++) { value = callback.apply(elements[i],[elements[i],i]); if (value !== nundefined) values.push(value); } } else if ($.isObject(elements)){ for (key in elements) { if (!elements.hasOwnProperty(key) || key === "length") continue; value = callback(elements[key],[elements[key],key]); if (value !== nundefined) values.push(value); } } return values; }; /** * Iterates through elements and executes a callback. Returns if false ``` $.each([1,2],function(ind){console.log(ind);}); ``` * @param {Array|Object} elements * @param {Function} callback * @return {Array} elements * @title $.each(elements,callback) */ $.each = function(elements, callback) { var i, key; if ($.isArray(elements)){ for (i = 0; i < elements.length; i++) { if (callback(i, elements[i]) === false) return elements; } } else if ($.isObject(elements)){ for (key in elements) { if (!elements.hasOwnProperty(key) || key === "length") continue; if (callback(key, elements[key]) === false) return elements; } } return elements; }; /** * Extends an object with additional arguments ``` $.extend({foo:"bar"}); $.extend(element,{foo:"bar"}); ``` * @param {Object} [target] element * @param any number of additional arguments * @return {Object} [target] * @title $.extend(target,{params}) */ $.extend = function(target) { if (target == nundefined) target = this; if (arguments.length === 1) { for (var key in target) this[key] = target[key]; return this; } else { slice.call(arguments, 1).forEach(function(source) { for (var key in source) target[key] = source[key]; }); } return target; }; /** * Checks to see if the parameter is an array ``` var arr=[]; $.isArray(arr); ``` * @param {*} obj * @return {boolean} * @example $.isArray([1]); * @title $.isArray(param) */ $.isArray = function(obj) { return obj instanceof Array && obj.push != nundefined; //ios 3.1.3 doesn"t have Array.isArray }; /** * Checks to see if the parameter is a function ``` var func=function(){}; $.isFunction(func); ``` * @param {*} obj * @return {boolean} * @title $.isFunction(param) */ $.isFunction = function(obj) { return typeof obj === "function" && !(obj instanceof RegExp); }; /** * Checks to see if the parameter is a object ``` var foo={bar:"bar"}; $.isObject(foo); ``` * @param {*} obj * @return {boolean} * @title $.isObject(param) */ $.isObject = function(obj) { return typeof obj === "object" && obj !== null; }; /** * Prototype for afm object. Also extends $.fn */ $.fn = $afm.prototype = { namespace: "appframework", constructor: $afm, forEach: emptyArray.forEach, reduce: emptyArray.reduce, push: emptyArray.push, indexOf: emptyArray.indexOf, concat: emptyArray.concat, selector: _selector, oldElement: undefined, sort: emptyArray.sort, slice: emptyArray.slice, length: 0, /** * This is a utility function for .end() * @param {Object} params * @return {Object} an appframework with params.oldElement set to this * @api private */ setupOld: function(params) { if (params == nundefined) return $(); params.oldElement = this; return params; }, /** * This is a wrapper to $.map on the selected elements ``` $().map(function(){this.value+=ind}); ``` * @param {Function} fn callback * @return {$afm} an appframework object * @title $().map(function) */ map: function(fn) { var value, values = [], i; for (i = 0; i < this.length; i++) { value = fn.apply(this[i],[i,this[i]]); if (value !== nundefined) values.push(value); } return $(values); }, /** * Iterates through all elements and applys a callback function ``` $().each(function(){console.log(this.value)}); ``` * @param {Function} callback * @return {Object} an appframework object * @title $().each(function) */ each: function(callback) { this.forEach(function(el, idx) { callback.call(el, idx, el); }); return this; }, /** * This is executed when DOMContentLoaded happens, or after if you"ve registered for it. ``` $(document).ready(function(){console.log("I'm ready");}); ``` * @param {Function} callback * @return {Object} an appframework object * @title $().ready(function) */ ready: function(callback) { if (document.readyState === "complete" || document.readyState === "loaded" || (!$.os.ie && document.readyState === "interactive")) //IE10 fires interactive too early callback(); else document.addEventListener("DOMContentLoaded", callback, false); return this; }, /** * Searches through the collection and reduces them to elements that match the selector ``` $("#foo").find(".bar"); $("#foo").find($(".bar")); $("#foo").find($(".bar").get(0)); ``` * @param {String|Object|Array} sel Selector * @return {Object} an appframework object filtered * * @title $().find(selector) */ find: function(sel) { if (this.length === 0) return this; var elems = []; var tmpElems; for (var i = 0; i < this.length; i++) { tmpElems = ($(sel, this[i])); for (var j = 0; j < tmpElems.length; j++) { elems.push(tmpElems[j]); } } return $(unique(elems)); }, /** * Gets or sets the innerHTML for the collection. * If used as a get, the first elements innerHTML is returned ``` $("#foo").html(); //gets the first elements html $("#foo").html("new html");//sets the html $("#foo").html("new html",false); //Do not do memory management cleanup ``` * @param {String} html to set * @param {Bool} [cleanup] - set to false for performance tests and if you do not want to execute memory management cleanup * @return {$afm} an appframework object * @title $().html([html]) */ html: function(html, cleanup) { var msFix=function(){ item.innerHTML=html; }; if (this.length === 0) return this; if (html === nundefined) return this[0].innerHTML; for (var i = 0; i < this.length; i++) { if (cleanup !== false) $.cleanUpContent(this[i], false, true); if (isWin8) { var item=this[i]; MSApp.execUnsafeLocalFunction(msFix); } else this[i].innerHTML = html; } return this; }, /** * Gets or sets the innerText for the collection. * If used as a get, the first elements innerText is returned ``` $("#foo").text(); //gets the first elements text; $("#foo").text("new text"); //sets the text ``` * @param {String} text to set * @return {$afm} an appframework object * @title $().text([text]) */ text: function(text) { if (this.length === 0) return this; if (text === nundefined) return this[0].textContent; for (var i = 0; i < this.length; i++) { this[i].textContent = text; } return this; }, /** * Gets or sets a css property for the collection * If used as a get, the first elements css property is returned * This will add px to properties that need it. ``` $().css("background"); // Gets the first elements background $().css("background","red") //Sets the elements background to red ``` * @param {String} attribute The attribute to get * @param {String} value Value to set as * @param {Element=} obj * @return {Object} obj An appframework object * @title $().css(attribute,[value]) */ css: function(attribute, value, obj) { var toAct = obj != nundefined ? obj : this[0]; if (this.length === 0) return this; if (value == nundefined && typeof(attribute) === "string") { var styles = window.getComputedStyle(toAct); return toAct.style[attribute] ? toAct.style[attribute] : window.getComputedStyle(toAct)[attribute]; } for (var i = 0; i < this.length; i++) { if ($.isObject(attribute)) { for (var j in attribute) { this[i].style[j] = _addPx(j, attribute[j]); } } else { this[i].style[attribute] = _addPx(attribute, value); } } return this; }, /** * Gets or sets css vendor specific css properties * If used as a get, the first elements css property is returned ``` $().vendorCss("transform"); // Gets the first elements background $().vendorCss("transform","Translate3d(0,40,0)") //Sets the elements background to red ``` * @param {string} attribute The attribute to get * @param {string} value Value to set as * @param {Element} obj Value to set as * @return {$afm} An appframework object * @title $().vendorCss(attribute,[value]) */ vendorCss: function(attribute, value, obj) { return this.css($.feat.cssPrefix + attribute, value, obj); }, /** * Performs a css vendor specific transform:translate operation on the collection. ``` $("#main").cssTranslate("200px,0,0"); ``` * @param {string} val Transform values * @return {Object} an appframework object * @title $().cssTranslate(value) */ cssTranslate: function(val) { return this.vendorCss("Transform", "translate" + $.feat.cssTransformStart + val + $.feat.cssTransformEnd); }, /** * Gets the computed style of CSS values ``` $("#main").computedStyle("display"); ``` * @param {String} val CSS property * @return {number|string} CSS value * @title $().computedStyle() */ computedStyle: function(val) { if (this.length === 0 || val == nundefined) return; return window.getComputedStyle(this[0], "")[val]; }, /** * Sets the innerHTML of all elements to an empty string ``` $().empty(); ``` * @return {Object} an appframework object * @title $().empty() */ empty: function() { for (var i = 0; i < this.length; i++) { $.cleanUpContent(this[i], false, true); this[i].textContent = ""; } return this; }, /** * Sets the elements display property to "none". * This will also store the old property into an attribute for hide ``` $().hide(); ``` * @return {Object} an appframework object * @title $().hide() */ hide: function() { if (this.length === 0) return this; for (var i = 0; i < this.length; i++) { if (this.css("display", null, this[i]) !== "none") { this[i].setAttribute("afmOldStyle", this.css("display", null, this[i])); this[i].style.display = "none"; } } return this; }, /** * Shows all the elements by setting the css display property * We look to see if we were retaining an old style (like table-cell) and restore that, otherwise we set it to block ``` $().show(); ``` * @return {Object} an appframework object * @title $().show() */ show: function() { if (this.length === 0) return this; for (var i = 0; i < this.length; i++) { if (this.css("display", null, this[i]) === "none") { this[i].style.display = this[i].getAttribute("afmOldStyle") ? this[i].getAttribute("afmOldStyle") : "block"; this[i].removeAttribute("afmOldStyle"); } } return this; }, /** * Toggle the visibility of a div ``` $().toggle(); $().toggle(true); //force showing ``` * @param {Boolean} [show] -force the hiding or showing of the element * @return {Object} an appframework object * @title $().toggle([show]) */ toggle: function(show) { if(this.length === 0) return this; var show2 = show===true; for (var i = 0; i < this.length; i++) { if (this.css("display", null, this[i]) !== "none" && (show == nundefined || show2 === false)) { this[i].setAttribute("afmOldStyle", this.css("display", null, this[i])); this[i].style.display = "none"; } else if (this.css("display", null, this[i]) === "none" && (show == nundefined || show2 === true)) { this[i].style.display = this[i].getAttribute("afmOldStyle") ? this[i].getAttribute("afmOldStyle") : "block"; this[i].removeAttribute("afmOldStyle"); } } return this; }, /** * Gets or sets an elements value * If used as a getter, we return the first elements value. If nothing is in the collection, we return undefined ``` $().value; //Gets the first elements value; $().value="bar"; //Sets all elements value to bar ``` * @param {string=} value [optional] Value to set * @return {String|$afm} A string as a getter, appframework object as a setter * @title $().val([value]) */ val: function(value) { if (this.length === 0) return (value === nundefined) ? undefined : this; if (value == nundefined) return this[0].value; for (var i = 0; i < this.length; i++) { this[i].value = value; } return this; }, /** * Gets or sets an attribute on an element * If used as a getter, we return the first elements value. If nothing is in the collection, we return undefined ``` $().attr("foo"); //Gets the first elements "foo" attribute $().attr("foo","bar");//Sets the elements "foo" attribute to "bar" $().attr("foo",{bar:"bar"}) //Adds the object to an internal cache ``` * @param {string|Object} attr Attribute to act upon. If it is an object (hashmap), it will set the attributes based off the kvp. * @param {string|Array|Object|function|undefined} value [optional] Value to set * @return {string|Object|Array|Function} If used as a getter, return the attribute value. If a setter, return an appframework object * @title $().attr(attribute,[value]) */ attr: function(attr, value) { if (this.length === 0) return (value === nundefined) ? undefined : this; if (value === nundefined && !$.isObject(attr)) { var val = (this[0].afmCacheId && _attrCache[this[0].afmCacheId] && _attrCache[this[0].afmCacheId][attr]) ? _attrCache[this[0].afmCacheId][attr] : this[0].getAttribute(attr); return val; } for (var i = 0; i < this.length; i++) { if ($.isObject(attr)) { for (var key in attr) { $(this[i]).attr(key, attr[key]); } } else if ($.isArray(value) || $.isObject(value) || $.isFunction(value)) { if (!this[i].afmCacheId) this[i].afmCacheId = $.uuid(); if (!_attrCache[this[i].afmCacheId]) _attrCache[this[i].afmCacheId] = {}; _attrCache[this[i].afmCacheId][attr] = value; } else if (value === null) { this[i].removeAttribute(attr); if (this[i].afmCacheId && _attrCache[this[i].afmCacheId][attr]) delete _attrCache[this[i].afmCacheId][attr]; } else { this[i].setAttribute(attr, value); if (this[i].afmCacheId && _attrCache[this[i].afmCacheId][attr]) delete _attrCache[this[i].afmCacheId][attr]; } } return this; }, /** * Removes one or several attribute on the elements ``` $().removeAttr("foo"); ``` * @param {string} attr Attributes that can be space delimited * @return {Object} appframework object * @title $().removeAttr(attribute) */ removeAttr: function(attr) { var removeFixer=function(param) { that[i].removeAttribute(param); if (that[i].afmCacheId && _attrCache[that[i].afmCacheId]) delete _attrCache[that[i].afmCacheId][attr]; }; var that = this; for (var i = 0; i < this.length; i++) { attr.split(/\s+/g).forEach(removeFixer); } return this; }, /** * Gets or sets a property on an element * If used as a getter, we return the first elements value. If nothing is in the collection, we return undefined ``` $().prop("foo"); //Gets the first elements "foo" property $().prop("foo","bar");//Sets the elements "foo" property to "bar" $().prop("foo",{bar:"bar"}) //Adds the object to an internal cache ``` * @param {string|Object} prop The property to act upon. If it is an object (hashmap), it will set the attributes based off the kvp. * @param {string|Array|Object|function} [value] to set * @return {string|Object|Array|Function} If used as a getter, return the property value. If a setter, return an appframework object * @title $().prop(property,[value]) */ prop: function(prop, value) { if (this.length === 0) return (value === nundefined) ? undefined : this; if (value === nundefined && !$.isObject(prop)) { var res; var val = (this[0].afmCacheId && _propCache[this[0].afmCacheId] && _propCache[this[0].afmCacheId][prop]) ? _propCache[this[0].afmCacheId][prop] : !(res = this[0][prop]) && prop in this[0] ? this[0][prop] : res; return val; } for (var i = 0; i < this.length; i++) { if ($.isObject(prop)) { for (var key in prop) { $(this[i]).prop(key, prop[key]); } } else if ($.isArray(value) || $.isObject(value) || $.isFunction(value)) { if (!this[i].afmCacheId) this[i].afmCacheId = $.uuid(); if (!_propCache[this[i].afmCacheId]) _propCache[this[i].afmCacheId] = {}; _propCache[this[i].afmCacheId][prop] = value; } else if (value === null && value !== undefined) { $(this[i]).removeProp(prop); } else { $(this[i]).removeProp(prop); this[i][prop] = value; } } return this; }, /** * Removes one or several properties on the elements ``` $().removeProp("foo"); ``` * @param {string} prop Properties that can be space delimited * @return {$afm} appframework object * @title $().removeProp(attribute) */ removeProp: function(prop) { var removePropFn=function(param) { if (that[i][param]) that[i][param] = undefined; if (that[i].afmCacheId && _propCache[that[i].afmCacheId]) { delete _propCache[that[i].afmCacheId][prop]; } }; var that = this; for (var i = 0; i < this.length; i++) { prop.split(/\s+/g).forEach(removePropFn); } return this; }, /** * Removes elements based off a selector ``` $().remove(); //Remove all $().remove(".foo");//Remove off a string selector var element=$("#foo").get(0); $().remove(element); //Remove by an element $().remove($(".foo")); //Remove by a collection ``` * @param {String|Object|Array} selector to filter against * @return {Object} appframework object * @title $().remove(selector) */ remove: function(selector) { var elems = $(this).filter(selector); if (elems == nundefined) return this; for (var i = 0; i < elems.length; i++) { $.cleanUpContent(elems[i], true, true); if (elems[i] && elems[i].parentNode) { elems[i].parentNode.removeChild(elems[i]); } } return this; }, /** * Adds a css class to elements. ``` $().addClass("selected"); ``` * @param {string} name classes that are space delimited * @return {$afm} appframework object * @title $().addClass(name) */ addClass: function(name) { var addClassLoop=function(cname) { if (!that.hasClass(cname, that[i])) classList.push(cname); }; if (name == nundefined) return this; for (var i = 0; i < this.length; i++) { var cls = this[i].className; var classList = []; var that = this; name.split(/\s+/g).forEach(addClassLoop); this[i].className += (cls ? " " : "") + classList.join(" "); this[i].className = this[i].className.trim(); } return this; }, /** * Removes a css class from elements. ``` $().removeClass("foo"); //single class $().removeClass("foo selected");//remove multiple classess ``` * @param {string} name classes that are space delimited * @return {Object} appframework object * @title $().removeClass(name) */ removeClass: function(name) { if (name == nundefined) return this; var removeClassLoop=function(cname) { classList = classList.replace(classRE(cname), " "); }; for (var i = 0; i < this.length; i++) { if (name == nundefined) { this[i].className = ""; return this; } var classList = this[i].className; //SGV LINK EVENT if (typeof this[i].className === "object") { classList = " "; } name.split(/\s+/g).forEach(removeClassLoop); if (classList.length > 0) this[i].className = classList.trim(); else this[i].className = ""; } return this; }, /** * Adds or removes one or several css classes to/from elements. ``` $().toggleClass("selected"); ``` * @param {string} name Classes that are space delimited * @param {boolean=} state [optional] Force toggle to add or remove classes * @return {Object} appframework object * @title $().toggleClass(name) */ toggleClass: function(name, state) { if (name == nundefined) return this; for (var i = 0; i < this.length; i++) { if (typeof state !== "boolean") { state = this.hasClass(name, this[i]); } $(this[i])[state ? "removeClass" : "addClass"](name); } return this; }, /** * Replaces a css class on elements. ``` $().replaceClass("on", "off"); ``` * @param {string} name classes that are space delimited * @param {string} newName classes that are space delimited * @return {Object} appframework object * @title $().replaceClass(old, new) */ replaceClass: function(name, newName) { if (name == nundefined || newName == nundefined) return this; var replaceClassFn=function(cname) { classList = classList.replace(classRE(cname), " "); }; for (var i = 0; i < this.length; i++) { if (name == nundefined) { this[i].className = newName; continue; } var classList = this[i].className; name.split(/\s+/g).concat(newName.split(/\s+/g)).forEach(replaceClassFn); classList = classList.trim(); if (classList.length > 0) { this[i].className = (classList + " " + newName).trim(); } else this[i].className = newName; } return this; }, /** * Checks to see if an element has a class. ``` $().hasClass("foo"); $().hasClass("foo",element); ``` * @param {string} name Class name to check against * @param {Object=} element [optional] Element to check against * @return {boolean} * @title $().hasClass(name,[element]) */ hasClass: function(name, element) { if (this.length === 0) return false; if (!element) element = this[0]; return classRE(name).test(element.className); }, /** * Appends to the elements * We boil everything down to an appframework object and then loop through that. * If it is HTML, we create a dom element so we do not break event bindings. * if it is a script tag, we evaluate it. ``` $().append("<div></div>"); //Creates the object from the string and appends it $().append($("#foo")); //Append an object; ``` * * @title $().append(element, [insert], [content]) * * @param {string|Object} element Element/string to add * @param {string|Object} content Element/string to add * @param {boolean=} insert [optional] insert or append * @return {Object} appframework object */ append: function(element, content, insert) { if (element && element.length != nundefined && element.length === 0) return this; if ($.isArray(element) || $.isObject(element)) element = $(element); var i, node; if(content) $(this).add(content); for (i = 0; i < this.length; i++) { if (element.length && typeof element !== "string") { element = $(element); _insertFragments(element, this[i], insert); } else { var obj = fragmentRE.test(element) ? $(element) : undefined; if (obj == nundefined || obj.length === 0) { obj = document.createTextNode(element); } if (obj instanceof $afm) { for (var k=0,lenk=obj.length; k<lenk; k++) { node = obj[k]; if (node.nodeName != nundefined && node.nodeName.toLowerCase() === "script" && (!node.type || node.type.toLowerCase() === "text/javascript")) { window["eval"](node.innerHTML); } else { _insertFragments($(node), this[i], insert); } } } else { insert != nundefined ? this[i].insertBefore(obj, this[i].firstChild) : this[i].appendChild(obj); } } } return this; }, /** * Appends the current collection to the selector ``` $().appendTo("#foo"); //Append an object; ``` * @param {string|Object} selector to append to * @param {boolean=} insert [optional] Insert or append * @title $().appendTo(element,[insert]) */ appendTo: function(selector, insert) { var tmp = $(selector); tmp.append(this); return this; }, /** * Prepends the current collection to the selector ``` $().prependTo("#foo"); //Prepend an object; ``` * @param {string|Object} selector Selector to prepend to * @return {$afm} * @title $().prependTo(element) */ prependTo: function(selector) { var tmp = $(selector); tmp.append(this, null,true); return this; }, /** * Prepends to the elements * This simply calls append and sets insert to true ``` $().prepend("<div></div>");//Creates the object from the string and appends it $().prepend($("#foo")); //Prepends an object ``` * @param {Object|string} element Element/string to add * @return {$afm} appframework object * @title $().prepend(element) */ prepend: function(element) { return this.append(element,null, 1); }, /** * Inserts collection before the target (adjacent) ``` $().insertBefore(af("#target")); ``` * @param {string|Object} target Target * @param {boolean=} after [default=false] When true, do an insert after the target * @return {$afm} * @title $().insertBefore(target); */ insertBefore: function(target, after) { if (this.length === 0) return this; target = $(target).get(0); if (!target) return this; for (var i = 0; i < this.length; i++) { after ? target.parentNode.insertBefore(this[i], target.nextSibling) : target.parentNode.insertBefore(this[i], target); } return this; }, /** * Inserts collection after the target (adjacent) ``` $().insertAfter(af("#target")); ``` * @param {String|Object} target * @title $().insertAfter(target); */ insertAfter: function(target) { this.insertBefore(target, true); }, /** * Returns the raw DOM element. ``` $().get(0); //returns the first element $().get(2);// returns the third element ``` * @param {Int} [index] * @return {Object} raw DOM element * @title $().get([index]) */ get: function(index) { index = index == nundefined ? null : index; if (index < 0) index += this.length; if(index===null){ var elems=[]; for(var i=0;i<this.length;i++){ elems.push(this[i]); } return elems; } return (this[index]) ? this[index] : undefined; }, /** * Returns the offset of the element, including traversing up the tree ``` $().offset(); ``` * @return {Object} with left, top, width and height properties * @title $().offset() */ offset: function() { var obj; if (this.length === 0) return this; if (this[0] === window) return { left: 0, top: 0, right: 0, bottom: 0, width: window.innerWidth, height: window.innerHeight }; else obj = this[0].getBoundingClientRect(); return { left: obj.left + window.pageXOffset, top: obj.top + window.pageYOffset, right: obj.right + window.pageXOffset, bottom: obj.bottom + window.pageYOffset, width: obj.right - obj.left, height: obj.bottom - obj.top }; }, /** * Returns the height of the element, including padding on IE ``` $().height(); ``` * @param {string=} val New Height * @return {number|$afm} * @title $().height() */ height: function(val) { if (this.length === 0) return this; if (val != nundefined) return this.css("height", val); if (this[0] === this[0].window) return window.innerHeight; if (this[0].nodeType === this[0].DOCUMENT_NODE) return this[0].documentElement.offsetHeight; else { var tmpVal = this.computedStyle("height").replace("px", ""); if (tmpVal) return +tmpVal; else return this.offset().height; } }, /** * Returns the width of the element, including padding on IE ``` $().width(); ``` * @param {string=} val New Width * @return {number|$afm} * @title $().width() */ width: function(val) { if (this.length === 0) return this; if (val != nundefined) return this.css("width", val); if (this[0] === this[0].window) return window.innerWidth; if (this[0].nodeType === this[0].DOCUMENT_NODE) return this[0].documentElement.offsetWidth; else { var tmpVal = this.computedStyle("width").replace("px", ""); if (tmpVal) return +tmpVal; else return this.offset().width; } }, /** * Returns the parent nodes of the elements based off the selector ``` $("#foo").parent(".bar"); $("#foo").parent($(".bar")); $("#foo").parent($(".bar").get(0)); `` * @param {String|Array|Object|undefined} selector [optional] * @param {boolean=} recursive * @return {Object} appframework object with unique parents * @title $().parent(selector) */ parent: function(selector, recursive) { if (this.length === 0) return this; var elems = []; for (var i = 0; i < this.length; i++) { var tmp = this[i]; while (tmp.parentNode && tmp.parentNode !== document) { elems.push(tmp.parentNode); if (tmp.parentNode) tmp = tmp.parentNode; if (!recursive) break; } } return this.setupOld($(unique(elems)).filter(selector)); }, /** * Returns the parents of the elements based off the selector (traversing up until html document) ``` $("#foo").parents(".bar"); $("#foo").parents($(".bar")); $("#foo").parents($(".bar").get(0)); ``` * @param {string|Array|Object|undefined} [selector] * @return {Object} appframework object with unique parents * @title $().parents(selector) */ parents: function(selector) { return this.parent(selector, true); }, /** * Returns the child nodes of the elements based off the selector ``` $("#foo").children(".bar"); //Selector $("#foo").children($(".bar")); //Objects $("#foo").children($(".bar").get(0)); //Single element ``` * @param {string|Array|Object|undefined} selector [optional] * @return {Object} appframework object with unique children * @title $().children(selector) */ children: function(selector) { if (this.length === 0) return this; var elems = []; for (var i = 0; i < this.length; i++) { elems = elems.concat(siblings(this[i].firstChild)); } return this.setupOld($((elems)).filter(selector)); }, /** * Returns the siblings of the element based off the selector ``` $("#foo").siblings(".bar"); //Selector $("#foo").siblings($(".bar")); //Objects $("#foo").siblings($(".bar").get(0)); //Single element ``` * @param {string|Array|Object|undefined} selector [optional] * @return {Object} appframework object with unique siblings * @title $().siblings(selector) */ siblings: function(selector) { if (this.length === 0) return this; var elems = []; for (var i = 0; i < this.length; i++) { if (this[i].parentNode) elems = elems.concat(siblings(this[i].parentNode.firstChild, this[i])); } return this.setupOld($(elems).filter(selector)); }, /** * Returns the child nodes of the elements based off the selector and includes text nodes ``` $("#foo").contents(".bar"); //Selector $("#foo").contents($(".bar")); //Objects $("#foo").contents($(".bar").get(0)); //Single element ``` * @param {string|Array|Object|undefined} selector [optional] * @return {Object} appframework object with unique children * @title $().contents(selector) */ contents:function(selector){ if (this.length === 0) return this; var elems = []; for (var i = 0; i < this.length; i++) { if (this[i].parentNode) //elems = elems.concat(this[i].childNodes); _shimNodes(this[i].childNodes,elems); } return this.setupOld($(elems).filter(selector)); }, /** * Returns the closest element based off the selector and optional context ``` $("#foo").closest(".bar"); //Selector $("#foo").closest($(".bar")); //Objects $("#foo").closest($(".bar").get(0)); //Single element ``` * @param {String|Array|Object} selector * @param {Object} [context] * @return {Object} Returns an appframework object with the closest element based off the selector * @title $().closest(selector,[context]); */ closest: function(selector, context) { if (this.length === 0) return this; var elems = [], cur = this[0]; var start = $(selector, context); if (start.length === 0) return $(); while (cur && start.indexOf(cur) === -1) { cur = cur !== context && cur !== document && cur.parentNode; } return $(cur); }, /** * Filters elements based off the selector ``` $("#foo").filter(".bar"); //Selector $("#foo").filter($(".bar")); //Objects $("#foo").filter($(".bar").get(0)); //Single element ``` * @param {String|Array|Object} selector * @return {Object} Returns an appframework object after the filter was run * @title $().filter(selector); */ filter: function(selector) { if (this.length === 0) return this; if (selector == nundefined) return this; var elems = []; for (var i = 0; i < this.length; i++) { var val = this[i]; if (val.parentNode && $(selector, val.parentNode).indexOf(val) >= 0) elems.push(val); } return this.setupOld($(unique(elems))); }, /** * Basically the reverse of filter. Return all elements that do NOT match the selector ``` $("#foo").not(".bar"); //Selector $("#foo").not($(".bar")); //Objects $("#foo").not($(".bar").get(0)); //Single element ``` * @param {String|Array|Object} selector * @return {Object} Returns an appframework object after the filter was run * @title $().not(selector); */ not: function(selector) { if (this.length === 0) return this; var elems = []; for (var i = 0; i < this.length; i++) { var val = this[i]; if (val.parentNode && $(selector, val.parentNode).indexOf(val) === -1) elems.push(val); } return this.setupOld($(unique(elems))); }, /** * Gets or set data-* attribute parameters on elements (when a string) * When used as a getter, it's only the first element ``` $().data("foo"); //Gets the data-foo attribute for the first element $().data("foo","bar"); //Sets the data-foo attribute for all elements $().data("foo",{bar:"bar"});//object as the data ``` * @param {string} key * @param {string|Array|Object|undefined} value [optional] * @return {string|Object} returns the value or appframework object * @title $().data(key,[value]); */ data: function(key, value) { return this.attr("data-" + key, value); }, /** * Rolls back the appframework elements when filters were applied * This can be used after .not(), .filter(), .children(), .parent() ``` $().filter(".panel").end(); //This will return the collection BEFORE filter is applied ``` * @return {Object} returns the previous appframework object before filter was applied * @title $().end(); */ end: function() { return this.oldElement != nundefined ? this.oldElement : $(); }, /** * Clones the nodes in the collection. ``` $().clone();// Deep clone of all elements $().clone(false); //Shallow clone ``` * @param {Boolean} [deep] - do a deep copy or not * @return {Object} appframework object of cloned nodes * @title $().clone(); */ clone: function(deep) { deep = deep === false ? false : true; if (this.length === 0) return this; var elems = []; for (var i = 0; i < this.length; i++) { elems.push(this[i].cloneNode(deep)); } return $(elems); }, /** * Returns the number of elements in the collection ``` $().size(); ``` * @return {Int} * @title $().size(); */ size: function() { return this.length; }, /** * Serializes a form into a query string ``` $().serialize(); ``` * @return {string} * @title $().serialize() */ serialize: function() { if (this.length === 0) return ""; var serializeFn=function(elem) { var type = elem.getAttribute("type"); if (elem.nodeName.toLowerCase() !== "fieldset" && !elem.disabled && type !== "submit" && type !== "reset" && type !== "button" && ((type !== "radio" && type !== "checkbox") || elem.checked)) { if (elem.getAttribute("name")) { if (elem.type === "select-multiple") { for (var j = 0; j < elem.options.length; j++) { if (elem.options[j].selected) params.push(elem.getAttribute("name") + "=" + encodeURIComponent(elem.options[j].value)); } } else params.push(elem.getAttribute("name") + "=" + encodeURIComponent(elem.value)); } } }; var params = []; for (var i = 0; i < this.length; i++) { this.slice.call(this[i].elements).forEach(serializeFn); } return params.join("&"); }, /* added in 1.2 */ /** * Reduce the set of elements based off index ``` $().eq(index) ``` * @param {number} ind Index to filter by. If negative, it will go back from the end * @return {$afm} appframework object * @title $().eq(index) */ eq: function(ind) { return $(this.get(ind)); }, /** * Returns the index of the selected element in the collection ``` $().index(elem) ``` * @param {string|Object} elem The element to look for. Can be a selector or object * @return {number} Index of selected element * @title $().index(elem) */ index: function(elem) { return elem ? this.indexOf($(elem)[0]) : this.parent().children().indexOf(this[0]); }, /** * Returns boolean if the object is a type of the selector ``` $().is(selector) ``` * @param {string|Object} selector to act upon * @return {boolean} * @title $().is(selector) */ is: function(selector) { return !!selector && this.filter(selector).length > 0; }, /** * adds a result to an existing AF collection ``` $().add(selector) ``` * @param {string|Object} selector to act upon * @return {$afm} appframework object * @title $().add(selector) */ add:function(selector){ var els=$(selector); var i,len=els.length; for(i=0;i<len;i++){ this[this.length++]=els[i]; } return this; } }; /* AJAX functions */ function empty() {} $.ajaxSettings = { type: "GET", beforeSend: empty, success: empty, error: empty, complete: empty, context: undefined, timeout: 0, crossDomain: null, processData: true }; /** * Execute a jsonP call, allowing cross domain scripting * * options.url - URL to call * options.success - Success function to call * options.error - Error function to call ``` $.jsonP({url:"mysite.php?callback=?&foo=bar",success:function(){},error:function(){}}); ``` * @param {Object} options * @title $.jsonP(options) */ $.jsonP = function(options) { if (isWin8) { options.type = "get"; options.dataType = null; return $.get(options); } var callbackName = "jsonp_callback" + (++_jsonPID); var abortTimeout = "", context, callback; var script = document.createElement("script"); var abort = function() { $(script).remove(); if (window[callbackName]) window[callbackName] = empty; }; window[callbackName] = function(data) { clearTimeout(abortTimeout); $(script).remove(); delete window[callbackName]; options.success.call(context, data); }; if (options.url.indexOf("callback=?") !== -1) { script.src = options.url.replace(/=\?/, "=" + callbackName); } else { callback = options.jsonp ? options.jsonp : "callback"; if (options.url.indexOf("?") === -1) { options.url += ("?" + callback + "=" + callbackName); } else { if(options.url.indexOf("callback=")!==-1){ var searcher="callback="; var offset=options.url.indexOf(searcher)+searcher.length; var amp=options.url.indexOf(offset); if(amp===-1) amp=options.url.length; var oldCB=options.url.substr(offset,amp); options.url=options.url.replace(searcher+oldCB,searcher+callbackName); oldCB=oldCB.replace("window.",""); options.success=window[oldCB]; } else { options.url += ("&" + callback + "=" + callbackName); } } script.src = options.url; } if (options.error) { script.onerror = function() { clearTimeout(abortTimeout); options.error.call(context, "", "error"); }; } $("head").append(script); if (options.timeout > 0) abortTimeout = setTimeout(function() { options.error.call(context, "", "timeout"); }, options.timeout); return {}; }; /** * Execute an Ajax call with the given options * options.type - Type of request * options.beforeSend - function to execute before sending the request * options.success - success callback * options.error - error callback * options.complete - complete callback - called with a success or error * options.timeout - timeout to wait for the request * options.url - URL to make request against * options.contentType - HTTP Request Content Type * options.headers - Object of headers to set * options.dataType - Data type of request * options.data - data to pass into request. $.param is called on objects ``` var opts={ type:"GET", success:function(data){}, url:"mypage.php", data:{bar:"bar"}, } $.ajax(opts); ``` * @param {object} opts Options * @title $.ajax(options) */ $.ajax = function(opts) { var xhr; var deferred=$.Deferred(); var url; if(typeof(opts)==="string") { var oldUrl=opts; opts={ url:oldUrl }; } var settings = opts || {}; for (var key in $.ajaxSettings) { if (typeof(settings[key]) === "undefined") settings[key] = $.ajaxSettings[key]; } try{ if (!settings.url) settings.url = window.location; if (!settings.headers) settings.headers = {}; if (!("async" in settings) || settings.async !== false) settings.async = true; if (settings.processData && $.isObject(settings.data)) settings.data = $.param(settings.data); if (settings.type.toLowerCase() === "get" && settings.data) { if (settings.url.indexOf("?") === -1) settings.url += "?" + settings.data; else settings.url += "&" + settings.data; } if(settings.data) { if (!settings.contentType && settings.contentType!==false) settings.contentType = "application/x-www-form-urlencoded; charset=UTF-8"; } if (!settings.dataType) settings.dataType = "text/html"; else { switch (settings.dataType) { case "script": settings.dataType = "text/javascript, application/javascript"; break; case "json": settings.dataType = "application/json"; break; case "xml": settings.dataType = "application/xml, text/xml"; break; case "html": settings.dataType = "text/html"; break; case "text": settings.dataType = "text/plain"; break; case "jsonp": return $.jsonP(opts); default: settings.dataType = "text/html"; break; } } if (/=\?/.test(settings.url)) { return $.jsonP(settings); } if (settings.crossDomain === null) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) && RegExp.$2 !== window.location.host; if (!settings.crossDomain) settings.headers = $.extend({ "X-Requested-With": "XMLHttpRequest" }, settings.headers); var abortTimeout; var context = settings.context; var protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol; //ok, we are really using xhr xhr = new window.XMLHttpRequest(); $.extend(xhr,deferred.promise); xhr.onreadystatechange = function() { var mime = settings.dataType; if (xhr.readyState === 4) { clearTimeout(abortTimeout); var result, error = false; var contentType=xhr.getResponseHeader("content-type")||""; if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0 && protocol === "file:") { if ((contentType==="application/json")||(mime === "application/json" && !(/^\s*$/.test(xhr.responseText)))) { try { result = JSON.parse(xhr.responseText); } catch (e) { error = e; } } else if(contentType.indexOf("javascript")!==-1){ try{ result=xhr.responseText; window["eval"](result); } catch(e){ console.log(e); } } else if (mime === "application/xml, text/xml") { result = xhr.responseXML; } else if (mime === "text/html") { result = xhr.responseText; $.parseJS(result); } else result = xhr.responseText; //If we're looking at a local file, we assume that no response sent back means there was an error if (xhr.status === 0 && result.length === 0) error = true; if (error){ settings.error.call(context, xhr, "parsererror", error); deferred.reject.call(context, xhr, "parsererror", error); } else { deferred.resolve.call(context, result, "success", xhr); settings.success.call(context, result, "success", xhr); } } else { error = true; deferred.reject.call(context,xhr, "error"); settings.error.call(context, xhr, "error"); } var respText=error?"error":"success"; settings.complete.call(context, xhr,respText); } }; xhr.open(settings.type, settings.url, settings.async); if (settings.withCredentials) xhr.withCredentials = true; if (settings.contentType) settings.headers["Content-Type"] = settings.contentType; for (var name in settings.headers) if (typeof settings.headers[name] === "string") xhr.setRequestHeader(name, settings.headers[name]); if (settings.beforeSend.call(context, xhr, settings) === false) { xhr.abort(); return false; } if (settings.timeout > 0) abortTimeout = setTimeout(function() { xhr.onreadystatechange = empty; xhr.abort(); settings.error.call(context, xhr, "timeout"); }, settings.timeout); xhr.send(settings.data); } catch (e) { // General errors (e.g. access denied) should also be sent to the error callback deferred.resolve(context, xhr, "error",e); settings.error.call(context, xhr, "error", e); } return xhr; }; /** * Shorthand call to an Ajax GET request ``` $.get("mypage.php?foo=bar",function(data){}); ``` * @param {string} url URL to hit * @param {Function} success * @title $.get(url,success) */ $.get = function(url, success) { return this.ajax({ url: url, success: success }); }; /** * Shorthand call to an Ajax POST request ``` $.post("mypage.php",{bar:"bar"},function(data){}); ``` * @param {string} url URL to hit * @param {Object|Function|undefined} data Data to pass in or the success callback * @param {Function=} success [optional] Success Callback when data is given * @param {string=} dataType [default="html"] Expected type of data to be returned * @title $.post(url,[data],success,[dataType]) */ $.post = function(url, data, success, dataType) { if (typeof(data) === "function") { success = data; data = {}; } if (dataType === nundefined) dataType = "html"; return this.ajax({ url: url, type: "POST", data: data, dataType: dataType, success: success }); }; /** * Shorthand call to an Ajax request that expects a JSON response ``` $.getJSON("mypage.php",{bar:"bar"},function(data){}); ``` * @param {String} url to hit * @param {Object} [data] * @param {Function} [success] * @title $.getJSON(url,data,success) */ $.getJSON = function(url, data, success) { if (typeof(data) === "function") { success = data; data = {}; } return this.ajax({ url: url, data: data, success: success, dataType: "json" }); }; /** * Shorthand call to an Ajax request that expects a javascript file. ``` $.getScript("myscript.js", function(data) {} ); ``` * @param {String} url javascript file to load * @param {function(Object)=} [success] * @title $.getScript(url, success) */ $.getScript = function(url, success){ var isCrossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(url); if(isCrossDomain){ //create the script var deferred = $.Deferred(); var scr=$.create("script",{async:true,src:url}).get(0); scr.onload=function(){ success&&success(); deferred.resolve.call(this,"success"); $(this).remove(); }; scr.onerror=function(){ $(this).remove(); deferred.reject.call(this,"success"); }; document.head.appendChild(scr); return deferred.promise; } else { return this.ajax({ url:url, success:success, dataType:"script" }); } }; /** * Converts an object into a key/value par with an optional prefix. Used for converting objects to a query string ``` var obj={ foo:"foo", bar:"bar" } var kvp=$.param(obj,"data"); ``` * @param {Object} obj object * @param {string=} prefix * @return {string} Key/value pair representation * @title $.param(object,[prefix]; */ $.param = function(obj, prefix) { var str = []; if (obj instanceof $afm) { obj.each(function() { var k = prefix ? prefix + "[" + this.id + "]" : this.id, v = this.value; str.push((k) + "=" + encodeURIComponent(v)); }); } else { for (var p in obj) { if ($.isFunction(obj[p])) continue; var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p]; str.push($.isObject(v) ? $.param(v, k) : (k) + "=" + encodeURIComponent(v)); } } return str.join("&"); }; /** * Used for backwards compatibility. Uses native JSON.parse function ``` var obj=$.parseJSON("{\"bar\":\"bar\"}"); ``` * @param {string} string * @return {Object} * @title $.parseJSON(string) */ $.parseJSON = function(string) { return JSON.parse(string); }; /** * Helper function to convert XML into the DOM node representation ``` var xmlDoc=$.parseXML("<xml><foo>bar</foo></xml>"); ``` * @param {String} string * @return {Object} DOM nodes * @title $.parseXML(string) */ $.parseXML = function(string) { if (isWin8) { MSApp.execUnsafeLocalFunction(function() { return (new DOMParser()).parseFromString(string, "text/xml"); }); } else return (new DOMParser()).parseFromString(string, "text/xml"); }; /** * Helper function to parse the user agent. Sets the following * .os.webkit * .os.android * .os.ipad * .os.iphone * .os.webos * .os.touchpad * .os.blackberry * .os.opera * .os.fennec * .os.ie * .os.ieTouch * .os.supportsTouch * .os.playbook * .os.tizen * .feat.nativeTouchScroll * * @param {Object} $ * @param {string} userAgent * @api private */ function detectUA($, userAgent) { $.os = {}; $.os.webkit = userAgent.match(/WebKit\/([\d.]+)/) ? true : false; $.os.android = userAgent.match(/(Android)\s+([\d.]+)/) || userAgent.match(/Silk-Accelerated/) ? true : false; $.os.androidICS = $.os.android && userAgent.match(/(Android)\s4/) ? true : false; $.os.ipad = userAgent.match(/(iPad).*OS\s([\d_]+)/) ? true : false; $.os.iphone = !$.os.ipad && userAgent.match(/(iPhone\sOS)\s([\d_]+)/) ? true : false; $.os.ios7 = ($.os.ipad||$.os.iphone)&&userAgent.match(/7_/) ? true : false; $.os.webos = userAgent.match(/(webOS|hpwOS)[\s\/]([\d.]+)/) ? true : false; $.os.touchpad = $.os.webos && userAgent.match(/TouchPad/) ? true : false; $.os.ios = $.os.ipad || $.os.iphone; $.os.playbook = userAgent.match(/PlayBook/) ? true : false; $.os.blackberry10 = userAgent.match(/BB10/) ? true : false; $.os.blackberry = $.os.playbook || $.os.blackberry10|| userAgent.match(/BlackBerry/) ? true : false; $.os.chrome = userAgent.match(/Chrome/) ? true : false; $.os.opera = userAgent.match(/Opera/) ? true : false; $.os.fennec = userAgent.match(/fennec/i) ? true : userAgent.match(/Firefox/) ? true : false; $.os.ie = userAgent.match(/MSIE 10.0/i)||userAgent.match(/Trident\/7/i) ? true : false; $.os.ieTouch = $.os.ie && userAgent.toLowerCase().match(/touch/i) ? true : false; $.os.tizen = userAgent.match(/Tizen/i)?true:false; $.os.supportsTouch = ((window.DocumentTouch && document instanceof window.DocumentTouch) || "ontouchstart" in window); $.os.kindle=userAgent.match(/Silk-Accelerated/)?true:false; //features $.feat = {}; var head = document.documentElement.getElementsByTagName("head")[0]; $.feat.nativeTouchScroll = typeof(head.style["-webkit-overflow-scrolling"]) !== "undefined" && ($.os.ios||$.os.blackberry10); $.feat.cssPrefix = $.os.webkit ? "Webkit" : $.os.fennec ? "Moz" : $.os.ie ? "ms" : $.os.opera ? "O" : ""; $.feat.cssTransformStart = !$.os.opera ? "3d(" : "("; $.feat.cssTransformEnd = !$.os.opera ? ",0)" : ")"; if ($.os.android && !$.os.webkit) $.os.android = false; var items=["Webkit","Moz","ms","O"]; for(var j=0;j<items.length;j++){ if(document.documentElement.style[items[j]+"Transform"]==="") $.feat.cssPrefix=items[j]; } } detectUA($, navigator.userAgent); $.__detectUA = detectUA; //needed for unit tests /** * Utility function to create a psuedo GUID ``` var id= $.uuid(); ``` * @title $.uuid */ $.uuid = function() { var S4 = function() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); }; return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()); }; /** * Gets the css matrix, or creates a fake one ``` $.getCssMatrix(domElement) ``` * @param {$afm|string|undefined} ele * @return {Object} matrix with postion */ $.getCssMatrix = function(ele) { if ($.is$(ele)) ele = ele.get(0); var matrixFn = window.WebKitCSSMatrix || window.MSCSSMatrix; if (ele === nundefined) { if (matrixFn) { return new matrixFn(); } else { return { a: 0, b: 0, c: 0, d: 0, e: 0, f: 0 }; } } var computedStyle = window.getComputedStyle(ele); var transform = computedStyle.webkitTransform || computedStyle.transform || computedStyle[$.feat.cssPrefix + "Transform"]; if (matrixFn) return new matrixFn(transform); else if (transform) { //fake css matrix var mat = transform.replace(/[^0-9\-.,]/g, "").split(","); return { a: +mat[0], b: +mat[1], c: +mat[2], d: +mat[3], e: +mat[4], f: +mat[5] }; } else { return { a: 0, b: 0, c: 0, d: 0, e: 0, f: 0 }; } }; /** * $.create - a faster alternative to $("<div id="main">this is some text</div>"); ``` $.create("div",{id:"main",innerHTML:"this is some text"}); $.create("<div id="main">this is some text</div>"); ``` * @param {string} type DOM Element type or html * @param {Object=} props Properties to apply to the element * @return {$afm} Returns an appframework object * @title $.create(type,[params]) */ $.create = function(type, props) { var elem; var f = new $afm(); if (props || type[0] !== "<") { if (props.html){ props.innerHTML = props.html; delete props.html; } elem = document.createElement(type); for (var j in props) { elem[j] = props[j]; } f[f.length++] = elem; } else { elem = document.createElement("div"); if (isWin8) { MSApp.execUnsafeLocalFunction(function() { elem.innerHTML = type.trim(); }); } else elem.innerHTML = type; _shimNodes(elem.childNodes, f); } return f; }; /** * $.query - a faster alternative to $("div"); ``` $.query(".panel"); ``` * @param {string} sel selector * @param {Object=} what Context * @return {$afm} Returns an appframework object * @title $.query(selector,[context]) */ $.query = function(sel, what) { if (!sel) return new $afm(); what = what || document; var f = new $afm(); return f.selector(sel, what); }; /** * The following is modified from Zepto.js / events.js * We've removed deprecated events like .live and allow anonymous functions to be removed */ /** * @api private * @type Array.<Function> */ var handlers = [], /** * @type {number} */ _afmid = 1; /** * Gets or sets the expando property on a javascript element * Also increments the internal counter for elements; * @param {Object} element * @return {Int} afmid * @api private */ function afmid(element) { return element._afmid || (element._afmid = _afmid++); } /** * Searches through a local array that keeps track of event handlers for proxying. * Since we listen for multiple events, we match up the event, function and selector. * This is used to find, execute, remove proxied event functions * * @param {Object} element * @param {string=} event * @param {function()} fn function [optional] * @param {String|Object|Array|undefined} selector [optional] * @return {Function|null} handler function or false if not found * @api private */ function findHandlers(element, event, fn, selector) { event = parse(event); if (event.ns) var matcher = matcherFor(event.ns); return (handlers[afmid(element)] || []).filter(function(handler) { return handler && (!event.e || handler.e === event.e) && (!event.ns || matcher.test(handler.ns)) && (!fn || handler.fn === fn || (typeof handler.fn === "function" && typeof fn === "function" && handler.fn === fn)) && (!selector || handler.sel === selector); }); } /** * Splits an event name by "." to look for namespaces (e.g touch.click) * @param {String} event * @return {Object} an object with the event name and namespace * @api private */ function parse(event) { var parts = ("" + event).split("."); return { e: parts[0], ns: parts.slice(1).sort().join(" ") }; } /** * Regular expression checker for event namespace checking * @param {string} ns namespace * @return {Regex} regular expression * @api private */ function matcherFor(ns) { return new RegExp("(?:^| )" + ns.replace(" ", " .* ?") + "(?: |$)"); } /** * Utility function that will loop through events that can be a hash or space delimited and executes the function * @param {String|Object} events * @param {Function} fn * @param {Iterator} [iterator] * @api private */ function eachEvent(events, fn, iterator) { if ($.isObject(events)) $.each(events, iterator); else events.split(/\s/).forEach(function(type) { iterator(type, fn); }); } /** * Helper function for adding an event and creating the proxy handler function. * All event handlers call this to wire event listeners up. We create proxy handlers so they can be removed then. * This is needed for delegate/on * @param {Object} element * @param {String|Object} events * @param {Function} fn Function that will be executed when event triggers * @param {String|Array|Object|undefined} selector [optional] * @param {function()=} getDelegate {optional} * @api private */ function add(element, events, fn, selector, getDelegate) { var id = afmid(element), set = (handlers[id] || (handlers[id] = [])); eachEvent(events, fn, function(event, fn) { var delegate = getDelegate && getDelegate(fn, event), callback = delegate || fn; var proxyfn = function(event) { if (event.ns){ var matcher = matcherFor(event.ns); if(!matcher.test(handler.ns)) return; } var result = callback.apply(element, [event].concat(event.data)); if (result === false) event.preventDefault(); return result; }; var handler = $.extend(parse(event), { fn: fn, proxy: proxyfn, sel: selector, del: delegate, i: set.length }); set.push(handler); element.addEventListener(handler.e, proxyfn, false); }); } /** * Helper function to remove event listeners. We look through each event and then the proxy handler array to see if it exists * If found, we remove the listener and the entry from the proxy array. If no function is specified, we remove all listeners that match * * @param {Object} element * @param {String|Object} events * @param {Function= } fn [optional] * @param {String|Array|Object|undefined} selector [optional] * @api private */ function remove(element, events, fn, selector) { var id = afmid(element); eachEvent(events || "", fn, function(event, fn) { findHandlers(element, event, fn, selector).forEach(function(handler) { delete handlers[id][handler.i]; element.removeEventListener(handler.e, handler.proxy, false); }); }); } $.event = { add: add, remove: remove }; /** * Binds an event to each element in the collection and executes the callback ``` $().bind("click",function(){console.log("I clicked "+this.id);}); ``` * @param {String|Object} event * @param {Function} callback * @return {Object} appframework object * @title $().bind(event,callback) */ $.fn.bind = function(event, callback) { for (var i = 0, len = this.length; i < len; i++) { add(this[i], event, callback); } return this; }; /** * Unbinds an event to each element in the collection. If a callback is passed in, we remove just that one, otherwise we remove all callbacks for those events ``` $().unbind("click"); //Unbinds all click events $().unbind("click",myFunc); //Unbinds myFunc ``` * @param {string|Object} event * @param {Function} [callback] * @return {$afm} appframework object * @title $().unbind(event,[callback]); */ $.fn.unbind = function(event, callback) { for (var i = 0, len = this.length; i < len; i++) { remove(this[i], event, callback); } return this; }; /** * Binds an event to each element in the collection that will only execute once. When it executes, we remove the event listener then right away so it no longer happens ``` $().one("click",function(){console.log("I was clicked once");}); ``` * @param {string|Object} event * @param {Function} [callback] * @return appframework object * @title $().one(event,callback); */ $.fn.one = function(event, callback) { return this.each(function(i, element) { add(this, event, callback, null, function(fn, type) { return function() { remove(element, type, fn); var result = fn.apply(element, arguments); return result; }; }); }); }; /** * internal variables * @return {boolean} always returns true * @api private */ var returnTrue = function() { return true; }; /** * @return {boolean} always returns false */ var returnFalse = function() { return false; }; var eventMethods = { preventDefault: "isDefaultPrevented", stopImmediatePropagation: "isImmediatePropagationStopped", stopPropagation: "isPropagationStopped" }; /** * Creates a proxy function for event handlers. * As "some" browsers dont support event.stopPropagation this call is bypassed if it cant be found on the event object. * @param {String} event * @return {Function} proxy * @api private */ function createProxy(event) { var proxy = $.extend({ originalEvent: event }, event); $.each(eventMethods, function(name, predicate) { proxy[name] = function() { this[predicate] = returnTrue; if (name === "stopImmediatePropagation" || name === "stopPropagation") { event.cancelBubble = true; if (!event[name]) return; } return event[name].apply(event, arguments); }; proxy[predicate] = returnFalse; }); return proxy; } /** * Delegate an event based off the selector. The event will be registered at the parent level, but executes on the selector. ``` $("#div").delegate("p","click",callback); ``` * @param {string|Object} element * @param {String|Object} event * @param {Function} callback * @param {String|Array|Object|undefined} selector [optional] * @param {Object=} data [optional] * @return {$afm} appframework object * @title $().delegate(selector,event,[data],callback) */ function addDelegate(element,event,callback,selector,data){ add(element, event, callback, selector, function(fn) { return function(e) { var evt, match = $(e.target).closest(selector, element).get(0); if (match) { evt = $.extend(createProxy(e), { currentTarget: match, liveFired: element, delegateTarget:element, data:data }); return fn.apply(match, [evt].concat([].slice.call(arguments, 1))); } }; }); } $.fn.delegate = function(selector, event, data, callback) { if ($.isFunction(data)) { callback = data; data = null; } for (var i = 0, len = this.length; i < len; i++) { addDelegate(this[i],event,callback,selector,data); } return this; }; /** * Unbinds events that were registered through delegate. It acts upon the selector and event. If a callback is specified, it will remove that one, otherwise it removes all of them. ``` $("#div").undelegate("p","click",callback);//Undelegates callback for the click event $("#div").undelegate("p","click");//Undelegates all click events ``` * @param {String|Array|Object} selector * @param {String|Object} event * @param {Function} callback * @return {Object} appframework object * @title $().undelegate(selector,event,[callback]); */ $.fn.undelegate = function(selector, event, callback) { for (var i = 0, len = this.length; i < len; i++) { remove(this[i], event, callback, selector); } return this; }; /** * Similar to delegate, but the function parameter order is easier to understand. * If selector is undefined or a function, we just call .bind, otherwise we use .delegate ``` $("#div").on("click","p",callback); ``` * @param {String|Array|Object} selector * @param {String|Object} event * @param {Object} data * @param {Function} callback * @return {Object} appframework object * @title $().on(event,selector,[data],callback); */ $.fn.on = function(event, selector, data, callback) { if ($.isFunction(data)) { callback = data; data = null; } return selector === nundefined || $.isFunction(selector) ? this.bind(event, selector) : this.delegate(selector, event, data,callback); }; /** * Removes event listeners for .on() * If selector is undefined or a function, we call unbind, otherwise it's undelegate ``` $().off("click","p",callback); //Remove callback function for click events $().off("click","p") //Remove all click events ``` * @param {String|Object} event * @param {String|Array|Object} selector * @param {Sunction} callback * @return {Object} appframework object * @title $().off(event,selector,[callback]) */ $.fn.off = function(event, selector, callback) { return selector === nundefined || $.isFunction(selector) ? this.unbind(event, selector) : this.undelegate(selector, event, callback); }; /** This triggers an event to be dispatched. Usefull for emulating events, etc. ``` $().trigger("click",{foo:"bar"});//Trigger the click event and pass in data ``` * @param {string|Object} event * @param {Object=} data * @param {Object=} props * @return {$afm} appframework object * @title $().trigger(event,data); */ $.fn.trigger = function(event, data, props) { if (typeof event === "string"){ props=props || {}; event = parse(event); props.ns=event.ns; event = $.Event(event.e, props); } event.data = data; for (var i = 0, len = this.length; i < len; i++) { this[i].dispatchEvent(event); } return this; }; /** Creates a custom event to be used internally. ``` $.Event('MouseEvent'); ``` * @api private * @title $.Event(type,props); * * @param {string} type * @param {Object=} props [properties] * @return {event} a custom event that can then be dispatched */ $.Event = function(type, props) { var event = document.createEvent("Events"), bubbles = true; if (props) for (var name in props) (name === "bubbles") ? (bubbles = !! props[name]) : (event[name] = props[name]); event.initEvent(type, bubbles, true, null, null, null, null, null, null, null, null, null, null, null, null); return event; }; /** * The following are for objects and not DOM nodes * @api private */ /** * Bind an event to an object instead of a DOM Node ``` $.bind(this,"event",function(){}); ``` * @param {Object} obj Object * @param {string} ev Event name * @param {Function} f Function to execute * @title $.bind(object,event,function); */ $.bind = function(obj, ev, f) { if (!obj) return; if (!obj.__events) obj.__events = {}; if (!$.isArray(ev)) ev = [ev]; for (var i = 0; i < ev.length; i++) { if (!obj.__events[ev[i]]) obj.__events[ev[i]] = []; obj.__events[ev[i]].push(f); } }; /** * Trigger an event to an object instead of a DOM Node ``` $.trigger(this,"event",arguments); ``` * @param {Object} obj object * @param {string} ev event name * @param {Array} args arguments * @title $.trigger(object,event,argments); */ $.trigger = function(obj, ev, args) { if (!obj) return; var ret = true; if (!obj.__events) return ret; if (!$.isArray(ev)) ev = [ev]; if (!$.isArray(args)) args = []; for (var i = 0; i < ev.length; i++) { if (obj.__events[ev[i]]) { var evts = obj.__events[ev[i]].slice(0); for (var j = 0; j < evts.length; j++) if ($.isFunction(evts[j]) && evts[j].apply(obj, args) === false) ret = false; } } return ret; }; /** * Unbind an event to an object instead of a DOM Node ``` $.unbind(this,"event",function(){}); ``` * @param {Object} obj Object * @param {String} ev Event name * @param {Function} f Function to execute * @title $.unbind(object,event,function); */ $.unbind = function(obj, ev, f) { if (!obj.__events) return; if (!$.isArray(ev)) ev = [ev]; for (var i = 0; i < ev.length; i++) { if (obj.__events[ev[i]]) { var evts = obj.__events[ev[i]]; for (var j = 0; j < evts.length; j++) { if (f == nundefined) delete evts[j]; if (evts[j] === f) { evts.splice(j, 1); break; } } } } }; /** * Creates a proxy function so you can change "this" context in the function ``` var newObj={foo:bar} $("#main").bind("click",$.proxy(function(evt){console.log(this)},newObj); ( $.proxy(function(foo, bar){console.log(this+foo+bar)}, newObj) )("foo", "bar"); ( $.proxy(function(foo, bar){console.log(this+foo+bar)}, newObj, ["foo", "bar"]) )(); ``` * @param {Function} f Callback * @param {Object} c Context * @param {Object=} args [optional] Arguments * @title $.proxy(callback, context, [arguments]); */ $.proxy = function(f, c, args) { return function() { if (args) return f.apply(c, args); //use provided arguments return f.apply(c, arguments); //use scope function call arguments }; }; /** * Removes listeners on a div and its children recursively ``` cleanUpNode(node,kill) ``` * @param {HTMLDivElement} node the element to clean up recursively * @param {boolean} kill * @api private */ function cleanUpNode(node, kill) { //kill it before it lays eggs! if (kill && node.dispatchEvent) { var e = $.Event("destroy", { bubbles: false }); node.dispatchEvent(e); } //cleanup itself var id = afmid(node); if (id && handlers[id]) { for (var key in handlers[id]) node.removeEventListener(handlers[id][key].e, handlers[id][key].proxy, false); delete handlers[id]; } } function cleanUpContent(node, kill) { if (!node) return; //cleanup children var children = node.childNodes; if (children && children.length > 0) { for (var i; i < children.length; i++) { cleanUpContent(children[i], kill); } } cleanUpNode(node, kill); } var cleanUpAsap = function(els, kill) { for (var i = 0; i < els.length; i++) { cleanUpContent(els[i], kill); } }; /** * Function to clean up node content to prevent memory leaks ``` $.cleanUpContent(node, itself, kill) ``` * @param {HTMLNode} node * @param {boolean} itself * @param {boolean=} kill When set to true, this will emit a non-bubbling "destroy" Event on the node * @title $.cleanUpContent(node,itself,kill) */ $.cleanUpContent = function(node, itself, kill) { if (!node) return; //cleanup children var cn = node.childNodes; if (cn && cn.length > 0) { //destroy everything in a few ms to avoid memory leaks //remove them all and copy objs into new array $.asap(cleanUpAsap, {}, [slice.apply(cn, [0]), kill]); } //cleanUp this node if (itself) cleanUpNode(node, kill); }; // Like setTimeout(fn, 0); but much faster var timeouts = []; var contexts = []; var params = []; /** * This adds a command to execute in the JS stack, but is faster then setTimeout ``` $.asap(function,context,args) ``` * @param {Function} fn function * @param {Object} context * @param {Array} args arguments */ $.asap = function(fn, context, args) { if (!$.isFunction(fn)) throw "$.asap - argument is not a valid function"; timeouts.push(fn); contexts.push(context ? context : {}); params.push(args ? args : []); //post a message to ourselves so we know we have to execute a function from the stack window.postMessage("afm-asap", "*"); }; window.addEventListener("message", function(event) { if (event.source === window && event.data === "afm-asap") { event.stopPropagation(); if (timeouts.length > 0) { //just in case... (timeouts.shift()).apply(contexts.shift(), params.shift()); } } }, true); /** * this function executes javascript in HTML. ``` $.parseJS(content) ``` * @param {String|DOM} content * @title $.parseJS(content); */ var remoteJSPages = {}; $.parseJS = function(div) { if (!div) return; if (typeof(div) === "string") { var elem = document.createElement("div"); if (isWin8) { MSApp.execUnsafeLocalFunction(function() { elem.innerHTML = div; }); } else elem.innerHTML = div; div = elem; } var scripts = div.getElementsByTagName("script"); div = null; for (var i = 0; i < scripts.length; i++) { if (scripts[i].src.length > 0 && !remoteJSPages[scripts[i].src] && !isWin8) { var doc = document.createElement("script"); doc.type = scripts[i].type; doc.src = scripts[i].src; document.getElementsByTagName("head")[0].appendChild(doc); remoteJSPages[scripts[i].src] = 1; doc = null; } else { window["eval"](scripts[i].innerHTML); } } }; /* custom events since people want to do $().click instead of $().bind("click") */ ["click", "keydown", "keyup", "keypress", "submit", "load", "resize", "change", "select", "error"].forEach(function(event) { $.fn[event] = function(cb) { return cb ? this.bind(event, cb) : this.trigger(event); }; }); ["focus", "blur"].forEach(function(name) { $.fn[name] = function(callback) { if (this.length === 0) return; if (callback) this.bind(name, callback); else{ for (var i = 0; i < this.length; i++) { try { this[i][name](); } catch (e) {} } } return this; }; }); $.Deferred = function(){ return { reject:function(){}, resolve:function(){}, promise:{ then:function(){}, fail:function(){} } }; }; /** * End of APIS * @api private */ return $; })(window); window.jq = af; //backwards compat "$" in window || (window.$ = af); if (typeof define === "function" && define.amd) { define("appframework", [], function() { "use strict"; return af; }); } else if (typeof module !== "undefined" && module.exports) { module.exports.af = af; module.exports.$ = af; } //Helper function used in af.mobi.plugins. if (!window.numOnly) { window.numOnly = function numOnly(val) { "use strict"; if (val === undefined || val === "") return 0; if (isNaN(parseFloat(val))) { if (val.replace) { val = val.replace(/[^0-9.-]/g, ""); } else return 0; } return parseFloat(val); }; } }
{ "content_hash": "57f06d00fade6bbc97d0b521108aa1e2", "timestamp": "", "source": "github", "line_count": 2978, "max_line_length": 273, "avg_line_length": 38.79012760241773, "alnum_prop": 0.4358579256732775, "repo_name": "c4cat/hello", "id": "81fe344fb7d084c6f32d911688d167e72dbf3b8a", "size": "115966", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "appframework.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "344471" }, { "name": "JavaScript", "bytes": "908152" }, { "name": "PHP", "bytes": "16947" } ], "symlink_target": "" }
package polyite.schedule.schedule_tree.normalization import polyite.schedule.schedule_tree.BandNode import polyite.schedule.schedule_tree.DimNode import polyite.schedule.schedule_tree.ScheduleNodeVisitorLeaveNDegUnchanged import polyite.schedule.schedule_tree.LeafNode import polyite.schedule.schedule_tree.ScheduleNode import isl.Isl.TypeAliases._ import isl.VoidCallback2 import isl.Conversions._ import polyite.schedule.ScheduleUtils import polyite.schedule.DomainCoeffInfo import polyite.util.Rat import polyite.schedule.ScheduleVectorUtils class ShiftOffsetToTheLeftVisitor extends PartialSchedMapNormalizationVisitor { def simplifySchedMap(sched : isl.UnionMap, domain : isl.UnionSet) : Option[isl.UnionMap] = { val negInfty : isl.Val = isl.Val.neginfty(sched.getCtx) val maxCoeff : Array[isl.Val] = Array.fill(sched.params().dim(T_PAR) + 1)(negInfty) sched.foreachMap((m : isl.Map) => { val pwMaff : isl.PwMultiAff = isl.PwMultiAff.fromMap(m) var nPiece : Int = 0 pwMaff.foreachPiece(((_ : isl.Set), (mAff : isl.MultiAff)) => { if (mAff.dim(T_OUT) > 1) throw new IllegalArgumentException("sched is multidimensional.") val aff : isl.Aff = mAff.getAff(0) val cst : isl.Val = aff.getConstantVal if (cst.gt(maxCoeff(0))) maxCoeff(0) = cst for (i <- 0 until aff.dim(T_PAR)) { val coeff : isl.Val = aff.getCoefficientVal(T_PAR, i) if (coeff.gt(maxCoeff(i + 1))) maxCoeff(i + 1) = coeff } nPiece += 1 if (nPiece > 1) throw new IllegalArgumentException("sched is defined piecewise: " + sched) }) }) var newSched : isl.UnionMap = isl.UnionMap.empty(sched.getSpace) sched.foreachMap((m : isl.Map) => { val pwMaff : isl.PwMultiAff = isl.PwMultiAff.fromMap(m) pwMaff.foreachPiece(((_ : isl.Set), (mAff : isl.MultiAff)) => { var aff : isl.Aff = mAff.getAff(0) if (maxCoeff(0).gt(negInfty)) aff = aff.setConstantVal(aff.getConstantVal.sub(maxCoeff(0))) for (i <- 0 until aff.dim(T_PAR)) if (maxCoeff(i + 1).gt(negInfty)) aff = aff.setCoefficientVal(T_PAR, i, aff.getCoefficientVal(T_PAR, i).sub(maxCoeff(i + 1))) newSched = newSched.addMap(isl.Map.fromAff(aff)) }) }) val reducedDomInfo : DomainCoeffInfo = DomainCoeffInfo(domain) val coeffs : Array[BigInt] = ScheduleUtils.islUnionMap2CoeffMatrix(reducedDomInfo, newSched).head if (ScheduleVectorUtils.checkAllZeroBigInt(coeffs)) return None return Some(newSched) } }
{ "content_hash": "3423c2705a883060beb517c0c1d588bf", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 103, "avg_line_length": 40.07692307692308, "alnum_prop": 0.6752399232245682, "repo_name": "stganser/polyite", "id": "3c2c5887c44ca295d0ddd2b115bc86dc1e073aac", "size": "2605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/polyite/schedule/schedule_tree/normalization/ShiftOffsetToTheLeftVisitor.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "2788" }, { "name": "Scala", "bytes": "796230" }, { "name": "Shell", "bytes": "43469" }, { "name": "TeX", "bytes": "20618" } ], "symlink_target": "" }
sudo rpm -Uvh thingsboard-3.1pe.rpm
{ "content_hash": "c241d34832d98d40fadca5ac74603a7e", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 35, "avg_line_length": 36, "alnum_prop": 0.7777777777777778, "repo_name": "volodymyr-babak/thingsboard.github.io", "id": "76ab01ee7405fb027b15030dd60fdb237ba2ea05", "size": "36", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/user-guide/install/pe/resources/3.1pe/thingsboard-centos-installation.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "22537" }, { "name": "Dockerfile", "bytes": "237" }, { "name": "HTML", "bytes": "207770" }, { "name": "JavaScript", "bytes": "36100" }, { "name": "Makefile", "bytes": "553" }, { "name": "Ruby", "bytes": "599" }, { "name": "SCSS", "bytes": "5189" }, { "name": "Sass", "bytes": "298237" }, { "name": "Shell", "bytes": "9108" } ], "symlink_target": "" }
"""TODO: DO NOT SUBMIT without one-line documentation for dataset. """ import os import numpy as np from typing import List from dataclasses import dataclass @dataclass class MaskingCurve: masking_frequency: str masking_level: int probe_level: int probe_frequencies: List[float] decibel_masking: List[float] probe_frequencies_bark: List[float] bel_masking: List[float] class MaskingDataset(object): def __init__(self): self._curves = {} self.critical_bands = [ 20, 100, 200, 300, 400, 505, 630, 770, 915, 1080, 1265, 1475, 1720, 1990, 2310, 2690, 3125, 3675, 4350, 5250, 6350, 7650, 9400, 11750, 15250, 20000 ] def add_curve(self, curve: MaskingCurve): if curve.masking_frequency not in self._curves: self._curves[curve.masking_frequency] = {} if curve.probe_level not in self._curves[curve.masking_frequency]: self._curves[curve.masking_frequency][curve.probe_level] = {} self._curves[curve.masking_frequency][curve.probe_level][ curve.masking_level] = curve @staticmethod def binary_search(arr, item): """Finds closest index to the left of an item in arr.""" low = 0 high = len(arr) - 1 mid = 0 while low <= high: mid = (high + low) // 2 # Check if item is present at mid if arr[mid] < item: low = mid # If item is greater, ignore left half elif arr[mid] > item: high = mid # If item is smaller, ignore right half else: return mid if arr[high] <= item: return high if arr[low] <= item < arr[low + 1]: return low return mid def frequency_to_cb(self, frequency: float) -> int: return self.binary_search(self.critical_bands, frequency) + 1 def read_data(self, directory: str, input_file: str): metadata = input_file.strip(".txt").split("_") masking_frequency = metadata[1] probe_level = metadata[3] with open(os.path.join(directory, input_file), "r") as infile: for line in infile: split_line = line.split(":") masking_level = split_line[0].split("[")[1].strip("]").split(",")[0] data_points = split_line[1].split(";") probe_frequencies = [] probe_frequencies_bark = [] decibel_masking = [] bel_masking = [] for point in data_points: split_point = point.split(",") probe_frequency = float(split_point[0]) probe_cb = self.frequency_to_cb(probe_frequency) probe_frequencies.append(probe_frequency) decibel_masking.append(float(split_point[1])) probe_frequencies_bark.append(probe_cb) bel_masking.append(float(split_point[1]) / 10) masking_curve = MaskingCurve(str(masking_frequency), int(masking_level), int(probe_level), probe_frequencies, decibel_masking, probe_frequencies_bark, bel_masking) self.add_curve(masking_curve) return def get_curve_data(self, masking_frequency: float, probe_level: int, masking_level: int): if masking_frequency not in self._curves: raise ValueError( "No curve for masking frequency {}".format(masking_frequency)) print(self._curves[masking_frequency].keys(), probe_level) if probe_level not in self._curves[masking_frequency]: raise ValueError("No curve for probe level {}".format(probe_level)) if masking_level not in self._curves[masking_frequency][probe_level]: raise ValueError("No curve for masking level {}".format(masking_level)) curve = self._curves[masking_frequency][probe_level][masking_level] data = list(zip(curve.probe_frequencies_bark, curve.bel_masking)) return data def get_all_data(self): for masking_frequency, probe_masker_curves in self._curves.items(): for probe_level, masker_curves in probe_masker_curves.items(): for masker_level, curve_data in masker_curves.items(): for (probe_frequency_bark, bel_masking) in zip(curve_data.probe_frequencies_bark, curve_data.bel_masking): yield {"masker_frequency": masking_frequency, "probe_level": probe_level, "masker_level": masker_level, "probe_frequency_bark": probe_frequency_bark, "target_bel_masking": bel_masking}
{ "content_hash": "eae7e43aec8ae261c0671accb57ce1a6", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 91, "avg_line_length": 37.66393442622951, "alnum_prop": 0.5993471164309031, "repo_name": "google-research/korvapuusti", "id": "d7cbcb1d1c3816f2697714a0d8ef0c9d69a9ff89", "size": "5159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "listening_test_summer_2020/modelling/simplex_bark/dataset_threetone.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1773" }, { "name": "C++", "bytes": "6251" }, { "name": "Go", "bytes": "234916" }, { "name": "HTML", "bytes": "13547" }, { "name": "JavaScript", "bytes": "24738" }, { "name": "Jupyter Notebook", "bytes": "48175" }, { "name": "Python", "bytes": "388946" }, { "name": "Shell", "bytes": "2918" } ], "symlink_target": "" }
REM Copyright 2014 Steve Francia REM REM Licensed under the Apache License, Version 2.0 (the "License"); REM you may not use this file except in compliance with the License. REM You may obtain a copy of the License at REM REM http://www.apache.org/licenses/LICENSE-2.0 REM REM Unless required by applicable law or agreed to in writing, software REM distributed under the License is distributed on an "AS IS" BASIS, REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. REM See the License for the specific language governing permissions and REM limitations under the License. @if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH% @if not exist "%HOME%" @set HOME=%USERPROFILE% @set APP_PATH=%HOME%\.all3n-vim @if not exist "%APP_PATH%" ( echo backing up existing vim config @set today=%DATE% @if exist "%HOME%\.vim" call xcopy /s/e/h/y/r/q/i "%HOME%\.vim" "%HOME%\.vim.%today%" @if exist "%HOME%\.vimrc" call copy "%HOME%\.vimrc" "%HOME%\.vimrc.%today%" @if exist "%HOME%\_vimrc" call copy "%HOME%\_vimrc" "%HOME%\_vimrc.%today%" @if exist "%HOME%\.gvimrc" call copy "%HOME%\.gvimrc" "%HOME%\.gvimrc.%today%" ) @if exist "%APP_PATH%" ( @set ORIGINAL_DIR=%CD% echo updating spf13-vim chdir /d "%APP_PATH%" && git pull chdir /d "%ORIGINAL_DIR%" ) else ( echo cloning spf13-vim call git clone --depth=1 -b all3n git://github.com/all3n/spf13-vim.git "%APP_PATH%" ) @if not exist "%APP_PATH%\.vim\bundle" call mkdir "%APP_PATH%\.vim\bundle" call xcopy /s/e/h/y/r/q/i "%APP_PATH%\.vim" "%HOME%\.vim" call copy "%APP_PATH%\.vimrc" "%HOME%\.vimrc" call copy "%APP_PATH%\.vimrc" "%HOME%\_vimrc" call copy "%APP_PATH%\.vimrc.fork" "%HOME%\.vimrc.fork" call copy "%APP_PATH%\.vimrc.bundles" "%HOME%\.vimrc.bundles" call copy "%APP_PATH%\.vimrc.bundles.fork" "%HOME%\.vimrc.bundles.fork" call copy "%APP_PATH%\.vimrc.before" "%HOME%\.vimrc.before" call copy "%APP_PATH%\.vimrc.before.fork" "%HOME%\.vimrc.before.fork" @if not exist "%HOME%/.vim/bundle/vundle" call git clone https://github.com/gmarik/vundle.git "%HOME%/.vim/bundle/vundle" call vim -u "%APP_PATH%/.vimrc.bundles" - +BundleInstall! +BundleClean +qall
{ "content_hash": "fb85f6a53e5ce1a8c411f8242a87ea63", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 121, "avg_line_length": 44.42, "alnum_prop": 0.6753714542998649, "repo_name": "all3n/spf13-vim", "id": "53f06e7bac1f393a534c6d94612c109f7f721331", "size": "2221", "binary": false, "copies": "1", "ref": "refs/heads/all3n", "path": "spf13-vim-windows-xp-install.cmd", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4120" }, { "name": "Shell", "bytes": "5433" }, { "name": "Vim script", "bytes": "50999" } ], "symlink_target": "" }
package com.kirelcodes.RoboticCraft.pathFinders; import java.util.ArrayList; import java.util.List; import org.bukkit.Material; import org.bukkit.block.Block; import com.kirelcodes.RoboticCraft.robot.RobotBase; import com.kirelcodes.RoboticCraft.robot.RobotLumberjack; public class LumberjackPathfinder extends BasicPathfinder { private RobotLumberjack robot; private Block target; private ArrayList<Block> blackList = new ArrayList<Block>(); private List<Block> blocks = new ArrayList<>(); public LumberjackPathfinder(RobotLumberjack robot) { this.robot = robot; } @Override public void onStart() { blackList = new ArrayList<>(); } @Override public boolean shouldStart() { return robot.isCutting(); } @Override public void afterTask() { if (target == null) return; if (target.getType() == Material.AIR || (target.getY() - robot.getLocation().getY()) >= 9) target = null; if (target == null || robot == null) return; if ((target.getY() - robot.getLocation().getY()) >= 9) blackList.add(target); blocks.clear(); } @Override public void updateTask() { int radius = 10; if (target == null) { int x = robot.getLocation().getBlockX(); int z = robot.getLocation().getBlockZ(); for (int y = radius; y > -radius; y--) { blocks.addAll(RobotBase.getNearbyBlocks( robot.getWorld().getBlockAt(x, robot.getLocation().getBlockY() + y, z).getLocation(), radius)); } } for (Block b : blocks) { if (b == null) continue; if (blackList.contains(b)) continue; if (b.getType() == Material.LOG || b.getType() == Material.LOG_2) { if (!blackList.contains(b)) { target = b; break; } } } if (target == null) return; try { if (robot == null || target == null) return; robot.setTargetLocation(target.getLocation()); if (target.getLocation().distance(robot.getLocation()) <= 6) { robot.mineBlock(target); target = null; } else if (target.getLocation().getBlockX() == robot.getLocation().getBlockX()) { if (target.getLocation().getBlockZ() == robot.getLocation().getBlockZ()) { blackList.add(target); target = null; } } } catch (Exception e) { } } }
{ "content_hash": "d4bcb8d9539366702f3fa5e428d9fb4e", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 101, "avg_line_length": 25.32183908045977, "alnum_prop": 0.6559237403540626, "repo_name": "NacOJerk/RoboticCraft", "id": "6c2332cb94b3ad2da66520d5fe8ff1d14ea963ca", "size": "2203", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/kirelcodes/RoboticCraft/pathFinders/LumberjackPathfinder.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "159081" } ], "symlink_target": "" }
require 'dm-core' require 'dm-types/support/flags' module DataMapper class Property class Flag < Object include Flags load_as ::Object dump_as ::Integer def initialize(model, name, options = {}) super @flag_map = {} flags = options.fetch(:flags, self.class.flags) flags.each_with_index do |flag, i| flag_map[i] = flag end end def load(value) return [] if value.nil? || value <= 0 begin matches = [] 0.upto(flag_map.size - 1) do |i| matches << flag_map[i] if value[i] == 1 end matches.compact rescue TypeError, Errno::EDOM [] end end def dump(value) unless value.nil? flags = Array(value).map { |flag| flag.to_sym } flags.uniq! flag = 0 flag_map.invert.values_at(*flags).each do |i| next if i.nil? flag += (1 << i) end flag end end def typecast(value) case value when nil then nil when ::Array then value.map { |v| v.to_sym } else [value.to_sym] end end end # class Flag end # class Property end # module DataMapper
{ "content_hash": "9c6222603bda36f4ff4d682a8ce6159b", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 57, "avg_line_length": 20.03076923076923, "alnum_prop": 0.4946236559139785, "repo_name": "basex/dm-types", "id": "abe98116afdae08a51f4ec4374264eec0d209a8f", "size": "1302", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "lib/dm-types/flag.rb", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
namespace flutter { namespace { constexpr double kAspectRatioChangedThreshold = 0.01; } // namespace ImageDecoder::ImageDecoder( TaskRunners runners, std::shared_ptr<fml::ConcurrentTaskRunner> concurrent_task_runner, fml::WeakPtr<IOManager> io_manager) : runners_(std::move(runners)), concurrent_task_runner_(std::move(concurrent_task_runner)), io_manager_(std::move(io_manager)), weak_factory_(this) { FML_DCHECK(runners_.IsValid()); FML_DCHECK(runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()) << "The image decoder must be created & collected on the UI thread."; } ImageDecoder::~ImageDecoder() = default; static double AspectRatio(const SkISize& size) { return static_cast<double>(size.width()) / size.height(); } // Get the updated dimensions of the image. If both dimensions are specified, // use them. If one of them is specified, respect the one that is and use the // aspect ratio to calculate the other. If neither dimension is specified, use // intrinsic dimensions of the image. static SkISize GetResizedDimensions(SkISize current_size, std::optional<uint32_t> target_width, std::optional<uint32_t> target_height) { if (current_size.isEmpty()) { return SkISize::MakeEmpty(); } if (target_width && target_height) { return SkISize::Make(target_width.value(), target_height.value()); } const auto aspect_ratio = AspectRatio(current_size); if (target_width) { return SkISize::Make(target_width.value(), target_width.value() / aspect_ratio); } if (target_height) { return SkISize::Make(target_height.value() * aspect_ratio, target_height.value()); } return current_size; } static sk_sp<SkImage> ResizeRasterImage(sk_sp<SkImage> image, const SkISize& resized_dimensions, const fml::tracing::TraceFlow& flow) { FML_DCHECK(!image->isTextureBacked()); TRACE_EVENT0("flutter", __FUNCTION__); flow.Step(__FUNCTION__); if (resized_dimensions.isEmpty()) { FML_LOG(ERROR) << "Could not resize to empty dimensions."; return nullptr; } if (image->dimensions() == resized_dimensions) { return image->makeRasterImage(); } if (resized_dimensions.width() > image->dimensions().width() || resized_dimensions.height() > image->dimensions().height()) { FML_LOG(WARNING) << "Image is being upsized from " << image->dimensions().width() << "x" << image->dimensions().height() << " to " << resized_dimensions.width() << "x" << resized_dimensions.height() << ". Are cache(Height|Width) used correctly?"; // TOOD(48885): consider exiting here, there's no good reason to support // upsampling in a "caching"-optimization context.. } const bool aspect_ratio_changed = std::abs(AspectRatio(resized_dimensions) - AspectRatio(image->dimensions())) > kAspectRatioChangedThreshold; if (aspect_ratio_changed) { // This is probably a bug. If a user passes dimensions that change the // aspect ratio in a "caching" context that's probably not working as // intended and rather a signal that the API is hard to use. FML_LOG(WARNING) << "Aspect ratio changes. Are cache(Height|Width) used correctly?"; } const auto scaled_image_info = image->imageInfo().makeDimensions(resized_dimensions); SkBitmap scaled_bitmap; if (!scaled_bitmap.tryAllocPixels(scaled_image_info)) { FML_LOG(ERROR) << "Failed to allocate memory for bitmap of size " << scaled_image_info.computeMinByteSize() << "B"; return nullptr; } if (!image->scalePixels(scaled_bitmap.pixmap(), kLow_SkFilterQuality, SkImage::kDisallow_CachingHint)) { FML_LOG(ERROR) << "Could not scale pixels"; return nullptr; } // Marking this as immutable makes the MakeFromBitmap call share the pixels // instead of copying. scaled_bitmap.setImmutable(); auto scaled_image = SkImage::MakeFromBitmap(scaled_bitmap); if (!scaled_image) { FML_LOG(ERROR) << "Could not create a scaled image from a scaled bitmap."; return nullptr; } return scaled_image; } static sk_sp<SkImage> ImageFromDecompressedData( sk_sp<SkData> data, ImageDecoder::ImageInfo info, std::optional<uint32_t> target_width, std::optional<uint32_t> target_height, const fml::tracing::TraceFlow& flow) { TRACE_EVENT0("flutter", __FUNCTION__); flow.Step(__FUNCTION__); auto image = SkImage::MakeRasterData(info.sk_info, data, info.row_bytes); if (!image) { FML_LOG(ERROR) << "Could not create image from decompressed bytes."; return nullptr; } if (!target_width && !target_height) { // No resizing requested. Just rasterize the image. return image->makeRasterImage(); } auto resized_dimensions = GetResizedDimensions(image->dimensions(), target_width, target_height); return ResizeRasterImage(std::move(image), resized_dimensions, flow); } sk_sp<SkImage> ImageFromCompressedData(sk_sp<SkData> data, std::optional<uint32_t> target_width, std::optional<uint32_t> target_height, const fml::tracing::TraceFlow& flow) { TRACE_EVENT0("flutter", __FUNCTION__); flow.Step(__FUNCTION__); if (!target_width && !target_height) { // No resizing requested. Just decode & rasterize the image. return SkImage::MakeFromEncoded(data)->makeRasterImage(); } auto codec = SkCodec::MakeFromData(data); if (codec == nullptr) { return nullptr; } const auto* codec_ptr = codec.get(); // Note that we cannot read the dimensions from the codec since they don't // respect image orientation provided e.g. in EXIF data. auto image_generator = SkCodecImageGenerator::MakeFromCodec(std::move(codec)); const auto& source_dimensions = image_generator->getInfo().dimensions(); auto resized_dimensions = GetResizedDimensions(source_dimensions, target_width, target_height); // No resize needed. if (resized_dimensions == source_dimensions) { return SkImage::MakeFromEncoded(data)->makeRasterImage(); } auto decode_dimensions = codec_ptr->getScaledDimensions( std::max(static_cast<double>(resized_dimensions.width()) / source_dimensions.width(), static_cast<double>(resized_dimensions.height()) / source_dimensions.height())); // If the codec supports efficient sub-pixel decoding, decoded at a resolution // close to the target resolution before resizing. if (decode_dimensions != codec_ptr->dimensions()) { if (source_dimensions != codec_ptr->dimensions()) { decode_dimensions = SkISize::Make(decode_dimensions.height(), decode_dimensions.width()); } auto scaled_image_info = image_generator->getInfo().makeDimensions(decode_dimensions); SkBitmap scaled_bitmap; if (!scaled_bitmap.tryAllocPixels(scaled_image_info)) { FML_LOG(ERROR) << "Failed to allocate memory for bitmap of size " << scaled_image_info.computeMinByteSize() << "B"; return nullptr; } const auto& pixmap = scaled_bitmap.pixmap(); if (image_generator->getPixels(pixmap.info(), pixmap.writable_addr(), pixmap.rowBytes())) { // Marking this as immutable makes the MakeFromBitmap call share // the pixels instead of copying. scaled_bitmap.setImmutable(); auto decoded_image = SkImage::MakeFromBitmap(scaled_bitmap); FML_DCHECK(decoded_image); if (!decoded_image) { FML_LOG(ERROR) << "Could not create a scaled image from a scaled bitmap."; return nullptr; } return ResizeRasterImage(std::move(decoded_image), resized_dimensions, flow); } } auto image = SkImage::MakeFromEncoded(data); if (!image) { return nullptr; } return ResizeRasterImage(std::move(image), resized_dimensions, flow); } static SkiaGPUObject<SkImage> UploadRasterImage( sk_sp<SkImage> image, fml::WeakPtr<IOManager> io_manager, const fml::tracing::TraceFlow& flow) { TRACE_EVENT0("flutter", __FUNCTION__); flow.Step(__FUNCTION__); // Should not already be a texture image because that is the entire point of // the this method. FML_DCHECK(!image->isTextureBacked()); if (!io_manager->GetResourceContext() || !io_manager->GetSkiaUnrefQueue()) { FML_LOG(ERROR) << "Could not acquire context of release queue for texture upload."; return {}; } SkPixmap pixmap; if (!image->peekPixels(&pixmap)) { FML_LOG(ERROR) << "Could not peek pixels of image for texture upload."; return {}; } SkiaGPUObject<SkImage> result; io_manager->GetIsGpuDisabledSyncSwitch()->Execute( fml::SyncSwitch::Handlers() .SetIfTrue([&result, &pixmap, &image] { SkSafeRef(image.get()); sk_sp<SkImage> texture_image = SkImage::MakeFromRaster( pixmap, [](const void* pixels, SkImage::ReleaseContext context) { SkSafeUnref(static_cast<SkImage*>(context)); }, image.get()); result = {texture_image, nullptr}; }) .SetIfFalse([&result, context = io_manager->GetResourceContext(), &pixmap, queue = io_manager->GetSkiaUnrefQueue()] { sk_sp<SkImage> texture_image = SkImage::MakeCrossContextFromPixmap( context.get(), // context pixmap, // pixmap true, // buildMips, true // limitToMaxTextureSize ); if (!texture_image) { FML_LOG(ERROR) << "Could not make x-context image."; result = {}; } else { result = {texture_image, queue}; } })); return result; } void ImageDecoder::Decode(ImageDescriptor descriptor, const ImageResult& callback) { TRACE_EVENT0("flutter", __FUNCTION__); fml::tracing::TraceFlow flow(__FUNCTION__); FML_DCHECK(callback); FML_DCHECK(runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); // Always service the callback on the UI thread. auto result = [callback, ui_runner = runners_.GetUITaskRunner()]( SkiaGPUObject<SkImage> image, fml::tracing::TraceFlow flow) { ui_runner->PostTask(fml::MakeCopyable( [callback, image = std::move(image), flow = std::move(flow)]() mutable { // We are going to terminate the trace flow here. Flows cannot // terminate without a base trace. Add one explicitly. TRACE_EVENT0("flutter", "ImageDecodeCallback"); flow.End(); callback(std::move(image)); })); }; if (!descriptor.data || descriptor.data->size() == 0) { result({}, std::move(flow)); return; } concurrent_task_runner_->PostTask( fml::MakeCopyable([descriptor, // io_manager = io_manager_, // io_runner = runners_.GetIOTaskRunner(), // result, // flow = std::move(flow) // ]() mutable { // Step 1: Decompress the image. // On Worker. auto decompressed = descriptor.decompressed_image_info ? ImageFromDecompressedData( std::move(descriptor.data), // descriptor.decompressed_image_info.value(), // descriptor.target_width, // descriptor.target_height, // flow // ) : ImageFromCompressedData(std::move(descriptor.data), // descriptor.target_width, // descriptor.target_height, // flow); if (!decompressed) { FML_LOG(ERROR) << "Could not decompress image."; result({}, std::move(flow)); return; } // Step 2: Update the image to the GPU. // On IO Thread. io_runner->PostTask(fml::MakeCopyable([io_manager, decompressed, result, flow = std::move(flow)]() mutable { if (!io_manager) { FML_LOG(ERROR) << "Could not acquire IO manager."; return result({}, std::move(flow)); } // If the IO manager does not have a resource context, the caller // might not have set one or a software backend could be in use. // Either way, just return the image as-is. if (!io_manager->GetResourceContext()) { result({std::move(decompressed), io_manager->GetSkiaUnrefQueue()}, std::move(flow)); return; } auto uploaded = UploadRasterImage(std::move(decompressed), io_manager, flow); if (!uploaded.get()) { FML_LOG(ERROR) << "Could not upload image to the GPU."; result({}, std::move(flow)); return; } // Finally, all done. result(std::move(uploaded), std::move(flow)); })); })); } fml::WeakPtr<ImageDecoder> ImageDecoder::GetWeakPtr() const { return weak_factory_.GetWeakPtr(); } } // namespace flutter
{ "content_hash": "4ffe6c7e4d044dec7500de950fd0d32a", "timestamp": "", "source": "github", "line_count": 386, "max_line_length": 80, "avg_line_length": 36.26424870466321, "alnum_prop": 0.5856550935847978, "repo_name": "mikejurka/engine", "id": "b730de7d66c352d172bf23e94bde3e16725f3e42", "size": "14391", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/ui/painting/image_decoder.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "2566" }, { "name": "C", "bytes": "32294" }, { "name": "C++", "bytes": "3408794" }, { "name": "CSS", "bytes": "64" }, { "name": "Dart", "bytes": "3292024" }, { "name": "Dockerfile", "bytes": "1557" }, { "name": "HTML", "bytes": "200" }, { "name": "Java", "bytes": "1057638" }, { "name": "JavaScript", "bytes": "28917" }, { "name": "Objective-C", "bytes": "244850" }, { "name": "Objective-C++", "bytes": "436465" }, { "name": "PowerShell", "bytes": "3086" }, { "name": "Python", "bytes": "145612" }, { "name": "Roff", "bytes": "55608" }, { "name": "Ruby", "bytes": "1571" }, { "name": "Shell", "bytes": "34904" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_101) on Sat Aug 20 05:42:14 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Solr 6.2.0 API</title> <script type="text/javascript"> targetPage = "" + window.location.search; if (targetPage != "" && targetPage != "undefined") targetPage = targetPage.substring(1); if (targetPage.indexOf(":") != -1 || (targetPage != "" && !validURL(targetPage))) targetPage = "undefined"; function validURL(url) { try { url = decodeURIComponent(url); } catch (error) { return false; } var pos = url.indexOf(".html"); if (pos == -1 || pos != url.length - 5) return false; var allowNumber = false; var allowSep = false; var seenDot = false; for (var i = 0; i < url.length - 5; i++) { var ch = url.charAt(i); if ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '$' || ch == '_' || ch.charCodeAt(0) > 127) { allowNumber = true; allowSep = true; } else if ('0' <= ch && ch <= '9' || ch == '-') { if (!allowNumber) return false; } else if (ch == '/' || ch == '.') { if (!allowSep) return false; allowNumber = false; allowSep = false; if (ch == '.') seenDot = true; if (ch == '/' && seenDot) return false; } else { return false; } } return true; } function loadFrames() { if (targetPage != "" && targetPage != "undefined") top.classFrame.location = top.targetPage; } </script> </head> <frameset cols="20%,80%" title="Documentation frame" onload="top.loadFrames()"> <frame src="allclasses-frame.html" name="packageFrame" title="All classes and interfaces (except non-static nested types)"> <frame src="overview-summary.html" name="classFrame" title="Package, class and interface descriptions" scrolling="yes"> <noframes> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <h2>Frame Alert</h2> <p>This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to <a href="overview-summary.html">Non-frame version</a>.</p> </noframes> </frameset> </html>
{ "content_hash": "37971dc825d6c55a81f8459a36c2614e", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 205, "avg_line_length": 38.18055555555556, "alnum_prop": 0.5121862495452892, "repo_name": "berkeleybop/bbop-manager-golr", "id": "df3a8d56f2d43964a96734f58e68a5ca32ef00b6", "size": "2749", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "solr/docs/solr-velocity/index.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AMPL", "bytes": "291" }, { "name": "Batchfile", "bytes": "59559" }, { "name": "CSS", "bytes": "454655" }, { "name": "HTML", "bytes": "74053220" }, { "name": "JavaScript", "bytes": "1565460" }, { "name": "Python", "bytes": "3829" }, { "name": "Shell", "bytes": "90362" }, { "name": "Web Ontology Language", "bytes": "1998135" }, { "name": "XSLT", "bytes": "124838" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd " > <bean id="sendSmsManager" class="org.esupportail.smsuapi.business.SendSmsManager"> <description>The business layer concerning the sending.</description> <property name="phoneNumberPattern" value="[ +0-9]*"/> <property name="defaultBroker" value="${sms.connector.name}"/> </bean> <bean id="statisticBuilder" class="org.esupportail.smsuapi.business.stats.StatisticBuilder"> </bean> <bean id="blackListManager" class="org.esupportail.smsuapi.business.BlackListManager"> </bean> <bean id="clientManager" class="org.esupportail.smsuapi.business.ClientManager"> </bean> <bean id="purgeSms" class="org.esupportail.smsuapi.business.purge.PurgeSms"> <property name="seniorityDay"> <value type="int">${purge.sms.seniorityDay}</value> </property> </bean> </beans>
{ "content_hash": "2805bee5b0c52ca429b86a85788b76b1", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 131, "avg_line_length": 32.114285714285714, "alnum_prop": 0.7072953736654805, "repo_name": "EsupPortail/esup-smsu-api", "id": "74b1dc0c1fdbc658924155156fc5861c0eb491dc", "size": "1124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/properties/business/business.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "359" }, { "name": "Java", "bytes": "202309" } ], "symlink_target": "" }
package gocb import ( "errors" "testing" ) func TestCollectionManagerCrud(t *testing.T) { if !globalCluster.SupportsFeature(CollectionsFeature) { t.Skip("Skipping test as collections not supported") } mgr := globalBucket.Collections() err := mgr.CreateScope("testScope", nil) if err != nil { t.Fatalf("Failed to create scope %v", err) } err = mgr.CreateScope("testScope", nil) if !errors.Is(err, ErrScopeExists) { t.Fatalf("Expected create scope to error with ScopeExists but was %v", err) } err = mgr.CreateCollection(CollectionSpec{ Name: "testCollection", ScopeName: "testScope", }, nil) if err != nil { t.Fatalf("Failed to create collection %v", err) } err = mgr.CreateCollection(CollectionSpec{ Name: "testCollection", ScopeName: "testScope", }, nil) if !errors.Is(err, ErrCollectionExists) { t.Fatalf("Expected create collection to error with CollectionExists but was %v", err) } scopes, err := mgr.GetAllScopes(nil) if err != nil { t.Fatalf("Failed to GetAllScopes %v", err) } if len(scopes) < 2 { t.Fatalf("Expected scopes to contain at least 2 scopes but was %v", scopes) } err = mgr.DropCollection(CollectionSpec{ Name: "testCollection", ScopeName: "testScope", }, nil) if err != nil { t.Fatalf("Expected DropCollection to not error but was %v", err) } err = mgr.DropScope("testScope", nil) if err != nil { t.Fatalf("Expected DropScope to not error but was %v", err) } }
{ "content_hash": "ded6a120ccaa95b5b7208db491f89211", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 87, "avg_line_length": 23.677419354838708, "alnum_prop": 0.6825613079019074, "repo_name": "brett19/gocb", "id": "08138656374b0e093d6a1f6368e53d52de1af814", "size": "1468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bucket_collectionsmgr_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "550794" }, { "name": "Makefile", "bytes": "907" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "7d6b82403b6bb7ed680b3a6a0166c047", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "d66f3e6f6d72447c38793649a6935e1b828107fe", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Strongylodon/Strongylodon crassifolius/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>euclidean-geometry: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.3 / euclidean-geometry - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> euclidean-geometry <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-09-29 23:37:41 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-29 23:37:41 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.5.3 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/euclidean-geometry&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/EuclideanGeometry&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: plane geometry&quot; &quot;keyword: Euclid&quot; &quot;keyword: ruler and compass&quot; &quot;category: Mathematics/Geometry/General&quot; ] authors: [ &quot;Jean Duprat &lt;Jean.Duprat@ens-lyon.fr&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/euclidean-geometry/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/euclidean-geometry.git&quot; synopsis: &quot;Basis of the Euclid&#39;s plane geometry&quot; description: &quot;&quot;&quot; This is a more recent version of the basis of Euclid&#39;s plane geometry, the previous version was the contribution intitled RulerCompassGeometry. The plane geometry is defined as a set of points, with two predicates : Clokwise for the orientation and Equidistant for the metric and three constructors, Ruler for the lines, Compass for the circles and Intersection for the points. For using it, we suggest to compile the files the name of which begin by a capital letter and a number from A1 to N7 in the lexicographic order and to keep modifiable the files of tacics (from Tactic1 to Tactic4) and the files of examples (Hilbert and Bolyai).&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/euclidean-geometry/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=d1341193f9fd7a8aa5c1d87ceda9ed61&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-euclidean-geometry.8.8.0 coq.8.5.3</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.3). The following dependencies couldn&#39;t be met: - coq-euclidean-geometry -&gt; coq &gt;= 8.8 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-euclidean-geometry.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "86d67891a265fd87182c6d187a2bfcf0", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 278, "avg_line_length": 45.662721893491124, "alnum_prop": 0.5683555785927173, "repo_name": "coq-bench/coq-bench.github.io", "id": "097c245eb9646e0890ab7225d17ddefd25b87858", "size": "7742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.5.3/euclidean-geometry/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package gnu.kawa.functions; import gnu.bytecode.*; import gnu.mapping.*; import gnu.expr.*; import gnu.kawa.reflect.*; import gnu.kawa.lispexpr.LangObjType; import gnu.lists.LList; import kawa.standard.Scheme; public class CompileMisc implements Inlineable { static final int CONVERT = 2; static final int NOT = 3; int code; Procedure proc; public CompileMisc(Procedure proc, int code) { this.proc = proc; this.code = code; } public static CompileMisc forConvert(Object proc) { return new CompileMisc((Procedure) proc, CONVERT); } public static CompileMisc forNot(Object proc) { return new CompileMisc((Procedure) proc, NOT); } public void compile (ApplyExp exp, Compilation comp, Target target) { switch (code) { case CONVERT: compileConvert((Convert) proc, exp, comp, target); return; case NOT: compileNot((Not) proc, exp, comp, target); return; default: throw new Error(); } } public static Expression validateApplyConstantFunction0 (ApplyExp exp, InlineCalls visitor, Type required, Procedure proc) { exp.visitArgs(visitor); int nargs = exp.getArgCount(); if (nargs != 0 && visitor != null) { String message = WrongArguments.checkArgCount(proc, nargs); return visitor.noteError(message); } return ((ConstantFunction0) proc).constant; } public static Expression validateApplyConvert (ApplyExp exp, InlineCalls visitor, Type required, Procedure proc) { Compilation comp = visitor.getCompilation(); Language language = comp.getLanguage(); Expression[] args = exp.getArgs(); if (args.length == 2) { args[0] = visitor.visit(args[0], null); Type type = language.getTypeFor(args[0]); if (type instanceof Type) { args[0] = new QuoteExp(type); args[1] = visitor.visit(args[1], type); CompileReflect.checkKnownClass(type, comp); exp.setType(type); return exp; } } exp.visitArgs(visitor); return exp; } public static Expression validateApplyNot (ApplyExp exp, InlineCalls visitor, Type required, Procedure proc) { exp.visitArgs(visitor); exp.setType(visitor.getCompilation().getLanguage().getTypeFor(Boolean.TYPE)); return exp.inlineIfConstant(proc, visitor); } /** Validate-apply handling for "format". * Sets the correct return-type, and may replace by call to a static method. */ public static Expression validateApplyFormat (ApplyExp exp, InlineCalls visitor, Type required, Procedure proc) { exp.visitArgs(visitor); Type retType = Type.objectType; Expression[] args = exp.getArgs(); if (args.length > 0) { ClassType typeFormat = ClassType.make("gnu.kawa.functions.Format"); Object f = args[0].valueIfConstant(); Type ftype = args[0].getType(); if (f == Boolean.FALSE || ftype.isSubtype(LangObjType.stringType)) { int skip = f == Boolean.FALSE ? 1 : 0; Expression[] xargs = new Expression[args.length+1-skip]; xargs[0] = new QuoteExp(Integer.valueOf(0), Type.intType); System.arraycopy(args, skip, xargs, 1, xargs.length-1); ApplyExp ae = new ApplyExp(typeFormat.getDeclaredMethod("formatToString", 2), xargs); ae.setType(Type.javalangStringType); return ae; } if (f == Boolean.TRUE || ftype.isSubtype(ClassType.make("java.io.Writer"))) { if (f == Boolean.TRUE) { Expression[] xargs = new Expression[args.length]; xargs[0] = QuoteExp.nullExp; System.arraycopy(args, 1, xargs, 1, args.length-1); args = xargs; } ApplyExp ae = new ApplyExp(typeFormat.getDeclaredMethod("formatToWriter", 3), args); ae.setType(Type.voidType); return ae; } if (ftype.isSubtype(ClassType.make("java.io.OutputStream"))) retType = Type.voidType; } exp.setType(retType); return null; } public static Expression validateApplyAppendValues (ApplyExp exp, InlineCalls visitor, Type required, Procedure proc) { exp.visitArgs(visitor); Expression[] args = exp.getArgs(); if (args.length == 1) return args[0]; if (args.length == 0) return QuoteExp.voidExp; Expression folded = exp.inlineIfConstant(proc, visitor); if (folded != exp) return folded; return exp; } public static Expression validateApplyMakeProcedure (ApplyExp exp, InlineCalls visitor, Type required, Procedure proc) { exp.visitArgs(visitor); Expression[] args = exp.getArgs(); int alen = args.length; Expression method = null; int countMethods = 0; String name = null; for (int i = 0; i < alen; i++) { Expression arg = args[i]; Object key; if (arg instanceof QuoteExp && (key = ((QuoteExp) arg).getValue()) instanceof Keyword) { String keyword = ((Keyword) key).getName(); Expression next = args[++i]; if (keyword == "name") { if (next instanceof QuoteExp) name = ((QuoteExp) next).getValue().toString(); } else if (keyword == "method") { countMethods++; method = next; } else ; // result.setProperty(keyword, value); } else { countMethods++; method = arg; } } if (countMethods == 1 && method instanceof LambdaExp) { LambdaExp lexp = (LambdaExp) method; for (int i = 0; i < alen; i++) { Expression arg = args[i]; Object key; if (arg instanceof QuoteExp && (key = ((QuoteExp) arg).getValue()) instanceof Keyword) { String keyword = ((Keyword) key).getName(); Expression next = args[++i]; if (keyword == "name") lexp.setName(name); else if (keyword == "method") ; else lexp.setProperty(Namespace.EmptyNamespace.getSymbol(keyword), next); } } return method; } return exp; } public static Expression validateApplyValuesMap (ApplyExp exp, InlineCalls visitor, Type required, Procedure proc) { exp.visitArgs(visitor); LambdaExp lexp = ValuesMap.canInline(exp, (ValuesMap) proc); if (lexp != null) { lexp.setInlineOnly(true); lexp.returnContinuation = exp; lexp.inlineHome = visitor.getCurrentLambda(); } return exp; } static gnu.bytecode.ClassType typeType; static gnu.bytecode.Method coerceMethod; public static void compileConvert (Convert proc, ApplyExp exp, Compilation comp, Target target) { Expression[] args = exp.getArgs(); if (args.length != 2) throw new Error ("wrong number of arguments to "+proc.getName()); CodeAttr code = comp.getCode(); Type type = Scheme.getTypeValue(args[0]); if (type != null) { args[1].compile(comp, Target.pushValue(type)); if (code.reachableHere()) target.compileFromStack(comp, type); } else { if (typeType == null) { typeType = ClassType.make("gnu.bytecode.Type"); } if (coerceMethod == null) { coerceMethod = typeType.addMethod("coerceFromObject", Compilation.apply1args, Type.pointer_type, gnu.bytecode.Access.PUBLIC); } args[0].compile(comp, LangObjType.typeClassType); args[1].compile(comp, Target.pushObject); code.emitInvokeVirtual(coerceMethod); target.compileFromStack(comp, Type.pointer_type); } } public void compileNot (Not proc, ApplyExp exp, Compilation comp, Target target) { Expression arg = exp.getArgs()[0]; Language language = proc.language; if (target instanceof ConditionalTarget) { ConditionalTarget ctarget = (ConditionalTarget) target; ConditionalTarget sub_target = new ConditionalTarget(ctarget.ifFalse, ctarget.ifTrue, language); sub_target.trueBranchComesFirst = ! ctarget.trueBranchComesFirst; arg.compile(comp, sub_target); return; } CodeAttr code = comp.getCode(); Type type = target.getType(); if (target instanceof StackTarget && type.getSignature().charAt(0) == 'Z') { arg.compile(comp, target); code.emitNot(target.getType()); } else { QuoteExp trueExp = QuoteExp.getInstance(language.booleanObject(true)); QuoteExp falseExp = QuoteExp.getInstance(language.booleanObject(false)); IfExp.compile(arg, falseExp, trueExp, comp, target); } } public static Expression validateApplyCallCC (ApplyExp exp, InlineCalls visitor, Type required, Procedure proc) { LambdaExp lexp = canInlineCallCC(exp); if (lexp != null) { lexp.setInlineOnly(true); lexp.returnContinuation = exp; lexp.inlineHome = visitor.getCurrentLambda(); Declaration contDecl = lexp.firstDecl(); if (! contDecl.getFlag(Declaration.TYPE_SPECIFIED)) contDecl.setType(typeContinuation); } exp.visitArgs(visitor); return exp; } public static final ClassType typeContinuation = ClassType.make("kawa.lang.Continuation"); public static void compileCallCC (ApplyExp exp, Compilation comp, Target target, Procedure proc) { LambdaExp lambda = canInlineCallCC(exp); if (lambda == null) { ApplyExp.compile(exp, comp, target); return; } CodeAttr code = comp.getCode(); final Declaration param = lambda.firstDecl(); if (param.isSimple() && ! param.getCanRead() && ! param.getCanWrite()) { CompileTimeContinuation contProxy = new CompileTimeContinuation(); Type rtype = target instanceof StackTarget ? target.getType() : null; boolean runFinallyBlocks = ExitThroughFinallyChecker.check(param, lambda.body); ExitableBlock bl = code.startExitableBlock(rtype, runFinallyBlocks); contProxy.exitableBlock = bl; contProxy.blockTarget = target; param.setValue(new QuoteExp(contProxy)); lambda.body.compile(comp, target); code.endExitableBlock(); return; } Scope sc = code.pushScope(); Variable contVar = sc.addVariable(code, typeContinuation, null); Declaration contDecl = new Declaration(contVar); code.emitNew(typeContinuation); code.emitDup(typeContinuation); comp.loadCallContext(); code.emitInvokeSpecial(typeContinuation.getDeclaredMethod("<init>", 1)); code.emitStore(contVar); code.emitTryStart(false, target instanceof IgnoreTarget || target instanceof ConsumerTarget ? null : Type.objectType); ApplyExp app = new ApplyExp(lambda, new Expression[] { new ReferenceExp(contDecl) }); app.compile(comp, target); // Emit: cont.invoked = true if (code.reachableHere()) { code.emitLoad(contVar); code.emitPushInt(1); code.emitPutField(typeContinuation.getField("invoked")); } code.emitTryEnd(); // Emit: catch (Throwable ex) { handleException$(ex, cont, ctx); } code.emitCatchStart(null); code.emitLoad(contVar); if (target instanceof ConsumerTarget) { comp.loadCallContext(); Method handleMethod = typeContinuation.getDeclaredMethod("handleException$X", 3); code.emitInvokeStatic(handleMethod); } else { Method handleMethod = typeContinuation.getDeclaredMethod("handleException", 2); code.emitInvokeStatic(handleMethod); target.compileFromStack(comp, Type.objectType); } code.emitCatchEnd(); code.emitTryCatchEnd(); code.popScope(); } /** If we can inline, return LambdaExp for first arg; otherwise null. */ private static LambdaExp canInlineCallCC (ApplyExp exp) { Expression[] args = exp.getArgs(); Expression arg0; if (args.length == 1 && (arg0 = args[0]) instanceof LambdaExp) { LambdaExp lexp = (LambdaExp) arg0; if (lexp.min_args == 1 && lexp.max_args == 1 && ! lexp.firstDecl().getCanWrite()) { return lexp; } } return null; } /** An ExpVisitor class to check if callcc exits through a try-finally. */ static class ExitThroughFinallyChecker extends ExpVisitor<Expression,TryExp> { Declaration decl; /** Does decl appear in body nested inside a try-finally? */ public static boolean check (Declaration decl, Expression body) { ExitThroughFinallyChecker visitor = new ExitThroughFinallyChecker(); visitor.decl = decl; visitor.visit(body, null); return visitor.exitValue != null; } protected Expression defaultValue(Expression r, TryExp d) { return r; } protected Expression visitReferenceExp (ReferenceExp exp, TryExp currentTry) { if (decl == exp.getBinding() && currentTry != null) exitValue = Boolean.TRUE; return exp; } protected Expression visitTryExp (TryExp exp, TryExp currentTry) { visitExpression(exp, exp.getFinallyClause() != null ? exp : currentTry); return exp; } } public static Expression validateApplyMap (ApplyExp exp, InlineCalls visitor, Type required, Procedure xproc) { Map mproc = (Map) xproc; boolean collect = mproc.collect; // FIXME: We should inline the list arguments first before inlining the // procedure argument, for better type inference etc. exp.visitArgs(visitor); Expression[] args = exp.getArgs(); int nargs = args.length; if (nargs < 2) return exp; // ERROR nargs--; Expression proc = args[0]; // If evaluating proc doesn't have side-effects, then we want to do // so inside loop, since that turns a "read" info a "call", which // may allow better inlining. boolean procSafeForMultipleEvaluation = ! proc.side_effects(); // First an outer (let ((%proc PROC)) L2), where PROC is args[0]. Expression[] inits1 = new Expression[1]; inits1[0] = proc; LetExp let1 = new LetExp(inits1); Declaration procDecl = let1.addDeclaration("%proc", Compilation.typeProcedure); procDecl.noteValue(args[0]); // Then an inner L2=(let ((%loop (lambda (argi ...) ...))) (%loop ...)) Expression[] inits2 = new Expression[1]; LetExp let2 = new LetExp(inits2); let1.setBody(let2); LambdaExp lexp = new LambdaExp(collect ? nargs + 1 : nargs); inits2[0] = lexp; Declaration loopDecl = let2.addDeclaration("%loop"); loopDecl.noteValue(lexp); // Finally an inner L3=(let ((parg1 (as <pair> arg1)) ...) ...) Expression[] inits3 = new Expression[nargs]; LetExp let3 = new LetExp(inits3); Declaration[] largs = new Declaration[nargs]; Declaration[] pargs = new Declaration[nargs]; for (int i = 0; i < nargs; i++) { String argName = "arg"+i; largs[i] = lexp.addDeclaration(argName); pargs[i] = let3.addDeclaration(argName, Compilation.typePair); inits3[i] = new ReferenceExp(largs[i]); pargs[i].noteValue(inits3[i]); } Declaration resultDecl = collect ? lexp.addDeclaration("result") : null; Expression[] doArgs = new Expression[1+nargs]; Expression[] recArgs = new Expression[collect ? nargs + 1 : nargs]; for (int i = 0; i < nargs; i++) { doArgs[i+1] = visitor.visitApplyOnly(SlotGet.makeGetField(new ReferenceExp(pargs[i]), "car"), null); recArgs[i] = visitor.visitApplyOnly(SlotGet.makeGetField(new ReferenceExp(pargs[i]), "cdr"), null); } if (! procSafeForMultipleEvaluation) proc = new ReferenceExp(procDecl); doArgs[0] = proc; Expression doit = visitor.visitApplyOnly(new ApplyExp(new ReferenceExp(mproc.applyFieldDecl), doArgs), null); if (collect) { Expression[] consArgs = new Expression[2]; consArgs[0] = doit; consArgs[1] = new ReferenceExp(resultDecl); recArgs[nargs] = Invoke.makeInvokeStatic(Compilation.typePair, "make", consArgs); } Expression rec = visitor.visitApplyOnly(new ApplyExp(new ReferenceExp(loopDecl), recArgs), null); lexp.body = collect ? rec : new BeginExp(doit, rec); let3.setBody(lexp.body); lexp.body = let3; Expression[] initArgs = new Expression[collect ? nargs + 1 : nargs]; QuoteExp empty = new QuoteExp(LList.Empty); for (int i = nargs; --i >= 0; ) { Expression[] compArgs = new Expression[2]; compArgs[0] = new ReferenceExp(largs[i]); compArgs[1] = empty; Expression result = collect ? (Expression) new ReferenceExp(resultDecl) : (Expression) QuoteExp.voidExp; lexp.body = new IfExp(visitor.visitApplyOnly(new ApplyExp(mproc.isEq, compArgs), null), result, lexp.body); initArgs[i] = args[i+1]; } if (collect) initArgs[nargs] = empty; Expression body = visitor.visitApplyOnly(new ApplyExp(new ReferenceExp(loopDecl), initArgs), null); if (collect) { Expression[] reverseArgs = new Expression[1]; reverseArgs[0] = body; body = Invoke.makeInvokeStatic(Compilation.scmListType, "reverseInPlace", reverseArgs); } let2.setBody(body); if (procSafeForMultipleEvaluation) return let2; else return let1; } }
{ "content_hash": "ca8f237162782edf1d52e02327c38b2d", "timestamp": "", "source": "github", "line_count": 535, "max_line_length": 122, "avg_line_length": 32.65046728971963, "alnum_prop": 0.6344744675978933, "repo_name": "thequixotic/ai2-kawa", "id": "4e803f091889795f7e2a881f077bf24175b1d856", "size": "17468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gnu/kawa/functions/CompileMisc.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "25294" }, { "name": "Common Lisp", "bytes": "814" }, { "name": "Emacs Lisp", "bytes": "264128" }, { "name": "HTML", "bytes": "17724" }, { "name": "Java", "bytes": "3992295" }, { "name": "KRL", "bytes": "223" }, { "name": "Scheme", "bytes": "815034" }, { "name": "Shell", "bytes": "29032" }, { "name": "XQuery", "bytes": "2330" }, { "name": "XSLT", "bytes": "889" } ], "symlink_target": "" }
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?android:attr/activatedBackgroundIndicator" android:fontFamily="sans-serif-light" android:gravity="center_vertical" android:minHeight="?android:attr/listPreferredItemHeightSmall" android:paddingLeft="16dp" android:paddingRight="16dp" android:textColor="#fff" android:textSize="24sp" />
{ "content_hash": "42c9f397872b3b53b5985f912d7f69aa", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 68, "avg_line_length": 43.583333333333336, "alnum_prop": 0.7437858508604207, "repo_name": "rushan-dev/Das-Musique", "id": "7712b6bb2346dfb5fab4f8bfcc800276def2f0c1", "size": "523", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/layout/drawer_list_item.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "24918" } ], "symlink_target": "" }
package socialite.util; import org.antlr.runtime.RecognitionException; import socialite.parser.Parser; public class ParseException extends RuntimeException { private static final long serialVersionUID = 1L; Parser p; int line; int pos; public ParseException(String _msg) { super(_msg); } public ParseException(Parser _p, RecognitionException _e, String _msg) { super(_msg); p = _p; line = _e.line-1; pos = _e.charPositionInLine; } public ParseException(Parser _p, int _line, int _pos, String _msg) { super(_msg); p = _p; line = _line; pos = _pos; } public void setParser(Parser p) { this.p = p; } public void setLine(int line) { this.line = line; } public void setPos(int pos) { this.pos = pos; } public int getLine() { return line; } public int getPos() { return pos; } public String compileErrorMsg() { assert p!=null; return p.generateErrorMsg(this); } }
{ "content_hash": "15bbd63f9f36687ee3483f10db3684dc", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 73, "avg_line_length": 22.675, "alnum_prop": 0.6835722160970231, "repo_name": "ofermend/medicare-demo", "id": "93827f9938117ddbd56e89d073ac910b464b3b4a", "size": "907", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "socialite/src/socialite/util/ParseException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GAP", "bytes": "35489" }, { "name": "Groff", "bytes": "21" }, { "name": "HTML", "bytes": "111577" }, { "name": "Java", "bytes": "2267927" }, { "name": "PigLatin", "bytes": "5097" }, { "name": "Python", "bytes": "10846103" }, { "name": "R", "bytes": "752" }, { "name": "Shell", "bytes": "30621" }, { "name": "Visual Basic", "bytes": "481" } ], "symlink_target": "" }
/* */ var arrayReduceRight = require('./_arrayReduceRight'), baseEachRight = require('./_baseEachRight'), baseIteratee = require('./_baseIteratee'), baseReduce = require('./_baseReduce'), isArray = require('./isArray'); function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } module.exports = reduceRight;
{ "content_hash": "bcf69b691e8bdf20c8510c0d003abd19", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 92, "avg_line_length": 43.833333333333336, "alnum_prop": 0.7129277566539924, "repo_name": "onlabsorg/olowc", "id": "e20f37bf65a2bad1bdd8b0898ea53c3a745ceca5", "size": "526", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "jspm_packages/npm/lodash@4.17.4/reduceRight.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2128" }, { "name": "JavaScript", "bytes": "2069038" }, { "name": "Makefile", "bytes": "188" }, { "name": "OCaml", "bytes": "485" }, { "name": "Shell", "bytes": "973" } ], "symlink_target": "" }
/** * New App Generator * ----------------- * Generates skeleton files needed to create a new SocketStream application */ 'use strict'; require('colors'); var fs = require('fs'), path = require('path'), log = console.log, dir_mode = '0755', // Private success = function(name, alternative) { return log(' ✓'.green, name, (alternative || '').grey); }, // TODO - investigate whether this would be better // using the async version of fs.mkdir - PJENSEN makeRootDirectory = function (name) { try { fs.mkdirSync(name, dir_mode); // Create the root directory return true; } catch (e) { if (e.code === 'EEXIST') { log('Sorry the \'' + name + '\' directory already exists. Please choose another name for your app.'); return false; } else { throw e; } } }; exports.generate = function(program) { var appjs, codeExtension = program.coffee && 'coffee' || 'js', selectedFormatters = [], name = program.args[1], source = path.join(__dirname, '../../new_project'), viewExtension = program.jade && 'jade' || 'html', styleExtension = '', mods = [], packagejs = '', clientFiles = { css: [], code: [] }, /** * [mkdir description] * @param {String} dir Directory path to create * @return {Boolean} True if directory successfully created */ mkdir = function(dir) { return fs.mkdirSync(path.join(name, dir), dir_mode); }, /** * Copy files/directories * @param {[String} src Copy From directory * @param {[String} dest Copy To directory * @return {Object} Stream object */ cp = function(src, dest) { var destination = path.join(name, dest || src), read = fs.createReadStream(path.join(source, src)), write = fs.createWriteStream(destination); return read.pipe(write); }, /** * Writes content to the file * @param {String} fileName The filepath to write to * @param {[type]} content Content string * @return {Boolean} */ write = function(fileName, content) { return fs.writeFileSync(path.join(name, fileName), content, 'utf8'); }; /* Check for application name existing */ if (name === void 0) { return log('Please provide a name for your application: $> socketstream new <MyAppName>'); } /* Select stylesheet language */ if (program.less) { styleExtension = 'less'; } else if (program.stylus) { styleExtension = 'styl'; } else { styleExtension = 'css'; } /* Select formatters for file extensions */ if (makeRootDirectory(name)) { ['coffee', 'jade', 'less', 'stylus'].forEach(function(formatter) { if (program[formatter]) { return selectedFormatters.push(formatter); } }); /* Create essential directories */ mkdir('/client'); mkdir('/client/code'); mkdir('/client/code/app'); mkdir('/client/code/libs'); mkdir('/client/views'); mkdir('/client/css'); mkdir('/client/css/libs'); mkdir('/client/templates'); mkdir('/client/static'); mkdir('/client/static/images'); mkdir('/server'); mkdir('/server/rpc'); mkdir('/server/middleware'); /* Copy essential files */ cp('/scm_ignore_file', '/.gitignore'); cp('/node_monitor_ignore_file', '/.nodemonignore'); cp('/README.md'); cp('/client/static/favicon.ico'); cp('/client/code/libs/jquery.min.js'); cp('/client/code/app/entry.' + codeExtension); clientFiles.code.push('libs/jquery.min.js'); clientFiles.code.push('app'); /* Install chat demo files */ if (program.minimal) { cp('/client/views/app.minimal.' + viewExtension, '/client/views/app.' + viewExtension); cp('/client/code/app/app.minimal.' + codeExtension, '/client/code/app/app.' + codeExtension); cp('/client/css/app.minimal.' + styleExtension, '/client/css/app.' + styleExtension); cp('/server/rpc/.gitkeep'); cp('/server/middleware/.gitkeep'); cp('/client/templates/.gitkeep'); clientFiles.css.push('app.' + styleExtension); } else { cp('/client/static/images/logo.png'); cp('/client/code/app/app.demo.' + codeExtension, '/client/code/app/app.' + codeExtension); cp('/server/middleware/example.' + codeExtension); cp('/server/rpc/demo.' + codeExtension); cp('/client/css/libs/reset.css'); cp('/client/css/app.demo.' + styleExtension, '/client/css/app.' + styleExtension); mkdir('/client/templates/chat'); cp('/client/templates/chat/message.' + viewExtension); cp('/client/views/app.demo.' + viewExtension, '/client/views/app.' + viewExtension); clientFiles.css.push('libs/reset.css'); clientFiles.css.push('app.' + styleExtension); } /* Generate app.js */ appjs = '// My SocketStream 0.3 app\n\nvar http = require(\'http\'),\n ss = require(\'socketstream\');\n\n// Define a single-page client called \'main\'\nss.client.define(\'main\', {\n view: \'app.' + viewExtension + '\',\n css: [\'' + (clientFiles.css.join('\', \'')) + '\'],\n code: [\'' + (clientFiles.code.join('\', \'')) + '\'],\n tmpl: \'*\'\n});\n\n// Serve this client on the root URL\nss.http.route(\'/\', function(req, res){\n res.serveClient(\'main\');\n});\n'; /* List any selected formatters */ if (selectedFormatters.length > 0) { appjs += '\n// Code Formatters\n'; } selectedFormatters.forEach(function (name) { return appjs += 'ss.client.formatters.add(require(\'ss-' + name + '\'));\n'; }); appjs += '\n// Use server-side compiled Hogan (Mustache) templates. Others engines available\nss.client.templateEngine.use(require(\'ss-hogan\'));\n\n// Minimize and pack assets if you type: SS_ENV=production node app.js\nif (ss.env === \'production\') ss.client.packAssets();\n\n// Start web server\nvar server = http.Server(ss.http.middleware);\nserver.listen(3000);\n'; if (program.repl) { appjs += '\n// Start Console Server (REPL)\n// To install client: sudo npm install -g ss-console\n// To connect: ss-console <optional_host_or_port>\nvar consoleServer = require(\'ss-console\')(ss);\nconsoleServer.listen(5000);\n'; } appjs += '\n// Start SocketStream\nss.start(server);'; write('/app.js', appjs); /* Generate package.json */ packagejs = '{\n "name": "' + name + '",\n "description": "An awesome real time application",\n "version": "0.0.1",\n "author": "Me <me@mydomain.com>",\n "private": true,\n "engines": { "node": ">= 0.10.0" },\n "dependencies": {\n'; packagejs += ' "socketstream": "0.3.x"'; mods = selectedFormatters.concat(['hogan']); if (program.repl) { mods.push('console'); } mods.forEach(function (name) { return packagejs += ',\n "ss-' + name + '": "0.1.x"'; }); packagejs += '\n },\n "scripts":{\n "start":"node app.js"\n }\n}'; write('/package.json', packagejs); /* Show finish text */ log(('Success! Created app \'' + name + '\' with:').yellow); if (program.minimal) { success('Minimal install (no demo)'); } else { success('Basic chat demo', '(-m for minimal install)'); } if (program.coffee) { success('CoffeeScript example code'); } else { success('Javascript example code', '(-c if you prefer CoffeeScript)'); } if (program.jade) { success('Jade for views'); } else { success('Plain HTML for views', '(-j if you prefer Jade)'); } if (program.less) { success('Less for CSS'); } else if (program.stylus) { success('Stylus for CSS') } else { success('Plain CSS', '(-s if you prefer Stylus, -l for Less)'); } /* Add the REPL if selected */ if (program.repl) { success('Console Server / REPL'); } log('Next, run the following commands:'.yellow); log(' cd ' + name); log(' [sudo] npm install'); log('To start your app:'.yellow); log(' node app.js'); } };
{ "content_hash": "45c17402ad0d7bf4233e7f9f072eeb1b", "timestamp": "", "source": "github", "line_count": 226, "max_line_length": 485, "avg_line_length": 36.60619469026549, "alnum_prop": 0.5760908981022603, "repo_name": "ListnPlay/socketstream", "id": "5bfe2797da87c79dbcf56967656c6d55697f51a6", "size": "8275", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/cli/generate.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10192" }, { "name": "CoffeeScript", "bytes": "2671" }, { "name": "HTML", "bytes": "1875" }, { "name": "JavaScript", "bytes": "309960" } ], "symlink_target": "" }
using System.ComponentModel.DataAnnotations; namespace SimplCommerce.Module.Catalog.ViewModels { public class BrandForm { public BrandForm() { IsPublished = true; } public long Id { get; set; } [Required] public string Name { get; set; } public bool IsPublished { get; set; } } }
{ "content_hash": "6e2f0f7d396118431f42437ce6bc0bcf", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 49, "avg_line_length": 19.210526315789473, "alnum_prop": 0.5753424657534246, "repo_name": "johnfosborneiii/SimplCommerceSQLServerRHEL", "id": "01a4e80629350d624dd0fe94e6b67cb960c5673b", "size": "367", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Modules/SimplCommerce.Module.Catalog/ViewModels/BrandForm.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "550425" }, { "name": "CSS", "bytes": "715341" }, { "name": "HTML", "bytes": "69496" }, { "name": "JavaScript", "bytes": "831816" }, { "name": "Shell", "bytes": "2614" } ], "symlink_target": "" }
 using System; namespace PageOfBob.NFountain.PDF { internal class NextLine : TextCommand { } }
{ "content_hash": "22594b3249516ca6854a66bf133747d3", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 42, "avg_line_length": 12.375, "alnum_prop": 0.7373737373737373, "repo_name": "mrdrbob/NFountain", "id": "aee36e49ec07f01596e2fe7062b3fc44e66e0ec6", "size": "702", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/PDF/PDF/NextLine.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "134631" } ], "symlink_target": "" }
using System.Collections.Generic; using Free.FileFormats.VRML.Fields; using Free.FileFormats.VRML.Interfaces; namespace Free.FileFormats.VRML.Nodes { /// <summary> /// The Polyline2D node specifies a series of contiguous line segments /// in the local 2D coordinate system connecting the specified vertices. /// </summary> public class x3dPolyline2D : X3DNode, X3DGeometryNode { public List<SFVec2f> LineSegments { get; set; } public x3dPolyline2D() { LineSegments=new List<SFVec2f>(); } internal override X3DPrototypeInstance GetProto() { return new x3dPolyline2DPROTO(); } internal override bool ParseNodeBodyElement(string id, VRMLParser parser) { if(id=="lineSegments") LineSegments.AddRange(parser.ParseSFVec2fOrMFVec2fValue()); else return false; return true; } } }
{ "content_hash": "348d955db462b702f4bd1f9ce1e0b915", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 88, "avg_line_length": 28, "alnum_prop": 0.75, "repo_name": "shintadono/Free.FileFormats.VRML", "id": "6c8e778e5a766edf5615199a4c5b706dab4e35af", "size": "814", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "14 Geometry2D/x3dPolyline2D.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "626596" } ], "symlink_target": "" }
package tv.baokan.baokanandroid.ui.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import tv.baokan.baokanandroid.R; import tv.baokan.baokanandroid.model.UserBean; import tv.baokan.baokanandroid.utils.ProgressHUD; import tv.baokan.baokanandroid.widget.NavigationViewRed; public class UserInfoActivity extends BaseActivity implements View.OnClickListener { private NavigationViewRed mNavigationViewRed; private SimpleDraweeView mPortraitImageView; private TextView mUsernameTextView; private TextView mGroupNameTextView; private TextView mPointsTextView; private View mModifyInfoLayout; private View mModifySafeInfoLayout; private TextView mRegisterTimeTextView; private TextView mMyPointsTextView; private TextView mMyGroupNameTextView; private Button mLogoutButton; private AlertDialog mLogoutDialog; /** * 便捷启动当前activity * * @param activity 启动当前activity的activity */ public static void start(Activity activity) { Intent intent = new Intent(activity, UserInfoActivity.class); activity.startActivity(intent); activity.overridePendingTransition(R.anim.push_enter, R.anim.push_exit); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_info); prepareUI(); prepareData(); } /** * 准备UI */ private void prepareUI() { mNavigationViewRed = (NavigationViewRed) findViewById(R.id.nav_user_info); mPortraitImageView = (SimpleDraweeView) findViewById(R.id.sdv_user_info_portrait); mUsernameTextView = (TextView) findViewById(R.id.tv_user_info_username); mGroupNameTextView = (TextView) findViewById(R.id.tv_user_info_groupname); mPointsTextView = (TextView) findViewById(R.id.tv_user_info_points); mModifyInfoLayout = findViewById(R.id.rl_user_info_modify_info_layout); mModifySafeInfoLayout = findViewById(R.id.rl_user_info_modify_safe_info_layout); mRegisterTimeTextView = (TextView) findViewById(R.id.tv_user_info_registertime); mMyPointsTextView = (TextView) findViewById(R.id.tv_user_info_mypoints); mMyGroupNameTextView = (TextView) findViewById(R.id.tv_user_info_mygroupname); mLogoutButton = (Button) findViewById(R.id.btn_user_info_logout); mNavigationViewRed.setupNavigationView(true, false, "我的资料", new NavigationViewRed.OnClickListener() { @Override public void onBackClick(View v) { finish(); } }); mModifyInfoLayout.setOnClickListener(this); mModifySafeInfoLayout.setOnClickListener(this); mLogoutButton.setOnClickListener(this); } /** * 准备页面数据 */ private void prepareData() { mPortraitImageView.setImageURI(UserBean.shared().getAvatarUrl()); mUsernameTextView.setText(UserBean.shared().getUsername()); mGroupNameTextView.setText("等级:" + UserBean.shared().getGroupName()); mPointsTextView.setText(UserBean.shared().getPoints() + "积分"); mRegisterTimeTextView.setText(UserBean.shared().getRegisterTime()); mMyPointsTextView.setText(UserBean.shared().getPoints()); mMyGroupNameTextView.setText(UserBean.shared().getGroupName()); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.rl_user_info_modify_info_layout: ModifyInfoActivity.start(mContext); break; case R.id.rl_user_info_modify_safe_info_layout: ModifySafeInfoActivity.start(mContext); break; case R.id.btn_user_info_logout: showLogoutDialog(); break; } } /** * 询问用户是否要退出 */ private void showLogoutDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setCancelable(true); builder.setTitle("您确定要退出登录吗?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mLogoutDialog.dismiss(); logout(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mLogoutDialog.dismiss(); } }); mLogoutDialog = builder.create(); mLogoutDialog.show(); } /** * 注销登录 */ private void logout() { UserBean.shared().logout(); ProgressHUD.showInfo(mContext, "退出成功"); finish(); } }
{ "content_hash": "b4ae07c3d602e6290a452a79fc2295d7", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 109, "avg_line_length": 35.179310344827584, "alnum_prop": 0.6683003332679867, "repo_name": "6ag/BaoKanAndroid", "id": "9f288ca49f4d15b4b002be863735c8c49e5c770d", "size": "5219", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/tv/baokan/baokanandroid/ui/activity/UserInfoActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "601" }, { "name": "HTML", "bytes": "23918" }, { "name": "Java", "bytes": "509325" }, { "name": "JavaScript", "bytes": "1515" } ], "symlink_target": "" }
""" The central management of Ryu applications. - Load Ryu applications - Provide `contexts` to Ryu applications - Route messages among Ryu applications """ import inspect import itertools import logging import sys import os from ryu import cfg from ryu import utils from ryu.app import wsgi from ryu.controller.handler import register_instance, get_dependent_services from ryu.controller.controller import Datapath from ryu.controller import event from ryu.controller.event import EventRequestBase, EventReplyBase from ryu.lib import hub from ryu.ofproto import ofproto_protocol LOG = logging.getLogger('ryu.base.app_manager') SERVICE_BRICKS = {} def lookup_service_brick(name): # LOG.info('lookup_service_brick %s', name) return SERVICE_BRICKS.get(name) def _lookup_service_brick_by_ev_cls(ev_cls): return _lookup_service_brick_by_mod_name(ev_cls.__module__) def _lookup_service_brick_by_mod_name(mod_name): return lookup_service_brick(mod_name.split('.')[-1]) def register_app(app): assert isinstance(app, RyuApp) # print "SERVICE_BRICKS:", SERVICE_BRICKS assert app.name not in SERVICE_BRICKS SERVICE_BRICKS[app.name] = app register_instance(app) def unregister_app(app): SERVICE_BRICKS.pop(app.name) def require_app(app_name, api_style=False): """ Request the application to be automatically loaded. If this is used for "api" style modules, which is imported by a client application, set api_style=True. If this is used for client application module, set api_style=False. """ if api_style: frm = inspect.stack()[2] # skip a frame for "api" module else: frm = inspect.stack()[1] m = inspect.getmodule(frm[0]) # client module m._REQUIRED_APP = getattr(m, '_REQUIRED_APP', []) m._REQUIRED_APP.append(app_name) LOG.debug('require_app: %s is required by %s', app_name, m.__name__) class RyuApp(object): """ The base class for Ryu applications. RyuApp subclasses are instantiated after ryu-manager loaded all requested Ryu application modules. __init__ should call RyuApp.__init__ with the same arguments. It's illegal to send any events in __init__. The instance attribute 'name' is the name of the class used for message routing among Ryu applications. (Cf. send_event) It's set to __class__.__name__ by RyuApp.__init__. It's discouraged for subclasses to override this. """ _CONTEXTS = {} """ A dictionary to specify contexts which this Ryu application wants to use. Its key is a name of context and its value is an ordinary class which implements the context. The class is instantiated by app_manager and the instance is shared among RyuApp subclasses which has _CONTEXTS member with the same key. A RyuApp subclass can obtain a reference to the instance via its __init__'s kwargs as the following. Example:: _CONTEXTS = { 'network': network.Network } def __init__(self, *args, *kwargs): self.network = kwargs['network'] """ _EVENTS = [] """ A list of event classes which this RyuApp subclass would generate. This should be specified if and only if event classes are defined in a different python module from the RyuApp subclass is. """ OFP_VERSIONS = None """ A list of supported OpenFlow versions for this RyuApp. The default is all versions supported by the framework. Examples:: OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION, ofproto_v1_2.OFP_VERSION] If multiple Ryu applications are loaded in the system, the intersection of their OFP_VERSIONS is used. """ @classmethod def context_iteritems(cls): """ Return iterator over the (key, contxt class) of application context """ return cls._CONTEXTS.iteritems() def __init__(self, *_args, **_kwargs): super(RyuApp, self).__init__() self.name = self.__class__.__name__ self.event_handlers = {} # ev_cls -> handlers:list self.observers = {} # ev_cls -> observer-name -> states:set self.threads = [] self.events = hub.Queue(128) if hasattr(self.__class__, 'LOGGER_NAME'): self.logger = logging.getLogger(self.__class__.LOGGER_NAME) else: self.logger = logging.getLogger(self.name) self.CONF = cfg.CONF # prevent accidental creation of instances of this class outside RyuApp class _EventThreadStop(event.EventBase): pass self._event_stop = _EventThreadStop() self.is_active = True def start(self): """ Hook that is called after startup initialization is done. """ self.threads.append(hub.spawn(self._event_loop)) def stop(self): self.is_active = False self._send_event(self._event_stop, None) hub.joinall(self.threads) def register_handler(self, ev_cls, handler): assert callable(handler) self.event_handlers.setdefault(ev_cls, []) self.event_handlers[ev_cls].append(handler) def unregister_handler(self, ev_cls, handler): assert callable(handler) self.event_handlers[ev_cls].remove(handler) if not self.event_handlers[ev_cls]: del self.event_handlers[ev_cls] def register_observer(self, ev_cls, name, states=None): states = states or set() ev_cls_observers = self.observers.setdefault(ev_cls, {}) ev_cls_observers.setdefault(name, set()).update(states) def unregister_observer(self, ev_cls, name): observers = self.observers.get(ev_cls, {}) observers.pop(name) def unregister_observer_all_event(self, name): for observers in self.observers.values(): observers.pop(name, None) def observe_event(self, ev_cls, states=None): brick = _lookup_service_brick_by_ev_cls(ev_cls) if brick is not None: brick.register_observer(ev_cls, self.name, states) def unobserve_event(self, ev_cls): brick = _lookup_service_brick_by_ev_cls(ev_cls) if brick is not None: brick.unregister_observer(ev_cls, self.name) def get_handlers(self, ev, state=None): """Returns a list of handlers for the specific event. :param ev: The event to handle. :param state: The current state. ("dispatcher") If None is given, returns all handlers for the event. Otherwise, returns only handlers that are interested in the specified state. The default is None. """ ev_cls = ev.__class__ handlers = self.event_handlers.get(ev_cls, []) if state is None: return handlers def test(h): if not hasattr(h, 'callers') or ev_cls not in h.callers: # dynamically registered handlers does not have # h.callers element for the event. return True states = h.callers[ev_cls].dispatchers if not states: # empty states means all states return True return state in states return filter(test, handlers) def get_observers(self, ev, state): observers = [] for k, v in self.observers.get(ev.__class__, {}).iteritems(): if not state or not v or state in v: observers.append(k) return observers def send_request(self, req): """ Make a synchronous request. Set req.sync to True, send it to a Ryu application specified by req.dst, and block until receiving a reply. Returns the received reply. The argument should be an instance of EventRequestBase. """ assert isinstance(req, EventRequestBase) req.sync = True req.reply_q = hub.Queue() self.send_event(req.dst, req) # going to sleep for the reply return req.reply_q.get() def _event_loop(self): while self.is_active or not self.events.empty(): ev, state = self.events.get() if ev == self._event_stop: continue handlers = self.get_handlers(ev, state) for handler in handlers: handler(ev) def _send_event(self, ev, state): self.events.put((ev, state)) def send_event(self, name, ev, state=None): """ Send the specified event to the RyuApp instance specified by name. """ if name in SERVICE_BRICKS: if isinstance(ev, EventRequestBase): ev.src = self.name LOG.debug("EVENT %s->%s %s" % (self.name, name, ev.__class__.__name__)) SERVICE_BRICKS[name]._send_event(ev, state) else: LOG.debug("EVENT LOST %s->%s %s" % (self.name, name, ev.__class__.__name__)) def send_event_to_observers(self, ev, state=None): """ Send the specified event to all observers of this RyuApp. """ for observer in self.get_observers(ev, state): self.send_event(observer, ev, state) def reply_to_request(self, req, rep): """ Send a reply for a synchronous request sent by send_request. The first argument should be an instance of EventRequestBase. The second argument should be an instance of EventReplyBase. """ assert isinstance(req, EventRequestBase) assert isinstance(rep, EventReplyBase) rep.dst = req.src if req.sync: req.reply_q.put(rep) else: self.send_event(rep.dst, rep) def close(self): """ teardown method. The method name, close, is chosen for python context manager """ pass class AppManager(object): # singletone _instance = None @staticmethod def run_apps(app_lists): """Run a set of Ryu applications A convenient method to load and instantiate apps. This blocks until all relevant apps stop. """ app_mgr = AppManager.get_instance() app_mgr.load_apps(app_lists) contexts = app_mgr.create_contexts() services = app_mgr.instantiate_apps(**contexts) webapp = wsgi.start_service(app_mgr) if webapp: services.append(hub.spawn(webapp)) try: hub.joinall(services) finally: app_mgr.close() @staticmethod def get_instance(): if not AppManager._instance: AppManager._instance = AppManager() return AppManager._instance def __init__(self): self.applications_cls = {} self.applications = {} self.contexts_cls = {} self.contexts = {} def load_app(self, name): mod = utils.import_module(name) clses = inspect.getmembers(mod, lambda cls: (inspect.isclass(cls) and issubclass(cls, RyuApp) and mod.__name__ == cls.__module__)) if clses: return clses[0][1] return None def load_apps(self, app_lists): app_lists = [app for app in itertools.chain.from_iterable(app.split(',') for app in app_lists)] while len(app_lists) > 0: app_cls_name = app_lists.pop(0) context_modules = map(lambda x: x.__module__, self.contexts_cls.values()) if app_cls_name in context_modules: continue LOG.info('loading app %s', app_cls_name) cls = self.load_app(app_cls_name) if cls is None: continue self.applications_cls[app_cls_name] = cls services = [] for key, context_cls in cls.context_iteritems(): v = self.contexts_cls.setdefault(key, context_cls) assert v == context_cls context_modules.append(context_cls.__module__) if issubclass(context_cls, RyuApp): services.extend(get_dependent_services(context_cls)) # we can't load an app that will be initiataed for # contexts. for i in get_dependent_services(cls): if i not in context_modules: services.append(i) if services: app_lists.extend([s for s in set(services) if s not in app_lists]) def create_contexts(self): for key, cls in self.contexts_cls.items(): if issubclass(cls, RyuApp): # hack for dpset context = self._instantiate(None, cls) else: context = cls() LOG.info('creating context %s', key) assert key not in self.contexts self.contexts[key] = context return self.contexts def _update_bricks(self): for i in SERVICE_BRICKS.values(): for _k, m in inspect.getmembers(i, inspect.ismethod): if not hasattr(m, 'callers'): continue for ev_cls, c in m.callers.iteritems(): if not c.ev_source: continue brick = _lookup_service_brick_by_mod_name(c.ev_source) if brick: brick.register_observer(ev_cls, i.name, c.dispatchers) # allow RyuApp and Event class are in different module for brick in SERVICE_BRICKS.itervalues(): if ev_cls in brick._EVENTS: brick.register_observer(ev_cls, i.name, c.dispatchers) @staticmethod def _report_brick(name, app): LOG.debug("BRICK %s" % name) for ev_cls, list_ in app.observers.items(): LOG.debug(" PROVIDES %s TO %s" % (ev_cls.__name__, list_)) for ev_cls in app.event_handlers.keys(): LOG.debug(" CONSUMES %s" % (ev_cls.__name__,)) @staticmethod def report_bricks(): for brick, i in SERVICE_BRICKS.items(): AppManager._report_brick(brick, i) def _instantiate(self, app_name, cls, *args, **kwargs): # for now, only single instance of a given module # Do we need to support multiple instances? # Yes, maybe for slicing. #LOG.info('instantiating app %s of %s', app_name, cls.__name__) if hasattr(cls, 'OFP_VERSIONS') and cls.OFP_VERSIONS is not None: ofproto_protocol.set_app_supported_versions(cls.OFP_VERSIONS) if app_name is not None: assert app_name not in self.applications app = cls(*args, **kwargs) register_app(app) assert app.name not in self.applications self.applications[app.name] = app return app def instantiate(self, cls, *args, **kwargs): app = self._instantiate(None, cls, *args, **kwargs) self._update_bricks() self._report_brick(app.name, app) return app def instantiate_apps(self, *args, **kwargs): for app_name, cls in self.applications_cls.items(): self._instantiate(app_name, cls, *args, **kwargs) self._update_bricks() self.report_bricks() threads = [] for app in self.applications.values(): t = app.start() if t is not None: threads.append(t) return threads @staticmethod def _close(app): close_method = getattr(app, 'close', None) if callable(close_method): close_method() def uninstantiate(self, name): app = self.applications.pop(name) unregister_app(app) for app_ in SERVICE_BRICKS.values(): app_.unregister_observer_all_event(name) app.stop() self._close(app) events = app.events if not events.empty(): app.logger.debug('%s events remians %d', app.name, events.qsize()) def close(self): def close_all(close_dict): for app in close_dict.values(): self._close(app) close_dict.clear() close_all(self.applications) close_all(self.contexts)
{ "content_hash": "a9b7a6a1a4ddbeaedfddfd863d234a56", "timestamp": "", "source": "github", "line_count": 503, "max_line_length": 79, "avg_line_length": 33.216699801192846, "alnum_prop": 0.5755925305242997, "repo_name": "muzixing/ryu", "id": "4a1b9961f1aa3acb809d7813feee8332b87add36", "size": "17390", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ryu/base/app_manager.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "410" }, { "name": "CSS", "bytes": "7182" }, { "name": "Erlang", "bytes": "872692" }, { "name": "HTML", "bytes": "4612" }, { "name": "JavaScript", "bytes": "46535" }, { "name": "Makefile", "bytes": "88" }, { "name": "Python", "bytes": "5236694" }, { "name": "Shell", "bytes": "15461" } ], "symlink_target": "" }
<!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_80) on Thu Oct 15 19:28:08 UTC 2015 --> <title>WorkspaceState (AWS SDK for Java - 1.10.27)</title> <meta name="date" content="2015-10-15"> <link rel="stylesheet" type="text/css" href="../../../../../JavaDoc.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="WorkspaceState (AWS SDK for Java - 1.10.27)"; } //--> </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="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <!-- Scripts for Syntax Highlighter START--> <script id="syntaxhighlight_script_core" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shCore.js"> </script> <script id="syntaxhighlight_script_java" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shBrushJava.js"> </script> <link id="syntaxhighlight_css_core" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shCoreDefault.css"/> <link id="syntaxhighlight_css_theme" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shThemeDefault.css"/> <!-- Scripts for Syntax Highlighter END--> <div> <!-- BEGIN-SECTION --> <div id="divsearch" style="float:left;"> <span id="lblsearch" for="searchQuery"> <label>Search</label> </span> <form id="nav-search-form" target="_parent" method="get" action="http://docs.aws.amazon.com/search/doc-search.html#facet_doc_guide=API+Reference&facet_doc_product=AWS+SDK+for+Java"> <div id="nav-searchfield-outer" class="nav-sprite"> <div class="nav-searchfield-inner nav-sprite"> <div id="nav-searchfield-width"> <input id="nav-searchfield" name="searchQuery"> </div> </div> </div> <div id="nav-search-button" class="nav-sprite"> <input alt="" id="nav-search-button-inner" type="image"> </div> <input name="searchPath" type="hidden" value="documentation-guide" /> <input name="this_doc_product" type="hidden" value="AWS SDK for Java" /> <input name="this_doc_guide" type="hidden" value="API Reference" /> <input name="doc_locale" type="hidden" value="en_us" /> </form> </div> <!-- END-SECTION --> <!-- BEGIN-FEEDBACK-SECTION --> <div id="feedback-section"> <h3>Did this page help you?</h3> <div id="feedback-link-sectioin"> <a id="feedback_yes" target="_blank" style="display:inline;">Yes</a>&nbsp;&nbsp; <a id="feedback_no" target="_blank" style="display:inline;">No</a>&nbsp;&nbsp; <a id="go_cti" target="_blank" style="display:inline;">Tell us about it...</a> </div> </div> <script type="text/javascript"> window.onload = function(){ /* Dynamically add feedback links */ var javadoc_root_name = "/javadoc/"; var javadoc_path = location.href.substring(0, location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var file_path = location.href.substring(location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var feedback_yes_url = javadoc_path + "javadoc-resources/feedbackyes.html?topic_id="; var feedback_no_url = javadoc_path + "javadoc-resources/feedbackno.html?topic_id="; var feedback_tellmore_url = "https://aws-portal.amazon.com/gp/aws/html-forms-controller/documentation/aws_doc_feedback_04?service_name=Java-Ref&file_name="; if(file_path != "overview-frame.html") { var file_name = file_path.replace(/[/.]/g, '_'); document.getElementById("feedback_yes").setAttribute("href", feedback_yes_url + file_name); document.getElementById("feedback_no").setAttribute("href", feedback_no_url + file_name); document.getElementById("go_cti").setAttribute("href", feedback_tellmore_url + file_name); } else { // hide the search box and the feeback links in overview-frame page, // show "AWS SDK for Java" instead. document.getElementById("feedback-section").outerHTML = "AWS SDK for Java"; document.getElementById("divsearch").outerHTML = ""; } }; </script> <!-- END-FEEDBACK-SECTION --> </div> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceRequest.html" title="class in com.amazonaws.services.workspaces.model"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/amazonaws/services/workspaces/model/WorkspaceState.html" target="_top">Frames</a></li> <li><a href="WorkspaceState.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><a href="#enum_constant_summary">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#enum_constant_detail">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&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">com.amazonaws.services.workspaces.model</div> <h2 title="Enum WorkspaceState" class="title">Enum WorkspaceState</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.lang.Enum&lt;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a>&gt;</li> <li> <ul class="inheritance"> <li>com.amazonaws.services.workspaces.model.WorkspaceState</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, java.lang.Comparable&lt;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a>&gt;</dd> </dl> <hr> <br> <pre>public enum <span class="strong">WorkspaceState</span> extends java.lang.Enum&lt;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a>&gt;</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="enum_constant_summary"> <!-- --> </a> <h3>Enum Constant Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation"> <caption><span>Enum Constants</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Enum Constant and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#AVAILABLE">AVAILABLE</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#ERROR">ERROR</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#IMPAIRED">IMPAIRED</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#PENDING">PENDING</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#REBOOTING">REBOOTING</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#REBUILDING">REBUILDING</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#SUSPENDED">SUSPENDED</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#TERMINATED">TERMINATED</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#TERMINATING">TERMINATING</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#UNHEALTHY">UNHEALTHY</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== 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>static <a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#fromValue(java.lang.String)">fromValue</a></strong>(java.lang.String&nbsp;value)</code> <div class="block">Use this in place of valueOf.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#toString()">toString</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String&nbsp;name)</code> <div class="block">Returns the enum constant of this type with the specified name.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a>[]</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html#values()">values</a></strong>()</code> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Enum"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Enum</h3> <code>compareTo, equals, getDeclaringClass, hashCode, name, ordinal, valueOf</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ ENUM CONSTANT DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="enum_constant_detail"> <!-- --> </a> <h3>Enum Constant Detail</h3> <a name="PENDING"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PENDING</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a> PENDING</pre> </li> </ul> <a name="AVAILABLE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AVAILABLE</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a> AVAILABLE</pre> </li> </ul> <a name="IMPAIRED"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IMPAIRED</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a> IMPAIRED</pre> </li> </ul> <a name="UNHEALTHY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>UNHEALTHY</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a> UNHEALTHY</pre> </li> </ul> <a name="REBOOTING"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>REBOOTING</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a> REBOOTING</pre> </li> </ul> <a name="REBUILDING"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>REBUILDING</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a> REBUILDING</pre> </li> </ul> <a name="TERMINATING"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TERMINATING</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a> TERMINATING</pre> </li> </ul> <a name="TERMINATED"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TERMINATED</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a> TERMINATED</pre> </li> </ul> <a name="SUSPENDED"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>SUSPENDED</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a> SUSPENDED</pre> </li> </ul> <a name="ERROR"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ERROR</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a> ERROR</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="values()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>values</h4> <pre>public static&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a>[]&nbsp;values()</pre> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: <pre> for (WorkspaceState c : WorkspaceState.values()) &nbsp; System.out.println(c); </pre></div> <dl><dt><span class="strong">Returns:</span></dt><dd>an array containing the constants of this enum type, in the order they are declared</dd></dl> </li> </ul> <a name="valueOf(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>valueOf</h4> <pre>public static&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a>&nbsp;valueOf(java.lang.String&nbsp;name)</pre> <div class="block">Returns the enum constant of this type with the specified name. The string must match <i>exactly</i> an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - the name of the enum constant to be returned.</dd> <dt><span class="strong">Returns:</span></dt><dd>the enum constant with the specified name</dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd> <dd><code>java.lang.NullPointerException</code> - if the argument is null</dd></dl> </li> </ul> <a name="toString()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Enum&lt;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a>&gt;</code></dd> </dl> </li> </ul> <a name="fromValue(java.lang.String)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>fromValue</h4> <pre>public static&nbsp;<a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceState.html" title="enum in com.amazonaws.services.workspaces.model">WorkspaceState</a>&nbsp;fromValue(java.lang.String&nbsp;value)</pre> <div class="block">Use this in place of valueOf.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>value</code> - real value</dd> <dt><span class="strong">Returns:</span></dt><dd>WorkspaceState corresponding to the value</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="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <div> <!-- Script for Syntax Highlighter START --> <script type="text/javascript"> SyntaxHighlighter.all() </script> <!-- Script for Syntax Highlighter END --> </div> <script src="http://a0.awsstatic.com/chrome/js/1.0.46/jquery.1.9.js" type="text/javascript"></script> <script>jQuery.noConflict();</script> <script> jQuery(function ($) { $("div.header").prepend('<!--REGION_DISCLAIMER_DO_NOT_REMOVE-->'); }); </script> <!-- BEGIN-URCHIN-TRACKER --> <script src="http://l0.awsstatic.com/js/urchin.js" type="text/javascript"></script> <script type="text/javascript">urchinTracker();</script> <!-- END-URCHIN-TRACKER --> <!-- SiteCatalyst code version: H.25.2. Copyright 1996-2012 Adobe, Inc. All Rights Reserved. More info available at http://www.omniture.com --> <script language="JavaScript" type="text/javascript" src="https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js (view-source:https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js)" /> <script language="JavaScript" type="text/javascript"> <!-- // Documentation Service Name s.prop66='AWS SDK for Java'; s.eVar66='D=c66'; // Documentation Guide Name s.prop65='API Reference'; s.eVar65='D=c65'; var s_code=s.t();if(s_code)document.write(s_code) //--> </script> <script language="JavaScript" type="text/javascript"> <!--if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-') //--> </script> <noscript> <img src="http://amazonwebservices.d2.sc.omtrdc.net/b/ss/awsamazondev/1/H.25.2--NS/0" height="1" width="1" border="0" alt="" /> </noscript> <!--/DO NOT REMOVE/--> <!-- End SiteCatalyst code version: H.25.2. --> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/amazonaws/services/workspaces/model/WorkspaceRequest.html" title="class in com.amazonaws.services.workspaces.model"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/amazonaws/services/workspaces/model/WorkspaceState.html" target="_top">Frames</a></li> <li><a href="WorkspaceState.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><a href="#enum_constant_summary">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#enum_constant_detail">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&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> Copyright &#169; 2013 Amazon Web Services, Inc. All Rights Reserved. </small></p> </body> </html>
{ "content_hash": "a496ce1c9e88b1c89338524adbcc1f9b", "timestamp": "", "source": "github", "line_count": 568, "max_line_length": 244, "avg_line_length": 43.769366197183096, "alnum_prop": 0.6334017135272113, "repo_name": "TomNong/Project2-Intel-Edison", "id": "ba85b19ba6c426a1df17f75551f4956873f14c42", "size": "24861", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documentation/javadoc/com/amazonaws/services/workspaces/model/WorkspaceState.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "5522" } ], "symlink_target": "" }
/*** * The goal of this file is to know How to debug a node.js program; * * * How to run this example: * 1. node debug debugger-1.js * 2. See the message get displayed on prompt. */ /* Debug action commands * cont, c - Continue execution * next, n - Step next * step, s - Step in * out, o - Step out */ var x = 5; var y = 10; function Add(x, y) { debugger; return x + y; } Add(x, y);
{ "content_hash": "c353fc7577685ead00f369eed0bf2c5a", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 67, "avg_line_length": 16.04, "alnum_prop": 0.6084788029925187, "repo_name": "hegdeashwin/Server-Side-Node.js", "id": "da7bfc441347053f2415fd8e2e5d9b06f4b2a2ed", "size": "401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "codes/Session-7/debugger/debugger-1.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "19" }, { "name": "HTML", "bytes": "921971" }, { "name": "JavaScript", "bytes": "48214" } ], "symlink_target": "" }
package ru.job4j.additionaltask; /** * Class is time of customer in bank. * * @since 22/10/2017 * @version 1 */ public class TimeDistance { public long start; public long end; public TimeDistance(long start, long end) { this.start = start; this.end = end; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TimeDistance that = (TimeDistance) o; if (start != that.start) return false; return end == that.end; } @Override public int hashCode() { int result = (int) (start ^ (start >>> 32)); result = 31 * result + (int) (end ^ (end >>> 32)); return result; } @Override public String toString() { return start + "-" + end; } }
{ "content_hash": "f8d9618e766ad1865823533571787cf7", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 66, "avg_line_length": 21.45, "alnum_prop": 0.548951048951049, "repo_name": "danailKondov/dkondov", "id": "36bb26a675a387ce54ac0565d08de89e2fd9068c", "size": "858", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_007/src/main/java/ru/job4j/additionaltask/TimeDistance.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "700" }, { "name": "HTML", "bytes": "2030" }, { "name": "Java", "bytes": "442180" }, { "name": "JavaScript", "bytes": "2855" }, { "name": "XSLT", "bytes": "410" } ], "symlink_target": "" }
'use strict'; var EOL = require('os').EOL; var expect = require('chai').expect; var MockUI = require('../../helpers/mock-ui'); var MockAnalytics = require('../../helpers/mock-analytics'); var CLI = require('../../../lib/cli/cli'); var td = require('testdouble'); var ui; var analytics; var commands = {}; var argv; var isWithinProject; // helper to similate running the CLI function ember(args) { return new CLI({ ui: ui, analytics: analytics, testing: true }).run({ tasks: {}, commands: commands, cliArgs: args || [], settings: {}, project: { isEmberCLIProject: function() { // similate being inside or outside of a project return isWithinProject; }, hasDependencies: function() { return true; }, blueprintLookupPaths: function() { return []; } } }); } function stubCallHelp() { return td.replace(CLI.prototype, 'callHelp', td.function()); } function stubValidateAndRunHelp(name) { var stub = stubValidateAndRun(name); td.when(stub(), {ignoreExtraArgs: true}).thenReturn('callHelp'); return stub; } function stubValidateAndRun(name) { commands[name] = require('../../../lib/commands/' + name); return td.replace(commands[name].prototype, 'validateAndRun', td.function()); } function stubRun(name) { commands[name] = require('../../../lib/commands/' + name); return td.replace(commands[name].prototype, 'run', td.function()); } beforeEach(function() { ui = new MockUI(); analytics = new MockAnalytics(); argv = []; commands = { }; isWithinProject = true; }); afterEach(function() { td.reset(); delete process.env.EMBER_ENV; commands = argv = ui = undefined; }); describe('Unit: CLI', function() { this.timeout(10000); it('exists', function() { expect(CLI).to.be.ok; }); it('ember', function() { var help = stubValidateAndRun('help'); return ember().then(function() { td.verify(help(), {ignoreExtraArgs: true, times: 1}); var output = ui.output.trim(); expect(output).to.equal('', 'expected no extra output'); }); }); /* it('logError', function() { var cli = new CLI({ ui: ui, analytics: analytics, testing: true }); var error = new Error('Error message!'); var expected = {exitCode: 1, ui: ui, error: error}; expect(cli.logError(error)).to.eql(expected, 'expected error object'); }); */ it('callHelp', function() { var cli = new CLI({ ui: ui, analytics: analytics, testing: true }); var init = stubValidateAndRun('init'); var help = stubValidateAndRun('help'); var helpOptions = { environment: { tasks: {}, commands: commands, cliArgs: [], settings: {}, project: { isEmberCLIProject: function() { // similate being inside or outside of a project return isWithinProject; }, hasDependencies: function() { return true; }, blueprintLookupPaths: function() { return []; } } }, commandName: 'init', commandArgs: [] }; cli.callHelp(helpOptions); td.verify(help(), {ignoreExtraArgs: true, times: 1}); td.verify(init(), {ignoreExtraArgs: true, times: 0}); }); describe('help', function() { ['--help', '-h'].forEach(function(command) { it('ember ' + command, function() { var help = stubValidateAndRun('help'); return ember([command]).then(function() { td.verify(help(), {ignoreExtraArgs: true, times: 1}); var output = ui.output.trim(); expect(output).to.equal('', 'expected no extra output'); }); }); it('ember new ' + command, function() { var help = stubCallHelp(); var newCommand = stubValidateAndRunHelp('new'); return ember(['new', command]).then(function() { td.verify(help(), {ignoreExtraArgs: true, times: 1}); var output = ui.output.trim(); expect(output).to.equal('', 'expected no extra output'); td.verify(newCommand(), {ignoreExtraArgs: true, times: 1}); }); }); }); }); ['--version', '-v'].forEach(function(command) { it('ember ' + command, function() { var version = stubValidateAndRun('version'); return ember([command]).then(function() { var output = ui.output.trim(); expect(output).to.equal('', 'expected no extra output'); td.verify(version(), {ignoreExtraArgs: true, times: 1}); }); }); }); describe('server', function() { ['server','s'].forEach(function(command) { it('ember ' + command + ' --port 9999', function() { var server = stubRun('serve'); return ember([command, '--port', '9999']).then(function() { var captor = td.matchers.captor(); td.verify(server(captor.capture()), {ignoreExtraArgs: true, times: 1}); expect(captor.value.port, 'port').to.equal(9999); }); }); it('ember ' + command + ' --host localhost', function() { var server = stubRun('serve'); return ember(['server', '--host', 'localhost']).then(function() { var captor = td.matchers.captor(); td.verify(server(captor.capture()), {ignoreExtraArgs: true, times: 1}); expect(captor.value.host, 'host').to.equal('localhost'); }); }); it('ember ' + command + ' --port 9292 --host localhost', function() { var server = stubRun('serve'); return ember([command, '--port', '9292', '--host', 'localhost']).then(function() { var captor = td.matchers.captor(); td.verify(server(captor.capture()), {ignoreExtraArgs: true, times: 1}); expect(captor.value.host, 'host').to.equal('localhost'); expect(captor.value.port, 'port').to.equal(9292); }); }); it('ember ' + command + ' --proxy http://localhost:3000/', function() { var server = stubRun('serve'); return ember([command, '--proxy', 'http://localhost:3000/']).then(function() { var captor = td.matchers.captor(); td.verify(server(captor.capture()), {ignoreExtraArgs: true, times: 1}); expect(captor.value.proxy, 'proxy').to.equal('http://localhost:3000/'); }); }); it('ember ' + command + ' --proxy https://localhost:3009/ --insecure-proxy', function () { var server = stubRun('serve'); return ember([command, '--insecure-proxy']).then(function() { var captor = td.matchers.captor(); td.verify(server(captor.capture()), {ignoreExtraArgs: true, times: 1}); expect(captor.value.insecureProxy, 'insecureProxy').to.equal(true); }); }); it('ember ' + command + ' --proxy https://localhost:3009/ --no-insecure-proxy', function () { var server = stubRun('serve'); return ember([command, '--no-insecure-proxy']).then(function() { var captor = td.matchers.captor(); td.verify(server(captor.capture()), {ignoreExtraArgs: true, times: 1}); expect(captor.value.insecureProxy, 'insecureProxy').to.equal(false); }); }); it('ember ' + command + ' --watcher events', function() { var server = stubRun('serve'); return ember([command, '--watcher', 'events']).then(function() { var captor = td.matchers.captor(); td.verify(server(captor.capture()), {ignoreExtraArgs: true, times: 1}); expect(captor.value.watcher, 'watcher').to.match(/node|events|watchman/); }); }); it('ember ' + command + ' --watcher polling', function() { var server = stubRun('serve'); return ember([command, '--watcher', 'polling']).then(function() { var captor = td.matchers.captor(); td.verify(server(captor.capture()), {ignoreExtraArgs: true, times: 1}); expect(captor.value.watcher, 'watcher').to.equal('polling'); }); }); it('ember ' + command, function() { var server = stubRun('serve'); return ember([command]).then(function() { var captor = td.matchers.captor(); td.verify(server(captor.capture()), {ignoreExtraArgs: true, times: 1}); expect(captor.value.watcher, 'watcher').to.match(/node|events|watchman/); }); }); ['production', 'development', 'foo'].forEach(function(env) { it('ember ' + command + ' --environment ' + env, function() { var server = stubRun('serve'); return ember([command, '--environment', env]).then(function() { var captor = td.matchers.captor(); td.verify(server(captor.capture()), {ignoreExtraArgs: true, times: 1}); expect(captor.value.environment, 'environment').to.equal(env); }); }); }); ['development', 'foo'].forEach(function(env) { it('ember ' + command + ' --environment ' + env, function() { var server = stubRun('serve'); process.env.EMBER_ENV = 'production'; return ember([command, '--environment', env]).then(function() { td.verify(server(), {ignoreExtraArgs: true, times: 1}); expect(process.env.EMBER_ENV).to.equal('production', 'uses EMBER_ENV over environment'); }); }); }); ['production', 'development', 'foo'].forEach(function(env) { it('EMBER_ENV=' + env + ' ember ' + command, function() { var server = stubRun('serve'); process.env.EMBER_ENV = env; return ember([command]).then(function() { td.verify(server(), {ignoreExtraArgs: true, times: 1}); expect(process.env.EMBER_ENV).to.equal(env, 'correct environment'); }); }); }); }); }); describe('generate', function() { ['generate', 'g'].forEach(function(command) { it('ember ' + command + ' foo bar baz', function() { var generate = stubRun('generate'); return ember([command, 'foo', 'bar', 'baz']).then(function() { var captor = td.matchers.captor(); td.verify(generate(captor.capture(), ['foo', 'bar', 'baz']), {times: 1}); var output = ui.output.trim(); var options = captor.value; if (/win\d+/.test(process.platform) || options.watcher === 'watchman') { expect(output).to.equal('', 'expected no extra output'); } else { expect(output.split(EOL).length).to.equal(2, 'expected no extra output'); } }); }); }); }); describe('init', function() { ['init'].forEach(function(command) { it('ember ' + command, function() { var init = stubValidateAndRun('init'); return ember([command]).then(function() { td.verify(init(), {ignoreExtraArgs: true, times: 1}); }); }); it('ember ' + command + ' <app-name>', function() { var init = stubRun('init'); return ember([command, 'my-blog']).then(function() { var captor = td.matchers.captor(); td.verify(init(captor.capture(), ['my-blog']), {times: 1}); var output = ui.output.trim(); var options = captor.value; if (/win\d+/.test(process.platform) || options.watcher === 'watchman') { expect(output).to.equal('', 'expected no extra output'); } else { expect(output.split(EOL).length).to.equal(2, 'expected no extra output'); } }); }); }); }); describe('new', function() { it('ember new', function() { isWithinProject = false; var newCommand = stubRun('new'); return ember(['new']).then(function() { td.verify(newCommand(), {ignoreExtraArgs: true, times: 1}); }); }); it('ember new MyApp', function() { isWithinProject = false; var newCommand = stubRun('new'); return ember(['new', 'MyApp']).then(function() { td.verify(newCommand(td.matchers.anything(), ['MyApp']), {times: 1}); }); }); }); describe('build', function() { ['build','b'].forEach(function(command) { it('ember ' + command, function() { var build = stubRun('build'); return ember([command]).then(function() { var captor = td.matchers.captor(); td.verify(build(captor.capture()), {ignoreExtraArgs: true, times: 1}); var options = captor.value; expect(options.watch).to.equal(false, 'expected the default watch flag to be false'); expect(options.suppressSizes).to.equal(false, 'expected the default supress-sizes flag to be false'); }); }); it('ember ' + command + ' --disable-analytics', function() { var build = stubRun('build'); return ember([command, '--disable-analytics']).then(function() { var captor = td.matchers.captor(); td.verify(build(captor.capture()), {ignoreExtraArgs: true, times: 1}); var options = captor.value; expect(options.disableAnalytics).to.equal(true, 'expected the disableAnalytics flag to be true'); }); }); it('ember ' + command + ' --watch', function() { var build = stubRun('build'); return ember([command, '--watch']).then(function() { var captor = td.matchers.captor(); td.verify(build(captor.capture()), {ignoreExtraArgs: true, times: 1}); var options = captor.value; expect(options.watch).to.equal(true, 'expected the watch flag to be true'); }); }); it('ember ' + command + ' --suppress-sizes', function() { var build = stubRun('build'); return ember([command, '--suppress-sizes']).then(function () { var captor = td.matchers.captor(); td.verify(build(captor.capture()), {ignoreExtraArgs: true, times: 1}); var options = captor.value; expect(options.suppressSizes).to.equal(true, 'expected the suppressSizes flag to be true'); }); }); ['production', 'development', 'baz'].forEach(function(env) { it('ember ' + command + ' --environment ' + env, function() { var build = stubRun('build'); return ember([command, '--environment', env]).then(function() { var captor = td.matchers.captor(); td.verify(build(captor.capture()), {ignoreExtraArgs: true, times: 1}); var options = captor.value; expect(options.environment).to.equal(env, 'correct environment'); }); }); }); ['development', 'baz'].forEach(function(env) { it('EMBER_ENV=production ember ' + command + ' --environment ' + env, function() { var build = stubRun('build'); process.env.EMBER_ENV = 'production'; return ember([command, '--environment', env]).then(function() { td.verify(build(), {ignoreExtraArgs: true, times: 1}); expect(process.env.EMBER_ENV).to.equal('production', 'uses EMBER_ENV over environment'); }); }); }); ['production', 'development', 'baz'].forEach(function(env) { it('EMBER_ENV=' + env + ' ember ' + command + ' ', function() { var build = stubRun('build'); process.env.EMBER_ENV = env; return ember([command]).then(function() { td.verify(build(), {ignoreExtraArgs: true, times: 1}); expect(process.env.EMBER_ENV).to.equal(env, 'correct environment'); }); }); }); }); }); it('ember <valid command>', function() { var help = stubValidateAndRun('help'); var serve = stubValidateAndRun('serve'); return ember(['serve']).then(function() { td.verify(help(), {ignoreExtraArgs: true, times: 0}); td.verify(serve(), {ignoreExtraArgs: true, times: 1}); var output = ui.output.trim(); expect(output).to.equal('', 'expected no extra output'); }); }); it.skip('ember <valid command with args>', function() { var help = stubValidateAndRun('help'); var serve = stubValidateAndRun('serve'); return ember(['serve', 'lorem', 'ipsum', 'dolor', '--flag1=one']).then(function() { var args = serve.calledWith[0][0].cliArgs; expect(help.called).to.equal(0, 'expected the help command NOT to be run'); expect(serve.called).to.equal(1, 'expected the foo command to be run'); expect(args).to.deep.equal(['serve', 'lorem', 'ipsum', 'dolor'], 'expects correct arguments'); expect(serve.calledWith[0].length).to.equal(2, 'expect foo to receive a total of 4 args'); var output = ui.output.trim(); expect(output).to.equal('', 'expected no extra output'); }); }); it('ember <invalid command>', function() { var help = stubValidateAndRun('help'); return ember(['unknownCommand']).then(function() { expect(false).to.be.ok; }).catch(function(error) { expect(help.called, 'help command was executed').to.not.be.ok; expect(error.name).to.equal('SilentError'); expect(error.message).to.equal('The specified command unknownCommand is invalid. For available options, see `ember help`.'); }); }); describe.skip('default options config file', function() { it('reads default options from .ember-cli file', function() { var defaults = ['--output', process.cwd()]; var build = stubValidateAndRun('build'); return ember(['build'], defaults).then(function() { var options = build.calledWith[0][1].cliOptions; expect(options.output).to.equal(process.cwd()); }); }); }); describe('logError', function() { it('returns error status code in production', function() { var cli = new CLI({ ui: new MockUI(), testing: false }); expect(cli.logError('foo')).to.equal(1); }); it('does not throw an error in production', function() { var cli = new CLI({ ui: new MockUI(), testing: false }); var invokeError = cli.logError.bind(cli, new Error('foo')); expect(invokeError).to.not.throw(); }); it('throws error in testing', function() { var cli = new CLI({ ui: new MockUI(), testing: true }); var invokeError = cli.logError.bind(cli, new Error('foo')); expect(invokeError).to.throw(Error, 'foo'); }); }); describe('Global command options', function() { var verboseCommand = function(args) { return ember(['fake-command', '--verbose'].concat(args)); }; describe('--verbose', function() { describe('option parsing', function() { afterEach(function() { delete process.env.EMBER_VERBOSE_FAKE_OPTION_1; delete process.env.EMBER_VERBOSE_FAKE_OPTION_2; }); it('sets process.env.EMBER_VERBOSE_${NAME} for each space delimited option', function() { return verboseCommand(['fake_option_1', 'fake_option_2']).then(function() { expect(false).to.be.true; }).catch(function(error) { expect(process.env.EMBER_VERBOSE_FAKE_OPTION_1).to.be.ok; expect(process.env.EMBER_VERBOSE_FAKE_OPTION_2).to.be.ok; expect(error.name).to.equal('SilentError'); expect(error.message).to.equal('The specified command fake-command is invalid. For available options, see `ember help`.'); }); }); it('ignores verbose options after --', function() { return verboseCommand(['fake_option_1', '--fake-option', 'fake_option_2']).then(function() { expect(false).to.be.true; }).catch(function(error) { expect(process.env.EMBER_VERBOSE_FAKE_OPTION_1).to.be.ok; expect(process.env.EMBER_VERBOSE_FAKE_OPTION_2).to.not.be.ok; expect(error.name).to.equal('SilentError'); expect(error.message).to.equal('The specified command fake-command is invalid. For available options, see `ember help`.'); }); }); it('ignores verbose options after -', function() { return verboseCommand(['fake_option_1', '-f', 'fake_option_2']).then(function() { expect(false).to.be.true; }).catch(function(error) { expect(process.env.EMBER_VERBOSE_FAKE_OPTION_1).to.be.ok; expect(process.env.EMBER_VERBOSE_FAKE_OPTION_2).to.not.be.ok; expect(error.name).to.equal('SilentError'); expect(error.message).to.equal('The specified command fake-command is invalid. For available options, see `ember help`.'); }); }); }); }); }); });
{ "content_hash": "27baadec039c9786ba488fd545d6e1a7", "timestamp": "", "source": "github", "line_count": 616, "max_line_length": 134, "avg_line_length": 33.70941558441559, "alnum_prop": 0.5678786419455815, "repo_name": "josemarluedke/ember-cli", "id": "8e548fc9ee52574644705f34efc840d299c16deb", "size": "20765", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tests/unit/cli/cli-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1749" }, { "name": "JavaScript", "bytes": "963851" }, { "name": "PowerShell", "bytes": "604" }, { "name": "Ruby", "bytes": "358" }, { "name": "Shell", "bytes": "1888" } ], "symlink_target": "" }
 namespace Fpm.ProfileData.Entities.Profile { public class GroupingSubheading { public int SubheadingId { get; set; } public int GroupId { get; set; } public int AreaTypeId { get; set; } public string Subheading { get; set; } public int Sequence { get; set; } } }
{ "content_hash": "bcb0df3d08f4ef48530dd5fe04d9fc13", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 46, "avg_line_length": 26.416666666666668, "alnum_prop": 0.6056782334384858, "repo_name": "PublicHealthEngland/fingertips-open", "id": "c576f25b700f2ee720cfc28d63a8befcdb45d6b3", "size": "319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FingertipsProfileManager/ProfileData/Entities/Profile/GroupingSubheading.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "743" }, { "name": "C#", "bytes": "4367358" }, { "name": "CSS", "bytes": "373415" }, { "name": "HTML", "bytes": "519215" }, { "name": "JavaScript", "bytes": "998759" }, { "name": "PowerShell", "bytes": "1119" }, { "name": "TypeScript", "bytes": "857356" } ], "symlink_target": "" }
module UOwhr class UnstableRatingException < RuntimeError; end class Base attr_accessor :players, :games def initialize(config = {}) @config = config @config[:w2] ||= 300.0 # elo^2 @games = [] @players = {} end def print_ordered_ratings players = @players.values.select {|p| p.days.count > 0} players.sort_by { |p| p.days.last.gamma }.each_with_index do |p,idx| if p.days.count > 0 puts "#{p.name} => #{p.days.map(&:elo)}" end end end def log_likelihood score = 0.0 @players.values.each do |p| unless p.days.empty? score += p.log_likelihood end end score end def player_by_name(name) players[name] || players[name] = Player.new(name, @config) end def ratings_for_player(name) player = player_by_name(name) player.days.map {|d| [d.day, d.elo.round, (d.uncertainty*100).round]} end def setup_game(uguale, opposto, outcome, time_step) # Avoid self-played games (no info) if uguale == opposto raise "Invalid game (uguale player == opposto player)" return nil end opposto_player = player_by_name(opposto) uguale_player = player_by_name(uguale) game = Game.new(uguale_player, opposto_player, outcome, time_step) game end def create_game(uguale, opposto, outcome, time_step) game = setup_game(uguale, opposto, outcome, time_step) add_game(game) end def add_game(game) game.opposto_player.add_game(game) game.uguale_player.add_game(game) if game.bpd.nil? puts "Bad game: #{options.inspect} -> #{game.inspect}" end @games << game game end def iterate(count) count.times { run_one_iteration } players.each do |name,player| player.update_uncertainty end nil end def run_one_iteration players.each do |name,player| player.run_one_newton_iteration end end end end
{ "content_hash": "461902425117a4727fc4423b6af236f6", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 75, "avg_line_length": 24.25287356321839, "alnum_prop": 0.5729857819905213, "repo_name": "trenta3/uowhr", "id": "0d4f20b357625a31d6d9718dff3cf6aeb5e3c1c7", "size": "2131", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/uowhr/base.rb", "mode": "33261", "license": "mit", "language": [ { "name": "Ruby", "bytes": "17749" } ], "symlink_target": "" }
module Azure::Network::Mgmt::V2016_09_01 module Models # # VpnClientParameters # class VpnClientParameters include MsRestAzure # @return [ProcessorArchitecture] VPN client Processor Architecture. # Possible values are: 'AMD64' and 'X86'. Possible values include: # 'Amd64', 'X86' attr_accessor :processor_architecture # # Mapper for VpnClientParameters class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'VpnClientParameters', type: { name: 'Composite', class_name: 'VpnClientParameters', model_properties: { processor_architecture: { client_side_validation: true, required: true, serialized_name: 'ProcessorArchitecture', type: { name: 'String' } } } } } end end end end
{ "content_hash": "423338a17141029bee7db8d72c6f9e2d", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 74, "avg_line_length": 25.953488372093023, "alnum_prop": 0.5376344086021505, "repo_name": "Azure/azure-sdk-for-ruby", "id": "489386f14cb75aa029507a2b47d1df31876e94f6", "size": "1280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "management/azure_mgmt_network/lib/2016-09-01/generated/azure_mgmt_network/models/vpn_client_parameters.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "345216400" }, { "name": "Shell", "bytes": "305" } ], "symlink_target": "" }
layout: rss exclude: true tags: - import ---
{ "content_hash": "f989e45ede77a62270c655d06bd03cf0", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 13, "avg_line_length": 9.4, "alnum_prop": 0.6382978723404256, "repo_name": "larsks/blog-old.oddbit.com", "id": "8a84877ff691d206a96dd2cae442809bb756a4c6", "size": "51", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "tag/import/rss/index.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25947" }, { "name": "Python", "bytes": "1644" }, { "name": "Shell", "bytes": "1123" } ], "symlink_target": "" }
TensorFlow is more of a low-level library; basically, we can think of TensorFlow as the Lego bricks (similar to NumPy and SciPy) that we can use to implement machine learning algorithms whereas scikit-learn comes with off-the-shelf algorithms, e.g., algorithms for classification such as SVMs, Random Forests, Logistic Regression, and many, many more. TensorFlow really shines if we want to implement deep learning algorithms, since it allows us to take advantage of GPUs for more efficient training. To get a better idea of how these two libraries differ, let's fit a softmax regression model on the Iris dataset via scikit-learn: ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt # Loading Data iris = load_iris() X = iris.data[:, [0, 3]] # sepal length and petal width y = iris.target # standardize X[:,0] = (X[:,0] - X[:,0].mean()) / X[:,0].std() X[:,1] = (X[:,1] - X[:,1].mean()) / X[:,1].std() lr = LogisticRegression(penalty='l2', dual=False, tol=0.000001, C=10.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=1, solver='newton-cg', max_iter=100, multi_class='multinomial', verbose=0, warm_start=False, n_jobs=1) lr.fit(X, y) ``` In addition, I have a little helper function to plot the 2D decision surface: ```python from mlxtend.evaluate import plot_decision_regions plot_decision_regions(X, y, clf=lr) plt.title('Softmax Regression in scikit-learn') plt.show() ``` ![](./tensorflow-vs-scikitlearn/scikit-softmax.png) That was easy, right? :). Now, if we want to fit a Softmax regression model via TensorFlow, however, we have to "build" the algorithm first. But it really sounds more complicated than it really is. TensorFlow comes with many "convenience" functions and utilities, for example, if we want to use a gradient descent optimization approach, the core or our implementation could look like this: ```python # Construct the Graph g = tf.Graph() with g.as_default(): if init_weights: self._n_classes = np.max(y) + 1 self._n_features = X.shape[1] tf_weights_, tf_biases_ = self._initialize_weights( n_features=self._n_features, n_classes=self._n_classes) self.cost_ = [] else: tf_weights_ = tf.Variable(self.weights_) tf_biases_ = tf.Variable(self.biases_) # Prepare the training data y_enc = self._one_hot(y, self._n_classes) n_idx = list(range(y.shape[0])) tf_X = tf.convert_to_tensor(value=X, dtype=self.dtype) tf_y = tf.convert_to_tensor(value=y_enc, dtype=self.dtype) tf_idx = tf.placeholder(tf.int32, shape=[int(y.shape[0] / n_batches)]) X_batch = tf.gather(params=tf_X, indices=tf_idx) y_batch = tf.gather(params=tf_y, indices=tf_idx) # Setup the graph for minimizing cross entropy cost logits = tf.matmul(X_batch, tf_weights_) + tf_biases_ cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, y_batch) cost = tf.reduce_mean(cross_entropy) optimizer = tf.train.GradientDescentOptimizer( learning_rate=self.eta) train = optimizer.minimize(cost) # Initializing the variables init = tf.initialize_all_variables() ``` And we can execute the training as follows: ```python # Launch the graph with tf.Session(graph=g) as sess: sess.run(init) self.init_time_ = time() for epoch in range(self.epochs): if self.minibatches > 1: n_idx = np.random.permutation(n_idx) minis = np.array_split(n_idx, self.minibatches) costs = [] for idx in minis: _, c = sess.run([train, cost], feed_dict={tf_idx: idx}) costs.append(c) ``` ```python For demonstration purposes, I have implemented Softmax regression via TensorFlow in an object oriented style that is somewhat similar to scikit-learn's implementation. The complete code example can be found here if you are interested: [mlxtend/tf_classifier/TfSoftmax](https://github.com/rasbt/mlxtend/blob/master/mlxtend/tf_classifier/tf_softmax.py). ``` ```python from mlxtend.tf_classifier import TfSoftmaxRegression lr = TfSoftmaxRegression(eta=0.75, epochs=1000, print_progress=True, minibatches=1, random_seed=1) lr.fit(X, y) Epoch: 1000/1000 | Cost 0.12 plt.plot(range(len(lr.cost_)), lr.cost_) plt.xlabel('Iterations') plt.ylabel('Cost') plt.show() ``` ![](./tensorflow-vs-scikitlearn/tf_cost.png) ```python from mlxtend.evaluate import plot_decision_regions plot_decision_regions(X, y, clf=lr) plt.title('Softmax Regression via Gradient Descent in TensorFlow') plt.show() ``` ![](./tensorflow-vs-scikitlearn/tf_softmax.png)
{ "content_hash": "3ddf0ecf70ea56a837a07c26b9959b73", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 500, "avg_line_length": 37.539568345323744, "alnum_prop": 0.6272518206209275, "repo_name": "chongyangma/python-machine-learning-book", "id": "38e2a9dd6f4296094477c691a6c90ca810c7ca64", "size": "5286", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "faq/tensorflow-vs-scikitlearn.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "186" }, { "name": "HTML", "bytes": "5592" }, { "name": "Jupyter Notebook", "bytes": "27629844" }, { "name": "Python", "bytes": "185008" }, { "name": "TeX", "bytes": "7729" } ], "symlink_target": "" }
var string1 = "Hello World"; var string2 = 'Hello World'; var string3 = 'He said, "How about this?"'; var string4 = "He said, \"How about this?\""; var string5 = "Isn't it?"; var string6 = 'Isn\'t it?'; // Character Data Type // 1. JavaScript does not have a character data type. Any string with one character can be used instead. var char1 = 'A'; // Escape sequence // 1. The escape sequences allow for inserting characters into strings that are not normally permitted, such // as backslashes, quotes, and control characters. // 2. Some common escape sequences used in JavaScript are as follows // +-------------------------------------------------------------------------------------------------+ // | Escape Sequence Unicode Character Character | // +-------------------------------------------------------------------------------------------------+ // | \n \u000A Newline | // | \" \u0022 ASCII Apostrophe (") | // | \' \u0027 ASCII Apostrophe (') | // | \` ASCII Grave Accent / Backtick (`) | // | \\ \u005C backslash (\) | // | \t \u0009 Tab | // | \b \u0008 Backspace | // | \nnn Character with given octal code (1, 2 or 3 digits) | // | \xnn Character with given hex code (1 or 2 hex digits) | // | \unnnn Unicode character with given code (1--4 hex digits) | // | \Unnnnnnnn Unicode character with given code (1--8 hex digits) | // +-------------------------------------------------------------------------------------------------+ var char2 = "\u0041"; // The \u convention allows for specifying character code points numerically // String Methods & Properties // 1. Strings have a length property. For example, "seven".length is 5. // 2. Strings are immutable. // 3. But it is easy to make a new string by concatenating other strings together with the + operator. // 4. Two strings containing exactly the same characters in the same order are considered to be the same // string. Eg 'c' + 'a' + 't' === 'cat'. string7 = 'c' + 'a' + 't'; string8 = "cat"; console.log(string7 === string8);
{ "content_hash": "79777afad432eb2badd4762880c429ac", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 108, "avg_line_length": 65.54761904761905, "alnum_prop": 0.4173628768616055, "repo_name": "vikash-india/JavaScriptNotes2Myself", "id": "9690dbf95be67a8c5f9302a73db6de7e01012c31", "size": "3114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/concepts/P007_DataType_Strings.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "318" }, { "name": "JavaScript", "bytes": "76225" } ], "symlink_target": "" }
<?php namespace Kirby\Cms; use Kirby\Data\Data; use Kirby\Exception\Exception; use Kirby\Filesystem\F; class ContentLocks { /** * Data from the `.lock` files * that have been read so far * cached by `.lock` file path * * @var array */ protected $data = []; /** * PHP file handles for all currently * open `.lock` files * * @var array */ protected $handles = []; /** * Closes the open file handles * * @codeCoverageIgnore */ public function __destruct() { foreach ($this->handles as $file => $handle) { $this->closeHandle($file); } } /** * Removes the file lock and closes the file handle * * @param string $file * @return void * @throws \Kirby\Exception\Exception */ protected function closeHandle(string $file) { if (isset($this->handles[$file]) === false) { return; } $handle = $this->handles[$file]; $result = flock($handle, LOCK_UN) && fclose($handle); if ($result !== true) { throw new Exception('Unexpected file system error.'); // @codeCoverageIgnore } unset($this->handles[$file]); } /** * Returns the path to a model's lock file * * @param \Kirby\Cms\ModelWithContent $model * @return string */ public static function file(ModelWithContent $model): string { return $model->contentFileDirectory() . '/.lock'; } /** * Returns the lock/unlock data for the specified model * * @param \Kirby\Cms\ModelWithContent $model * @return array */ public function get(ModelWithContent $model): array { $file = static::file($model); $id = static::id($model); // return from cache if file was already loaded if (isset($this->data[$file]) === true) { return $this->data[$file][$id] ?? []; } // first get a handle to ensure a file system lock $handle = $this->handle($file); if (is_resource($handle) === true) { // read data from file clearstatcache(); $filesize = filesize($file); if ($filesize > 0) { // always read the whole file rewind($handle); $string = fread($handle, $filesize); $data = Data::decode($string, 'yaml'); } } $this->data[$file] = $data ?? []; return $this->data[$file][$id] ?? []; } /** * Returns the file handle to a `.lock` file * * @param string $file * @param bool $create Whether to create the file if it does not exist * @return resource|null File handle * @throws \Kirby\Exception\Exception */ protected function handle(string $file, bool $create = false) { // check for an already open handle if (isset($this->handles[$file]) === true) { return $this->handles[$file]; } // don't create a file if not requested if (is_file($file) !== true && $create !== true) { return null; } $handle = @fopen($file, 'c+b'); if (is_resource($handle) === false) { throw new Exception('Lock file ' . $file . ' could not be opened.'); // @codeCoverageIgnore } // lock the lock file exclusively to prevent changes by other threads $result = flock($handle, LOCK_EX); if ($result !== true) { throw new Exception('Unexpected file system error.'); // @codeCoverageIgnore } return $this->handles[$file] = $handle; } /** * Returns model ID used as the key for the data array; * prepended with a slash because the $site otherwise won't have an ID * * @param \Kirby\Cms\ModelWithContent $model * @return string */ public static function id(ModelWithContent $model): string { return '/' . $model->id(); } /** * Sets and writes the lock/unlock data for the specified model * * @param \Kirby\Cms\ModelWithContent $model * @param array $data * @return bool * @throws \Kirby\Exception\Exception */ public function set(ModelWithContent $model, array $data): bool { $file = static::file($model); $id = static::id($model); $handle = $this->handle($file, true); $this->data[$file][$id] = $data; // make sure to unset model id entries, // if no lock data for the model exists foreach ($this->data[$file] as $id => $data) { // there is no data for that model whatsoever if ( isset($data['lock']) === false && (isset($data['unlock']) === false || count($data['unlock']) === 0) ) { unset($this->data[$file][$id]); // there is empty unlock data, but still lock data } elseif ( isset($data['unlock']) === true && count($data['unlock']) === 0 ) { unset($this->data[$file][$id]['unlock']); } } // there is no data left in the file whatsoever, delete the file if (count($this->data[$file]) === 0) { unset($this->data[$file]); // close the file handle, otherwise we can't delete it on Windows $this->closeHandle($file); return F::remove($file); } $yaml = Data::encode($this->data[$file], 'yaml'); // delete all file contents first if (rewind($handle) !== true || ftruncate($handle, 0) !== true) { throw new Exception('Could not write lock file ' . $file . '.'); // @codeCoverageIgnore } // write the new contents $result = fwrite($handle, $yaml); if (is_int($result) === false || $result === 0) { throw new Exception('Could not write lock file ' . $file . '.'); // @codeCoverageIgnore } return true; } }
{ "content_hash": "ed5cc028ae4a810190977f566fa0fc41", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 94, "avg_line_length": 23.69406392694064, "alnum_prop": 0.615340142609366, "repo_name": "mmewen/mewen.fr", "id": "2d08d9f1f40a387fe14dfe2c760f2f692fb9b566", "size": "5463", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kirby/src/Cms/ContentLocks.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "17090" }, { "name": "Hack", "bytes": "842" }, { "name": "JavaScript", "bytes": "198" }, { "name": "PHP", "bytes": "1868855" }, { "name": "Python", "bytes": "2225" } ], "symlink_target": "" }
// ----------------- // standard includes // ----------------- #include <algorithm> // ---------------- // library includes // ---------------- #include "interfaceMicrophone.h" // ----------- // Constructor // ----------- /** * Constructor * @brief Creates InterfaceMicrophone object and initilizes properties. */ InterfaceMicrophone::InterfaceMicrophone(): _samplingRate(44100), // Set sampling rate of audio signal. _streamInUse(false), // Reset recording state. _stopCalled(false), // Reset recording state. _bitEntropy(16,0.0f), // Bit occurrence probabilities initialized to 0. _bitCountCache(65536) { // Cache to accommodate 16bit sample space. } // ---------- // Destructor // ---------- /** * Destructor * @brief Releases microphone if stream is active and resets state. */ InterfaceMicrophone::~InterfaceMicrophone() { // If audio capture is active, stop recording before destroying object. if (_streamInUse) { stopFlow(); } } // ---------- // appendData // ---------- /** * @brief Appends available entropic data to the vector byte stream. * Implementation of pure virtual function from RandomSource. * * @param data a reference to a byte vector to be appended with * entropic data from the microphone. * * @return void */ void InterfaceMicrophone::appendData(std::vector<uint8_t>& data) { if (_streamInUse) { std::cerr << "Stream still running"; return; } try { // Reserve space for data to be appended. data.reserve(data.size() + (_microphoneData.size() * 2)); } catch (const std::bad_alloc& ba) { std::cerr << "[Memory Error] Cannot Append: " << std::endl; return; } // Convert samples to bytes and copy into data. int16toBytes( _microphoneData.begin(), _microphoneData.end(), std::back_inserter(data) ); // Clear entropic data _microphoneData.clear(); _bitEntropy.clear(); } // ---------- // bitEntropy // ---------- /** * @brief Returns entropy estimate of current microphone samples as * bit occurrence probabilities. * Implementation of pure virtual function from RandomSource. * * @return double vector with bit occurrence probabilities. */ std::vector<double> InterfaceMicrophone::bitEntropy() { // Compute present entropy estimate. auto tempEntropy = _bitEntropy; // Normalize to compute bit occurrence probabilities. double normalizer = _microphoneData.size(); if (std::fabs(normalizer)<0.01) { normalizer = 1.0f; } std::transform( tempEntropy.begin(), tempEntropy.end(), tempEntropy.begin(), [normalizer] (double val) { return val / normalizer; } ); // Return bit occurrence probabilities of entropic data. return tempEntropy; } // -------- // initFlow // -------- /** * @brief Establishes connection with a microphone to capture audio samples * asynchronously. * * @return int with value 1 if audio stream has been initialized, 0 if * a stream already exisits or -1 if initialization failed. */ int InterfaceMicrophone::initFlow() { // If stream has already been initialized, return 0 for continuing stream. if (_streamInUse) { return 0; } // Prepare port audio to begin interaction with mic. _err = Pa_Initialize(); if (_err != paNoError) { std::cerr << "Pa_Initialize error:" << Pa_GetErrorText(_err) << std::endl; std::cerr << "Unable to initialize port audio" << std::endl; return -1; } // Attempt to open stream. if (openStream() == 1) { // Attempt to start stream, return 1 if successful and -1 otherwise. return startStream(); } return -1; } // -------- // StopFlow // -------- /** * @brief Stops recording audio samples and releases microphone. Must be * called sucessfully before accessing bytes or entropy estimate. * @return true, if termination was successfull. */ bool InterfaceMicrophone::stopFlow() { // Attempt to close stream. if (closeStream()) { // End port audio interaction with mic. _err = Pa_Terminate(); } if (_err != paNoError) { std::cerr << "Pa_Terminate error:" << Pa_GetErrorText(_err) << std::endl; std::cerr << "Unable to terminate audio stream" << std::endl; return false; } // Reset recording state. _streamInUse = false; _stopCalled = false; return true; } // -------------- // memberCallback // -------------- /** * @brief Interacts with static callback, paCallback, at an object specific * level. * * @param input pointer to recorded data. * @param output pointer to output data. * @param frameCount unsigned long with number of frames in input buffer. * @param timeInfo const pointer to PaStreamCallbackTimeInfo. * @param statusFlags PaStreamCallbackFlags with status of stream. * * @return int communicating paContinue for continuation or PaComplete. */ int InterfaceMicrophone::memberCallback( const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags ) { // Cast input buffer to configured sample type. const int16_t* recordedData = (const int16_t*)input; // Check if buffer has data. if (recordedData == NULL) { return paContinue; } // Compute total storage required. size_t requiredStorage = _microphoneData.size() + frameCount; // Check if data can be held. if (_microphoneData.max_size() < requiredStorage) { std::cerr << "[Max Capacity] Samples discarded: " << std::endl; return paComplete; // cannot hold new data stop recording } try { // Reserve space to record samples from buffer. _microphoneData.reserve(requiredStorage); // Copy data from buffer and update bit occurrence in samples. copyNCompEntropy( recordedData, recordedData + frameCount, std::back_inserter(_microphoneData) ); } catch (const std::bad_alloc& ba) { std::cerr << "[Memory Error] Samples discarded: " << std::endl; return paComplete; } // Check if the stream has been requested to end. if (_stopCalled) { // Return paComplete to stop recording more samples. return paComplete; } // Continue recording. return paContinue; } // ---------- // openStream // ---------- /** * @brief Sets up connection to a microphone device, prepares and opens * stream parameters. * * @return int with value 1 for opening stream sucessfully or -1 otherwise. */ int InterfaceMicrophone::openStream() { // Find default recording device. _inputParameters.device = Pa_GetDefaultInputDevice(); if (_inputParameters.device == paNoDevice) { std::cerr << "Unable to find audio device" << std::endl; return -1; } // Setup recording parameters. _inputParameters.channelCount = 2; // Left and Right channels. _inputParameters.sampleFormat = paInt16; //16bit Int samples. _inputParameters.suggestedLatency = Pa_GetDeviceInfo(_inputParameters.device)->defaultLowInputLatency; _inputParameters.hostApiSpecificStreamInfo = NULL; // Open an audio I/O stream. _err = Pa_OpenStream( &_stream, // stream &_inputParameters, // input parameters NULL, // output paramteres _samplingRate, // sampling rate paFramesPerBufferUnspecified, // samples per callback paClipOff, // unfiltered &InterfaceMicrophone::paCallback, // callback this ); if (_err != paNoError) { std::cerr << "Unable to open an audio stream" << std::endl; return -1; } return 1; } // ----------- // startStream // ----------- /** * @brief Starts a configured stream. * * @return int with value 1 for a successful stream initiation else -1. */ int InterfaceMicrophone::startStream() { // Start configured stream. _err = Pa_StartStream(_stream); if (_err!=paNoError) { std::cerr << "Pa_StartStream error:" << Pa_GetErrorText(_err) << std::endl; return -1; } _streamInUse = true; return 1; } // ----------- // closeStream // ----------- /** * @brief Closes a running audio stream. Including, releasing microphone * device and resetting internal state. * * @return true, if stream was sucessfully stopped. */ bool InterfaceMicrophone::closeStream() { // Set stop called for stream callback to flush. _stopCalled = true; // Wait for stream callback to call paComplete. while (( _err = Pa_IsStreamActive(_stream)) == 1) { Pa_Sleep(1000); } // Stop stream. _err = Pa_StopStream(_stream); if (_err != paNoError) { std::cerr << "Pa_StopStream error:" << Pa_GetErrorText(_err) << std::endl; std::cerr << "Unable to stop audio stream" << std::endl; return false; } // Close stream. _err = Pa_CloseStream(_stream); if (_err != paNoError) { std::cerr << "Unable to close audio stream" << std::endl; return false; } return true; }
{ "content_hash": "0916744d6f0282b3276bc5948eca1ec3", "timestamp": "", "source": "github", "line_count": 360, "max_line_length": 77, "avg_line_length": 24.272222222222222, "alnum_prop": 0.6550698100251774, "repo_name": "paypal/seifrng", "id": "da825b6a52b9d28e9f1a392156d8fb1796e2a21f", "size": "10076", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "interfaceMicrophone/src/interfaceMicrophone.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "150300" }, { "name": "CMake", "bytes": "11881" } ], "symlink_target": "" }
using System.Collections.Generic; using System.IO; using Newtonsoft.Json; namespace TrainFeverMod.Tester { public class JsonParser { public List<JsonData> ReadJson(string file) { string json = File.ReadAllText(file); return JsonConvert.DeserializeObject<List<JsonData>>(json); } } }
{ "content_hash": "38dffead5d60fd30ed64c8a3c15c18c3", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 71, "avg_line_length": 21.8125, "alnum_prop": 0.6446991404011462, "repo_name": "Kampfmoehre/TrainFeverMod", "id": "a16600f450503b7f5487ebe543fca3f7832bad04", "size": "351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TrainFeverMod.Tester/JsonParser.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "102" }, { "name": "C#", "bytes": "57320" } ], "symlink_target": "" }
title: Select --- Displays a `<select>` dropdown. - *options*: This is a javascript object. In this object, the key becomes the option value value and the value is used as the option label.
{ "content_hash": "a04d8bc73cf8439f2767179585c281d7", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 139, "avg_line_length": 38.4, "alnum_prop": 0.734375, "repo_name": "spleenboy/pallium-cms", "id": "49178d36eef54b3cb97bc806043e66ae7cd14e85", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/content/fields/select.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "231825" }, { "name": "HTML", "bytes": "60887" }, { "name": "JavaScript", "bytes": "105960" } ], "symlink_target": "" }
package org.apache.commons.math4.analysis.integration.gauss; import org.apache.commons.math4.exception.DimensionMismatchException; import org.apache.commons.math4.util.FastMath; import org.apache.commons.math4.util.Pair; /** * Factory that creates a * <a href="http://en.wikipedia.org/wiki/Gauss-Hermite_quadrature"> * Gauss-type quadrature rule using Hermite polynomials</a> * of the first kind. * Such a quadrature rule allows the calculation of improper integrals * of a function * <p> * \(f(x) e^{-x^2}\) * </p><p> * Recurrence relation and weights computation follow * <a href="http://en.wikipedia.org/wiki/Abramowitz_and_Stegun"> * Abramowitz and Stegun, 1964</a>. * </p><p> * The coefficients of the standard Hermite polynomials grow very rapidly. * In order to avoid overflows, each Hermite polynomial is normalized with * respect to the underlying scalar product. * The initial interval for the application of the bisection method is * based on the roots of the previous Hermite polynomial (interlacing). * Upper and lower bounds of these roots are provided by </p> * <blockquote> * I. Krasikov, * <em>Nonnegative quadratic forms and bounds on orthogonal polynomials</em>, * Journal of Approximation theory <b>111</b>, 31-49 * </blockquote> * * @since 3.3 */ public class HermiteRuleFactory extends BaseRuleFactory<Double> { /** &pi;<sup>1/2</sup> */ private static final double SQRT_PI = 1.77245385090551602729; /** &pi;<sup>-1/4</sup> */ private static final double H0 = 7.5112554446494248286e-1; /** &pi;<sup>-1/4</sup> &radic;2 */ private static final double H1 = 1.0622519320271969145; /** {@inheritDoc} */ @Override protected Pair<Double[], Double[]> computeRule(int numberOfPoints) throws DimensionMismatchException { if (numberOfPoints == 1) { // Break recursion. return new Pair<>(new Double[] { 0d }, new Double[] { SQRT_PI }); } // Get previous rule. // If it has not been computed yet it will trigger a recursive call // to this method. final int lastNumPoints = numberOfPoints - 1; final Double[] previousPoints = getRuleInternal(lastNumPoints).getFirst(); // Compute next rule. final Double[] points = new Double[numberOfPoints]; final Double[] weights = new Double[numberOfPoints]; final double sqrtTwoTimesLastNumPoints = FastMath.sqrt(2 * lastNumPoints); final double sqrtTwoTimesNumPoints = FastMath.sqrt(2 * numberOfPoints); // Find i-th root of H[n+1] by bracketing. final int iMax = numberOfPoints / 2; for (int i = 0; i < iMax; i++) { // Lower-bound of the interval. double a = (i == 0) ? -sqrtTwoTimesLastNumPoints : previousPoints[i - 1].doubleValue(); // Upper-bound of the interval. double b = (iMax == 1) ? -0.5 : previousPoints[i].doubleValue(); // H[j-1](a) double hma = H0; // H[j](a) double ha = H1 * a; // H[j-1](b) double hmb = H0; // H[j](b) double hb = H1 * b; for (int j = 1; j < numberOfPoints; j++) { // Compute H[j+1](a) and H[j+1](b) final double jp1 = j + 1; final double s = FastMath.sqrt(2 / jp1); final double sm = FastMath.sqrt(j / jp1); final double hpa = s * a * ha - sm * hma; final double hpb = s * b * hb - sm * hmb; hma = ha; ha = hpa; hmb = hb; hb = hpb; } // Now ha = H[n+1](a), and hma = H[n](a) (same holds for b). // Middle of the interval. double c = 0.5 * (a + b); // P[j-1](c) double hmc = H0; // P[j](c) double hc = H1 * c; boolean done = false; while (!done) { done = b - a <= Math.ulp(c); hmc = H0; hc = H1 * c; for (int j = 1; j < numberOfPoints; j++) { // Compute H[j+1](c) final double jp1 = j + 1; final double s = FastMath.sqrt(2 / jp1); final double sm = FastMath.sqrt(j / jp1); final double hpc = s * c * hc - sm * hmc; hmc = hc; hc = hpc; } // Now h = H[n+1](c) and hm = H[n](c). if (!done) { if (ha * hc < 0) { b = c; hmb = hmc; hb = hc; } else { a = c; hma = hmc; ha = hc; } c = 0.5 * (a + b); } } final double d = sqrtTwoTimesNumPoints * hmc; final double w = 2 / (d * d); points[i] = c; weights[i] = w; final int idx = lastNumPoints - i; points[idx] = -c; weights[idx] = w; } // If "numberOfPoints" is odd, 0 is a root. // Note: as written, the test for oddness will work for negative // integers too (although it is not necessary here), preventing // a FindBugs warning. if (numberOfPoints % 2 != 0) { double hm = H0; for (int j = 1; j < numberOfPoints; j += 2) { final double jp1 = j + 1; hm = -FastMath.sqrt(j / jp1) * hm; } final double d = sqrtTwoTimesNumPoints * hm; final double w = 2 / (d * d); points[iMax] = 0d; weights[iMax] = w; } return new Pair<>(points, weights); } }
{ "content_hash": "5a650f67267d3a81cc966df963bddbfa", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 99, "avg_line_length": 36.77160493827161, "alnum_prop": 0.504616417659896, "repo_name": "virtualdataset/metagen-java", "id": "e65f5bdeb3d25392d4eb5d3b7d7790286eada375", "size": "6759", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/HermiteRuleFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "4866" }, { "name": "Java", "bytes": "548350" }, { "name": "Shell", "bytes": "444" } ], "symlink_target": "" }
package cloudsearch import ( "github.com/gunosy/aws-sdk-go/aws" "github.com/gunosy/aws-sdk-go/internal/protocol/query" "github.com/gunosy/aws-sdk-go/internal/signer/v4" ) // You use the Amazon CloudSearch configuration service to create, configure, // and manage search domains. Configuration service requests are submitted using // the AWS Query protocol. AWS Query requests are HTTP or HTTPS requests submitted // via HTTP GET or POST with a query parameter named Action. // // The endpoint for configuration service requests is region-specific: cloudsearch.region.amazonaws.com. // For example, cloudsearch.us-east-1.amazonaws.com. For a current list of supported // regions and endpoints, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#cloudsearch_region" // target="_blank). type CloudSearch struct { *aws.Service } // Used for custom service initialization logic var initService func(*aws.Service) // Used for custom request initialization logic var initRequest func(*aws.Request) // New returns a new CloudSearch client. func New(config *aws.Config) *CloudSearch { service := &aws.Service{ Config: aws.DefaultConfig.Merge(config), ServiceName: "cloudsearch", APIVersion: "2013-01-01", } service.Initialize() // Handlers service.Handlers.Sign.PushBack(v4.Sign) service.Handlers.Build.PushBack(query.Build) service.Handlers.Unmarshal.PushBack(query.Unmarshal) service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) // Run custom service initialization if present if initService != nil { initService(service) } return &CloudSearch{service} } // newRequest creates a new request for a CloudSearch operation and runs any // custom request initialization. func (c *CloudSearch) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { req := aws.NewRequest(c.Service, op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
{ "content_hash": "2e47ddf02a7755aae66b4c2d357db482", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 128, "avg_line_length": 32.682539682539684, "alnum_prop": 0.7678484701311317, "repo_name": "gunosy/aws-sdk-go", "id": "2d4c5b164aa4fc9de55656857a5114a0ce993fdc", "size": "2114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "service/cloudsearch/service.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Cucumber", "bytes": "22856" }, { "name": "Go", "bytes": "9512242" }, { "name": "HTML", "bytes": "3690" }, { "name": "Makefile", "bytes": "1742" }, { "name": "Ruby", "bytes": "7365" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <class name="Cuyahoga.Core.Domain.Site, Cuyahoga.Core" table="cuyahoga_site"> <cache usage="read-write" /> <id name="Id" column="siteid" type="Int32" unsaved-value="-1"> <generator class="native"> <param name="sequence">cuyahoga_site_siteid_seq</param> </generator> </id> <timestamp name="UpdateTimestamp" column="updatetimestamp" /> <property name="Name" column="name" type="String" length="100" /> <property name="SiteUrl" column="homeurl" type="String" length="100" /> <property name="DefaultCulture" column="defaultculture" type="String" length="8" /> <property name="DefaultPlaceholder" column="defaultplaceholder" type="String" length="100" /> <property name="WebmasterEmail" column="webmasteremail" type="String" length="100" /> <property name="UseFriendlyUrls" column="usefriendlyurls" type="Boolean" /> <property name="MetaKeywords" column="metakeywords" type="String" length="500" /> <property name="MetaDescription" column="metadescription" type="String" length="500" /> <many-to-one name="DefaultTemplate" class="Cuyahoga.Core.Domain.Template, Cuyahoga.Core" column="templateid" not-null="false" outer-join="false" /> <!-- # added for v1.6.0 --> <many-to-one name="OfflineTemplate" class="Cuyahoga.Core.Domain.Template, Cuyahoga.Core" column="offlinetemplateid" not-null="false" outer-join="false" /> <!-- # added for v1.6.0 --> <many-to-one name="DefaultRole" class="Cuyahoga.Core.Domain.Role, Cuyahoga.Core" column="roleid" not-null="true" outer-join="true" /> <bag name="RootNodes" cascade="none" where="parentnodeid is null" order-by="position asc" lazy="true"> <key column="siteid" /> <one-to-many class="Cuyahoga.Core.Domain.Node, Cuyahoga.Core" /> </bag> </class> </hibernate-mapping>
{ "content_hash": "5128dc1939d192f86e516eecd232992a", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 158, "avg_line_length": 56.35294117647059, "alnum_prop": 0.68580375782881, "repo_name": "cuyahogaproject/cuyahoga-1", "id": "0a522e1cd28a5d2520d30a256c3f9662508a1c9c", "size": "1916", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core/Domain/Site.hbm.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "196611" }, { "name": "C#", "bytes": "941492" }, { "name": "CSS", "bytes": "91926" }, { "name": "JavaScript", "bytes": "300125" }, { "name": "SQL", "bytes": "306384" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("08.NumberAsArray")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("08.NumberAsArray")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7fef44df-1853-48fc-b706-ab66d824e1b9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "9fe04e1a5a4fa88bf6149359d104714a", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.02777777777778, "alnum_prop": 0.7451957295373666, "repo_name": "jorosoft/Telerik-Academy", "id": "1df4d0f4143bef9d1864987194c10a77ed0c4ddd", "size": "1408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Homeworks/C# Part 2/03.Methods/08.NumberAsArray/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "802179" }, { "name": "CSS", "bytes": "28985" }, { "name": "HTML", "bytes": "94575" }, { "name": "JavaScript", "bytes": "84023" }, { "name": "XSLT", "bytes": "3604" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>AngularProjectGuidelines</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html>
{ "content_hash": "f36bcf3e3f3d6ddb35f80307fcae0f0c", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 70, "avg_line_length": 22.214285714285715, "alnum_prop": 0.6527331189710611, "repo_name": "marcoturi/angular-project-guidelines", "id": "502eebfb5d7c2ded2c85b0d22ab6dbddc4215f0e", "size": "311", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "80" }, { "name": "HTML", "bytes": "2184" }, { "name": "JavaScript", "bytes": "1646" }, { "name": "TypeScript", "bytes": "12248" } ], "symlink_target": "" }
<!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_80) on Wed Mar 30 15:52:40 CDT 2016 --> <title>UsbModuleAttachmentHandler</title> <meta name="date" content="2016-03-30"> <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="UsbModuleAttachmentHandler"; } //--> </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="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/qualcomm/ftccommon/UpdateUI.Callback.html" title="class in com.qualcomm.ftccommon"><span class="strong">Prev Class</span></a></li> <li><a href="../../../com/qualcomm/ftccommon/ViewLogsActivity.html" title="class in com.qualcomm.ftccommon"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/qualcomm/ftccommon/UsbModuleAttachmentHandler.html" target="_top">Frames</a></li> <li><a href="UsbModuleAttachmentHandler.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">com.qualcomm.ftccommon</div> <h2 title="Interface UsbModuleAttachmentHandler" class="title">Interface UsbModuleAttachmentHandler</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../com/qualcomm/ftccommon/FtcEventLoop.DefaultUsbModuleAttachmentHandler.html" title="class in com.qualcomm.ftccommon">FtcEventLoop.DefaultUsbModuleAttachmentHandler</a></dd> </dl> <hr> <br> <pre>public interface <span class="strong">UsbModuleAttachmentHandler</span></pre> <div class="block">UsbModuleAttachmentHandler is a notification interface through which policies for dealing with the attachment and detachment can be provided.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../com/qualcomm/ftccommon/FtcEventLoop.html#setUsbModuleAttachmentHandler(com.qualcomm.ftccommon.UsbModuleAttachmentHandler)"><code>FtcEventLoop.setUsbModuleAttachmentHandler(UsbModuleAttachmentHandler)</code></a></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>void</code></td> <td class="colLast"><code><strong><a href="../../../com/qualcomm/ftccommon/UsbModuleAttachmentHandler.html#handleUsbModuleAttach(RobotUsbModule)">handleUsbModuleAttach</a></strong>(RobotUsbModule&nbsp;module)</code> <div class="block">One of the hardware modules in the current robot configuration (such as a Modern Robotics DC Motor Controller, a Modern Robotics Legacy Module, etc) is now newly attached to the system.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../com/qualcomm/ftccommon/UsbModuleAttachmentHandler.html#handleUsbModuleDetach(RobotUsbModule)">handleUsbModuleDetach</a></strong>(RobotUsbModule&nbsp;module)</code> <div class="block">One of the hardware modules in the current robot configuration (such as a Modern Robotics DC Motor Controller, a Modern Robotics Legacy Module, etc) has been disconnected from the system.</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="handleUsbModuleAttach(RobotUsbModule)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>handleUsbModuleAttach</h4> <pre>void&nbsp;handleUsbModuleAttach(RobotUsbModule&nbsp;module) throws <a href="../../../com/qualcomm/robotcore/exception/RobotCoreException.html" title="class in com.qualcomm.robotcore.exception">RobotCoreException</a>, java.lang.InterruptedException</pre> <div class="block">One of the hardware modules in the current robot configuration (such as a Modern Robotics DC Motor Controller, a Modern Robotics Legacy Module, etc) is now newly attached to the system. The code in this method should deal with this event by, e.g., putting the module into a correctly operating state.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>module</code> - the module which is newly attached</dd> <dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../../com/qualcomm/robotcore/exception/RobotCoreException.html" title="class in com.qualcomm.robotcore.exception">RobotCoreException</a></code></dd> <dd><code>java.lang.InterruptedException</code></dd></dl> </li> </ul> <a name="handleUsbModuleDetach(RobotUsbModule)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>handleUsbModuleDetach</h4> <pre>void&nbsp;handleUsbModuleDetach(RobotUsbModule&nbsp;module) throws <a href="../../../com/qualcomm/robotcore/exception/RobotCoreException.html" title="class in com.qualcomm.robotcore.exception">RobotCoreException</a>, java.lang.InterruptedException</pre> <div class="block">One of the hardware modules in the current robot configuration (such as a Modern Robotics DC Motor Controller, a Modern Robotics Legacy Module, etc) has been disconnected from the system. The code in this method should deal with this event by, e.g., putting the module in a state where it merely pretends to function.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>module</code> - the module which has become disconnected</dd> <dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../../com/qualcomm/robotcore/exception/RobotCoreException.html" title="class in com.qualcomm.robotcore.exception">RobotCoreException</a></code></dd> <dd><code>java.lang.InterruptedException</code></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="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/qualcomm/ftccommon/UpdateUI.Callback.html" title="class in com.qualcomm.ftccommon"><span class="strong">Prev Class</span></a></li> <li><a href="../../../com/qualcomm/ftccommon/ViewLogsActivity.html" title="class in com.qualcomm.ftccommon"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/qualcomm/ftccommon/UsbModuleAttachmentHandler.html" target="_top">Frames</a></li> <li><a href="UsbModuleAttachmentHandler.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 ======= --> </body> </html>
{ "content_hash": "0fae6fff823dd16ff5b8f1681704f495", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 292, "avg_line_length": 40.87301587301587, "alnum_prop": 0.6722330097087379, "repo_name": "YoshiRulz/Thunderbolts-Robotics-FTC", "id": "9fd7fd4dbb193ae5aa7485740f6fb28561764f21", "size": "10300", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/javadoc/com/qualcomm/ftccommon/UsbModuleAttachmentHandler.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "227256" } ], "symlink_target": "" }
from keystoneauth1 import loading from keystoneauth1 import session from oslo_log import log as logging from deckhand.conf import config from deckhand import errors from barbicanclient import barbican from barbicanclient import exceptions as barbican_exc CONF = config.CONF LOG = logging.getLogger(__name__) class BarbicanClientWrapper(object): """Barbican client wrapper class that encapsulates authentication logic.""" def __init__(self): """Initialise the BarbicanClientWrapper for use.""" self._cached_client = None def _invalidate_cached_client(self): """Tell the wrapper to invalidate the cached barbican-client.""" self._cached_client = None def _get_client(self, retry_on_conflict=True): # If we've already constructed a valid, authed client, just return # that. if retry_on_conflict and self._cached_client is not None: return self._cached_client # TODO(fmontei): Deckhand's configuration file needs to be populated # with correct Keysone authentication values as well as the Barbican # endpoint URL automatically. barbican_url = CONF.barbican.api_endpoint auth = loading.load_auth_from_conf_options(CONF, 'keystone_authtoken') sess = session.Session(auth=auth) try: cli = barbican.client.Client(endpoint=barbican_url, session=sess) # Cache the client so we don't have to reconstruct and # reauthenticate it every time we need it. if retry_on_conflict: self._cached_client = cli except barbican_exc.HTTPAuthError as e: LOG.exception(str(e)) raise errors.BarbicanException(details=str(e)) return cli def _multi_getattr(self, obj, attr): """Support nested attribute path for getattr(). :param obj: Root object. :param attr: Path of final attribute to get. E.g., "a.b.c.d" :returns: The value of the final named attribute. :raises: AttributeError will be raised if the path is invalid. """ for attribute in attr.split("."): obj = getattr(obj, attribute) return obj def call(self, method, *args, **kwargs): """Call a barbican client method and retry on stale token. :param method: Name of the client method to call as a string. :param args: Client method arguments. :param kwargs: Client method keyword arguments. :param retry_on_conflict: Boolean value. Whether the request should be retried in case of a conflict error (HTTP 409) or not. If retry_on_conflict is False the cached instance of the client won't be used. Defaults to True. """ retry_on_conflict = kwargs.pop('retry_on_conflict', True) for attempt in range(2): client = self._get_client(retry_on_conflict=retry_on_conflict) try: return self._multi_getattr(client, method)(*args, **kwargs) except barbican_exc.HTTPAuthError: # In this case, the authorization token of the cached # barbican-client probably expired. So invalidate the cached # client and the next try will start with a fresh one. if not attempt: self._invalidate_cached_client() LOG.debug("The Barbican client became unauthorized. " "Will attempt to reauthorize and try again.") else: # This code should be unreachable actually raise
{ "content_hash": "3b40f97059d85aca901ad0609ebdf373", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 79, "avg_line_length": 38.765306122448976, "alnum_prop": 0.6046327981047644, "repo_name": "att-comdev/deckhand", "id": "96514e75df85bf50487f6955b95bcf6151bcc4be", "size": "4419", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deckhand/barbican/client_wrapper.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "1699" }, { "name": "Mako", "bytes": "494" }, { "name": "Python", "bytes": "715959" }, { "name": "Shell", "bytes": "19114" } ], "symlink_target": "" }
package com.github.drinkjava2.jsqlbox; import java.lang.reflect.Method; import com.github.drinkjava2.cglib.proxy.Enhancer; import com.github.drinkjava2.cglib.proxy.MethodInterceptor; import com.github.drinkjava2.cglib.proxy.MethodProxy; import com.github.drinkjava2.jdbpro.SqlItem; import com.github.drinkjava2.jdialects.StrUtils; import com.github.drinkjava2.jdialects.TableModelUtils; import com.github.drinkjava2.jdialects.model.ColumnModel; import com.github.drinkjava2.jdialects.model.TableModel; /** * AliasProxyUtils used to create alias proxy * * @author Yong Zhu * @since 1.7.0 */ public class AliasProxyUtil {//NOSONAR public static ThreadLocal<AliasItemInfo> aliasItemInfo = new ThreadLocal<AliasItemInfo>();// NOSONAR static class AliasItemInfo { public String tableName = null;// NOSONAR public String alias = null;// NOSONAR public String colName = null;// NOSONAR public AliasItemInfo(String tableName, String alias, String colName) { this.tableName = tableName; this.alias = alias; this.colName = colName; } } /** * This proxy bean return null for all methods call, but based on current method * name write TableName, Alias,ColumnName these info into a ThreadLocal variant * aliasItemInfo. * * The MethodInterceptor depends on CgLib, not AOP alliance, CgLib is included * in jBeanBox(changed package name), jBeanBox is included in jBeanBox's Java8 * version */ static class ProxyBean implements MethodInterceptor { private TableModel tableModel; private String alias; public ProxyBean(TableModel tableModel, String alias) { this.tableModel = tableModel; this.alias = alias; } public Object intercept(Object obj, Method method, Object[] args, MethodProxy cgLibMethodProxy) throws Throwable { aliasItemInfo.remove(); if (method != null && tableModel != null) { String fieldName; String methodNm = method.getName(); if (methodNm.startsWith("get")) fieldName = methodNm.substring(3); else fieldName = methodNm.substring(2); String columnName = null; for (ColumnModel col : tableModel.getColumns()) if (col.getEntityField().equalsIgnoreCase(fieldName)) columnName = col.getColumnName(); aliasItemInfo.set(new AliasItemInfo(tableModel.getTableName(), alias, columnName)); } return null; } } /** * Create a alias proxy for iQuery query * * @param clazz * target class * @return proxy bean which make all methods only return null */ public static <T> T createAliasProxy(Class<T> c) { return createAliasProxy(c, null); } /** * Create a alias proxy for iQuery query * * @param clazz * The target entity class * @param alias * The alias in SQL * @return Proxy entity bean which make all methods only return null */ @SuppressWarnings("unchecked") public static <T> T createAliasProxy(Class<T> c, String alias) { TableModel t = TableModelUtils.entity2ReadOnlyModel(c); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(c); enhancer.setCallback(new ProxyBean(t, alias)); return (T) enhancer.create(); } public static SqlItem clean() { aliasItemInfo.remove(); return new SqlItem(""); } public static SqlItem alias(Object o) {// NOSONAR try { AliasItemInfo a = aliasItemInfo.get(); if (StrUtils.isEmpty(a.colName)) throw new DbException("Column name not found."); if (StrUtils.isEmpty(a.alias)) return new SqlItem(a.colName); else return new SqlItem(new StringBuilder(a.alias).append(".").append(a.colName).append(" as ") .append(a.alias).append("_").append(a.colName).toString()); } finally { aliasItemInfo.remove(); } } public static SqlItem c_alias(Object o) {// NOSONAR try { AliasItemInfo a = aliasItemInfo.get(); if (StrUtils.isEmpty(a.colName)) throw new DbException("Column name not found."); if (StrUtils.isEmpty(a.alias)) return new SqlItem(", " + a.colName); else return new SqlItem(new StringBuilder(", ").append(a.alias).append(".").append(a.colName).append(" as ") .append(a.alias).append("_").append(a.colName).toString()); } finally { aliasItemInfo.remove(); } } public static SqlItem col(Object o) {// NOSONAR try { AliasItemInfo a = aliasItemInfo.get(); if (StrUtils.isEmpty(a.colName)) throw new DbException("Column name not found."); if (StrUtils.isEmpty(a.alias)) return new SqlItem(a.colName); else return new SqlItem(new StringBuilder(a.alias).append(".").append(a.colName).toString()); } finally { aliasItemInfo.remove(); } } public static SqlItem table(Object o) { try { o.toString(); AliasItemInfo a = aliasItemInfo.get(); if (StrUtils.isEmpty(a.alias)) return new SqlItem(a.tableName); else return new SqlItem(new StringBuilder(a.tableName).append(" ").append(a.alias).toString()); } finally { aliasItemInfo.remove(); } } public static SqlItem TABLE(Object o) {// NOSONAR return table(o); } }
{ "content_hash": "41dc93617b64e35e5912b44414cc8081", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 107, "avg_line_length": 29.857142857142858, "alnum_prop": 0.7009569377990431, "repo_name": "drinkjava2/jSQLBox", "id": "c2f188beaaca2329f4a41754fab129b2567a7f57", "size": "5016", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/com/github/drinkjava2/jsqlbox/AliasProxyUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "81" }, { "name": "Java", "bytes": "275239" } ], "symlink_target": "" }
from django.core.paginator import Paginator, Page, PageNotAnInteger, EmptyPage class InfinitePaginator(Paginator): """ Paginator designed for cases when it's not important to know how many total pages. This is useful for any object_list that has no count() method or can be used to improve performance for MySQL by removing counts. The orphans parameter has been removed for simplicity and there's a link template string for creating the links to the next and previous pages. """ def __init__(self, object_list, per_page, allow_empty_first_page=True, link_template='/page/%d/'): orphans = 0 # no orphans super(InfinitePaginator, self).__init__(object_list, per_page, orphans, allow_empty_first_page) # no count or num pages del self._num_pages, self._count # bonus links self.link_template = link_template def validate_number(self, number): """ Validates the given 1-based page number. """ try: number = int(number) except ValueError: raise PageNotAnInteger('That page number is not an integer') if number < 1: raise EmptyPage('That page number is less than 1') return number def page(self, number): """ Returns a Page object for the given 1-based page number. """ number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page page_items = self.object_list[bottom:top] # check moved from validate_number if not page_items: if number == 1 and self.allow_empty_first_page: pass else: raise EmptyPage('That page contains no results') return InfinitePage(page_items, number, self) def _get_count(self): """ Returns the total number of objects, across all pages. """ raise NotImplementedError count = property(_get_count) def _get_num_pages(self): """ Returns the total number of pages. """ raise NotImplementedError num_pages = property(_get_num_pages) def _get_page_range(self): """ Returns a 1-based range of pages for iterating through within a template for loop. """ raise NotImplementedError page_range = property(_get_page_range) class InfinitePage(Page): def __repr__(self): return '<Page %s>' % self.number def has_next(self): """ Checks for one more item than last on this page. """ try: self.paginator.object_list[self.number * self.paginator.per_page] except IndexError: return False return True def end_index(self): """ Returns the 1-based index of the last object on this page, relative to total objects found (hits). """ return ((self.number - 1) * self.paginator.per_page + len(self.object_list)) #Bonus methods for creating links def next_link(self): if self.has_next(): return self.paginator.link_template % (self.number + 1) return None def previous_link(self): if self.has_previous(): return self.paginator.link_template % (self.number - 1) return None class FinitePaginator(InfinitePaginator): """ Paginator for cases when the list of items is already finite. A good example is a list generated from an API call. This is a subclass of InfinitePaginator because we have no idea how many items exist in the full collection. To accurately determine if the next page exists, a FinitePaginator MUST be created with an object_list_plus that may contain more items than the per_page count. Typically, you'll have an object_list_plus with one extra item (if there's a next page). You'll also need to supply the offset from the full collection in order to get the page start_index. This is a very silly class but useful if you love the Django pagination conventions. """ def __init__(self, object_list_plus, per_page, offset=None, allow_empty_first_page=True, link_template='/page/%d/'): super(FinitePaginator, self).__init__(object_list_plus, per_page, allow_empty_first_page, link_template) self.offset = offset def validate_number(self, number): super(FinitePaginator, self).validate_number(number) # check for an empty list to see if the page exists if not self.object_list: if number == 1 and self.allow_empty_first_page: pass else: raise EmptyPage('That page contains no results') return number def page(self, number): """ Returns a Page object for the given 1-based page number. """ number = self.validate_number(number) # remove the extra item(s) when creating the page page_items = self.object_list[:self.per_page] return FinitePage(page_items, number, self) class FinitePage(InfinitePage): def has_next(self): """ Checks for one more item than last on this page. """ try: self.paginator.object_list[self.paginator.per_page] except IndexError: return False return True def start_index(self): """ Returns the 1-based index of the first object on this page, relative to total objects in the paginator. """ ## TODO should this holler if you haven't defined the offset? return self.paginator.offset
{ "content_hash": "ca62bdb330072d821a99857495b584fc", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 79, "avg_line_length": 33.15028901734104, "alnum_prop": 0.6160418482999128, "repo_name": "alternativshik/django-pagination", "id": "61c7b52d3403232b0db057619d77ad09daf9450f", "size": "7389", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "alter_django_pagination/paginator.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "2906" }, { "name": "Python", "bytes": "50505" } ], "symlink_target": "" }
@interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UIButton *sortedKey; @property (weak, nonatomic) IBOutlet UIButton *sortedValue; @end
{ "content_hash": "4b7ef56b6100034ac8c901f20af35354", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 59, "avg_line_length": 33.8, "alnum_prop": 0.8047337278106509, "repo_name": "tamptse/Sorted", "id": "d9e6548cb22b80e8d5b063abeb9608e67cda5b5c", "size": "322", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "5833" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="PublishConfigData"> <serverData> <paths name="lkiora000webhost"> <serverdata> <mappings> <mapping local="$PROJECT_DIR$" web="/" /> </mappings> </serverdata> </paths> <paths name="sailing-cancun.com"> <serverdata> <mappings> <mapping local="$PROJECT_DIR$" web="/" /> </mappings> </serverdata> </paths> <paths name="www.cancuntt.com"> <serverdata> <mappings> <mapping local="$PROJECT_DIR$" web="/" /> </mappings> </serverdata> </paths> <paths name="www.qtrinus.com"> <serverdata> <mappings> <mapping local="$PROJECT_DIR$" web="/" /> </mappings> </serverdata> </paths> <paths name="www.restaurant-masters.com"> <serverdata> <mappings> <mapping local="$PROJECT_DIR$" web="/" /> </mappings> </serverdata> </paths> </serverData> </component> </project>
{ "content_hash": "f1b8b79fa4ee0bfb3c2eee75b123e8bb", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 53, "avg_line_length": 27.047619047619047, "alnum_prop": 0.49471830985915494, "repo_name": "JorgeProyecto/azulCancun", "id": "a33a2939df1b12db73cd84543d89730174b9573b", "size": "1136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/deployment.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "232" }, { "name": "CSS", "bytes": "165735" }, { "name": "HTML", "bytes": "157659" }, { "name": "JavaScript", "bytes": "93106" }, { "name": "PHP", "bytes": "15047" }, { "name": "Ruby", "bytes": "161" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:tileMode="repeat" android:src="@drawable/slidingmenu_bkg_piece" />
{ "content_hash": "2ff1dd3ca1ed80a1e0a93a5091283445", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 66, "avg_line_length": 48.25, "alnum_prop": 0.694300518134715, "repo_name": "liyaguang/PalHunterClient", "id": "b1590272bd91b1acbeed39070b8b8f633bd46aa2", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/drawable/slidingmenu_repeat_bkg.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "162852" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> <meta name="description" content=""> <meta name="author" content=""> </head> <body> <a href="http://servers.rickvanlieshout.com/scalatest/page2.html">page 2</a> <a href="http://servers.rickvanlieshout.com/scalatest/page3.html">page 3</a> <a href="http://servers.rickvanlieshout.com/scalatest/page3.html">page 3</a> <!-- Should be ignored --> <a href="http://google.nl">google</a> <a href="www.google.com">google</a> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ad consequatur delectus enim eos est eum ex, facere id maxime molestiae nam, nihil officia perspiciatis reprehenderit suscipit vel velit veritatis? </p> </body> </html>
{ "content_hash": "cc237288cf25facf031f512b40479de5", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 219, "avg_line_length": 33.65217391304348, "alnum_prop": 0.6886304909560723, "repo_name": "Mastermindzh/Seven-Languages-in-Seven-Weeks", "id": "0d70b5f75a788a6f07b422a97b30187f6438c321", "size": "774", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Scala/Day 4/src/main/resources/TestSite/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1792" }, { "name": "Ruby", "bytes": "1361" }, { "name": "Scala", "bytes": "17424" } ], "symlink_target": "" }
%SerialLink.MANIPLTY Manipulability measure % % M = R.maniplty(Q, OPTIONS) is the manipulability index measure for the robot % at the joint configuration Q. It indicates dexterity, how isotropic the % robot's motion is with respect to the 6 degrees of Cartesian motion. % The measure is low when the manipulator is close to a singularity. % If Q is a matrix M is a column vector of manipulability % indices for each pose specified by a row of Q. % % Two measures can be selected: % - Yoshikawa's manipulability measure is based on the shape of the velocity % ellipsoid and depends only on kinematic parameters. % - Asada's manipulability measure is based on the shape of the acceleration % ellipsoid which in turn is a function of the Cartesian inertia matrix and % the dynamic parameters. The scalar measure computed here is the ratio of % the smallest/largest ellipsoid axis. Ideally the ellipsoid would be % spherical, giving a ratio of 1, but in practice will be less than 1. % % Options:: % 'T' compute manipulability for just transational motion % 'R' compute manipulability for just rotational motion % 'yoshikawa' use Asada algorithm (default) % 'asada' use Asada algorithm % % Notes:: % - by default the measure includes rotational and translational dexterity, but % this involves adding different units. It can be more useful to look at the % translational and rotational manipulability separately. % % See also SerialLink.inertia, SerialLink.jacob0. % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, by Peter I. Corke % % This file is part of The Robotics Toolbox for MATLAB (RTB). % % RTB is free software: you can redistribute it and/or modify % it under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % RTB is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU Lesser General Public License for more details. % % You should have received a copy of the GNU Leser General Public License % along with RTB. If not, see <http://www.gnu.org/licenses/>. % % http://www.petercorke.com function [w,mx] = maniplty(robot, q, varargin) n = robot.n; opt.yoshikawa = true; opt.asada = false; opt.axes = {'all', 'T', 'R'}; opt = tb_optparse(opt, varargin); if length(q) == robot.n, q = q(:)'; end w = []; MX = []; if opt.yoshikawa for Q = q', w = [w; yoshi(robot, Q, opt)]; end elseif opt.asada for Q = q', if nargout > 1 [ww,mm] = asada(robot, Q); w = [w; ww]; MX = cat(3, MX, mm); else w = [w; asada(robot, Q, opt)]; end end end if nargout > 1 mx = MX; end function m = yoshi(robot, q, opt) J = jacob0(robot, q); switch opt.axes case 'T' J = J(1:3,:); case 'R' J = J(4:6,:); end m = sqrt(det(J * J')); function [m, mx] = asada(robot, q, opt) J = jacob0(robot, q); if rank(J) < 6, warning('robot is in degenerate configuration') m = 0; return; end switch opt.axes case 'T' J = J(1:3,:) case 'R' J = J(4:6,:); end Ji = inv(J); M = inertia(robot, q); Mx = Ji' * M * Ji; e = eig(Mx(1:3,1:3)); m = min(e) / max(e); if nargout > 1 mx = Mx; end
{ "content_hash": "db86403e6ccb78655d8feed3f696f702", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 79, "avg_line_length": 29.442622950819672, "alnum_prop": 0.6428173719376392, "repo_name": "madratman/riss_bingham", "id": "0a165c804839d2da95e559b3e6feed22dba97032", "size": "3592", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "matlab/robot-9.10/rvctools/robot/Octave/@SerialLink/maniplty.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "17198129" }, { "name": "C++", "bytes": "22178342" }, { "name": "CSS", "bytes": "14525" }, { "name": "Fortran", "bytes": "285254" }, { "name": "HTML", "bytes": "3452018" }, { "name": "Java", "bytes": "36102" }, { "name": "JavaScript", "bytes": "22349" }, { "name": "Lua", "bytes": "29317" }, { "name": "M", "bytes": "3179" }, { "name": "Makefile", "bytes": "7138" }, { "name": "Mathematica", "bytes": "465" }, { "name": "Matlab", "bytes": "3540588" }, { "name": "Mercury", "bytes": "201" }, { "name": "Perl", "bytes": "2698" }, { "name": "R", "bytes": "2166" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Misc. bot. 67, tab. 11 (1803) #### Original name Agaricus albidus Balb. ### Remarks null
{ "content_hash": "4c18d79b91aaaa3c5d6514c5f7f4dae2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 29, "avg_line_length": 11.692307692307692, "alnum_prop": 0.6776315789473685, "repo_name": "mdoering/backbone", "id": "14c3b1133aaecf523a44bdd5b33b9afa7ece19a8", "size": "198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Agaricaceae/Agaricus/Agaricus albidus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!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_80) on Thu Oct 15 19:27:11 UTC 2015 --> <title>Relationship (AWS SDK for Java - 1.10.27)</title> <meta name="date" content="2015-10-15"> <link rel="stylesheet" type="text/css" href="../../../../../JavaDoc.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Relationship (AWS SDK for Java - 1.10.27)"; } //--> </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="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <!-- Scripts for Syntax Highlighter START--> <script id="syntaxhighlight_script_core" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shCore.js"> </script> <script id="syntaxhighlight_script_java" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shBrushJava.js"> </script> <link id="syntaxhighlight_css_core" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shCoreDefault.css"/> <link id="syntaxhighlight_css_theme" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shThemeDefault.css"/> <!-- Scripts for Syntax Highlighter END--> <div> <!-- BEGIN-SECTION --> <div id="divsearch" style="float:left;"> <span id="lblsearch" for="searchQuery"> <label>Search</label> </span> <form id="nav-search-form" target="_parent" method="get" action="http://docs.aws.amazon.com/search/doc-search.html#facet_doc_guide=API+Reference&facet_doc_product=AWS+SDK+for+Java"> <div id="nav-searchfield-outer" class="nav-sprite"> <div class="nav-searchfield-inner nav-sprite"> <div id="nav-searchfield-width"> <input id="nav-searchfield" name="searchQuery"> </div> </div> </div> <div id="nav-search-button" class="nav-sprite"> <input alt="" id="nav-search-button-inner" type="image"> </div> <input name="searchPath" type="hidden" value="documentation-guide" /> <input name="this_doc_product" type="hidden" value="AWS SDK for Java" /> <input name="this_doc_guide" type="hidden" value="API Reference" /> <input name="doc_locale" type="hidden" value="en_us" /> </form> </div> <!-- END-SECTION --> <!-- BEGIN-FEEDBACK-SECTION --> <div id="feedback-section"> <h3>Did this page help you?</h3> <div id="feedback-link-sectioin"> <a id="feedback_yes" target="_blank" style="display:inline;">Yes</a>&nbsp;&nbsp; <a id="feedback_no" target="_blank" style="display:inline;">No</a>&nbsp;&nbsp; <a id="go_cti" target="_blank" style="display:inline;">Tell us about it...</a> </div> </div> <script type="text/javascript"> window.onload = function(){ /* Dynamically add feedback links */ var javadoc_root_name = "/javadoc/"; var javadoc_path = location.href.substring(0, location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var file_path = location.href.substring(location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var feedback_yes_url = javadoc_path + "javadoc-resources/feedbackyes.html?topic_id="; var feedback_no_url = javadoc_path + "javadoc-resources/feedbackno.html?topic_id="; var feedback_tellmore_url = "https://aws-portal.amazon.com/gp/aws/html-forms-controller/documentation/aws_doc_feedback_04?service_name=Java-Ref&file_name="; if(file_path != "overview-frame.html") { var file_name = file_path.replace(/[/.]/g, '_'); document.getElementById("feedback_yes").setAttribute("href", feedback_yes_url + file_name); document.getElementById("feedback_no").setAttribute("href", feedback_no_url + file_name); document.getElementById("go_cti").setAttribute("href", feedback_tellmore_url + file_name); } else { // hide the search box and the feeback links in overview-frame page, // show "AWS SDK for Java" instead. document.getElementById("feedback-section").outerHTML = "AWS SDK for Java"; document.getElementById("divsearch").outerHTML = ""; } }; </script> <!-- END-FEEDBACK-SECTION --> </div> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/amazonaws/services/config/model/RecordingGroup.html" title="class in com.amazonaws.services.config.model"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/amazonaws/services/config/model/ResourceIdentifier.html" title="class in com.amazonaws.services.config.model"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/amazonaws/services/config/model/Relationship.html" target="_top">Frames</a></li> <li><a href="Relationship.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><a href="#constructor_summary">Constr</a>&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><a href="#constructor_detail">Constr</a>&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">com.amazonaws.services.config.model</div> <h2 title="Class Relationship" class="title">Class Relationship</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.amazonaws.services.config.model.Relationship</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, java.lang.Cloneable</dd> </dl> <hr> <br> <pre>public class <span class="strong">Relationship</span> extends java.lang.Object implements java.io.Serializable, java.lang.Cloneable</pre> <div class="block"><p> The relationship of the related resource to the main resource. </p></div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../serialized-form.html#com.amazonaws.services.config.model.Relationship">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#Relationship()">Relationship</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== 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><a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#clone()">clone</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#equals(java.lang.Object)">equals</a></strong>(java.lang.Object&nbsp;obj)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#getRelationshipName()">getRelationshipName</a></strong>()</code> <div class="block"> The type of relationship with the related resource.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#getResourceId()">getResourceId</a></strong>()</code> <div class="block"> The ID of the related resource (for example, <code>sg-xxxxxx</code>).</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#getResourceName()">getResourceName</a></strong>()</code> <div class="block"> The custom name of the related resource, if available.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#getResourceType()">getResourceType</a></strong>()</code> <div class="block"> The resource type of the related resource.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#hashCode()">hashCode</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#setRelationshipName(java.lang.String)">setRelationshipName</a></strong>(java.lang.String&nbsp;relationshipName)</code> <div class="block"> The type of relationship with the related resource.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#setResourceId(java.lang.String)">setResourceId</a></strong>(java.lang.String&nbsp;resourceId)</code> <div class="block"> The ID of the related resource (for example, <code>sg-xxxxxx</code>).</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#setResourceName(java.lang.String)">setResourceName</a></strong>(java.lang.String&nbsp;resourceName)</code> <div class="block"> The custom name of the related resource, if available.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#setResourceType(com.amazonaws.services.config.model.ResourceType)">setResourceType</a></strong>(<a href="../../../../../com/amazonaws/services/config/model/ResourceType.html" title="enum in com.amazonaws.services.config.model">ResourceType</a>&nbsp;resourceType)</code> <div class="block"> The resource type of the related resource.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#setResourceType(java.lang.String)">setResourceType</a></strong>(java.lang.String&nbsp;resourceType)</code> <div class="block"> The resource type of the related resource.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#toString()">toString</a></strong>()</code> <div class="block">Returns a string representation of this object; useful for testing and debugging.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#withRelationshipName(java.lang.String)">withRelationshipName</a></strong>(java.lang.String&nbsp;relationshipName)</code> <div class="block"> The type of relationship with the related resource.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#withResourceId(java.lang.String)">withResourceId</a></strong>(java.lang.String&nbsp;resourceId)</code> <div class="block"> The ID of the related resource (for example, <code>sg-xxxxxx</code>).</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#withResourceName(java.lang.String)">withResourceName</a></strong>(java.lang.String&nbsp;resourceName)</code> <div class="block"> The custom name of the related resource, if available.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#withResourceType(com.amazonaws.services.config.model.ResourceType)">withResourceType</a></strong>(<a href="../../../../../com/amazonaws/services/config/model/ResourceType.html" title="enum in com.amazonaws.services.config.model">ResourceType</a>&nbsp;resourceType)</code> <div class="block"> The resource type of the related resource.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/config/model/Relationship.html#withResourceType(java.lang.String)">withResourceType</a></strong>(java.lang.String&nbsp;resourceType)</code> <div class="block"> The resource type of the related resource.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Relationship()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Relationship</h4> <pre>public&nbsp;Relationship()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="setResourceType(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setResourceType</h4> <pre>public&nbsp;void&nbsp;setResourceType(java.lang.String&nbsp;resourceType)</pre> <div class="block"><p> The resource type of the related resource. </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>resourceType</code> - The resource type of the related resource.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../com/amazonaws/services/config/model/ResourceType.html" title="enum in com.amazonaws.services.config.model"><code>ResourceType</code></a></dd></dl> </li> </ul> <a name="getResourceType()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getResourceType</h4> <pre>public&nbsp;java.lang.String&nbsp;getResourceType()</pre> <div class="block"><p> The resource type of the related resource. </p></div> <dl><dt><span class="strong">Returns:</span></dt><dd>The resource type of the related resource.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../com/amazonaws/services/config/model/ResourceType.html" title="enum in com.amazonaws.services.config.model"><code>ResourceType</code></a></dd></dl> </li> </ul> <a name="withResourceType(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withResourceType</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a>&nbsp;withResourceType(java.lang.String&nbsp;resourceType)</pre> <div class="block"><p> The resource type of the related resource. </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>resourceType</code> - The resource type of the related resource.</dd> <dt><span class="strong">Returns:</span></dt><dd>Returns a reference to this object so that method calls can be chained together.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../com/amazonaws/services/config/model/ResourceType.html" title="enum in com.amazonaws.services.config.model"><code>ResourceType</code></a></dd></dl> </li> </ul> <a name="setResourceType(com.amazonaws.services.config.model.ResourceType)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setResourceType</h4> <pre>public&nbsp;void&nbsp;setResourceType(<a href="../../../../../com/amazonaws/services/config/model/ResourceType.html" title="enum in com.amazonaws.services.config.model">ResourceType</a>&nbsp;resourceType)</pre> <div class="block"><p> The resource type of the related resource. </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>resourceType</code> - The resource type of the related resource.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../com/amazonaws/services/config/model/ResourceType.html" title="enum in com.amazonaws.services.config.model"><code>ResourceType</code></a></dd></dl> </li> </ul> <a name="withResourceType(com.amazonaws.services.config.model.ResourceType)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withResourceType</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a>&nbsp;withResourceType(<a href="../../../../../com/amazonaws/services/config/model/ResourceType.html" title="enum in com.amazonaws.services.config.model">ResourceType</a>&nbsp;resourceType)</pre> <div class="block"><p> The resource type of the related resource. </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>resourceType</code> - The resource type of the related resource.</dd> <dt><span class="strong">Returns:</span></dt><dd>Returns a reference to this object so that method calls can be chained together.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../com/amazonaws/services/config/model/ResourceType.html" title="enum in com.amazonaws.services.config.model"><code>ResourceType</code></a></dd></dl> </li> </ul> <a name="setResourceId(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setResourceId</h4> <pre>public&nbsp;void&nbsp;setResourceId(java.lang.String&nbsp;resourceId)</pre> <div class="block"><p> The ID of the related resource (for example, <code>sg-xxxxxx</code>). </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>resourceId</code> - The ID of the related resource (for example, <code>sg-xxxxxx</code>).</dd></dl> </li> </ul> <a name="getResourceId()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getResourceId</h4> <pre>public&nbsp;java.lang.String&nbsp;getResourceId()</pre> <div class="block"><p> The ID of the related resource (for example, <code>sg-xxxxxx</code>). </p></div> <dl><dt><span class="strong">Returns:</span></dt><dd>The ID of the related resource (for example, <code>sg-xxxxxx</code>).</dd></dl> </li> </ul> <a name="withResourceId(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withResourceId</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a>&nbsp;withResourceId(java.lang.String&nbsp;resourceId)</pre> <div class="block"><p> The ID of the related resource (for example, <code>sg-xxxxxx</code>). </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>resourceId</code> - The ID of the related resource (for example, <code>sg-xxxxxx</code>).</dd> <dt><span class="strong">Returns:</span></dt><dd>Returns a reference to this object so that method calls can be chained together.</dd></dl> </li> </ul> <a name="setResourceName(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setResourceName</h4> <pre>public&nbsp;void&nbsp;setResourceName(java.lang.String&nbsp;resourceName)</pre> <div class="block"><p> The custom name of the related resource, if available. </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>resourceName</code> - The custom name of the related resource, if available.</dd></dl> </li> </ul> <a name="getResourceName()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getResourceName</h4> <pre>public&nbsp;java.lang.String&nbsp;getResourceName()</pre> <div class="block"><p> The custom name of the related resource, if available. </p></div> <dl><dt><span class="strong">Returns:</span></dt><dd>The custom name of the related resource, if available.</dd></dl> </li> </ul> <a name="withResourceName(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withResourceName</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a>&nbsp;withResourceName(java.lang.String&nbsp;resourceName)</pre> <div class="block"><p> The custom name of the related resource, if available. </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>resourceName</code> - The custom name of the related resource, if available.</dd> <dt><span class="strong">Returns:</span></dt><dd>Returns a reference to this object so that method calls can be chained together.</dd></dl> </li> </ul> <a name="setRelationshipName(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setRelationshipName</h4> <pre>public&nbsp;void&nbsp;setRelationshipName(java.lang.String&nbsp;relationshipName)</pre> <div class="block"><p> The type of relationship with the related resource. </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>relationshipName</code> - The type of relationship with the related resource.</dd></dl> </li> </ul> <a name="getRelationshipName()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getRelationshipName</h4> <pre>public&nbsp;java.lang.String&nbsp;getRelationshipName()</pre> <div class="block"><p> The type of relationship with the related resource. </p></div> <dl><dt><span class="strong">Returns:</span></dt><dd>The type of relationship with the related resource.</dd></dl> </li> </ul> <a name="withRelationshipName(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withRelationshipName</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a>&nbsp;withRelationshipName(java.lang.String&nbsp;relationshipName)</pre> <div class="block"><p> The type of relationship with the related resource. </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>relationshipName</code> - The type of relationship with the related resource.</dd> <dt><span class="strong">Returns:</span></dt><dd>Returns a reference to this object so that method calls can be chained together.</dd></dl> </li> </ul> <a name="toString()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <div class="block">Returns a string representation of this object; useful for testing and debugging.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> <dt><span class="strong">Returns:</span></dt><dd>A string representation of this object.</dd><dt><span class="strong">See Also:</span></dt><dd><code>Object.toString()</code></dd></dl> </li> </ul> <a name="equals(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(java.lang.Object&nbsp;obj)</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>equals</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="hashCode()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;hashCode()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>hashCode</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="clone()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>clone</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/config/model/Relationship.html" title="class in com.amazonaws.services.config.model">Relationship</a>&nbsp;clone()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>clone</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></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="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <div> <!-- Script for Syntax Highlighter START --> <script type="text/javascript"> SyntaxHighlighter.all() </script> <!-- Script for Syntax Highlighter END --> </div> <script src="http://a0.awsstatic.com/chrome/js/1.0.46/jquery.1.9.js" type="text/javascript"></script> <script>jQuery.noConflict();</script> <script> jQuery(function ($) { $("div.header").prepend('<!--REGION_DISCLAIMER_DO_NOT_REMOVE-->'); }); </script> <!-- BEGIN-URCHIN-TRACKER --> <script src="http://l0.awsstatic.com/js/urchin.js" type="text/javascript"></script> <script type="text/javascript">urchinTracker();</script> <!-- END-URCHIN-TRACKER --> <!-- SiteCatalyst code version: H.25.2. Copyright 1996-2012 Adobe, Inc. All Rights Reserved. More info available at http://www.omniture.com --> <script language="JavaScript" type="text/javascript" src="https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js (view-source:https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js)" /> <script language="JavaScript" type="text/javascript"> <!-- // Documentation Service Name s.prop66='AWS SDK for Java'; s.eVar66='D=c66'; // Documentation Guide Name s.prop65='API Reference'; s.eVar65='D=c65'; var s_code=s.t();if(s_code)document.write(s_code) //--> </script> <script language="JavaScript" type="text/javascript"> <!--if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-') //--> </script> <noscript> <img src="http://amazonwebservices.d2.sc.omtrdc.net/b/ss/awsamazondev/1/H.25.2--NS/0" height="1" width="1" border="0" alt="" /> </noscript> <!--/DO NOT REMOVE/--> <!-- End SiteCatalyst code version: H.25.2. --> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/amazonaws/services/config/model/RecordingGroup.html" title="class in com.amazonaws.services.config.model"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/amazonaws/services/config/model/ResourceIdentifier.html" title="class in com.amazonaws.services.config.model"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/amazonaws/services/config/model/Relationship.html" target="_top">Frames</a></li> <li><a href="Relationship.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><a href="#constructor_summary">Constr</a>&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><a href="#constructor_detail">Constr</a>&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> Copyright &#169; 2013 Amazon Web Services, Inc. All Rights Reserved. </small></p> </body> </html>
{ "content_hash": "a2f4976326d228a74243965bf739eaca", "timestamp": "", "source": "github", "line_count": 736, "max_line_length": 383, "avg_line_length": 45.22690217391305, "alnum_prop": 0.6480307627602367, "repo_name": "TomNong/Project2-Intel-Edison", "id": "d451209acbe50a6f439de2e7bd50e9c04da4bd50", "size": "33287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documentation/javadoc/com/amazonaws/services/config/model/Relationship.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "5522" } ], "symlink_target": "" }
using System; using Server.Network; using Server.Targeting; using Server.Items; namespace Server.Items { public interface ILockpickable : IPoint2D { int LockLevel{ get; set; } bool Locked{ get; set; } Mobile Picker{ get; set; } int MaxLockLevel{ get; set; } int RequiredSkill{ get; set; } void LockPick( Mobile from ); } [FlipableAttribute( 0x14fc, 0x14fb )] public class Lockpick : Item { [Constructable] public Lockpick() : this( 1 ) { } [Constructable] public Lockpick( int amount ) : base( 0x14FC ) { Stackable = true; Amount = amount; } public Lockpick( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); if ( version == 0 && Weight == 0.1 ) Weight = -1; } public override void OnDoubleClick( Mobile from ) { from.SendLocalizedMessage( 502068 ); // What do you want to pick? from.Target = new InternalTarget( this ); } private class InternalTarget : Target { private Lockpick m_Item; public InternalTarget( Lockpick item ) : base( 1, false, TargetFlags.None ) { m_Item = item; } protected override void OnTarget( Mobile from, object targeted ) { if ( m_Item.Deleted ) return; if ( targeted is ILockpickable ) { Item item = (Item)targeted; from.Direction = from.GetDirectionTo( item ); if ( ((ILockpickable)targeted).Locked ) { from.PlaySound( 0x241 ); new InternalTimer( from, (ILockpickable)targeted, m_Item ).Start(); } else { // The door is not locked from.SendLocalizedMessage( 502069 ); // This does not appear to be locked } } else { from.SendLocalizedMessage( 501666 ); // You can't unlock that! } } private class InternalTimer : Timer { private Mobile m_From; private ILockpickable m_Item; private Lockpick m_Lockpick; public InternalTimer( Mobile from, ILockpickable item, Lockpick lockpick ) : base( TimeSpan.FromSeconds( 3.0 ) ) { m_From = from; m_Item = item; m_Lockpick = lockpick; Priority = TimerPriority.TwoFiftyMS; } protected void BrokeLockPickTest() { // When failed, a 25% chance to break the lockpick if ( Utility.Random( 4 ) == 0 ) { Item item = (Item)m_Item; // You broke the lockpick. item.SendLocalizedMessageTo( m_From, 502074 ); m_From.PlaySound( 0x3A4 ); m_Lockpick.Consume(); } } protected override void OnTick() { Item item = (Item)m_Item; if ( !m_From.InRange( item.GetWorldLocation(), 1 ) ) return; if ( m_Item.LockLevel == 0 || m_Item.LockLevel == -255 ) { // LockLevel of 0 means that the door can't be picklocked // LockLevel of -255 means it's magic locked item.SendLocalizedMessageTo( m_From, 502073 ); // This lock cannot be picked by normal means return; } if ( m_From.Skills[SkillName.Lockpicking].Value < m_Item.RequiredSkill ) { /* // Do some training to gain skills m_From.CheckSkill( SkillName.Lockpicking, 0, m_Item.LockLevel );*/ // The LockLevel is higher thant the LockPicking of the player item.SendLocalizedMessageTo( m_From, 502072 ); // You don't see how that lock can be manipulated. return; } if ( m_From.CheckTargetSkill( SkillName.Lockpicking, m_Item, m_Item.LockLevel, m_Item.MaxLockLevel ) ) { // Success! Pick the lock! item.SendLocalizedMessageTo( m_From, 502076 ); // The lock quickly yields to your skill. m_From.PlaySound( 0x4A ); m_Item.LockPick( m_From ); } else { // The player failed to pick the lock BrokeLockPickTest(); item.SendLocalizedMessageTo( m_From, 502075 ); // You are unable to pick the lock. } } } } } }
{ "content_hash": "30a5a8ad41285ab485f95ab83ed7fa17", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 116, "avg_line_length": 23.84795321637427, "alnum_prop": 0.6235899950956351, "repo_name": "ggobbe/vivre-uo", "id": "3b73e24a2f64f233fcfa63225ae7bc3143d3111d", "size": "4078", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "Scripts/Items/Skill Items/Thief/LockPick.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C#", "bytes": "19852349" }, { "name": "CSS", "bytes": "699" }, { "name": "HTML", "bytes": "3008" } ], "symlink_target": "" }
<?php /* Safe sample input : get the field userData from the variable $_GET via an object SANITIZE : use in_array to check if $tainted is in the white list construction : interpretation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ class Input{ public function getInput(){ return $_GET['UserData'] ; } } $temp = new Input(); $tainted = $temp->getInput(); $legal_table = array("safe1", "safe2"); if (in_array($tainted, $legal_table, true)) { $tainted = $tainted; } else { $tainted = $legal_table[0]; } $query = "//User[@id=' $tainted ']"; $xml = simplexml_load_file("users.xml");//file load echo "query : ". $query ."<br /><br />" ; $res=$xml->xpath($query);//execution print_r($res); echo "<br />" ; ?>
{ "content_hash": "6c2b477c258034f44f5f71c570571666", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 75, "avg_line_length": 22.97142857142857, "alnum_prop": 0.7257462686567164, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "8c03141757d0460c6cd80eaa08ad3830e2d6e2ec", "size": "1608", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Injection/CWE_91/safe/CWE_91__object-directGet__whitelist_using_array__ID_test-interpretation_simple_quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <entity_gender> <fields id="name" class="Gender" image="genders"> <field name="type"/> </fields> <entities> <gender id="Mr" type="0"/> <gender id="Mrs" type="1"/> </entities> </entity_gender>
{ "content_hash": "1130c9daaad7778a425bd3602aec357f", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 51, "avg_line_length": 25.1, "alnum_prop": 0.5936254980079682, "repo_name": "djfm/pstaf", "id": "6e963492d58dc3b87b708c0fb79e2afe71968c00", "size": "251", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "FunctionalTest/UpgradeTest/prestashop/install-dev/data/xml/gender.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "737495" }, { "name": "JavaScript", "bytes": "1766460" }, { "name": "PHP", "bytes": "15744500" }, { "name": "Ruby", "bytes": "770" }, { "name": "Shell", "bytes": "9311" } ], "symlink_target": "" }
namespace myoddweb.classifier.forms { partial class OptionsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.reCheckCategories = new System.Windows.Forms.CheckBox(); this.ok = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.reCheckIfCtrl = new System.Windows.Forms.CheckBox(); this.checkCategoryIfUnknown = new System.Windows.Forms.CheckBox(); this.label3 = new System.Windows.Forms.Label(); this.comboUser = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.comboMagnets = new System.Windows.Forms.ComboBox(); this.Categories = new System.Windows.Forms.Button(); this.Magnets = new System.Windows.Forms.Button(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.labelUserTrained = new System.Windows.Forms.Label(); this.labelMagnets = new System.Windows.Forms.Label(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.labelNumberOfItemsToParse = new System.Windows.Forms.Label(); this.labelDefaultNumberOfItemsToParse = new System.Windows.Forms.Label(); this.numericNumberOfItemsToParse = new System.Windows.Forms.NumericUpDown(); this.checkConfirmCategoryWhenMultiple = new System.Windows.Forms.CheckBox(); this.checkAutomaticallyMoveTrain = new System.Windows.Forms.CheckBox(); this.label12 = new System.Windows.Forms.Label(); this.numericMinPercentage = new System.Windows.Forms.NumericUpDown(); this.labelMinPercentage = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.checkUnProcessedEmails = new System.Windows.Forms.CheckBox(); this.label8 = new System.Windows.Forms.Label(); this.labelDefaultClassifyDelay = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.numericUpDownClassifyDelay = new System.Windows.Forms.NumericUpDown(); this.checkAutomaticallyMagnetTrain = new System.Windows.Forms.CheckBox(); this.checkAutomaticallyTrain = new System.Windows.Forms.CheckBox(); this.numericCommonPercent = new System.Windows.Forms.NumericUpDown(); this.label4 = new System.Windows.Forms.Label(); this.labelCommonWord = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.labelDisplaySizeDefault = new System.Windows.Forms.Label(); this.comboDisplaySize = new System.Windows.Forms.ComboBox(); this.label9 = new System.Windows.Forms.Label(); this.Log = new System.Windows.Forms.Button(); this.labelDefaultRetention = new System.Windows.Forms.Label(); this.comboRetention = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.labelDefaultLogLevel = new System.Windows.Forms.Label(); this.comboLogLevel = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericNumberOfItemsToParse)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numericMinPercentage)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownClassifyDelay)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numericCommonPercent)).BeginInit(); this.groupBox4.SuspendLayout(); this.SuspendLayout(); // // reCheckCategories // this.reCheckCategories.AutoSize = true; this.reCheckCategories.Location = new System.Drawing.Point(6, 19); this.reCheckCategories.Name = "reCheckCategories"; this.reCheckCategories.Size = new System.Drawing.Size(278, 17); this.reCheckCategories.TabIndex = 0; this.reCheckCategories.Text = "Always re-check possible new category (can be slow)"; this.reCheckCategories.UseVisualStyleBackColor = true; this.reCheckCategories.CheckedChanged += new System.EventHandler(this.reCheckCategories_CheckedChanged); // // ok // this.ok.DialogResult = System.Windows.Forms.DialogResult.OK; this.ok.Location = new System.Drawing.Point(375, 566); this.ok.Name = "ok"; this.ok.Size = new System.Drawing.Size(75, 23); this.ok.TabIndex = 8; this.ok.Text = "&Ok"; this.ok.UseVisualStyleBackColor = true; this.ok.Click += new System.EventHandler(this.Ok_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(456, 566); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(79, 23); this.btnCancel.TabIndex = 9; this.btnCancel.Text = "&Cancel"; this.btnCancel.UseVisualStyleBackColor = true; // // groupBox1 // this.groupBox1.Controls.Add(this.reCheckIfCtrl); this.groupBox1.Controls.Add(this.checkCategoryIfUnknown); this.groupBox1.Controls.Add(this.reCheckCategories); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(524, 100); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Debug"; // // reCheckIfCtrl // this.reCheckIfCtrl.AutoSize = true; this.reCheckIfCtrl.Location = new System.Drawing.Point(6, 65); this.reCheckIfCtrl.Name = "reCheckIfCtrl"; this.reCheckIfCtrl.Size = new System.Drawing.Size(207, 17); this.reCheckIfCtrl.TabIndex = 2; this.reCheckIfCtrl.Text = "Always re-check if the Ctrl key is down"; this.reCheckIfCtrl.UseVisualStyleBackColor = true; // // checkCategoryIfUnknown // this.checkCategoryIfUnknown.AutoSize = true; this.checkCategoryIfUnknown.Location = new System.Drawing.Point(23, 42); this.checkCategoryIfUnknown.Name = "checkCategoryIfUnknown"; this.checkCategoryIfUnknown.Size = new System.Drawing.Size(192, 17); this.checkCategoryIfUnknown.TabIndex = 1; this.checkCategoryIfUnknown.Text = "Only if current category is unknown"; this.checkCategoryIfUnknown.UseVisualStyleBackColor = true; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(6, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 13); this.label3.TabIndex = 7; this.label3.Text = "User trained"; // // comboUser // this.comboUser.FormattingEnabled = true; this.comboUser.Location = new System.Drawing.Point(115, 45); this.comboUser.Name = "comboUser"; this.comboUser.Size = new System.Drawing.Size(98, 21); this.comboUser.TabIndex = 4; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 19); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(48, 13); this.label2.TabIndex = 2; this.label2.Text = "Magnets"; // // comboMagnets // this.comboMagnets.FormattingEnabled = true; this.comboMagnets.Location = new System.Drawing.Point(115, 16); this.comboMagnets.Name = "comboMagnets"; this.comboMagnets.Size = new System.Drawing.Size(98, 21); this.comboMagnets.TabIndex = 3; // // Categories // this.Categories.Location = new System.Drawing.Point(12, 566); this.Categories.Name = "Categories"; this.Categories.Size = new System.Drawing.Size(79, 23); this.Categories.TabIndex = 6; this.Categories.Text = "C&ategories ..."; this.Categories.UseVisualStyleBackColor = true; this.Categories.Click += new System.EventHandler(this.Categories_Click); // // Magnets // this.Magnets.Location = new System.Drawing.Point(97, 566); this.Magnets.Name = "Magnets"; this.Magnets.Size = new System.Drawing.Size(79, 23); this.Magnets.TabIndex = 7; this.Magnets.Text = "&Magnets ..."; this.Magnets.UseVisualStyleBackColor = true; this.Magnets.Click += new System.EventHandler(this.Magnets_Click); // // groupBox2 // this.groupBox2.Controls.Add(this.labelUserTrained); this.groupBox2.Controls.Add(this.labelMagnets); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.comboMagnets); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.comboUser); this.groupBox2.Location = new System.Drawing.Point(13, 118); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(523, 83); this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; this.groupBox2.Text = "Weights"; // // labelUserTrained // this.labelUserTrained.AutoSize = true; this.labelUserTrained.Location = new System.Drawing.Point(360, 48); this.labelUserTrained.Name = "labelUserTrained"; this.labelUserTrained.Size = new System.Drawing.Size(45, 13); this.labelUserTrained.TabIndex = 9; this.labelUserTrained.Text = "[default]"; // // labelMagnets // this.labelMagnets.AutoSize = true; this.labelMagnets.Location = new System.Drawing.Point(360, 19); this.labelMagnets.Name = "labelMagnets"; this.labelMagnets.Size = new System.Drawing.Size(45, 13); this.labelMagnets.TabIndex = 8; this.labelMagnets.Text = "[default]"; // // groupBox3 // this.groupBox3.Controls.Add(this.labelNumberOfItemsToParse); this.groupBox3.Controls.Add(this.labelDefaultNumberOfItemsToParse); this.groupBox3.Controls.Add(this.numericNumberOfItemsToParse); this.groupBox3.Controls.Add(this.checkConfirmCategoryWhenMultiple); this.groupBox3.Controls.Add(this.checkAutomaticallyMoveTrain); this.groupBox3.Controls.Add(this.label12); this.groupBox3.Controls.Add(this.numericMinPercentage); this.groupBox3.Controls.Add(this.labelMinPercentage); this.groupBox3.Controls.Add(this.label11); this.groupBox3.Controls.Add(this.checkUnProcessedEmails); this.groupBox3.Controls.Add(this.label8); this.groupBox3.Controls.Add(this.labelDefaultClassifyDelay); this.groupBox3.Controls.Add(this.label6); this.groupBox3.Controls.Add(this.numericUpDownClassifyDelay); this.groupBox3.Controls.Add(this.checkAutomaticallyMagnetTrain); this.groupBox3.Controls.Add(this.checkAutomaticallyTrain); this.groupBox3.Controls.Add(this.numericCommonPercent); this.groupBox3.Controls.Add(this.label4); this.groupBox3.Controls.Add(this.labelCommonWord); this.groupBox3.Controls.Add(this.label1); this.groupBox3.Location = new System.Drawing.Point(12, 207); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(524, 244); this.groupBox3.TabIndex = 2; this.groupBox3.TabStop = false; this.groupBox3.Text = "Misc"; // // labelNumberOfItemsToParse // this.labelNumberOfItemsToParse.AutoSize = true; this.labelNumberOfItemsToParse.Location = new System.Drawing.Point(84, 220); this.labelNumberOfItemsToParse.Name = "labelNumberOfItemsToParse"; this.labelNumberOfItemsToParse.Size = new System.Drawing.Size(145, 13); this.labelNumberOfItemsToParse.TabIndex = 28; this.labelNumberOfItemsToParse.Text = "Max number of items to parse"; // // labelDefaultNumberOfItemsToParse // this.labelDefaultNumberOfItemsToParse.AutoSize = true; this.labelDefaultNumberOfItemsToParse.Location = new System.Drawing.Point(362, 218); this.labelDefaultNumberOfItemsToParse.Name = "labelDefaultNumberOfItemsToParse"; this.labelDefaultNumberOfItemsToParse.Size = new System.Drawing.Size(45, 13); this.labelDefaultNumberOfItemsToParse.TabIndex = 27; this.labelDefaultNumberOfItemsToParse.Text = "[default]"; // // numericNumberOfItemsToParse // this.numericNumberOfItemsToParse.Location = new System.Drawing.Point(6, 218); this.numericNumberOfItemsToParse.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.numericNumberOfItemsToParse.Name = "numericNumberOfItemsToParse"; this.numericNumberOfItemsToParse.Size = new System.Drawing.Size(72, 20); this.numericNumberOfItemsToParse.TabIndex = 26; this.numericNumberOfItemsToParse.Value = new decimal(new int[] { 1, 0, 0, 0}); // // checkConfirmCategoryWhenMultiple // this.checkConfirmCategoryWhenMultiple.AutoSize = true; this.checkConfirmCategoryWhenMultiple.Location = new System.Drawing.Point(23, 142); this.checkConfirmCategoryWhenMultiple.Name = "checkConfirmCategoryWhenMultiple"; this.checkConfirmCategoryWhenMultiple.Size = new System.Drawing.Size(249, 17); this.checkConfirmCategoryWhenMultiple.TabIndex = 25; this.checkConfirmCategoryWhenMultiple.Text = "Confirm training category when multiple choices"; this.checkConfirmCategoryWhenMultiple.UseVisualStyleBackColor = true; // // checkAutomaticallyMoveTrain // this.checkAutomaticallyMoveTrain.AutoSize = true; this.checkAutomaticallyMoveTrain.Location = new System.Drawing.Point(7, 119); this.checkAutomaticallyMoveTrain.Name = "checkAutomaticallyMoveTrain"; this.checkAutomaticallyMoveTrain.Size = new System.Drawing.Size(294, 17); this.checkAutomaticallyMoveTrain.TabIndex = 24; this.checkAutomaticallyMoveTrain.Text = "Automatically use messages moved to folders for training."; this.checkAutomaticallyMoveTrain.UseVisualStyleBackColor = true; this.checkAutomaticallyMoveTrain.CheckedChanged += new System.EventHandler(this.checkAutomaticallyMoveTrain_CheckedChanged); // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(82, 47); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(15, 13); this.label12.TabIndex = 23; this.label12.Text = "%"; // // numericMinPercentage // this.numericMinPercentage.Location = new System.Drawing.Point(7, 45); this.numericMinPercentage.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.numericMinPercentage.Name = "numericMinPercentage"; this.numericMinPercentage.Size = new System.Drawing.Size(72, 20); this.numericMinPercentage.TabIndex = 22; this.numericMinPercentage.Value = new decimal(new int[] { 1, 0, 0, 0}); // // labelMinPercentage // this.labelMinPercentage.AutoSize = true; this.labelMinPercentage.Location = new System.Drawing.Point(361, 47); this.labelMinPercentage.Name = "labelMinPercentage"; this.labelMinPercentage.Size = new System.Drawing.Size(45, 13); this.labelMinPercentage.TabIndex = 21; this.labelMinPercentage.Text = "[default]"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(113, 48); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(131, 13); this.label11.TabIndex = 20; this.label11.Text = "Minimum category percent"; // // checkUnProcessedEmails // this.checkUnProcessedEmails.AutoSize = true; this.checkUnProcessedEmails.Location = new System.Drawing.Point(6, 191); this.checkUnProcessedEmails.Name = "checkUnProcessedEmails"; this.checkUnProcessedEmails.Size = new System.Drawing.Size(203, 17); this.checkUnProcessedEmails.TabIndex = 19; this.checkUnProcessedEmails.Text = "Check unprocessed emails on startup"; this.checkUnProcessedEmails.UseVisualStyleBackColor = true; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(84, 167); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(27, 13); this.label8.TabIndex = 18; this.label8.Text = "sec."; // // labelDefaultClassifyDelay // this.labelDefaultClassifyDelay.AutoSize = true; this.labelDefaultClassifyDelay.Location = new System.Drawing.Point(362, 167); this.labelDefaultClassifyDelay.Name = "labelDefaultClassifyDelay"; this.labelDefaultClassifyDelay.Size = new System.Drawing.Size(45, 13); this.labelDefaultClassifyDelay.TabIndex = 17; this.labelDefaultClassifyDelay.Text = "[default]"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(117, 167); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(130, 13); this.label6.TabIndex = 16; this.label6.Text = "Delay before classification"; // // numericUpDownClassifyDelay // this.numericUpDownClassifyDelay.Location = new System.Drawing.Point(6, 165); this.numericUpDownClassifyDelay.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.numericUpDownClassifyDelay.Name = "numericUpDownClassifyDelay"; this.numericUpDownClassifyDelay.Size = new System.Drawing.Size(72, 20); this.numericUpDownClassifyDelay.TabIndex = 15; this.numericUpDownClassifyDelay.Value = new decimal(new int[] { 1, 0, 0, 0}); // // checkAutomaticallyMagnetTrain // this.checkAutomaticallyMagnetTrain.AutoSize = true; this.checkAutomaticallyMagnetTrain.Location = new System.Drawing.Point(23, 96); this.checkAutomaticallyMagnetTrain.Name = "checkAutomaticallyMagnetTrain"; this.checkAutomaticallyMagnetTrain.Size = new System.Drawing.Size(298, 17); this.checkAutomaticallyMagnetTrain.TabIndex = 14; this.checkAutomaticallyMagnetTrain.Text = "Automatically use new messages with magnets for training"; this.checkAutomaticallyMagnetTrain.UseVisualStyleBackColor = true; // // checkAutomaticallyTrain // this.checkAutomaticallyTrain.AutoSize = true; this.checkAutomaticallyTrain.Location = new System.Drawing.Point(6, 73); this.checkAutomaticallyTrain.Name = "checkAutomaticallyTrain"; this.checkAutomaticallyTrain.Size = new System.Drawing.Size(233, 17); this.checkAutomaticallyTrain.TabIndex = 13; this.checkAutomaticallyTrain.Text = "Automatically use new messages for training"; this.checkAutomaticallyTrain.UseVisualStyleBackColor = true; this.checkAutomaticallyTrain.CheckedChanged += new System.EventHandler(this.checkAutomaticallyTrain_CheckedChanged); // // numericCommonPercent // this.numericCommonPercent.Location = new System.Drawing.Point(6, 19); this.numericCommonPercent.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.numericCommonPercent.Name = "numericCommonPercent"; this.numericCommonPercent.Size = new System.Drawing.Size(72, 20); this.numericCommonPercent.TabIndex = 12; this.numericCommonPercent.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(82, 22); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(15, 13); this.label4.TabIndex = 11; this.label4.Text = "%"; // // labelCommonWord // this.labelCommonWord.AutoSize = true; this.labelCommonWord.Location = new System.Drawing.Point(361, 21); this.labelCommonWord.Name = "labelCommonWord"; this.labelCommonWord.Size = new System.Drawing.Size(45, 13); this.labelCommonWord.TabIndex = 10; this.labelCommonWord.Text = "[default]"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(112, 22); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(113, 13); this.label1.TabIndex = 8; this.label1.Text = "Common word percent"; // // groupBox4 // this.groupBox4.Controls.Add(this.labelDisplaySizeDefault); this.groupBox4.Controls.Add(this.comboDisplaySize); this.groupBox4.Controls.Add(this.label9); this.groupBox4.Controls.Add(this.Log); this.groupBox4.Controls.Add(this.labelDefaultRetention); this.groupBox4.Controls.Add(this.comboRetention); this.groupBox4.Controls.Add(this.label7); this.groupBox4.Controls.Add(this.labelDefaultLogLevel); this.groupBox4.Controls.Add(this.comboLogLevel); this.groupBox4.Controls.Add(this.label5); this.groupBox4.Location = new System.Drawing.Point(13, 457); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(524, 103); this.groupBox4.TabIndex = 15; this.groupBox4.TabStop = false; this.groupBox4.Text = "Log"; // // labelDisplaySizeDefault // this.labelDisplaySizeDefault.AutoSize = true; this.labelDisplaySizeDefault.Location = new System.Drawing.Point(361, 73); this.labelDisplaySizeDefault.Name = "labelDisplaySizeDefault"; this.labelDisplaySizeDefault.Size = new System.Drawing.Size(45, 13); this.labelDisplaySizeDefault.TabIndex = 21; this.labelDisplaySizeDefault.Text = "[default]"; // // comboDisplaySize // this.comboDisplaySize.FormattingEnabled = true; this.comboDisplaySize.Location = new System.Drawing.Point(115, 70); this.comboDisplaySize.Name = "comboDisplaySize"; this.comboDisplaySize.Size = new System.Drawing.Size(98, 21); this.comboDisplaySize.TabIndex = 20; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(6, 73); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(85, 13); this.label9.TabIndex = 19; this.label9.Text = "Display Log Size"; // // Log // this.Log.Location = new System.Drawing.Point(445, 43); this.Log.Name = "Log"; this.Log.Size = new System.Drawing.Size(73, 23); this.Log.TabIndex = 16; this.Log.Text = "&Log ..."; this.Log.UseVisualStyleBackColor = true; this.Log.Click += new System.EventHandler(this.Log_Click); // // labelDefaultRetention // this.labelDefaultRetention.AutoSize = true; this.labelDefaultRetention.Location = new System.Drawing.Point(361, 46); this.labelDefaultRetention.Name = "labelDefaultRetention"; this.labelDefaultRetention.Size = new System.Drawing.Size(45, 13); this.labelDefaultRetention.TabIndex = 18; this.labelDefaultRetention.Text = "[default]"; // // comboRetention // this.comboRetention.FormattingEnabled = true; this.comboRetention.Location = new System.Drawing.Point(115, 43); this.comboRetention.Name = "comboRetention"; this.comboRetention.Size = new System.Drawing.Size(98, 21); this.comboRetention.TabIndex = 17; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(6, 46); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(83, 13); this.label7.TabIndex = 16; this.label7.Text = "Retention policy"; // // labelDefaultLogLevel // this.labelDefaultLogLevel.AutoSize = true; this.labelDefaultLogLevel.Location = new System.Drawing.Point(361, 19); this.labelDefaultLogLevel.Name = "labelDefaultLogLevel"; this.labelDefaultLogLevel.Size = new System.Drawing.Size(45, 13); this.labelDefaultLogLevel.TabIndex = 15; this.labelDefaultLogLevel.Text = "[default]"; // // comboLogLevel // this.comboLogLevel.FormattingEnabled = true; this.comboLogLevel.Location = new System.Drawing.Point(115, 16); this.comboLogLevel.Name = "comboLogLevel"; this.comboLogLevel.Size = new System.Drawing.Size(121, 21); this.comboLogLevel.TabIndex = 1; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(6, 19); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(33, 13); this.label5.TabIndex = 0; this.label5.Text = "Level"; // // OptionsForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(548, 603); this.Controls.Add(this.groupBox4); this.Controls.Add(this.groupBox3); this.Controls.Add(this.groupBox2); this.Controls.Add(this.Magnets); this.Controls.Add(this.Categories); this.Controls.Add(this.groupBox1); this.Controls.Add(this.btnCancel); this.Controls.Add(this.ok); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "OptionsForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "Options"; this.Load += new System.EventHandler(this.OnLoad); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericNumberOfItemsToParse)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numericMinPercentage)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownClassifyDelay)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numericCommonPercent)).EndInit(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.CheckBox reCheckCategories; private System.Windows.Forms.Button ok; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.CheckBox checkCategoryIfUnknown; private System.Windows.Forms.CheckBox reCheckIfCtrl; private System.Windows.Forms.Button Categories; private System.Windows.Forms.Button Magnets; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox comboUser; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox comboMagnets; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label labelUserTrained; private System.Windows.Forms.Label labelMagnets; private System.Windows.Forms.Label labelCommonWord; private System.Windows.Forms.Label label4; private System.Windows.Forms.NumericUpDown numericCommonPercent; private System.Windows.Forms.CheckBox checkAutomaticallyTrain; private System.Windows.Forms.CheckBox checkAutomaticallyMagnetTrain; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.Label labelDefaultRetention; private System.Windows.Forms.ComboBox comboRetention; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label labelDefaultLogLevel; private System.Windows.Forms.ComboBox comboLogLevel; private System.Windows.Forms.Label label5; private System.Windows.Forms.Button Log; private System.Windows.Forms.NumericUpDown numericUpDownClassifyDelay; private System.Windows.Forms.Label labelDefaultClassifyDelay; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label labelDisplaySizeDefault; private System.Windows.Forms.ComboBox comboDisplaySize; private System.Windows.Forms.Label label9; private System.Windows.Forms.CheckBox checkUnProcessedEmails; private System.Windows.Forms.Label label12; private System.Windows.Forms.NumericUpDown numericMinPercentage; private System.Windows.Forms.Label labelMinPercentage; private System.Windows.Forms.Label label11; private System.Windows.Forms.CheckBox checkAutomaticallyMoveTrain; private System.Windows.Forms.CheckBox checkConfirmCategoryWhenMultiple; private System.Windows.Forms.Label labelNumberOfItemsToParse; private System.Windows.Forms.Label labelDefaultNumberOfItemsToParse; private System.Windows.Forms.NumericUpDown numericNumberOfItemsToParse; } }
{ "content_hash": "e62d58a3bbb111052650e88068a56cff", "timestamp": "", "source": "github", "line_count": 681, "max_line_length": 130, "avg_line_length": 44.65638766519824, "alnum_prop": 0.6846864621354115, "repo_name": "FFMG/myoddweb.classifier", "id": "1e1341b099c7f86cc20f2b5d6fae9a378e10011b", "size": "30413", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Classifier.Outlook/forms/OptionsForm.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2020" }, { "name": "C#", "bytes": "361006" }, { "name": "C++", "bytes": "46116" }, { "name": "Inno Setup", "bytes": "10534" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Deutschl. Krypt. -Fl. (Leipzig) 2: 42 (1845) #### Original name Lichen muralis Schreb. ### Remarks null
{ "content_hash": "6ffce57f5d42c30d1e7d1876480af232", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 44, "avg_line_length": 12.846153846153847, "alnum_prop": 0.6826347305389222, "repo_name": "mdoering/backbone", "id": "a22167d313856c02986cd5f7b3fd99b7825bdb05", "size": "225", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Lecanoraceae/Lecanora/Lecanora muralis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
require 'aop-client/response/base' require 'aop-client/response/category_postcat_get' require 'aop-client/response/category_attr_get' require 'aop-client/response/category_attrvalue_get' require 'aop-client/response/photobank_list' require 'aop-client/response/photobank_upload' require 'aop-client/response/open_product_post' require 'aop-client/response/oauth'
{ "content_hash": "7acfa67222fe1fbe79ed123070f22bd3", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 52, "avg_line_length": 45.375, "alnum_prop": 0.8181818181818182, "repo_name": "yoolk/aop-client", "id": "a5fc7ecb4f94c8fc201f6b1c5e22c8a5f6166af3", "size": "363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/aop-client/response.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "48012" }, { "name": "Shell", "bytes": "115" } ], "symlink_target": "" }
package com.noprestige.kanaquiz.options; import android.content.Context; import android.graphics.Paint; import android.graphics.Typeface; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Checkable; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import com.noprestige.kanaquiz.R; import com.noprestige.kanaquiz.questions.QuestionManagement; import java.util.Map; import java.util.TreeMap; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; public class QuestionSelectionPage extends Fragment { private static final String ARG_QUESTION_TYPE_REF = "questionTypeRef"; private static final String ARG_ITEM_IDS = "prefIds"; private static final String ARG_ITEM_STATES = "states"; LinearLayout screen; private static final char STATUS_TRUE = 'T'; private static final char STATUS_FALSE = 'F'; private static final char STATUS_NEUTRAL = 'N'; public static QuestionSelectionPage newInstance(int questionTypeRef) { QuestionSelectionPage screen = new QuestionSelectionPage(); Bundle args = new Bundle(); args.putInt(ARG_QUESTION_TYPE_REF, questionTypeRef); screen.setArguments(args); return screen; } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { int questionTypeRef = getArguments().getInt(ARG_QUESTION_TYPE_REF, 0); if (questionTypeRef == R.string.hiragana) screen = QuestionManagement.getHiragana().getSelectionScreen(getContext()); else if (questionTypeRef == R.string.katakana) screen = QuestionManagement.getKatakana().getSelectionScreen(getContext()); else if (questionTypeRef == R.string.kanji) { screen = new LinearLayout(getContext()); screen.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); screen.setOrientation(LinearLayout.VERTICAL); for (int i = 0; i < QuestionManagement.getKanjiFileCount(); i++) { screen.addView(buildHeader(getContext(), QuestionManagement.getKanjiTitle(i))); QuestionManagement.getKanji(i).populateSelectionScreen(screen); } } else if (questionTypeRef == R.string.vocabulary) screen = QuestionManagement.getVocabulary().getSelectionScreen(getContext()); ScrollView scrollView = new ScrollView(getContext()); scrollView.addView(screen); return scrollView; } @Override public void onStart() { super.onStart(); //This block of code could also work in the onResume method char[] record = getArguments().getCharArray(ARG_ITEM_STATES); String[] prefIds = getArguments().getStringArray(ARG_ITEM_IDS); if (record != null) { Map<String, QuestionSelectionItem> itemList = new TreeMap<>(); for (int i = 0; i < screen.getChildCount(); i++) if (screen.getChildAt(i) instanceof Checkable) { QuestionSelectionItem item = (QuestionSelectionItem) screen.getChildAt(i); itemList.put(item.getPrefId(), item); } for (int i = 0; i < record.length; i++) if (prefIds[i] != null) { QuestionSelectionItem item = itemList.get(prefIds[i]); if (item != null) if (record[i] == STATUS_NEUTRAL) item.nullify(); else item.setChecked(record[i] == STATUS_TRUE); } } } @Override public void onStop() { super.onStop(); //This block of code could also work in the onPause and onStop methods int count = screen.getChildCount(); char[] record = new char[count]; String[] prefIds = new String[count]; for (int i = 0; i < count; i++) if (screen.getChildAt(i) instanceof Checkable) { QuestionSelectionItem item = (QuestionSelectionItem) screen.getChildAt(i); prefIds[i] = item.getPrefId(); if (item.isNeutral()) record[i] = STATUS_NEUTRAL; else if (item.isChecked()) record[i] = STATUS_TRUE; else record[i] = STATUS_FALSE; } getArguments().putCharArray(ARG_ITEM_STATES, record); getArguments().putStringArray(ARG_ITEM_IDS, prefIds); } public static TextView buildHeader(Context context, CharSequence title) { TextView header = new TextView(context); header.setText(title); header.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); header.setGravity(Gravity.CENTER); header.setTextSize(context.getResources().getDimension(R.dimen.headerTextSize)); header.setPadding(0, context.getResources().getDimensionPixelSize(R.dimen.headerTopPaddingQuestionSelection), 0, context.getResources().getDimensionPixelSize(R.dimen.headerBottomPadding)); header.setTypeface(header.getTypeface(), Typeface.BOLD); header.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG); header.setAllCaps(true); return header; } }
{ "content_hash": "79dfea92d61da1c6e16f2deae4a172c9", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 120, "avg_line_length": 38.795918367346935, "alnum_prop": 0.6330001753463089, "repo_name": "theblackwidower/KanaQuiz", "id": "dc40f00d8de64b3a07d302faee78fa0f2fa9ad96", "size": "6328", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "app/src/main/java/com/noprestige/kanaquiz/options/QuestionSelectionPage.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "510275" } ], "symlink_target": "" }
package com.ntilde.percentagelayout; public interface IPercentageLayout{ public int getPHeight(); public int getPWidth(); public float getPercentageHeight(); public float getPercentageWidth(); public boolean pixelExtraHeight(); public boolean pixelExtraWidth(); public void setPercentageParameters(float w, float h, float p); public void setPercentageParameters(float w, float h, float lp, float tp, float rp, float bp); public void applyStyles(); }
{ "content_hash": "227ef9275187711f1ba9eba793864cba", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 95, "avg_line_length": 20.82608695652174, "alnum_prop": 0.755741127348643, "repo_name": "nTildeStudio/percentageLayout", "id": "9f235ff5e80c555adc2e1b07bab6ae05e6f0193f", "size": "479", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "percentagelayout/src/main/java/com/ntilde/percentagelayout/IPercentageLayout.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "54700" } ], "symlink_target": "" }
 #pragma once #include <aws/timestream-query/TimestreamQuery_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace TimestreamQuery { namespace Model { /** * <p>Represents an available endpoint against which to make API calls against, as * well as the TTL for that endpoint.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/timestream-query-2018-11-01/Endpoint">AWS * API Reference</a></p> */ class AWS_TIMESTREAMQUERY_API Endpoint { public: Endpoint(); Endpoint(Aws::Utils::Json::JsonView jsonValue); Endpoint& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>An endpoint address.</p> */ inline const Aws::String& GetAddress() const{ return m_address; } /** * <p>An endpoint address.</p> */ inline bool AddressHasBeenSet() const { return m_addressHasBeenSet; } /** * <p>An endpoint address.</p> */ inline void SetAddress(const Aws::String& value) { m_addressHasBeenSet = true; m_address = value; } /** * <p>An endpoint address.</p> */ inline void SetAddress(Aws::String&& value) { m_addressHasBeenSet = true; m_address = std::move(value); } /** * <p>An endpoint address.</p> */ inline void SetAddress(const char* value) { m_addressHasBeenSet = true; m_address.assign(value); } /** * <p>An endpoint address.</p> */ inline Endpoint& WithAddress(const Aws::String& value) { SetAddress(value); return *this;} /** * <p>An endpoint address.</p> */ inline Endpoint& WithAddress(Aws::String&& value) { SetAddress(std::move(value)); return *this;} /** * <p>An endpoint address.</p> */ inline Endpoint& WithAddress(const char* value) { SetAddress(value); return *this;} /** * <p>The TTL for the endpoint, in minutes.</p> */ inline long long GetCachePeriodInMinutes() const{ return m_cachePeriodInMinutes; } /** * <p>The TTL for the endpoint, in minutes.</p> */ inline bool CachePeriodInMinutesHasBeenSet() const { return m_cachePeriodInMinutesHasBeenSet; } /** * <p>The TTL for the endpoint, in minutes.</p> */ inline void SetCachePeriodInMinutes(long long value) { m_cachePeriodInMinutesHasBeenSet = true; m_cachePeriodInMinutes = value; } /** * <p>The TTL for the endpoint, in minutes.</p> */ inline Endpoint& WithCachePeriodInMinutes(long long value) { SetCachePeriodInMinutes(value); return *this;} private: Aws::String m_address; bool m_addressHasBeenSet; long long m_cachePeriodInMinutes; bool m_cachePeriodInMinutesHasBeenSet; }; } // namespace Model } // namespace TimestreamQuery } // namespace Aws
{ "content_hash": "9fa8c315543359fe9ae349d4e4b7b1a4", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 133, "avg_line_length": 26.736363636363638, "alnum_prop": 0.6490989459367562, "repo_name": "cedral/aws-sdk-cpp", "id": "3356c7e7cf98c9a7ab616b99e159e1cdf83dccb5", "size": "3060", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-timestream-query/include/aws/timestream-query/model/Endpoint.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
using System.Windows.Forms; using DogAgilityCompetition.Circe; using DogAgilityCompetition.Controller.Engine.Visualization; using DogAgilityCompetition.WinForms; namespace DogAgilityCompetition.Controller.UI; /// <summary> /// Applies visualization changes on a WinForms form/control on the UI thread. /// </summary> public sealed class WinFormsVisualizer : ICompetitionRunVisualizer { private readonly Control invokeContext; private readonly IVisualizationActor target; public WinFormsVisualizer(Control invokeContext, IVisualizationActor target) { Guard.NotNull(invokeContext, nameof(invokeContext)); Guard.NotNull(target, nameof(target)); this.invokeContext = invokeContext; this.target = target; } public void Apply(IReadOnlyCollection<VisualizationChange> changes) { invokeContext.EnsureOnMainThread(() => { foreach (VisualizationChange change in changes) { change.ApplyTo(target); } }); } }
{ "content_hash": "924c3c008bd99cc68c913e78dea16270", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 80, "avg_line_length": 29.771428571428572, "alnum_prop": 0.7063339731285988, "repo_name": "bkoelman/DogAgilityCompetitionManagement", "id": "005d13eafa91f6a810e4d5dc5e8920d8951ca331", "size": "1042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Controller/UI/WinFormsVisualizer.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1134823" } ], "symlink_target": "" }
import { FC, memo } from 'react' import Link from 'next/link' import type { TUser } from '@/spec' import { Wrapper, Member, Avatar, Intro, Name, Bio } from './styles/teams' type TProps = { teammates: TUser[] } const Teams: FC<TProps> = ({ teammates }) => { return ( <Wrapper> {teammates.map((user) => ( <Member key={user.login}> <Avatar src={user.avatar} /> <Intro> <Link href={`/u/${user.login}`} passHref> <Name>{user.nickname}</Name> </Link> <Bio>{user.bio}</Bio> </Intro> </Member> ))} </Wrapper> ) } export default memo(Teams)
{ "content_hash": "d0d20894a3f03318c9b33af607bd8ece", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 74, "avg_line_length": 22.689655172413794, "alnum_prop": 0.5212765957446809, "repo_name": "mydearxym/mastani", "id": "6f38ce54b0647830c63ce98fe6e4f30995f8b663", "size": "658", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/widgets/WorksInfoCard/Teams.tsx", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "5475" }, { "name": "JavaScript", "bytes": "449787" } ], "symlink_target": "" }
import PropTypes from "prop-types"; import React from "react"; import { connect } from "react-redux"; import { loadAllCertificates } from "../../AC"; import accordion from "../../decorators/accordion"; import { filteredCrlsSelector } from "../../selectors/crlsSelectors"; import ProgressBars from "../ProgressBars"; import CRLListItem from "./CRLListItem"; interface ICRLListProps { activeCert: (certificate: any) => void; certificates: any; isLoaded: boolean; isLoading: boolean; loadAllCertificates: () => void; verifyCertificate: (id: number) => void; } class CRLList extends React.Component<ICRLListProps, {}> { static contextTypes = { locale: PropTypes.string, localize: PropTypes.func, }; componentDidMount() { // tslint:disable-next-line:no-shadowed-variable const { isLoaded, isLoading, loadAllCertificates } = this.props; if (!isLoading && !isLoaded) { loadAllCertificates(); } $(".collapsible").collapsible(); } render() { const { isLoading } = this.props; if (isLoading) { return <ProgressBars />; } return ( <React.Fragment> <ul className="collapsible" data-collapsible="accordion"> {this.getCollapsibleBody()} </ul> </React.Fragment> ); } getCollapsibleBody() { const { crls, activeCert, selectedCert, operation, toggleOpenItem, isItemOpened } = this.props; if (!crls || crls.length === 0) { return null; } const elements = crls.map((crl: any) => <CRLListItem key={crl.id} crl={crl} chooseCert={() => activeCert(crl)} operation={operation} selectedCert={() => selectedCert(crl)} isOpen={isItemOpened(crl.id.toString())} toggleOpen={toggleOpenItem(crl.id.toString())} />); return ( <li> <div className="collapsible-header color"> <i className="material-icons left intermediate" /> Список отзыва сертификатов </div> <div className="collapsible-body"> {elements} </div> </li> ); } } export default connect((state) => { return { crls: filteredCrlsSelector(state), isLoaded: state.crls.loaded, isLoading: state.crls.loading, }; }, { loadAllCertificates })(accordion(CRLList));
{ "content_hash": "b1727baf41299517c8beaa311a4ff0d8", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 99, "avg_line_length": 25.910112359550563, "alnum_prop": 0.6244579358196011, "repo_name": "TrustedPlus/esign", "id": "824f7805f9d2b294e1f4989b7b62138265e80c14", "size": "2330", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/components/CRL/CRLList.tsx", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "800" }, { "name": "CSS", "bytes": "83283" }, { "name": "HTML", "bytes": "17693" }, { "name": "JavaScript", "bytes": "104958" }, { "name": "Shell", "bytes": "4579" }, { "name": "TypeScript", "bytes": "785529" } ], "symlink_target": "" }