code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<!-- Footer --> <footer class="text-center"> <div class="footer-above"> <div class="container"> <div class="row"> <div class="footer-col col-md-4"> <h3>{{ site.footer.location }}</h3> <p> {% for adress in site.address %} {{ adress.line }} <br> {% endfor %} </p> </div> <div class="footer-col col-md-4"> <h3>{{ site.footer.social }}</h3> <ul class="list-inline"> {% for network in site.social %} <li> {% if network.title == "goodreads" %} <a target="_blank" href="{{ network.url }}"><img src="/img/portfolio/goodreads.png"></a> {% else %} <a target="_blank" href="{{ network.url }}" class="btn-social btn-outline"><i class="fa fa-fw fa-{{ network.title }}"></i></a> {% endif %} </li> {% endfor %} </ul> </div> <div class="footer-col col-md-4"> <h3>Mail To:</h3> <p><i>pprakhar30[at]gmail.com</i></p> </div> </div> </div> </div> <div class="footer-below"> <div class="container"> <div class="row"> <div class="col-lg-12"> Copyright &copy; {{ site.footer.copyright }} 20{{ site.time | date: '%y' }} </div> </div> </div> </div> </footer> <!-- Scroll to Top Button (Only visible on small and extra-small screen sizes) --> <div class="scroll-top page-scroll visible-xs visible-sm"> <a class="btn btn-primary" href="#page-top"> <i class="fa fa-chevron-up"></i> </a> </div>
pprakhar30/pprakhar30.github.io
_includes/footer.html
HTML
apache-2.0
2,187
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2018.02.17 at 03:24:36 PM CET // package no.api.meteo.jaxb.locationforecast.v1_9; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * Element denoting the cloudiness in percent or eights. * * * <p>Java class for cloudiness complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="cloudiness"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="eights"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}integer"> * &lt;minInclusive value="0"/> * &lt;maxInclusive value="8"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="percent" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "cloudiness") public class Cloudiness { @XmlAttribute(name = "eights") protected Integer eights; @XmlAttribute(name = "percent") protected String percent; @XmlAttribute(name = "id") protected String id; /** * Gets the value of the eights property. * * @return * possible object is * {@link Integer } * */ public Integer getEights() { return eights; } /** * Sets the value of the eights property. * * @param value * allowed object is * {@link Integer } * */ public void setEights(Integer value) { this.eights = value; } /** * Gets the value of the percent property. * * @return * possible object is * {@link String } * */ public String getPercent() { return percent; } /** * Sets the value of the percent property. * * @param value * allowed object is * {@link String } * */ public void setPercent(String value) { this.percent = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
amedia/meteo
meteo-jaxb/src/main/java/no/api/meteo/jaxb/locationforecast/v1_9/Cloudiness.java
Java
apache-2.0
3,164
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.shield.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/DeleteSubscription" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteSubscriptionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteSubscriptionRequest == false) return false; DeleteSubscriptionRequest other = (DeleteSubscriptionRequest) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public DeleteSubscriptionRequest clone() { return (DeleteSubscriptionRequest) super.clone(); } }
aws/aws-sdk-java
aws-java-sdk-shield/src/main/java/com/amazonaws/services/shield/model/DeleteSubscriptionRequest.java
Java
apache-2.0
2,162
/** Copyright 2010 FAV ZCU Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using SpaceTraffic.Game; using SpaceTraffic.Game.Navigation; using SpaceTraffic.Entities; namespace SpaceTraffic.Engine { /// <summary> /// Správce herního světa. /// Stará se o objekty herního světa, ze kterých vytváří datovou strukturu navázanou na mapu galaxie a seznam aktivních hráčů. /// Obsahuje operace dostupné nad herním světem. /// Stará se o zámky a synchronizaci mezi vlákny, které přistupují k této struktuře. /// </summary> public interface IWorldManager { GalaxyMap Map { get; } /// <summary> /// Property of dictionary with active player indexed by player id. /// </summary> IDictionary<int, IGamePlayer> ActivePlayers { get; } /// <summary> /// Vrací seznam aktivních hráčů. /// Aktivní hráč je takový, jehož objekty se aktivně podílí na změnách v herním světě. /// </summary> /// <returns>seznam aktivních hráčů</returns> IList<IGamePlayer> GetActivePlayers(); /// <summary> /// Method for getting active player. /// </summary> /// <param name="playerId">player id</param> /// <returns>returns active player or null</returns> IGamePlayer GetPlayer(int playerId); void ShipDock(int spaceshipId); void ShipTakeoff(int spaceshipId, NavPath path, GameTime gameTime); void ShipUpdateLocation(int spaceshipId, GameTime gameTime); /// <summary> /// Generate bases and traders and insert into db. /// </summary> void GenerateBasesAndTraders(); Achievements Achievements { get; set; } ExperienceLevels ExperienceLevels { get; set; } TAchievement GetAchievementById(int id); /// <summary> /// Method for adding player into active players. /// </summary> /// <param name="playerId">player id</param> /// <returns>return false when player not exists, otherwise true</returns> bool AddPlayer(int playerId); /// <summary> /// Method for removing player from active players. /// </summary> /// <param name="playerId">player id</param> void RemovePlayer(int playerId); } }
SpaceTrafficDevelopers/SpaceTraffic
GameServer/Engine/IWorldManager.cs
C#
apache-2.0
2,905
$(function() { var currentPhone = null; $("#input_submit").click(function() { var phone = $("#input_phone").val(); currentPhone = phone; load(phone); loadUserLocation(phone); $("#imageDiv1 div").empty().append("<img src='api/graphic/orignaggregation/" + phone + "' width='1200' height='600'>"); $("#imageDiv2 div").empty().append("<img src='api/graphic/aggregation/" + phone + "' width='1200' height='600'>"); }); $("#userDiv a").click(function() { if (currentPhone == null) { return; } var userLocation = ajax.GET("/location/mining/" + currentPhone, null); updateUserLocation(userLocation); }); function load(phone) { var $tbody = $("#resultDiv tbody"); $tbody.empty(); var locations = ajax.GET("/location/" + phone, null); for ( var i = 0; i < locations.length; i++) { var location = locations[i]; var $tr = $("<tr></tr>"); $tr.append($("<td></td>").text(i + 1)); var loginDate = new Date(location.loginTime); var logoutDate = new Date(location.logoutTime); $tr.append($("<td></td>").text(loginDate.format("yyyy-MM-dd hh:mm:ss") + " - " + logoutDate.format("yyyy-MM-dd hh:mm:ss"))); $tr.append($("<td></td>").text(location.lac)); $tr.append($("<td></td>").text(location.ci)); var state = location.state; var tdClass = ""; if (state == -1) { tdClass = "unknown"; } else if (state == 0) { tdClass = "normal"; } else if (state == 1) { tdClass = "abnormal"; } else if (state == 2) { tdClass = "guess"; } if (location.state == -1) { // 无法定位坐标 $tr.append($("<td class='" + tdClass + "'></td>").text("UnKnown")); } else { // 可以定位坐标 var station = location.station; $tr.append($("<td class='" + tdClass + "'></td>").text("(" + station.lng + "," + station.lat + ")")); } $tbody.append($tr); } } function loadUserLocation(phone) { var userLocation = ajax.GET("/userlocation/" + phone, null); updateUserLocation(userLocation); } function updateUserLocation(userLocation) { var $tbody = $("#userDiv tbody"); $tbody.empty(); $("#userDiv .li_number span").text(""); $("#userDiv .li_accuracy span").text(""); $("#userDiv .li_noise span").text(""); $("#userDiv .li_station span").text(""); if (userLocation == null) { return; } $("#userDiv .li_number span").text(userLocation.number); $("#userDiv .li_accuracy span").text(formatNumber(userLocation.accuracy, "#,##0.00")); $("#userDiv .li_noise span").text(formatNumber(userLocation.noise, "#,##0.00")); $("#userDiv .li_station span").text(formatNumber(userLocation.station, "#,##0.00")); if (userLocation.number > 0) { var pArray = userLocation.locations; var tArray = userLocation.timeSegments; var eArray = userLocation.degrees; for ( var i = 0; i < userLocation.number; i++) { var $tr = $("<tr></tr>"); $tr.append($("<td></td>").text(i + 1)); $tr.append($("<td></td>").text(pArray[i])); $tr.append($("<td></td>").text(tArray[i])); $tr.append($("<td></td>").text(formatNumber(eArray[i], "#,##0.00"))); $tbody.append($tr); } } } });
pqpo/polaris.framework
org.polaris.framework.debug/webcontent/debug/js/location.js
JavaScript
apache-2.0
3,110
<article ng-controller="GenericController"> <section class="privacy" > <h3>Privacy Concerns</h3> <p > Lets talk more about this. </p> </section> <article > <div class="privacy-content" > <p> 1. Terms By accessing this web site, you are agreeing to be bound by these web site Terms and Conditions of Use, all applicable laws and regulations, and agree that you are responsible for compliance with any applicable local laws. If you do not agree with any of these terms, you are prohibited from using or accessing this site. The materials contained in this web site are protected by applicable copyright and trade mark law. <br/><br/> 2. Use License Permission is granted to temporarily download one copy of the materials (information or software) on Mahalakshmi Traders's web site for personal, non-commercial transitory viewing only. This is the grant of a license, not a transfer of title, and under this license you may not: modify or copy the materials; use the materials for any commercial purpose, or for any public display (commercial or non-commercial); attempt to decompile or reverse engineer any software contained on Mahalakshmi Traders's web site; remove any copyright or other proprietary notations from the materials; or transfer the materials to another person or "mirror" the materials on any other server. This license shall automatically terminate if you violate any of these restrictions and may be terminated by Mahalakshmi Traders at any time. Upon terminating your viewing of these materials or upon the termination of this license, you must destroy any downloaded materials in your possession whether in electronic or printed format. <br/><br/> 3. Disclaimer The materials on Mahalakshmi Traders's web site are provided "as is". Mahalakshmi Traders makes no warranties, expressed or implied, and hereby disclaims and negates all other warranties, including without limitation, implied warranties or conditions of merchantability, fitness for a particular purpose, or non-infringement of intellectual property or other violation of rights. Further, Mahalakshmi Traders does not warrant or make any representations concerning the accuracy, likely results, or reliability of the use of the materials on its Internet web site or otherwise relating to such materials or on any sites linked to this site. <br/><br/> 4. Limitations In no event shall Mahalakshmi Traders or its suppliers be liable for any damages (including, without limitation, damages for loss of data or profit, or due to business interruption,) arising out of the use or inability to use the materials on Mahalakshmi Traders's Internet site, even if Mahalakshmi Traders or a Mahalakshmi Traders authorized representative has been notified orally or in writing of the possibility of such damage. Because some jurisdictions do not allow limitations on implied warranties, or limitations of liability for consequential or incidental damages, these limitations may not apply to you. <br/><br/> 5. Revisions and Errata The materials appearing on Mahalakshmi Traders's web site could include technical, typographical, or photographic errors. Mahalakshmi Traders does not warrant that any of the materials on its web site are accurate, complete, or current. Mahalakshmi Traders may make changes to the materials contained on its web site at any time without notice. Mahalakshmi Traders does not, however, make any commitment to update the materials. <br/><br/> 6. Links Mahalakshmi Traders has not reviewed all of the sites linked to its Internet web site and is not responsible for the contents of any such linked site. The inclusion of any link does not imply endorsement by Mahalakshmi Traders of the site. Use of any such linked web site is at the user's own risk. <br/><br/> 7. Site Terms of Use Modifications Mahalakshmi Traders may revise these terms of use for its web site at any time without notice. By using this web site you are agreeing to be bound by the then current version of these Terms and Conditions of Use. <br/><br/> 8. Governing Law Any claim relating to Mahalakshmi Traders's web site shall be governed by the laws of the State of Maharashtra without regard to its conflict of law provisions. <br/><br/> Privacy :<br/><br/> General Terms and Conditions applicable to Use of a Web Site. Your privacy is very important to us. Accordingly, we have developed this Policy in order for you to understand how we collect, use, communicate and disclose and make use of personal information. The following outlines our privacy policy. <br/><br/> Before or at the time of collecting personal information, we will identify the purposes for which information is being collected. We will collect and use of personal information solely with the objective of fulfilling those purposes specified by us and for other compatible purposes, unless we obtain the consent of the individual concerned or as required by law. <br/><br/> We will only retain personal information as long as necessary for the fulfillment of those purposes. We will collect personal information by lawful and fair means and, where appropriate, with the knowledge or consent of the individual concerned. Personal data should be relevant to the purposes for which it is to be used, and, to the extent necessary for those purposes, should be accurate, complete, and up-to-date. <br/><br/> We will protect personal information by reasonable security safeguards against loss or theft, as well as unauthorized access, disclosure, copying, use or modification. We will make readily available to customers information about our policies and practices relating to the management of personal information. We are committed to conducting our business in accordance with these principles in order to ensure that the confidentiality of personal information is protected and maintained. </p> </div> </article> </article>
mahalakshmitraders/mahalakshmitraders.github.io
privacy.html
HTML
apache-2.0
5,950
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // test basic coffeescript functionality couchTests.coffee = function(debug) { var db_name = get_random_db_name(); var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"}); db.createDb(); if (debug) debugger; var ddoc = { _id: "_design/coffee", language: "coffeescript", views: { myview: { map: '(doc) -> if doc.foo\n emit(doc.foo, 1)', reduce: '(keys, values, rereduce) ->\n sum = 0\n for x in values\n sum = sum + x\n sum' } }, shows: { myshow: '(doc) ->\n "Foo #{doc.foo}"' }, lists: { mylist: '(head, req) ->\n while row = getRow()\n send("Foo #{row.value}")\n return "Foo"' }, filters: { filter: "(doc) ->\n doc.foo" } }; db.save(ddoc); var docs = [ {_id:"a", foo: 100}, {foo:1}, {foo:1}, {foo:2}, {foo:2}, {bar:1}, {bar:1}, {bar:2}, {bar:2} ]; db.bulkSave(docs); var res = db.view("coffee/myview"); TEquals(5, res.rows[0].value, "should sum up values"); var res = CouchDB.request("GET", "/" + db.name + "/_design/coffee/_show/myshow/a"); TEquals("Foo 100", res.responseText, "should show 100"); var res = CouchDB.request("GET", "/" + db.name + "/_design/coffee/_list/mylist/myview"); TEquals("Foo 5Foo", res.responseText, "should list"); var changes = db.changes({filter: "coffee/filter"}); TEquals(5, changes.results.length, "should have changes"); // cleanup db.deleteDb(); };
fkaempfer/couchdb
test/javascript/tests/coffee.js
JavaScript
apache-2.0
2,030
#!/usr/bin/env python import argparse import logging import json import subprocess import sys import os.path import urllib2 from base64 import b64decode from distutils.dir_util import mkpath from tempfile import TemporaryFile from shutil import copyfileobj from urlparse import urlparse from urllib2 import urlopen from StringIO import StringIO from boto import connect_s3 from boto.kms.layer1 import KMSConnection def download_to_file(s3, src, f): logging.debug('download_to_file: %s -> %s', src, f) url = urlparse(src) if url.scheme == 's3': bucket = s3.get_bucket(url.netloc, validate=False) key = bucket.get_key(url.path, validate=False) key.get_contents_to_file(f) else: response = urlopen(src) copyfileobj(response, f, 16 * 1024) def download_to_filename(s3, src, dst, mode=None): dirname, os.path.dirname = os.path.split(dst) mkpath(dirname) with open(dst, 'wb') as f: download_to_file(s3, src, f) if mode is not None: os.chmod(dst, mode) def download_to_string(s3, src): logging.debug('download_to_string: %s', src) f = StringIO() download_to_file(s3, src, f) s = f.getvalue() logging.debug('download_to_string: %s: %s', src, s) f.close() return s def download(s3, src=None, dst=None, mode=None): assert src and dst logging.info('download: %s -> %s', src, dst) download_to_filename(s3, src, dst, mode=mode) def process_parameter(kms, parameter): logging.debug('process_parameter: %s', parameter) t = parameter['type'] value = parameter['value'] if t == 'plain': return value elif t == 'kms_encrypted': decrypted = kms.decrypt(value.decode('base64')) return decrypted['Plaintext'] else: raise Exception("Unexpected parameter type: '%s'" % (t, )) def debug_parameter(kms, parameter): t = parameter['type'] if t == 'plain': return parameter['value'] elif t == 'kms_encrypted': return '***' else: return '<unknown:%s>' % (t, ) def process_env(kms, parameters): return dict((key, process_parameter(kms, parameter)) for key, parameter in parameters.iteritems()) def main(): parser = argparse.ArgumentParser() parser.add_argument('config_uri') parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('--aws-credentials', type=file) args = parser.parse_args() logging.basicConfig( format='%(asctime)s %(levelname)s %(message)s', level=(logging.DEBUG if args.verbose else logging.INFO)) aws_credentials = {} if args.aws_credentials: aws_credentials = json.loads(args.aws_credentials.read()) s3 = connect_s3(host='s3.amazonaws.com', **aws_credentials) # Fetch config json config_filename = os.path.basename(args.config_uri) download_to_filename(s3, args.config_uri, config_filename) with open(config_filename, 'rb') as f: config = json.load(f) # Compile environment variables env_parameters = {} kms = KMSConnection(**aws_credentials) env_parameters = process_env(kms, config.get('env', {})) # Create working directory working_directory = config['working_directory'] mkpath(working_directory) # Download staging files for item in config.get('download', []): download(s3, **item) # Execute command env = dict(os.environ) env.update(env_parameters) debug_command = [debug_parameter(kms, parameter) for parameter in config['command']] command = [process_parameter(kms, parameter) for parameter in config['command']] logging.info('executing command: %s', debug_command) logging.debug('Popen: command=%s, env=%s', command, env) process = subprocess.Popen(command, env=env, cwd=working_directory) return process.wait() if __name__ == '__main__': status = main() sys.exit(status)
treasure-data/digdag
digdag-standards/src/main/resources/io/digdag/standards/operator/aws/runner.py
Python
apache-2.0
3,923
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2018] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package EnsEMBL::Web::JSONServer::Tools::AlleleFrequency; use strict; use warnings; use parent qw(EnsEMBL::Web::JSONServer::Tools); sub object_type { 'AlleleFrequency' } 1;
muffato/public-plugins
tools/modules/EnsEMBL/Web/JSONServer/Tools/AlleleFrequency.pm
Perl
apache-2.0
888
/* * Copyright 2014 Madhu Siddalingaiah * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.madhu.mr.job; public class CardSortParameters { public int Number_of_reducers = 4; public boolean Enable_partitioner; public boolean Enable_sort_comparator; }
msiddalingaiah/MRViewer
src/com/madhu/mr/job/CardSortParameters.java
Java
apache-2.0
780
/* * Javassist, a Java-bytecode translator toolkit. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved. * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. Alternatively, the contents of this file may be used under * the terms of the GNU Lesser General Public License Version 2.1 or later, * or the Apache License Version 2.0. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. */ package javassist.bytecode; import java.io.OutputStream; import java.io.DataOutputStream; import java.io.IOException; /** * A quick class-file writer. This is useful when a generated * class file is simple and the code generation should be fast. * * <p>Example: * * <blockquote><pre> * ClassFileWriter cfw = new ClassFileWriter(ClassFile.JAVA_4, 0); * ConstPoolWriter cpw = cfw.getConstPool(); * * FieldWriter fw = cfw.getFieldWriter(); * fw.add(AccessFlag.PUBLIC, "value", "I", null); * fw.add(AccessFlag.PUBLIC, "value2", "J", null); * * int thisClass = cpw.addClassInfo("sample/Test"); * int superClass = cpw.addClassInfo("java/lang/Object"); * * MethodWriter mw = cfw.getMethodWriter(); * * mw.begin(AccessFlag.PUBLIC, MethodInfo.nameInit, "()V", null, null); * mw.add(Opcode.ALOAD_0); * mw.add(Opcode.INVOKESPECIAL); * int signature = cpw.addNameAndTypeInfo(MethodInfo.nameInit, "()V"); * mw.add16(cpw.addMethodrefInfo(superClass, signature)); * mw.add(Opcode.RETURN); * mw.codeEnd(1, 1); * mw.end(null, null); * * mw.begin(AccessFlag.PUBLIC, "one", "()I", null, null); * mw.add(Opcode.ICONST_1); * mw.add(Opcode.IRETURN); * mw.codeEnd(1, 1); * mw.end(null, null); * * byte[] classfile = cfw.end(AccessFlag.PUBLIC, thisClass, superClass, * null, null); * </pre></blockquote> * * <p>The code above generates the following class: * * <blockquote><pre> * package sample; * public class Test { * public int value; * public long value2; * public Test() { super(); } * public one() { return 1; } * } * </pre></blockquote> * * @since 3.13 */ public class ClassFileWriter { private ByteStream output; private ConstPoolWriter constPool; private FieldWriter fields; private MethodWriter methods; int thisClass, superClass; /** * Constructs a class file writer. * * @param major the major version ({@link ClassFile#JAVA_4}, {@link ClassFile#JAVA_5}, ...). * @param minor the minor version (0 for JDK 1.3 and later). */ public ClassFileWriter(int major, int minor) { output = new ByteStream(512); output.writeInt(0xCAFEBABE); // magic output.writeShort(minor); output.writeShort(major); constPool = new ConstPoolWriter(output); fields = new FieldWriter(constPool); methods = new MethodWriter(constPool); } /** * Returns a constant pool. */ public ConstPoolWriter getConstPool() { return constPool; } /** * Returns a filed writer. */ public FieldWriter getFieldWriter() { return fields; } /** * Returns a method writer. */ public MethodWriter getMethodWriter() { return methods; } /** * Ends writing and returns the contents of the class file. * * @param accessFlags access flags. * @param thisClass this class. an index indicating its <code>CONSTANT_Class_info</code>. * @param superClass super class. an index indicating its <code>CONSTANT_Class_info</code>. * @param interfaces implemented interfaces. * index numbers indicating their <code>ClassInfo</code>. * It may be null. * @param aw attributes of the class file. May be null. * * @see AccessFlag */ public byte[] end(int accessFlags, int thisClass, int superClass, int[] interfaces, AttributeWriter aw) { constPool.end(); output.writeShort(accessFlags); output.writeShort(thisClass); output.writeShort(superClass); if (interfaces == null) output.writeShort(0); else { int n = interfaces.length; output.writeShort(n); for (int i = 0; i < n; i++) output.writeShort(interfaces[i]); } output.enlarge(fields.dataSize() + methods.dataSize() + 6); try { output.writeShort(fields.size()); fields.write(output); output.writeShort(methods.size()); methods.write(output); } catch (IOException e) {} writeAttribute(output, aw, 0); return output.toByteArray(); } /** * Ends writing and writes the contents of the class file into the * given output stream. * * @param accessFlags access flags. * @param thisClass this class. an index indicating its <code>CONSTANT_Class_info</code>. * @param superClass super class. an index indicating its <code>CONSTANT_Class_info</code>. * @param interfaces implemented interfaces. * index numbers indicating their <code>CONSTATNT_Class_info</code>. * It may be null. * @param aw attributes of the class file. May be null. * * @see AccessFlag */ public void end(DataOutputStream out, int accessFlags, int thisClass, int superClass, int[] interfaces, AttributeWriter aw) throws IOException { constPool.end(); output.writeTo(out); out.writeShort(accessFlags); out.writeShort(thisClass); out.writeShort(superClass); if (interfaces == null) out.writeShort(0); else { int n = interfaces.length; out.writeShort(n); for (int i = 0; i < n; i++) out.writeShort(interfaces[i]); } out.writeShort(fields.size()); fields.write(out); out.writeShort(methods.size()); methods.write(out); if (aw == null) out.writeShort(0); else { out.writeShort(aw.size()); aw.write(out); } } /** * This writes attributes. * * <p>For example, the following object writes a synthetic attribute: * * <pre> * ConstPoolWriter cpw = ...; * final int tag = cpw.addUtf8Info("Synthetic"); * AttributeWriter aw = new AttributeWriter() { * public int size() { * return 1; * } * public void write(DataOutputStream out) throws java.io.IOException { * out.writeShort(tag); * out.writeInt(0); * } * }; * </pre> */ public static interface AttributeWriter { /** * Returns the number of attributes that this writer will * write. */ public int size(); /** * Writes all the contents of the attributes. The binary representation * of the contents is an array of <code>attribute_info</code>. */ public void write(DataOutputStream out) throws IOException; } static void writeAttribute(ByteStream bs, AttributeWriter aw, int attrCount) { if (aw == null) { bs.writeShort(attrCount); return; } bs.writeShort(aw.size() + attrCount); DataOutputStream dos = new DataOutputStream(bs); try { aw.write(dos); dos.flush(); } catch (IOException e) {} } /** * Field. */ public static final class FieldWriter { protected ByteStream output; protected ConstPoolWriter constPool; private int fieldCount; FieldWriter(ConstPoolWriter cp) { output = new ByteStream(128); constPool = cp; fieldCount = 0; } /** * Adds a new field. * * @param accessFlags access flags. * @param name the field name. * @param descriptor the field type. * @param aw the attributes of the field. may be null. * @see AccessFlag */ public void add(int accessFlags, String name, String descriptor, AttributeWriter aw) { int nameIndex = constPool.addUtf8Info(name); int descIndex = constPool.addUtf8Info(descriptor); add(accessFlags, nameIndex, descIndex, aw); } /** * Adds a new field. * * @param accessFlags access flags. * @param name the field name. an index indicating its <code>CONSTANT_Utf8_info</code>. * @param descriptor the field type. an index indicating its <code>CONSTANT_Utf8_info</code>. * @param aw the attributes of the field. may be null. * @see AccessFlag */ public void add(int accessFlags, int name, int descriptor, AttributeWriter aw) { ++fieldCount; output.writeShort(accessFlags); output.writeShort(name); output.writeShort(descriptor); writeAttribute(output, aw, 0); } int size() { return fieldCount; } int dataSize() { return output.size(); } /** * Writes the added fields. */ void write(OutputStream out) throws IOException { output.writeTo(out); } } /** * Method. */ public static final class MethodWriter { protected ByteStream output; protected ConstPoolWriter constPool; private int methodCount; protected int codeIndex; protected int throwsIndex; protected int stackIndex; private int startPos; private boolean isAbstract; private int catchPos; private int catchCount; MethodWriter(ConstPoolWriter cp) { output = new ByteStream(256); constPool = cp; methodCount = 0; codeIndex = 0; throwsIndex = 0; stackIndex = 0; } /** * Starts Adding a new method. * * @param accessFlags access flags. * @param name the method name. * @param descriptor the method signature. * @param exceptions throws clause. It may be null. * The class names must be the JVM-internal * representations like <code>java/lang/Exception</code>. * @param aw attributes to the <code>Method_info</code>. */ public void begin(int accessFlags, String name, String descriptor, String[] exceptions, AttributeWriter aw) { int nameIndex = constPool.addUtf8Info(name); int descIndex = constPool.addUtf8Info(descriptor); int[] intfs; if (exceptions == null) intfs = null; else intfs = constPool.addClassInfo(exceptions); begin(accessFlags, nameIndex, descIndex, intfs, aw); } /** * Starts adding a new method. * * @param accessFlags access flags. * @param name the method name. an index indicating its <code>CONSTANT_Utf8_info</code>. * @param descriptor the field type. an index indicating its <code>CONSTANT_Utf8_info</code>. * @param exceptions throws clause. indexes indicating <code>CONSTANT_Class_info</code>s. * It may be null. * @param aw attributes to the <code>Method_info</code>. */ public void begin(int accessFlags, int name, int descriptor, int[] exceptions, AttributeWriter aw) { ++methodCount; output.writeShort(accessFlags); output.writeShort(name); output.writeShort(descriptor); isAbstract = (accessFlags & AccessFlag.ABSTRACT) != 0; int attrCount = isAbstract ? 0 : 1; if (exceptions != null) ++attrCount; writeAttribute(output, aw, attrCount); if (exceptions != null) writeThrows(exceptions); if (!isAbstract) { if (codeIndex == 0) codeIndex = constPool.addUtf8Info(CodeAttribute.tag); startPos = output.getPos(); output.writeShort(codeIndex); output.writeBlank(12); // attribute_length, maxStack, maxLocals, code_lenth } catchPos = -1; catchCount = 0; } private void writeThrows(int[] exceptions) { if (throwsIndex == 0) throwsIndex = constPool.addUtf8Info(ExceptionsAttribute.tag); output.writeShort(throwsIndex); output.writeInt(exceptions.length * 2 + 2); output.writeShort(exceptions.length); for (int i = 0; i < exceptions.length; i++) output.writeShort(exceptions[i]); } /** * Appends an 8bit value of bytecode. * * @see Opcode */ public void add(int b) { output.write(b); } /** * Appends a 16bit value of bytecode. */ public void add16(int b) { output.writeShort(b); } /** * Appends a 32bit value of bytecode. */ public void add32(int b) { output.writeInt(b); } /** * Appends a invokevirtual, inovkespecial, or invokestatic bytecode. * * @see Opcode */ public void addInvoke(int opcode, String targetClass, String methodName, String descriptor) { int target = constPool.addClassInfo(targetClass); int nt = constPool.addNameAndTypeInfo(methodName, descriptor); int method = constPool.addMethodrefInfo(target, nt); add(opcode); add16(method); } /** * Ends appending bytecode. */ public void codeEnd(int maxStack, int maxLocals) { if (!isAbstract) { output.writeShort(startPos + 6, maxStack); output.writeShort(startPos + 8, maxLocals); output.writeInt(startPos + 10, output.getPos() - startPos - 14); // code_length catchPos = output.getPos(); catchCount = 0; output.writeShort(0); // number of catch clauses } } /** * Appends an <code>exception_table</code> entry to the * <code>Code_attribute</code>. This method is available * only after the <code>codeEnd</code> method is called. * * @param catchType an index indicating a <code>CONSTANT_Class_info</code>. */ public void addCatch(int startPc, int endPc, int handlerPc, int catchType) { ++catchCount; output.writeShort(startPc); output.writeShort(endPc); output.writeShort(handlerPc); output.writeShort(catchType); } /** * Ends adding a new method. The <code>add</code> method must be * called before the <code>end</code> method is called. * * @param smap a stack map table. may be null. * @param aw attributes to the <code>Code_attribute</code>. * may be null. */ public void end(StackMapTable.Writer smap, AttributeWriter aw) { if (isAbstract) return; // exception_table_length output.writeShort(catchPos, catchCount); int attrCount = smap == null ? 0 : 1; writeAttribute(output, aw, attrCount); if (smap != null) { if (stackIndex == 0) stackIndex = constPool.addUtf8Info(StackMapTable.tag); output.writeShort(stackIndex); byte[] data = smap.toByteArray(); output.writeInt(data.length); output.write(data); } // Code attribute_length output.writeInt(startPos + 2, output.getPos() - startPos - 6); } int size() { return methodCount; } int dataSize() { return output.size(); } /** * Writes the added methods. */ void write(OutputStream out) throws IOException { output.writeTo(out); } } /** * Constant Pool. */ public static final class ConstPoolWriter { ByteStream output; protected int startPos; protected int num; ConstPoolWriter(ByteStream out) { output = out; startPos = out.getPos(); num = 1; output.writeShort(1); // number of entries } /** * Makes <code>CONSTANT_Class_info</code> objects for each class name. * * @return an array of indexes indicating <code>CONSTANT_Class_info</code>s. */ public int[] addClassInfo(String[] classNames) { int n = classNames.length; int[] result = new int[n]; for (int i = 0; i < n; i++) result[i] = addClassInfo(classNames[i]); return result; } /** * Adds a new <code>CONSTANT_Class_info</code> structure. * * <p>This also adds a <code>CONSTANT_Utf8_info</code> structure * for storing the class name. * * @param jvmname the JVM-internal representation of a class name. * e.g. <code>java/lang/Object</code>. * @return the index of the added entry. */ public int addClassInfo(String jvmname) { int utf8 = addUtf8Info(jvmname); output.write(ClassInfo.tag); output.writeShort(utf8); return num++; } /** * Adds a new <code>CONSTANT_Class_info</code> structure. * * @param name <code>name_index</code> * @return the index of the added entry. */ public int addClassInfo(int name) { output.write(ClassInfo.tag); output.writeShort(name); return num++; } /** * Adds a new <code>CONSTANT_NameAndType_info</code> structure. * * @param name <code>name_index</code> * @param type <code>descriptor_index</code> * @return the index of the added entry. */ public int addNameAndTypeInfo(String name, String type) { return addNameAndTypeInfo(addUtf8Info(name), addUtf8Info(type)); } /** * Adds a new <code>CONSTANT_NameAndType_info</code> structure. * * @param name <code>name_index</code> * @param type <code>descriptor_index</code> * @return the index of the added entry. */ public int addNameAndTypeInfo(int name, int type) { output.write(NameAndTypeInfo.tag); output.writeShort(name); output.writeShort(type); return num++; } /** * Adds a new <code>CONSTANT_Fieldref_info</code> structure. * * @param classInfo <code>class_index</code> * @param nameAndTypeInfo <code>name_and_type_index</code>. * @return the index of the added entry. */ public int addFieldrefInfo(int classInfo, int nameAndTypeInfo) { output.write(FieldrefInfo.tag); output.writeShort(classInfo); output.writeShort(nameAndTypeInfo); return num++; } /** * Adds a new <code>CONSTANT_Methodref_info</code> structure. * * @param classInfo <code>class_index</code> * @param nameAndTypeInfo <code>name_and_type_index</code>. * @return the index of the added entry. */ public int addMethodrefInfo(int classInfo, int nameAndTypeInfo) { output.write(MethodrefInfo.tag); output.writeShort(classInfo); output.writeShort(nameAndTypeInfo); return num++; } /** * Adds a new <code>CONSTANT_InterfaceMethodref_info</code> * structure. * * @param classInfo <code>class_index</code> * @param nameAndTypeInfo <code>name_and_type_index</code>. * @return the index of the added entry. */ public int addInterfaceMethodrefInfo(int classInfo, int nameAndTypeInfo) { output.write(InterfaceMethodrefInfo.tag); output.writeShort(classInfo); output.writeShort(nameAndTypeInfo); return num++; } /** * Adds a new <code>CONSTANT_String_info</code> * structure. * * <p>This also adds a new <code>CONSTANT_Utf8_info</code> * structure. * * @return the index of the added entry. */ public int addStringInfo(String str) { int utf8 = addUtf8Info(str); output.write(StringInfo.tag); output.writeShort(utf8); return num++; } /** * Adds a new <code>CONSTANT_Integer_info</code> * structure. * * @return the index of the added entry. */ public int addIntegerInfo(int i) { output.write(IntegerInfo.tag); output.writeInt(i); return num++; } /** * Adds a new <code>CONSTANT_Float_info</code> * structure. * * @return the index of the added entry. */ public int addFloatInfo(float f) { output.write(FloatInfo.tag); output.writeFloat(f); return num++; } /** * Adds a new <code>CONSTANT_Long_info</code> * structure. * * @return the index of the added entry. */ public int addLongInfo(long l) { output.write(LongInfo.tag); output.writeLong(l); int n = num; num += 2; return n; } /** * Adds a new <code>CONSTANT_Double_info</code> * structure. * * @return the index of the added entry. */ public int addDoubleInfo(double d) { output.write(DoubleInfo.tag); output.writeDouble(d); int n = num; num += 2; return n; } /** * Adds a new <code>CONSTANT_Utf8_info</code> * structure. * * @return the index of the added entry. */ public int addUtf8Info(String utf8) { output.write(Utf8Info.tag); output.writeUTF(utf8); return num++; } /** * Writes the contents of this class pool. */ void end() { output.writeShort(startPos, num); } } }
AndreJCL/JCL
JCL_Android/app/src/main/java/javassist/bytecode/ClassFileWriter.java
Java
apache-2.0
24,007
# Tithymalus dracunculoides subsp. volutianus SUBSPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Euphorbia/Euphorbia dracunculoides/ Syn. Tithymalus dracunculoides volutianus/README.md
Markdown
apache-2.0
203
--- title: Running calico/node with an init system redirect_from: latest/usage/configuration/as-service --- This guide explains how to run `calico/node` with an init system like systemd, inside either of the following container types: - [Docker](#running-caliconode-in-a-docker-container) - [rkt](#running-caliconode-in-a-rkt-container) ## Running calico/node in a Docker container This section describes how to run `calico/node` as a Docker container. > **Note**: We include examples for systemd, but the commands can be > applied to other init daemons such as upstart. {: .alert .alert-info} Included here is an `EnvironmentFile` that defines the environment variables for Calico and a sample systemd service file that uses the environment file and starts the `calico/node` image as a service. `calico.env` - the `EnvironmentFile`: ```shell ETCD_ENDPOINTS=http://localhost:2379 ETCD_CA_FILE="" ETCD_CERT_FILE="" ETCD_KEY_FILE="" CALICO_NODENAME="" CALICO_NO_DEFAULT_POOLS="" CALICO_IP="" CALICO_IP6="" CALICO_AS="" CALICO_LIBNETWORK_ENABLED=true CALICO_NETWORKING_BACKEND=bird ``` Be sure to update this environment file as necessary, such as modifying ETCD_ENDPOINTS to point at the correct etcd cluster endpoints. > **Note**: The `ETCD_CA_FILE`, `ETCD_CERT_FILE`, and `ETCD_KEY_FILE` > environment variables are required when using etcd with SSL/TLS. The values > here are standard values for a non-SSL version of etcd, but you can use this > template to define your SSL values if desired. > > If `CALICO_NODENAME` is blank, the compute server hostname will be used > to identify the Calico node. > > If `CALICO_IP` or `CALICO_IP6` are left blank, Calico will use the currently > configured values for the next hop IP addresses for this node—these can > be configured through the node resource. If no next hop addresses have > been configured, Calico will automatically determine an IPv4 next hop address > by querying the host interfaces (and it will configure this value in the > node resource). You may set `CALICO_IP` to `autodetect` to force > auto-detection of IP address every time the node starts. If you set IP > addresses through these environments it will reconfigure any values currently > set through the node resource. > > If `CALICO_AS` is left blank, Calico will use the currently configured value > for the AS Number for the node BGP client—this can be configured through > the node resource. If no value is set, Calico will inherit the AS Number > from the global default value. If you set a value through this environment > it will reconfigure any value currently set through the node resource. > > The `CALICO_NETWORKING_BACKEND` defaults to use BIRD as the routing daemon. > This may also be set to `gobgp` (to use GoBGP as the routing daemon, but note > that this does not support IP-in-IP), or `none` (if routing is handled by an > alternative mechanism). {: .alert .alert-info} ### systemd service example `calico-node.service` - the systemd service: ```shell [Unit] Description=calico-node After=docker.service Requires=docker.service [Service] EnvironmentFile=/etc/calico/calico.env ExecStartPre=-/usr/bin/docker rm -f calico-node ExecStart=/usr/bin/docker run --net=host --privileged \ --name=calico-node \ -e NODENAME=${CALICO_NODENAME} \ -e IP=${CALICO_IP} \ -e IP6=${CALICO_IP6} \ -e CALICO_NETWORKING_BACKEND=${CALICO_NETWORKING_BACKEND} \ -e AS=${CALICO_AS} \ -e NO_DEFAULT_POOLS=${CALICO_NO_DEFAULT_POOLS} \ -e CALICO_LIBNETWORK_ENABLED=${CALICO_LIBNETWORK_ENABLED} \ -e ETCD_ENDPOINTS=${ETCD_ENDPOINTS} \ -e ETCD_CA_CERT_FILE=${ETCD_CA_CERT_FILE} \ -e ETCD_CERT_FILE=${ETCD_CERT_FILE} \ -e ETCD_KEY_FILE=${ETCD_KEY_FILE} \ -v /var/log/calico:/var/log/calico \ -v /run/docker/plugins:/run/docker/plugins \ -v /lib/modules:/lib/modules \ -v /var/run/calico:/var/run/calico \ {{site.imageNames["node"]}}:{{site.data.versions[page.version].first.title}} ExecStop=-/usr/bin/docker stop calico-node Restart=on-failure StartLimitBurst=3 StartLimitInterval=60s [Install] WantedBy=multi-user.target ``` The systemd service above does the following on start: - Confirm Docker is installed under the `[Unit]` section - Get environment variables from the environment file above - Remove existing `calico-node` container (if it exists) - Start `calico/node` The script will also stop the calico-node container when the service is stopped. > **Note**: Depending on how you've installed Docker, the name of the Docker service > under the `[Unit]` section may be different (such as `docker-engine.service`). > Be sure to check this before starting the service. {: .alert .alert-info} ## Running calico/node in a rkt container Each Calico-rkt enabled node requires the `calico/node` container to be running. The `calico/node` container can be run directly through rkt and needs to be run as as a fly stage-1 container. ```shell sudo rkt run --stage1-path=/usr/share/rkt/stage1-fly.aci \ --set-env=ETCD_ENDPOINTS=http://<ETCD_IP>:<ETCD_PORT> \ --set-env=IP=autodetect \ --insecure-options=image \ --volume=birdctl,kind=host,source=/var/run/calico,readOnly=false \ --mount=volume=birdctl,target=/var/run/calico \ --volume=mods,kind=host,source=/lib/modules,readOnly=false \ --mount=volume=mods,target=/lib/modules \ --volume=logs,kind=host,source=/var/log/calico,readOnly=false \ --mount=volume=logs,target=/var/log/calico \ --net=host \ {{site.imageNames["node"]}}:{{site.data.versions[page.version].first.title}} & ``` > **Note**: Replace `<ETCD_IP>:<ETCD_PORT>` with your etcd configuration. The `ETCD_ENDPOINTS` > environment may contain a comma separated list of endpoints of your etcd cluster. {: .alert .alert-info} You can check that it's running using `sudo rkt list`. ```shell $ sudo rkt list UUID APP IMAGE NAME STATE CREATED STARTED NETWORKS b52bba11 node {{site.imageNames["node"]}}:{{site.data.versions[page.version].first.title}} running 10 seconds ago 10 seconds ago ```
gunjan5/calico
v3.0/usage/configuration/as-service.md
Markdown
apache-2.0
6,032
(function (exports) { 'use strict'; var obj = { playlistFormat: 'http://open.live.bbc.co.uk/mediaselector/5/select/mediaset/http-icy-mp3-a/vpid/$station/format/pls.pls', playableLinks: function (container) { return container.querySelectorAll('a[data-player-html5-stream]'); }, playlistUrl: function playlistUrl(el) { console.log('playlistUrl( %o )', el); return new Promise(function (resolve, reject) { var station = el.getAttribute('href').split('/').pop(), playlistUrl; if(station == '') { reject(playlistUrl); } else { console.log('o', obj); playlistUrl = obj.playlistFormat.replace('$station', station); resolve(playlistUrl); } }); }, extractStreamForUrl: function (url) { return obj.fetchPlsForUrl(url) .then(obj.parseStreamFromPls); }, fetchPlsForUrl: function (url) { return xhr.get(url); }, parseStreamFromPls: function (data) { return new Promise(function (resolve, reject) { var matches = data.match(/File[\d]=(.*)/); matches && matches.length > 1 ? resolve(matches[1]) : reject(); }); } } exports.radio = obj; })(window.bbc = window.bbc || {})
mediascape/discovery-extension
remote/js/lib/bbc-radio.js
JavaScript
apache-2.0
1,273
<!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 (1.8.0_92) on Wed Jul 27 21:19:23 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class net.sourceforge.pmd.lang.ruby.RubyLanguageModule (PMD 5.5.1 API)</title> <meta name="date" content="2016-07-27"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class net.sourceforge.pmd.lang.ruby.RubyLanguageModule (PMD 5.5.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../net/sourceforge/pmd/lang/ruby/RubyLanguageModule.html" title="class in net.sourceforge.pmd.lang.ruby">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sourceforge/pmd/lang/ruby/class-use/RubyLanguageModule.html" target="_top">Frames</a></li> <li><a href="RubyLanguageModule.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class net.sourceforge.pmd.lang.ruby.RubyLanguageModule" class="title">Uses of Class<br>net.sourceforge.pmd.lang.ruby.RubyLanguageModule</h2> </div> <div class="classUseContainer">No usage of net.sourceforge.pmd.lang.ruby.RubyLanguageModule</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../net/sourceforge/pmd/lang/ruby/RubyLanguageModule.html" title="class in net.sourceforge.pmd.lang.ruby">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sourceforge/pmd/lang/ruby/class-use/RubyLanguageModule.html" target="_top">Frames</a></li> <li><a href="RubyLanguageModule.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2002&#x2013;2016 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved.</small></p> </body> </html>
jasonwee/videoOnCloud
pmd/pmd-doc-5.5.1/apidocs/net/sourceforge/pmd/lang/ruby/class-use/RubyLanguageModule.html
HTML
apache-2.0
4,785
#include <stdio.h> #include <cxxabi.h> #include "kernel.hpp" using namespace raft; std::size_t kernel::kernel_count( 0 ); /** default **/ kernel::kernel() : kernel_id( kernel::kernel_count ) { kernel::kernel_count++; }; /** existing memory **/ kernel::kernel( void * const ptr, const std::size_t nbytes ) : input( this, ptr, nbytes ), output( this, ptr, nbytes ), kernel_id( kernel::kernel_count ) { } kernel::~kernel() { } std::size_t kernel::get_id() { return( kernel_id ); } std::size_t kernel::addPort() { return( 0 ); } void kernel::lock() { /** does nothing, just need a base impl **/ return; } void kernel::unlock() { /** does nothing, just need a base impl **/ return; } //std::string //kernel::getName() //{ // int status( 0 ); // const std::string name_a( // abi::__cxa_demangle( typeid( *(this) ).name(), 0, 0, &status ) ); // //}
adishavit/RaftLib
kernel.cpp
C++
apache-2.0
919
package nl.anchormen.sql4es.model.expression; import com.facebook.presto.sql.tree.ArithmeticUnaryExpression.Sign; import nl.anchormen.sql4es.ESResultSet; public class SingleValue implements ICalculation{ private Number value; public SingleValue(Number value) { this.value = value; } public void invertSign(){ this.value = value.doubleValue() * -1; } @Override public SingleValue setSign(Sign sign) { if(sign == Sign.MINUS) this.value = value.doubleValue() * -1; return this; } @Override public Number evaluate(ESResultSet result, int rowNr){ return this.value; } public String toString(){ return ""+value; } }
Anchormen/sql4es
src/main/java/nl/anchormen/sql4es/model/expression/SingleValue.java
Java
apache-2.0
648
package de.otto.rx.composer.client; import org.junit.Test; import static de.otto.rx.composer.client.ClientConfig.noResiliency; import static de.otto.rx.composer.client.ClientConfig.singleRetry; import static de.otto.rx.composer.client.DefaultRef.noResiliency; import static de.otto.rx.composer.client.DefaultRef.noRetries; import static de.otto.rx.composer.client.DefaultRef.singleRetry; import static de.otto.rx.composer.client.ServiceClients.defaultClients; import static de.otto.rx.composer.client.ServiceClients.defaultClientsWith; import static de.otto.rx.composer.client.ServiceClients.serviceClients; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class ServiceClientsTest { @Test public void shouldConfigureDefaultServiceClients() { ServiceClients serviceClients = defaultClients(); assertThat(serviceClients.getBy(singleRetry).getClientConfig().getRef(), is(DefaultRef.singleRetry)); assertThat(serviceClients.getBy(noRetries).getClientConfig().getRef(), is(noRetries)); assertThat(serviceClients.getBy(noResiliency).getClientConfig().getRef(), is(noResiliency)); } @Test public void shouldConfigureDefaultServiceClientsWithOtherDefault() { ServiceClients serviceClients = defaultClientsWith(noResiliency()); assertThat(serviceClients.getBy(singleRetry).getClientConfig().getRef(), is(DefaultRef.singleRetry)); assertThat(serviceClients.getBy(noRetries).getClientConfig().getRef(), is(noRetries)); assertThat(serviceClients.getBy(noResiliency).getClientConfig().getRef(), is(noResiliency)); } @Test public void shouldConfigureDefaultServiceClientsWithAdditionalDefault() { ServiceClients serviceClients = defaultClientsWith(noResiliency(()->"test", 100, 50)); assertThat(serviceClients.getBy(singleRetry).getClientConfig().getRef(), is(DefaultRef.singleRetry)); assertThat(serviceClients.getBy(noRetries).getClientConfig().getRef(), is(noRetries)); assertThat(serviceClients.getBy(noResiliency).getClientConfig().getRef(), is(noResiliency)); assertThat(serviceClients.getBy(()->"test").getClientConfig().getRef().name(), is("test")); assertThat(serviceClients.getBy(()->"test").getClientConfig().getRetries(), is(0)); assertThat(serviceClients.getBy(()->"test").getClientConfig().isResilient(), is(false)); assertThat(serviceClients.getBy(()->"test").getClientConfig().getConnectTimeout(), is(100)); assertThat(serviceClients.getBy(()->"test").getClientConfig().getReadTimeout(), is(50)); } @Test public void shouldConfigureSingleServiceClient() { ServiceClients serviceClients = serviceClients(noResiliency()); ServiceClient serviceClient = serviceClients.getBy(noResiliency); assertThat(serviceClient.getClientConfig().isResilient(), is(false)); } @Test public void shouldConfigureMoreServiceClients() { ServiceClients serviceClients = serviceClients(noResiliency(), singleRetry()); ServiceClient serviceClient = serviceClients.getBy(singleRetry); assertThat(serviceClient.getClientConfig().isResilient(), is(true)); assertThat(serviceClient.getClientConfig().getRetries(), is(1)); } }
gsteinacker/rx-composer
composer-core/src/test/java/de/otto/rx/composer/client/ServiceClientsTest.java
Java
apache-2.0
3,316
package com.lachesis.mnisqm.module.manualWork.dao; import java.util.List; import java.util.Map; import com.lachesis.mnisqm.module.manualWork.domain.ManualWork; public interface ManualWorkMapper { int deleteByPrimaryKey(Long seqId); int insert(ManualWork record); ManualWork selectByPrimaryKey(Long seqId); List<ManualWork> selectAll(); int updateByPrimaryKey(ManualWork record); int updateManualWorkForDelete(ManualWork record); public List<ManualWork> queryByDeptCodeAndDate(Map<String,Object> map); }
gavin2lee/incubator
mnisqm/mnisqm-services/src/main/java/com/lachesis/mnisqm/module/manualWork/dao/ManualWorkMapper.java
Java
apache-2.0
547
<!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org" th:fragment="sign(title, content)"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="Mosaddek"> <meta name="keyword" content="FlatLab, Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina"> <link rel="shortcut icon" href="img/favicon.png"> <title th:replace="${title}">JavaOA</title> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-reset.css" rel="stylesheet"> <!--external css--> <link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet" /> <!-- Custom styles for this template --> <link href="css/style.css" rel="stylesheet"> <link href="css/style-responsive.css" rel="stylesheet" /> <!-- HTML5 shim and Respond.js IE8 support of HTML5 tooltipss and media queries --> <!--[if lt IE 9]> <script src="js/html5shiv.js"></script> <script src="js/respond.min.js"></script> <![endif]--> </head> <body class="login-body"> <div class="container"> <div th:replace="${content}" ></div> </div> <!-- js placed at the end of the document so the pages load faster --> <script src="js/jquery.js"></script> <script src="js/bootstrap.min.js"></script> </body> </html>
sidneyhang/Java-oa
src/main/webapp/WEB-INF/views/layout/sign_layout.html
HTML
apache-2.0
1,425
/* ======================================================================== * bootstrap-tour - v0.10.2 * http://bootstraptour.com * ======================================================================== * Copyright 2012-2013 Ulrich Sossou * * ======================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ .tour-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1100; background-color: #000; opacity: 0.8; filter: alpha(opacity=80); } .tour-step-backdrop { position: relative; z-index: 1101; } .tour-step-backdrop > td { position: relative; z-index: 1101; } .tour-step-background { position: absolute !important; z-index: 1100; background: inherit; border-radius: 6px; } .popover[class*="tour-"] { z-index: 1100; } .popover[class*="tour-"] .popover-navigation { padding: 9px 14px; } .popover[class*="tour-"] .popover-navigation *[data-role="end"] { float: right; } .popover[class*="tour-"] .popover-navigation *[data-role="prev"], .popover[class*="tour-"] .popover-navigation *[data-role="next"], .popover[class*="tour-"] .popover-navigation *[data-role="end"] { cursor: pointer; } .popover[class*="tour-"] .popover-navigation *[data-role="prev"].disabled, .popover[class*="tour-"] .popover-navigation *[data-role="next"].disabled, .popover[class*="tour-"] .popover-navigation *[data-role="end"].disabled { cursor: default; } .popover[class*="tour-"].orphan { position: fixed; margin-top: 0; } .popover[class*="tour-"].orphan .arrow { display: none; }
webmaster444/webmaster444.github.io
react/react_ui_elements/css/lib/bootstrap-tour.css
CSS
apache-2.0
2,180
<?php /** * Login Controller * Handles displaying and initiating login * @author Chris Nasr * @copyright FUEL for the FIRE (see LICENSE file in root) * @created 2014-01-11 */ /** * Login controller * @name controller_login */ class controller_login extends Controller { /** * Action * Just show the login page * @name actionDefault * @access public * @return void */ public function action() {} /** * Action Submit * Handles login submission and redirection to previously requested page * @name actionSubmit * @access public * @return bool */ public function actionSubmit() { // Look for the user by email $aUser = table_User::findByFields(array('email' => $_POST['email'])); // If there's no user if(empty($aUser)) { $this->addViewVariable('error', 'No user with the given email.'); $this->addViewVariable('email', $_POST['email']); $this->setViewSource('www/views/login/default.tpl'); return true; } // Validate the password if(!$aUser[0]->validatePassword($_POST['passwd'])) { $this->addViewVariable('error', 'Invalid password for the given email.'); $this->addViewVariable('email', $_POST['email']); $this->setViewSource('www/views/login/default.tpl'); return true; } // Store the user's ID $_SESSION['www']['user'] = $aUser[0]; // If there's a redirect URL in the session if(isset($_SESSION['www']['loginRedirect'])) { $sURL = $_SESSION['www']['loginRedirect']; unset($_SESSION['www']['loginRedirect']); } // Else, go to the dashboard else { $sURL = '/dashboard'; } // Redirect header('Location: ' . $sURL); exit(0); } /** * Action Create * Creates new user * @name actionCreate * @access public * @param CView $view * @return void */ public function actionCreate(CView $view) { $oUser = new table_User(array( 'name' => $_GET['name'], 'email' => $_GET['email'], 'passwd' => table_User::hashPassword($_GET['passwd']) )); $oUser->insert(); echo $oUser->asJSON(); exit(0); } /** * Logout * Destroys the session thus logging out the user * @name actionLogout * @return void */ public function actionLogout() { // Unset the www session variable which will log out the user unset($_SESSION['www']); // Redirect to the dashboard $this->redirect('/dashboard/'); } }
ouroboroscoding/ouroborostask
www/controllers/login.php
PHP
apache-2.0
2,346
/* * Copyright 2016 Ratha Long * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nz.co.testamation.core.client.page; public class BaseUrlProviderImpl implements BaseUrlProvider { private String baseUrl; public BaseUrlProviderImpl( String host, int port, String contextPath ) { this( getBaseUrl( host, port, contextPath ) ); } public BaseUrlProviderImpl( String baseUrl ) { this.baseUrl = baseUrl; } private static String getBaseUrl( String host, int port, String contextPath ) { if ( !host.startsWith( "http://" ) ) { host = "http://" + host; } if ( !contextPath.startsWith( "/" ) ) { contextPath = "/" + contextPath; } return String.format( "%s:%s%s", host, port, contextPath ); } @Override public String getBaseUrl() { return baseUrl; } }
rlon008/testamation
testamation-core/src/main/java/nz/co/testamation/core/client/page/BaseUrlProviderImpl.java
Java
apache-2.0
1,396
create table BPEL_ACTIVITY_RECOVERY (ID number(19,0) not null, PIID number(19,0), AID number(19,0), CHANNEL varchar2(255 char), REASON varchar2(255 char), DATE_TIME timestamp, DETAILS blob(2G), ACTIONS varchar2(255 char), RETRIES number(10,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_CORRELATION_PROP (ID number(19,0) not null, NAME varchar2(255 char), NAMESPACE varchar2(255 char), VALUE varchar2(255 char), CORR_SET_ID number(19,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_CORRELATION_SET (ID number(19,0) not null, VALUE varchar2(255 char), CORR_SET_NAME varchar2(255 char), SCOPE_ID number(19,0), PIID number(19,0), PROCESS_ID number(19,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_CORRELATOR (ID number(19,0) not null, CID varchar2(255 char), PROCESS_ID number(19,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_CORRELATOR_MESSAGE_CKEY (ID number(19,0) not null, CKEY varchar2(255 char), CORRELATOR_MESSAGE_ID number(19,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_EVENT (ID number(19,0) not null, IID number(19,0), PID number(19,0), TSTAMP timestamp, TYPE varchar2(255 char), DETAIL clob, DATA blob(2G), SID number(19,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_FAULT (ID number(19,0) not null, FAULTNAME varchar2(255 char), DATA blob(2G), EXPLANATION varchar2(4000 char), LINE_NUM number(10,0), AID number(10,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_INSTANCE (ID number(19,0) not null, INSTANTIATING_CORRELATOR number(19,0), FAULT number(19,0), JACOB_STATE_DATA blob(2G), PREVIOUS_STATE number(5,0), PROCESS_ID number(19,0), STATE number(5,0), LAST_ACTIVE_DT timestamp, SEQUENCE number(19,0), FAILURE_COUNT number(10,0), FAILURE_DT timestamp, INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_MESSAGE (ID number(19,0) not null, MEX number(19,0), TYPE varchar2(255 char), MESSAGE_DATA blob(2G), MESSAGE_HEADER blob(2G), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_MESSAGE_EXCHANGE (ID number(19,0) not null, PORT_TYPE varchar2(255 char), CHANNEL_NAME varchar2(255 char), CLIENTKEY varchar2(255 char), ENDPOINT blob(2G), CALLBACK_ENDPOINT blob(2G), REQUEST number(19,0), RESPONSE number(19,0), INSERT_DT timestamp, OPERATION varchar2(255 char), STATE varchar2(255 char), PROCESS number(19,0), PIID number(19,0), DIR char(1 char), PLINK_MODELID number(10,0), PATTERN varchar2(255 char), CORR_STATUS varchar2(255 char), FAULT_TYPE varchar2(255 char), FAULT_EXPL varchar2(255 char), CALLEE varchar2(255 char), PARTNERLINK number(19,0), PIPED_ID varchar2(255 char), SUBSCRIBER_COUNT number(10,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_MEX_PROPS (MEX number(19,0) not null, VALUE long, NAME varchar2(255 char) not null, primary key (MEX, NAME)); create table BPEL_PLINK_VAL (ID number(19,0) not null, PARTNER_LINK varchar2(100 char) not null, PARTNERROLE varchar2(100 char), MYROLE_EPR_DATA blob(2G), PARTNERROLE_EPR_DATA blob(2G), PROCESS number(19,0), SCOPE number(19,0), SVCNAME varchar2(255 char), MYROLE varchar2(100 char), MODELID number(10,0), MYSESSIONID varchar2(255 char), PARTNERSESSIONID varchar2(255 char), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_PROCESS (ID number(19,0) not null, PROCID varchar2(255 char) not null unique, deployer varchar2(255 char), deploydate timestamp, type_name varchar2(255 char), type_ns varchar2(255 char), version number(19,0), ACTIVE_ number(1,0), guid varchar2(255 char), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_SCOPE (ID number(19,0) not null, PIID number(19,0), PARENT_SCOPE_ID number(19,0), STATE varchar2(255 char) not null, NAME varchar2(255 char) not null, MODELID number(10,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_SELECTORS (ID number(19,0) not null, PIID number(19,0) not null, SELGRPID varchar2(255 char) not null, IDX number(10,0) not null, CORRELATION_KEY varchar2(255 char) not null, PROC_TYPE varchar2(255 char) not null, ROUTE_POLICY varchar2(255 char), CORRELATOR number(19,0) not null, INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID), unique (CORRELATION_KEY, CORRELATOR)); create table BPEL_UNMATCHED (ID number(19,0) not null, MEX number(19,0), CORRELATION_KEY varchar2(255 char), CORRELATOR number(19,0) not null, INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table BPEL_XML_DATA (ID number(19,0) not null, DATA blob(2G), NAME varchar2(255 char) not null, SIMPLE_VALUE varchar2(255 char), SCOPE_ID number(19,0), PIID number(19,0), IS_SIMPLE_TYPE number(1,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table STORE_DU (NAME varchar2(255 char) not null, deployer varchar2(255 char), DEPLOYDT timestamp, DIR varchar2(255 char), primary key (NAME)); create table STORE_PROCESS (PID varchar2(255 char) not null, DU varchar2(255 char), TYPE varchar2(255 char), version number(19,0), STATE varchar2(255 char), primary key (PID)); create table STORE_PROCESS_PROP (propId varchar2(255 char) not null, value varchar2(2048 char), name varchar2(255 char) not null, primary key (propId, name)); create table STORE_VERSIONS (ID number(10,0) not null, VERSION number(19,0), primary key (ID)); create table TASK_ATTACHMENT (ID number(19,0) not null, ATTACHMENT_ID number(19,0), MESSAGE_EXCHANGE_ID number(19,0), INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create table VAR_PROPERTY (ID number(19,0) not null, XML_DATA_ID number(19,0), PROP_VALUE varchar2(255 char), PROP_NAME varchar2(255 char) not null, INSERT_TIME timestamp, MLOCK number(10,0) not null, primary key (ID)); create index IDX_CORRELATOR_CID on BPEL_CORRELATOR (CID); create index IDX_BPEL_CORRELATOR_MESSAGE_CKEY on BPEL_CORRELATOR_MESSAGE_CKEY (CKEY); create index IDX_SELECTOR_SELGRPID on BPEL_SELECTORS (SELGRPID); create index IDX_SELECTOR_CKEY on BPEL_SELECTORS (CORRELATION_KEY); create index IDX_SELECTOR_CORRELATOR on BPEL_SELECTORS (CORRELATOR); create index IDX_UNMATCHED_CORRELATOR on BPEL_UNMATCHED (CORRELATOR); create index IDX_UNMATCHED_CKEY on BPEL_UNMATCHED (CORRELATION_KEY); create sequence hibernate_seqhilo;
thiliA/wso2-ode
dao-hibernate-db/target/partial.oracle.sql
SQL
apache-2.0
6,583
#include <iostream> using namespace std; int main() { cerr << "Hello World" << endl; }
MicahChambers/waf_etest
src/hello_world.cpp
C++
apache-2.0
94
# Copyright 2019 Scalyr Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------------------ # # author: Imron Alston <imron@scalyr.com> from __future__ import absolute_import from __future__ import print_function __author__ = "imron@scalyr.com" import sys from scalyr_agent import UnsupportedSystem from scalyr_agent.test_base import ScalyrTestCase class MySqlMonitorTest(ScalyrTestCase): def _import_mysql_monitor(self): import scalyr_agent.builtin_monitors.mysql_monitor # NOQA self.assertTrue(True) def test_min_python_version(self): if sys.version_info[:2] < (2, 7): self.assertRaises(UnsupportedSystem, lambda: self._import_mysql_monitor()) else: self._import_mysql_monitor() def test_missing_qcache_hits(self): if sys.version_info[:2] < (2, 7): print( "Skipping test 'test_missing_qcache_hits'.\n" "This test is non-critical for pre-2.7 testing.\n" ) return from scalyr_agent.builtin_monitors.mysql_monitor import MysqlDB class TestMysqlDB(MysqlDB): def __init__(self): # do nothing, because we don't actually want to connect to a DB # for this test pass db = TestMysqlDB() globalVars = {} globalStatusMap = {"global.com_select": 10} expected = 0 actual = db._derived_stat_query_cache_efficiency(globalVars, globalStatusMap) self.assertEqual(expected, actual)
imron/scalyr-agent-2
tests/unit/builtin_monitors/mysql_monitor_test.py
Python
apache-2.0
2,104
# Triticum comosum (Sm.) K.Richt. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Pl. eur. 1:128. 1890 #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Aegilops/Aegilops comosa/ Syn. Triticum comosum/README.md
Markdown
apache-2.0
204
/* * Original copyright by Apache Software Foundation * Copyright (C) 2017-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.cli; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.Nonempty; import com.helger.commons.annotation.ReturnsMutableObject; import com.helger.commons.collection.impl.CommonsArrayList; import com.helger.commons.collection.impl.CommonsLinkedHashMap; import com.helger.commons.collection.impl.ICommonsList; import com.helger.commons.collection.impl.ICommonsOrderedMap; import com.helger.commons.string.StringHelper; import com.helger.commons.string.ToStringGenerator; import com.helger.commons.traits.IGetterByKeyTrait; /** * This class represents a parsed command line. Parsing happens in class * {@link CmdLineParser}. * * @author Philip Helger */ @NotThreadSafe public class ParsedCmdLine implements IGetterByKeyTrait <String> { private final ICommonsOrderedMap <IOptionBase, ICommonsList <String>> m_aParams = new CommonsLinkedHashMap <> (); private final ICommonsList <String> m_aUnknownTokens = new CommonsArrayList <> (); public ParsedCmdLine () {} void internalAddValue (@Nonnull final IOptionBase aOption, @Nonnull final ICommonsList <String> aValues) { ValueEnforcer.notNull (aOption, "Option"); ValueEnforcer.notNull (aValues, "Values"); m_aParams.computeIfAbsent (aOption, k -> new CommonsArrayList <> ()).addAll (aValues); } void internalAddUnhandledToken (@Nonnull @Nonempty final String sUnknownToken) { ValueEnforcer.notEmpty (sUnknownToken, "UnknownToken"); m_aUnknownTokens.add (sUnknownToken); } @Nullable private ICommonsList <String> _find (@Nullable final IOptionBase aOption) { return aOption == null ? null : m_aParams.get (aOption); } @Nullable private ICommonsList <String> _find (@Nullable final String sOption) { if (StringHelper.hasNoText (sOption)) return null; for (final Map.Entry <IOptionBase, ICommonsList <String>> aEntry : m_aParams.entrySet ()) if (aEntry.getKey () instanceof Option) { if (((Option) aEntry.getKey ()).matches (sOption)) return aEntry.getValue (); } else // Do not resolve option groups, as the resolution happens on insertion! if (false) { for (final Option aOption : (OptionGroup) aEntry.getKey ()) if (aOption.matches (sOption)) return aEntry.getValue (); } return null; } public boolean hasOption (@Nullable final IOptionBase aOption) { return _find (aOption) != null; } public boolean hasOption (@Nullable final String sOption) { return _find (sOption) != null; } @Nullable public String getValue (@Nonnull final IOptionBase aOption) { final ICommonsList <String> aValues = _find (aOption); return aValues == null ? null : aValues.getFirst (); } @Nullable public String getValue (@Nullable final String sOption) { final ICommonsList <String> aValues = _find (sOption); return aValues == null ? null : aValues.getFirst (); } @Nullable @ReturnsMutableObject public ICommonsList <String> values (@Nonnull final IOptionBase aOption) { final ICommonsList <String> aValues = _find (aOption); return aValues == null ? null : aValues.getClone (); } @Nullable @ReturnsMutableObject public ICommonsList <String> values (@Nonnull final String sOption) { final ICommonsList <String> aValues = _find (sOption); return aValues == null ? null : aValues.getClone (); } @Nonnull @ReturnsMutableObject public ICommonsList <String> unknownTokens () { return m_aUnknownTokens; } @Override public String toString () { return new ToStringGenerator (null).append ("Params", m_aParams).append ("UnknownTokens", m_aUnknownTokens).getToString (); } }
phax/ph-commons
ph-cli/src/main/java/com/helger/cli/ParsedCmdLine.java
Java
apache-2.0
4,600
# Allophylus setulosus Radlk. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Sapindaceae/Allophylus/Allophylus setulosus/README.md
Markdown
apache-2.0
177
package com.example.gpstest1; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.example.adapter.TongjiAdapter; import com.example.bean.ChooseCarBean; import com.example.bean.TongjiItem; import com.example.util.Constant; import com.example.util.SystemBarTintManager; import java.util.ArrayList; public class TongjiActivity extends Activity implements OnClickListener{ private ListView mListView; private static MainActivity mActivity; private static Context mContext; private TongjiAdapter mAdapter; private ChooseCarBean mBean; private ArrayList<TongjiItem> mList = new ArrayList<TongjiItem>();//本界面需要用的list private TextView topTextView; private ImageView backImg; private String departCode; private String departName; private String strdeviceId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); SystemBarTintManager tintManager = new SystemBarTintManager(this); tintManager.setStatusBarTintEnabled(true); tintManager.setStatusBarTintResource(R.color.top_bg_color);//通知栏所需颜色 } setContentView(R.layout.activity_tongji); MainActivity.activityList.add(this); findViews(); initData(); } public void findViews() { mListView = (ListView)findViewById(R.id.typeList); topTextView = (TextView)findViewById(R.id.TitleText); backImg = (ImageView)findViewById(R.id.backImage); backImg.setOnClickListener(this); topTextView.setText(getResources().getString(R.string.Tongjifenxi)); departCode = getIntent().getStringExtra("departCode"); departName = getIntent().getStringExtra("departName"); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //点击item int type =mList.get(position).getType(); if(type==1) { OnlineTongjiActivity.actionStart(TongjiActivity.this,mActivity,departCode, departName); }else if(type ==2) { AlarmTongjiActivity.actionStart(TongjiActivity.this,mActivity, departCode, departName); }else if(type ==3) { MeliageActivity2.actionStart(TongjiActivity.this,mActivity, departCode, departName,Constant.MELIAGETONGJI); }else if(type ==4) { MeliageActivity2.actionStart(TongjiActivity.this,mActivity, departCode, departName,Constant.OVERMELIAGETONGJI); } } }); } public void initData() { mList.clear(); TongjiItem itme1 =new TongjiItem(); itme1.setTypename("在线离线统计"); itme1.setType(1); mList.add(itme1); TongjiItem itme2 =new TongjiItem(); itme2.setTypename("报警统计"); itme2.setType(2); mList.add(itme2); TongjiItem itme3 =new TongjiItem(); itme3.setTypename("里程统计"); itme3.setType(3); mList.add(itme3); TongjiItem itme4 =new TongjiItem(); itme4.setTypename("超里程统计"); itme4.setType(4); mList.add(itme4); showUI(); } public void showUI() { if(mAdapter==null) { mAdapter = new TongjiAdapter(mContext, mList); mListView.setAdapter(mAdapter); }else{ mAdapter.notifyList(mList); } } public static void actionStart(Context context,String departCode,String departName) { mContext = context; mActivity = (MainActivity) context; Intent intent = new Intent(context,TongjiActivity.class); intent.putExtra("departCode", departCode); intent.putExtra("departName", departName); context.startActivity(intent); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.backImage: finish(); break; default: break; } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); MainActivity.activityList.remove(this); } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } @Override protected void onPause() { super.onPause(); } @Override protected void onRestart() { super.onRestart(); } }
dufangyu1990/NewGpsTest
app/src/main/java/com/example/gpstest1/TongjiActivity.java
Java
apache-2.0
5,004
# Carex depressa var. transsilvanica VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carex/Carex depressa/ Syn. Carex depressa transsilvanica/README.md
Markdown
apache-2.0
191
'use strict'; module.exports = function (app) { var AbuseService = { create: function (abuse) { return app.daos.Abuse.create(abuse).then(function (id) { return id; }); }, update: function (abuse) { return app.daos.Abuse.update(abuse).then(function (id) { return id; }); }, delete: function (id) { return app.daos.Abuse.delete(id).then(function (ok) { return ok; }); }, readById: function (id) { return app.daos.Abuse.readById(id).then(function (abuse) { return abuse; }); }, readByCriteria: function (criteria) { return app.daos.Abuse.readByCriteria(criteria).then(function (abuse) { return abuse; }); } }; return AbuseService; };
pablolmnora/helpthecity
server/app/services/AbuseService.js
JavaScript
apache-2.0
706
@import url("https://fonts.googleapis.com/css?family=Raleway:200,300,400,600"); *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .clearfix:before, .clearfix:after { content: ''; display: table; } .clearfix:after { clear: both; } body { font-family: 'Raleway'; line-height: 1.5; margin: 0; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; } h1 { font-weight: 300; } .grid { color: #fff; display: flex; font-size: 0; margin: 0 auto; position: fixed; bottom: 0px; width: 100%; } .grid__column { cursor: pointer; display: inline-block; font-size: 1rem; font-weight: 200; padding: 6em 0; text-align: center; transition: transform .1s ease-in; width: 33.3333333333%; z-index: 0; } .grid__column p { margin: 0 auto; width: 70%; } .grid__column:hover { transform: scale(1.15); z-index: 99; } .grid__column--pink { background: #f5756c; background: linear-gradient(#f5756c, #fd5480), #f5756c; } .grid__column--blue { background: #6585ed; background: linear-gradient(#6585ed, #349cff), #6585ed; } .grid__column--green { background: #5fd9ad; background: linear-gradient(#5fd9ad, #2ad4e9), #5fd9ad; } a { color: #FFF; text-decoration: none; outline: none; } a:hover, a:focus { color: #FFF; } .header { margin: 0 auto; padding: 2em 0 0; text-align: center; } .header h1 { margin: 0; font-weight: 300; font-size: 2.5em; } .header h1 span { display: block; padding: 0 0 0.6em 0.1em; font-size: 0.6em; opacity: 0.7; } .codrops-demos { margin: 30px auto 0; padding: 30px 0; } .codrops-demos a, section button { display: inline-block; background: #a9a9a9; color: #fff; font-weight: 400; padding: 10px 20px; margin: 5px; text-transform: uppercase; border-radius: 2px; letter-spacing: 1px; } section { padding: 1em 2em 5em; text-align: center; font-size: 1.5em; } section p { max-width: 600px; margin: 0 auto; padding: 20px 0; } section button { border: none; padding: 15px 30px; outline: none; background: #85b91e; } .related > a { border: 1px solid #99cc33; display: inline-block; text-align: center; margin: 20px 10px; padding: 25px; color: #99cc33; opacity: 0.8; -webkit-transition: color 0.2s, border-color 0.2s; transition: color 0.2s, border-color 0.2s; -webkit-backface-visibility: hidden; } .related a:hover { border-color: #82b222; color: #82b222; } .related a img { max-width: 100%; } .related a h3 { margin: 0; padding: 0.5em 0 0.3em; max-width: 300px; text-align: left; font-size: 65%; font-weight: 400; } /* Overlay style */ .overlay { position: fixed; width: 100%; height: 100%; top: 0; left: 0; background-color: #fd5480; } /* Overlay closing cross icon */ .overlay .overlay-close { width: 80px; height: 80px; position: absolute; right: 20px; top: 20px; overflow: hidden; border: none; background: url(../img/cross.png) no-repeat center center; text-indent: 200%; color: transparent; outline: none; z-index: 999; } /* Menu style */ .overlay nav { text-align: center; position: relative; top: 50%; height: 60%; font-size: 54px; -webkit-transform: translateY(-50%); transform: translateY(-50%); } .overlay ul { list-style: none; padding: 0; margin: 0 auto; display: inline-block; height: 100%; position: relative; } .overlay ul li { display: block; height: 20%; height: calc(100% / 5); min-height: 54px; } .overlay ul li a { font-weight: 300; display: block; color: #fff; -webkit-transition: color 0.2s; transition: color 0.2s; } .overlay ul li a:hover, .overlay ul li a:focus { color: #e3fcb1; } /* Effects */ .overlay-hugeinc { opacity: 0; visibility: hidden; -webkit-transition: opacity 0.5s, visibility 0s 0.25s; transition: opacity 0.25s, visibility 0s 0.25s; } .overlay-hugeinc.open { opacity: 1; visibility: visible; -webkit-transition: opacity 0.5s; transition: opacity 0.5s; } .overlay-hugeinc nav { -webkit-perspective: 1200px; perspective: 1200px; } .overlay-hugeinc nav ul { opacity: 0.4; -webkit-transform: translateY(-25%) rotateX(35deg); transform: translateY(-25%) rotateX(35deg); -webkit-transition: -webkit-transform 0.25s, opacity 0.25s; transition: transform 0.25s, opacity 0.25s; } .overlay-hugeinc.open nav ul { opacity: 1; -webkit-transform: rotateX(0deg); transform: rotateX(0deg); } .overlay-hugeinc.close nav ul { -webkit-transform: translateY(25%) rotateX(-35deg); transform: translateY(25%) rotateX(-35deg); } @media screen and (max-height: 30.5em) { .overlay nav { height: 70%; font-size: 34px; } .overlay ul li { min-height: 34px; } } @media screen and (max-width: 25em) { .codrops-icon span { display: none; } }
Juklab/emmaline
html/css/project.css
CSS
apache-2.0
4,753
<?php namespace Ree\Cocktail\Console; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Finder\SplFileInfo; use Illuminate\Filesystem\Filesystem; use Ree\Cocktail\Contracts\Mixer; use Ree\Cocktail\Cocktail; use Ree\Cocktail\Recipe; /** * Description of MixCommand * * @author Hieu Le <hieu@codeforcevina.com> */ class MixCommand extends Command { protected function configure() { $this->setName('mix') ->setDescription('Compile defined assets.') ->addOption('production', 'P', InputOption::VALUE_NONE, 'Is in production mode or not'); } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln($this->getApplication()->getName() . " - " . $this->getApplication()->getVersion() . " - by Hieu Le"); $files = new Filesystem; $dir = getcwd(); $cocktail = new Cocktail($files, $dir, $input->getOption('production')); $recipes = $this->parseRecipes($files); $numCups = count($recipes); $recipeFile = Cocktail::FILE_NAME; $output->writeln(''); $output->writeln("<info>Found {$numCups} cups from recipe files [{$recipeFile}].</info>"); $output->writeln(''); $cocktail->addCallback('recipe.before', function(Recipe $recipe) use ($output) { $output->writeln("<fg=green>Enter:</> <fg=yellow>{$recipe->getSourceDir()}</>"); }); $cocktail->addCallback('recipe.after', function(Recipe $recipe) use ($output) { $output->writeln("<fg=green>Done.</>\n"); }); $cocktail->addCallback('file.before', function(Recipe $recipe, Mixer $mixer, SplFileInfo $file) use($output) { $path = $file->getRelativePath(); $ext = $file->getExtension(); $name = $file->getBasename(".{$ext}"); $prefix = sprintf("%-8s", "[{$ext}]"); $output->writeln(" <info>{$prefix}</info> {$path}/{$name}.{$ext} ... "); }); foreach ($recipes as $recipe) { $cocktail->mix($recipe); } } protected function parseRecipes(Filesystem $files) { $recipes = []; if ($files->exists(Cocktail::FILE_NAME)) { foreach ($files->getRequire(Cocktail::FILE_NAME) as $config) { $recipes[] = new Recipe($config); } } return $recipes; } }
reecms/cocktail-php
src/Console/MixCommand.php
PHP
apache-2.0
2,588
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.usc.irds.sparkler.service import java.io.ByteArrayInputStream import java.net.URL import java.nio.file.Paths import java.security.MessageDigest import edu.usc.irds.sparkler.base.{CliTool, Loggable} import edu.usc.irds.sparkler.service.Injector.setLogLevel import org.apache.commons.codec.binary.Hex import org.apache.commons.io.IOUtils import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs._ import org.apache.hadoop.io.SequenceFile.Reader import org.apache.hadoop.io.{SequenceFile, Text} import org.apache.hadoop.util.ReflectionUtils import org.apache.nutch.protocol.Content import org.kohsuke.args4j.Option /** * A tool to dump sequence file records to raw files */ class Dumper extends CliTool with Loggable { @Option(name = "-i", aliases = Array("--job-dir", "--in"), required = true, usage="Sparkler Output Directory Containing Sequence Files") var jobDir: String = _ @Option(name = "-o", aliases = Array("--dump-root", "--out"), required = true, usage="Directory to store raw files") var dumpRoot: String = _ @Option(name = "-sc", aliases = Array("--skip-content"), usage = "Writes the index file and skips content write step") var skipContent: Boolean = false val digest = MessageDigest.getInstance("MD5") val metaFile = "_INDEX" override def run(): Unit = { LOG.info(s"DUmping Sequence Files to raw files: $jobDir --> $dumpRoot" ) LOG.warn(s"This may overwrite destination ($dumpRoot), and may fill the storage or exhaust its iNode numbers") LOG.info("Recommendation: Use Hadoop HDFS Java API to directly access files from sequence files instead.") val conf = new Configuration() val fileSys = FileSystem.get(conf) //NO Checksum to speed up! Enable later if somebody needs this feature fileSys.setVerifyChecksum(false) fileSys.setWriteChecksum(false) val jobPath = new Path(jobDir) val rootPath = new Path(dumpRoot) assert(fileSys.exists(jobPath), s"$jobDir does not exist") fileSys.mkdirs(rootPath) val files = fileSys.listFiles(jobPath, true) val seqFilePaths = collection.mutable.Buffer[Path]() while (files.hasNext){ val file = files.next() if (file.getPath.getName.matches("part-\\d{5}")){ seqFilePaths += file.getPath } } LOG.info(s"Found ${seqFilePaths.size} sequence file parts") dumpAll(seqFilePaths, rootPath, fileSys) } /*** * Converts URL to local file * @param url url * @param baseDir parent directory * @return path */ def urlToPath(url:URL, baseDir:String): String = { val hash = Hex.encodeHexString(digest.digest(url.toString.getBytes())) assert(hash.length >= 6, "longer hash expected") val (idx0, idx2, idx4, idx6) = (0, 2, 4, 6) Paths.get(baseDir, url.getHost, hash.substring(idx0, idx2), hash.substring(idx2, idx4), hash.substring(idx4, idx6), hash).toString } /*** * Write data to a file * @param fileSys : file system HDFS API * @param data : data * @param path: target path */ def writeFile(fileSys: FileSystem, data:Content, path: String): Unit ={ val tgtPath = new Path(path) fileSys.mkdirs(tgtPath.getParent) val writer = fileSys.create(tgtPath) val reader = new ByteArrayInputStream(data.getContent) try { IOUtils.copy(reader, writer) } finally { IOUtils.closeQuietly(writer) IOUtils.closeQuietly(reader) } } def dumpAll(seqFiles:Seq[Path], rootPath:Path, fileSys: FileSystem): Unit = { val bufferSize = 4096 val conf = fileSys.getConf val rootString = rootPath.toString // Index file val indexPath = new Path(new Path(rootPath, metaFile), System.currentTimeMillis() + ".tsv") LOG.info(s"Writing Index file to $indexPath") fileSys.mkdirs(indexPath.getParent) val indexStream = fileSys.create(indexPath, false) try { for (seqFile <- seqFiles) { LOG.info(s"Reading file $seqFile") var reader: SequenceFile.Reader = null try { reader = new SequenceFile.Reader(conf, Reader.file(seqFile), Reader.bufferSize(bufferSize), Reader.start(0)) val url = ReflectionUtils.newInstance(reader.getKeyClass, conf).asInstanceOf[Text] val data = ReflectionUtils.newInstance(reader.getValueClass, conf).asInstanceOf[Content] while (reader.next(url, data)) { try { val rawPath = urlToPath(new URL(url.toString), rootString) if (!skipContent) { writeFile(fileSys, data, rawPath) } indexStream.writeBytes(s"$rawPath\t$url\t${data.getContentType}\t${data.getContent.length}\n") } catch { case e: Exception => LOG.warn(s"${e.getMessage} while writing $url ", e) } } } finally { IOUtils.closeQuietly(reader) } } } finally { IOUtils.closeQuietly(indexStream) } } } object Dumper { def main(args: Array[String]): Unit = { setLogLevel() new Dumper().run(args) } }
USCDataScience/sparkler
sparkler-app/src/main/scala/edu/usc/irds/sparkler/service/Dumper.scala
Scala
apache-2.0
5,889
/******************************************************************************* * * Copyright (C) 2015-2021 the BBoxDB project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.bboxdb.storage.queryprocessor.operator; import java.io.IOException; import java.util.Iterator; import org.bboxdb.network.query.filter.UserDefinedFilter; import org.bboxdb.storage.entity.MultiTuple; import org.bboxdb.storage.queryprocessor.predicate.Predicate; import org.bboxdb.storage.queryprocessor.predicate.PredicateJoinedTupleFilterIterator; import org.bboxdb.storage.queryprocessor.predicate.UserDefinedFilterPredicate; public class UserDefinedFilterOperator implements Operator { /** * The operator */ private final Operator parentOperator; /** * The user defined filter operator */ private final UserDefinedFilter filterOperator; /** * The user defined filter data */ private byte[] userDefinedFilterData; public UserDefinedFilterOperator(final UserDefinedFilter filterOperator, final byte[] userDefinedFilterData, final Operator parentOperator) { this.filterOperator = filterOperator; this.userDefinedFilterData = userDefinedFilterData; this.parentOperator = parentOperator; } @Override public Iterator<MultiTuple> iterator() { final Predicate predicate = new UserDefinedFilterPredicate(filterOperator, userDefinedFilterData); return new PredicateJoinedTupleFilterIterator(parentOperator.iterator(), predicate); } @Override public void close() throws IOException { parentOperator.close(); } }
jnidzwetzki/scalephant
bboxdb-server/src/main/java/org/bboxdb/storage/queryprocessor/operator/UserDefinedFilterOperator.java
Java
apache-2.0
2,166
package com.example.tianwei.coolweather.model; public class County { private int id; private String countyName; private String countyCode; private int cityId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCountyName() { return countyName; } public void setCountyName(String countyName) { this.countyName = countyName; } public String getCountyCode() { return countyCode; } public void setCountyCode(String countyCode) { this.countyCode = countyCode; } public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } }
xtian123/coolweather
app/src/main/java/com/example/tianwei/coolweather/model/County.java
Java
apache-2.0
764
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides ByteString as a basic data type for protos. */ goog.module('proto.im.ByteString'); const Hashing = goog.require('proto.im.internal.Hashing'); const base64 = goog.require('goog.crypt.base64'); const {checkType} = goog.require('proto.im.internal.internalChecks'); /** * Immutable sequence of bytes. * * Bytes can be obtained as an Array of numbers or a base64 encoded string. * @final */ class ByteString { /** * @param {?Int8Array} bytes * @param {?string} base64 * @private */ constructor(bytes, base64) { /** @private */ this.bytes_ = bytes; /** @private */ this.base64_ = base64; /** @private */ this.hashCode_ = 0; } /** * Constructs a ByteString instance from a base64 string. * @param {string} value * @returns {!ByteString} */ static fromBase64String(value) { checkType(value != null); return new ByteString(/* bytes */ null, value); } /** * Constructs a ByteString from an array of numbers. * @param {!Uint8Array|!Int8Array|!Array<number>} bytes * @returns {!ByteString} */ static copyFrom(bytes) { return new ByteString(new Int8Array(bytes), /* base 64 */ null); } /** * Returns this ByteString as a Int8 byte array. * @return {!Int8Array} */ toInt8Array() { return new Int8Array(this.ensureBytes_()); } /** * Returns this ByteString as a Uint8 Byte array. * @return {!Uint8Array} */ toUint8Array() { return new Uint8Array(this.ensureBytes_()); } /** * Returns the number of bytes in the string. * @return {number} */ size() { return this.ensureBytes_().length; } /** * Returns the byte value at position `index` * @param {number} index * @return {number} */ byteAt(index) { return this.ensureBytes_()[index]; } /** * Returns this ByteString as a base64 encoded string. * @return {string} */ toBase64String() { return this.ensureBase64String_(); } /** * Returns true for Bytestrings that contain identical values. * @param {*} other * @return {boolean} */ equals(other) { if (this === other) { return true; } if (!(other instanceof ByteString)) { return false; } const otherByteString = /** @type{!ByteString} */ (other); return this.toBase64String() === otherByteString.toBase64String(); } /** * Returns a number (int32) that is suitable for using in hashed structures. * @return {number} */ hashCode() { if (this.hashCode_ == 0) { this.hashCode_ = Hashing.hashString(this.toBase64String()); } return this.hashCode_; } /** * Returns true if the bytestring is empty. * @return {boolean} */ isEmpty() { if (this.bytes_ != null && this.bytes_.length == 0) { return true; } if (this.base64_ != null && this.base64_.length == 0) { return true; } return false; } /** * @return {!Int8Array} * @private */ ensureBytes_() { if (this.bytes_ == null) { const uint8Array = base64.decodeStringToUint8Array(/** @type {string} */ (this.base64_)); this.bytes_ = new Int8Array(uint8Array.buffer); } return /** @type {!Int8Array} */ (this.bytes_); } /** * @return {string} * @private */ ensureBase64String_() { if (this.base64_ == null) { this.base64_ = base64.encodeByteArray( new Uint8Array(/** @type {!Int8Array} */ (this.bytes_).buffer)); } return /** @type {string} */ (this.base64_); } } /** @const {!ByteString} */ ByteString.EMPTY = new ByteString(new Int8Array(0), ''); exports = ByteString;
google/j2cl-protobuf
java/com/google/protobuf/contrib/immutablejs/runtime/bytestring.js
JavaScript
apache-2.0
4,253
package uri import ( "testing" "github.com/telehash/gogotelehash/Godeps/_workspace/src/github.com/stretchr/testify/assert" _ "github.com/telehash/gogotelehash/e3x" ) func Test_resolveDNS(t *testing.T) { // When using boot2docker run: // boot2docker stop // VBoxManage modifyvm "boot2docker-vm" --natdnshostresolver1 off // VBoxManage modifyvm "boot2docker-vm" --natdnsproxy1 on // boot2docker start assert := assert.New(t) uri, err := Parse("01.test.simonmenke.me") if err != nil { panic(err) } ident, err := resolveSRV(uri, "udp") if assert.NoError(err) && assert.NotNil(ident) { t.Logf("ident=%v addrs=%v keys=%v", ident, ident.Addresses(), ident.Keys()) } }
telehash/gogotelehash
uri/resolve_dns_test.go
GO
apache-2.0
695
define({"topics" : [{"title":"Send Data to the Listening Port","shortdesc":"\n <p class=\"shortdesc\">Configure the WebSocket clients to send data to the WebSocket Server listening port.</p>\n ","href":"datacollector\/UserGuide\/Origins\/WebSocketServer.html#concept_djp_bv2_3z","attributes": {"data-id":"concept_djp_bv2_3z",},"menu": {"hasChildren":false,},"tocID":"concept_djp_bv2_3z-d46e68799","topics":[]},{"title":"Include the Application ID in Requests","shortdesc":"\n <p class=\"shortdesc\">Configure the WebSocket clients to include the WebSocket Server application ID in each request.</p>\n ","href":"datacollector\/UserGuide\/Origins\/WebSocketServer.html#concept_i2q_qv2_3z","attributes": {"data-id":"concept_i2q_qv2_3z",},"menu": {"hasChildren":false,},"tocID":"concept_i2q_qv2_3z-d46e68824","topics":[]}]});
rockmkd/datacollector
docs/generated/oxygen-webhelp/app/nav-links/json/concept_thh_3rd_3z-d46e68757.js
JavaScript
apache-2.0
899
<?php /** * Copyright 2018 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ namespace LINE\Tests\LINEBot\MessageBuilder\Flex\ComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\ButtonComponentBuilder; use LINE\LINEBot\TemplateActionBuilder\UriTemplateActionBuilder; use PHPUnit\Framework\TestCase; use LINE\LINEBot\Constant\Flex\ComponentButtonHeight; use LINE\LINEBot\Constant\Flex\ComponentMargin; use LINE\LINEBot\Constant\Flex\ComponentButtonStyle; use LINE\LINEBot\Constant\Flex\ComponentGravity; use LINE\LINEBot\Constant\Flex\ComponentSpacing; use LINE\LINEBot\Constant\Flex\ComponentPosition; class ButtonComponentBuilderTest extends TestCase { public function test() { $result = <<<JSON { "type":"button", "action":{"type":"uri", "label":"OK", "uri":"http://linecorp.com/"}, "flex":2, "margin":"lg", "height":"sm", "style":"link", "color":"#FF0000", "gravity":"center", "position": "relative", "offsetTop": "4px", "offsetBottom": "4%", "offsetStart": "none", "offsetEnd": "sm" } JSON; $componentBuilder = new ButtonComponentBuilder( new UriTemplateActionBuilder('OK', 'http://linecorp.com/'), 2, ComponentMargin::LG, ComponentButtonHeight::SM, ComponentButtonStyle::LINK, '#FF0000', ComponentGravity::CENTER ); $componentBuilder->setPosition(ComponentPosition::RELATIVE) ->setOffsetTop('4px') ->setOffsetBottom('4%') ->setOffsetStart(ComponentSpacing::NONE) ->setOffsetEnd(ComponentSpacing::SM); $this->assertEquals(json_decode($result, true), $componentBuilder->build()); $componentBuilder = ButtonComponentBuilder::builder() ->setAction(new UriTemplateActionBuilder('OK', 'http://linecorp.com/')) ->setFlex(2) ->setMargin(ComponentMargin::LG) ->setHeight(ComponentButtonHeight::SM) ->setStyle(ComponentButtonStyle::LINK) ->setColor('#FF0000') ->setGravity(ComponentGravity::CENTER) ->setPosition(ComponentPosition::RELATIVE) ->setOffsetTop('4px') ->setOffsetBottom('4%') ->setOffsetStart(ComponentSpacing::NONE) ->setOffsetEnd(ComponentSpacing::SM); $this->assertEquals(json_decode($result, true), $componentBuilder->build()); } }
line/line-bot-sdk-php
tests/LINEBot/MessageBuilder/Flex/ComponentBuilder/ButtonComponentBuilderTest.php
PHP
apache-2.0
3,003
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.apimgt.rest.api.util.impl; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIProductIdentifier; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportException; import org.wso2.carbon.apimgt.impl.importexport.ExportFormat; import org.wso2.carbon.apimgt.impl.importexport.utils.APIExportUtil; import org.wso2.carbon.apimgt.impl.importexport.utils.APIProductExportUtil; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.rest.api.util.RestApiConstants; import org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.ws.rs.core.Response; import java.io.File; public class ExportApiUtil { private static final Log log = LogFactory.getLog(ExportApiUtil.class); /** * Exports an API or an API Product from API Manager. Meta information, API icon, documentation, client certificates, WSDL * and sequences are exported. This service generates a zipped archive which contains all the above mentioned * resources for a given API. * * @param name Name of the API that needs to be exported * @param version Version of the API that needs to be exported * @param providerName Provider name of the API that needs to be exported * @param format Format of output documents. Can be YAML or JSON * @param preserveStatus Preserve API status on export * @param type Whether an API or an API Product * @return Zipped file containing exported API */ public Response exportApiOrApiProductByParams(String name, String version, String providerName, String format, Boolean preserveStatus, String type) { ExportFormat exportFormat; String userName; APIProvider apiProvider; String apiDomain; String apiRequesterDomain; File file; //If not specified status is preserved by default boolean isStatusPreserved = preserveStatus == null || preserveStatus; if (name == null || version == null) { RestApiUtil.handleBadRequest("'name' (" + name + ") or 'version' (" + version + ") should not be null.", log); } try { //Default export format is YAML exportFormat = StringUtils.isNotEmpty(format) ? ExportFormat.valueOf(format.toUpperCase()) : ExportFormat.YAML; // Get currently logged in user's username and the domain userName = RestApiUtil.getLoggedInUsername(); apiRequesterDomain = RestApiUtil.getLoggedInUserTenantDomain(); // If provider name is not given if (StringUtils.isBlank(providerName)) { // Retrieve the provider who is in same tenant domain and who owns the same API (by comparing // API name and the version) providerName = APIUtil.getAPIProviderFromAPINameVersionTenant(name, version, apiRequesterDomain); // If there is no provider in current domain, the API cannot be exported if (providerName == null) { String errorMessage = "Error occurred while exporting. API: " + name + " version: " + version + " not found"; RestApiUtil.handleResourceNotFoundError(errorMessage, log); } } //provider names with @ signs are only accepted apiDomain = MultitenantUtils.getTenantDomain(providerName); if (!StringUtils.equals(apiDomain, apiRequesterDomain)) { //not authorized to export requested API RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API + " name:" + name + " version:" + version + " provider:" + providerName, log); } apiProvider = RestApiUtil.getLoggedInUserProvider(); if (!StringUtils.equals(type, RestApiConstants.RESOURCE_API_PRODUCT)) { APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(providerName), name, version); // Checking whether the API exists if (!apiProvider.isAPIAvailable(apiIdentifier)) { String errorMessage = "Error occurred while exporting. API: " + name + " version: " + version + " not found"; RestApiUtil.handleResourceNotFoundError(errorMessage, log); } file = APIExportUtil.exportApi(apiProvider, apiIdentifier, userName, exportFormat, preserveStatus); } else { APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(APIUtil.replaceEmailDomain(providerName), name, version); // Checking whether the API exists if (!apiProvider.isAPIProductAvailable(apiProductIdentifier)) { String errorMessage = "Error occurred while exporting. API Product: " + name + " version: " + version + " not found"; RestApiUtil.handleResourceNotFoundError(errorMessage, log); } file = APIProductExportUtil.exportApiProduct(apiProvider, apiProductIdentifier, userName, exportFormat, preserveStatus); } return Response.ok(file) .header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"") .build(); } catch (APIManagementException | APIImportExportException e) { RestApiUtil.handleInternalServerError("Error while exporting " + RestApiConstants.RESOURCE_API, e, log); } return null; } /** * Exports an API from API Manager for a given API using the ApiId. ID. Meta information, API icon, documentation, * WSDL and sequences are exported. This service generates a zipped archive which contains all the above mentioned * resources for a given API. * * @param apiIdentifier * @param preserveStatus Preserve API status on export * @return Zipped file containing exported API */ public Response exportApiById(APIIdentifier apiIdentifier, Boolean preserveStatus) { ExportFormat exportFormat; APIProvider apiProvider; String userName; File file; try { exportFormat = ExportFormat.YAML; apiProvider = RestApiUtil.getLoggedInUserProvider(); userName = RestApiUtil.getLoggedInUsername(); file = APIExportUtil.exportApi(apiProvider, apiIdentifier, userName, exportFormat, preserveStatus); return Response.ok(file) .header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"") .build(); } catch (APIManagementException | APIImportExportException e) { RestApiUtil.handleInternalServerError("Error while exporting " + RestApiConstants.RESOURCE_API, e, log); } return null; } }
nuwand/carbon-apimgt
components/apimgt/org.wso2.carbon.apimgt.rest.api.util/src/main/java/org/wso2/carbon/apimgt/rest/api/util/impl/ExportApiUtil.java
Java
apache-2.0
8,133
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.andes.server.filter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.andes.server.queue.Filterable; import java.util.concurrent.ConcurrentLinkedQueue; public class SimpleFilterManager implements FilterManager { private final Log _logger = LogFactory.getLog(SimpleFilterManager.class); private final ConcurrentLinkedQueue<MessageFilter> _filters; private String _toString = ""; public SimpleFilterManager() { _logger.debug("Creating SimpleFilterManager"); _filters = new ConcurrentLinkedQueue<MessageFilter>(); } public void add(MessageFilter filter) { _filters.add(filter); updateStringValue(); } public void remove(MessageFilter filter) { _filters.remove(filter); updateStringValue(); } public boolean allAllow(Filterable msg) { for (MessageFilter filter : _filters) { if (!filter.matches(msg)) { return false; } } return true; } public boolean hasFilters() { return !_filters.isEmpty(); } @Override public String toString() { return _toString; } private void updateStringValue() { StringBuilder toString = new StringBuilder(); for (MessageFilter filter : _filters) { toString.append(filter.toString()); toString.append(","); } if (_filters.size() > 0) { //Remove the last ',' toString.deleteCharAt(toString.length()-1); } _toString = toString.toString(); } }
wso2/andes
modules/andes-core/broker/src/main/java/org/wso2/andes/server/filter/SimpleFilterManager.java
Java
apache-2.0
2,383
# Hysterostomella spurcaria (Berk. & Broome) Höhn., 1909 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Sber. Akad. Wiss. Wien, Math. -naturw. Kl. , Abt. 1 118: 1516 (1909) #### Original name Rhytisma spurcarium Berk. & Broome ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Hysteriales/Parmulariaceae/Hysterostomella/Hysterostomella spurcaria/README.md
Markdown
apache-2.0
307
# Mollisia microstigme Pass. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Mollisia microstigme Pass. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Dermateaceae/Mollisia/Mollisia microstigme/README.md
Markdown
apache-2.0
181
# Ophrys cornuta subsp. orientalis SUBSPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Ophrys/Ophrys umbilicata/ Syn. Ophrys cornuta orientalis/README.md
Markdown
apache-2.0
192
# Pasania elizabethae (Tutcher) Chun SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fagales/Fagaceae/Pasania/Pasania elizabethae/README.md
Markdown
apache-2.0
184
# Psidium macrochlamys (DC.) Mattos SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Algrizea/Algrizea macrochlamys/ Syn. Psidium macrochlamys/README.md
Markdown
apache-2.0
190
# Cytisus monopessulanus L. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Cytisus/Cytisus monopessulanus/README.md
Markdown
apache-2.0
175
# Cortinarius cedretorum Maire, 1914 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Bull. Soc. mycol. Fr. 30: 210 (1914) #### Original name Cortinarius cedretorum Maire, 1914 ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Cortinarius/Cortinarius cedretorum/README.md
Markdown
apache-2.0
254
# Salix arctogena Flod. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Salicaceae/Salix/Salix arctogena/README.md
Markdown
apache-2.0
171
# Palaeocirrenalia elegans Ramanujam & Srisailam SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Botanique, Nagpur 9(1-4): 125 + pl. 1, figs 13-14; pl. 2, fig. 15 (1980) #### Original name Palaeocirrenalia elegans Ramanujam & Srisailam ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Palaeocirrenalia/Palaeocirrenalia elegans/README.md
Markdown
apache-2.0
289
# Selenihalanaerobacter shriftii Switzer Blum et al., 2001 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Bacteria/Firmicutes/Clostridia/Halanaerobiales/Halobacteroidaceae/Selenihalanaerobacter/Selenihalanaerobacter shriftii/README.md
Markdown
apache-2.0
214
# Gastrosulum praecox (M.Bieb.) Sch.Bip. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Tripleurospermum/Tripleurospermum parviflorum/ Syn. Gastrosulum praecox/README.md
Markdown
apache-2.0
195
# Aspicilia bohemica var. bohemica VARIETY #### Status ACCEPTED #### According to Index Fungorum #### Published in Syst. lich. germ. (Breslau) 162 (1855) #### Original name Aspicilia bohemica var. bohemica ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Lecanoromycetes/Pertusariales/Megasporaceae/Lobothallia/Lobothallia recedens/Aspicilia bohemica bohemica/README.md
Markdown
apache-2.0
227
# Phyllachora medellinensis (Chardón) Petr., 1940 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Annls mycol. 38(2/4): 213 (1940) #### Original name Clypeotrabutia medellinensis Chardón, 1930 ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Phyllachorales/Phyllachoraceae/Phyllachora/Phyllachora medellinensis/README.md
Markdown
apache-2.0
273
# Ammophila curtissii Vasey SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Calamovilfa/Calamovilfa curtissii/ Syn. Ammophila curtissii/README.md
Markdown
apache-2.0
182
using JetBrains.ReSharper.Psi.Parsing; namespace JetBrains.ReSharper.Plugins.Unity.Shaders.Cg.Psi.Parsing.TokenNodes { internal class CgPreprocessorTokenNode : CgGenericTokenNode { public CgPreprocessorTokenNode(TokenNodeType tokenNodeType, string text) : base(tokenNodeType, text) { } } }
JetBrains/resharper-unity
resharper/resharper-unity/src/Unity.Shaders/Cg/Psi/Parsing/TokenNodes/CgPreprocessorTokenNode.cs
C#
apache-2.0
341
package org.keedio.flume.interceptor.cacheable.service; //import org.keedio.flume.interceptor.cacheable.service.ICacheService; import com.google.common.collect.ImmutableMap; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import org.apache.flume.Event; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:beans.xml"}) public class FlumeCacheServiceTest { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(FlumeCacheServiceTest.class); @Autowired private ICacheService<Event> service; @Autowired private CacheManager cacheManager; private Cache cache; @PostConstruct public void init() { service.setProperties(ImmutableMap.of( ICacheService.PROPERTIES_CSV_SEPARATOR, ",", ICacheService.PROPERTIES_CSV_DIRECTORY, "src/main/resources")); cache = cacheManager.getCache("FlumeCachedEvent"); } /** * Test of enrichMap method, of class FlumeCacheService. */ @Test public void testEnrichMapSingleKey() throws IOException { System.out.println("enrichMapSingleKey"); Map<String, String> data = new HashMap<String, String>(); Map<String, String> data2 = new HashMap<String, String>(); data.put("ciid", "124"); data.put("vdc", "01"); data.put("item", "proxy"); data.put("delivery", "***REMOVED***"); data2.put("hostname", "host1"); assertEquals(data, service.enrichMap(data2)); } @Test public void testEnrichMapMultipleKeys() throws IOException { System.out.println("enrichMapMultipleKeys"); Map<String, String> data = new HashMap<String, String>(); Map<String, String> data2 = new HashMap<String, String>(); data.put("ciid", "124"); data.put("vdc", "01"); data.put("delivery", "***REMOVED***"); data2.put("hostname", "host1"); data2.put("item", "proxy"); Map<String, String> mapResult = service.enrichMap(data2); assertEquals(data, mapResult); } @Test public void testEnrichMapMultipleKeysNoMatch() throws IOException { System.out.println("enrichMapEnrichMapMultipleKeysNoMatch"); Map<String, String> data2 = new HashMap<String, String>(); data2.put("hostname", "host1"); data2.put("item", "FW"); Map<String, String> mapResult = service.enrichMap(data2); System.out.println(mapResult.toString()); org.junit.Assert.assertTrue(mapResult.isEmpty()); } @Test public void testCacheEviction() throws IOException { int cacheInitialSize = cache.getSize(); Map<String, String> data = new HashMap<>(); data.put("hostname", "host1"); service.enrichMap(data); assertEquals(cacheInitialSize + 1, cache.getSize()); service.evictCache(); assertEquals(0, cache.getSize()); } }
keedio/CacheableInterceptor
src/test/java/org/keedio/flume/interceptor/cacheable/service/FlumeCacheServiceTest.java
Java
apache-2.0
3,470
# AUTOGENERATED FILE FROM balenalib/nanopi-neo-air-fedora:30-build ENV NODE_VERSION 15.6.0 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "234871415c54174f91764f332a72631519a6af7b1a87797ad7c729855182f9cd node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Fedora 30 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.6.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/node/nanopi-neo-air/fedora/30/15.6.0/build/Dockerfile
Dockerfile
apache-2.0
2,759
package it.essepuntato.earmark.core.test; import it.essepuntato.earmark.core.EARMARKChildNode; import it.essepuntato.earmark.core.EARMARKDocument; import it.essepuntato.earmark.core.EARMARKHierarchicalNode; import it.essepuntato.earmark.core.Range; import java.util.ArrayList; import java.util.List; /* Ho alcune segnalazioni che riguardano le EARMARK API, spero ti siano utili: 1a) getNamespaceURI() ritorna una stringa (implementa un metodo dichiarato nell'interfaccia EARMARKNamedNode) "The namespace URI of the general identifier associated to this node, or null if it is unspecified." hasNamespace: ritorna URI "This method returns the namespace of this markup item." Forse c'e' da rivedere il javadoc: in realtà una torna l'URI del namespace, l'altro la stringa del namespace. E poi non è lineare: per l'ID c'è solo il metodo hasID che ritorna l'URI dell'ID, e non il metodo per avere la stringa: secondo me il metodo per la stringa andrebbe messo o in entrambi o eliminato. 1b) EARMARKDocument.generalIdentifierIsUsedBy(""); e EARMARKDocument.getMarkupItemByGeneralIdentifier(""); sono metodi diversi o duplicati? L'implementazione è diversa, la semantica sembra la stessa dal javadoc. 1c) EARMARKDocument.removeMarkupItem(mi) rimuove anche tutto il contenuto del markup item (tutti gli elementi dominati, a qualsiasi livello di profondita'), anche se altri sono in overlap su di esso. E' corretto cosi? 1d) problema in cloneNode() : la/le radici del grafo non sono appese al documento. Per esempio se: EARMARKDocument earDoc; // in earDoc carico un documento EARMARK // poi clono il documento EARMARKDocument earDocMainHierarchy; earDocMainHierarchy = (EARMARKDocument)earDoc.cloneNode(true); // cerco gi elementi figli del documento Collection roots = earDoc.getChildElements(); Collection roots2 = earDocMainHierarchy.getChildElements(); e qui trovo roots = { elemento/i radice }, mentre roots2 = {} vuoto. 1d2) l'elemento radice di un EARMARKDocument non ha genitori: rootElement.getParentNodes() ritorna un insieme vuoto: è corretto? non dovrebbe restituire l'EARMARKDocument che lo contiene? 1e) in un documento clonato il metodo hasChildNodes() non funziona correttamente. Per esempio: Collection children = node.getChildNodes(); // children contiene tre elementi, però se poi invoco boolean hasChildren = node.hasChildNodes(); // hasChildren è false... 1f) invocando una createPointerRange(Docuverse docuverse, Integer begin, Integer end) [la versione senza id specificato nei parametri] capita che mi generi un range con id gia' esistente nel documento (in particolare mi crea un range con id "r1" che era utilizzato precedentemente gia' da un altro range). Questo pero' capita in un documento ottenuto in seguito a una cloneNode() di un altro documento: puo' essere che sia dovuto a strutture non aggiornate. */ public class FrancescoPoggiTestOne extends AbstractTest { private EARMARKDocument document = null; public FrancescoPoggiTestOne(EARMARKDocument doc) { document = doc; } @Override public List<String> doTest() { List<String> result = new ArrayList<String>(); result.add("\n[i] Check parents of a root node"); EARMARKChildNode child = document.getChildNodes().iterator().next(); String msg1 = "Check if " + child + " has the document has father, test"; if (child.getParentNodes().contains(document)) { result.add(passed(msg1)); } else { result.add(failed(msg1, "The parents are: " + child.getParentNodes())); } result.add("\n[i] Clone the document"); EARMARKDocument newDoc = (EARMARKDocument) document.cloneNode(true); result.add("\n[i] Compare children of the document with the cloned one"); String msg2 = "Check if " + newDoc + " (cloned document) has the same number of" + " children of " + document + " (original document), test"; if (document.getChildNodes().size() == newDoc.getChildNodes().size()) { result.add(passed(msg2)); } else { result.add(failed(msg2, "The children are respectively: " + "\n\t- " + document + ": " + document.getChildNodes() + "\n\t- " + newDoc + ": " + newDoc.getChildNodes())); } result.add("\n[i] Methods for children in the cloned document"); String msg3 = "Check if in " + newDoc + " (cloned document) the methods getChildNodes() and hasChildNodes()" + "return consistent answers, both for the document and for a random node of it, test"; EARMARKHierarchicalNode childCloned = (EARMARKHierarchicalNode) newDoc.getChildNodes().iterator().next(); if ( newDoc.getChildNodes().isEmpty() == !newDoc.hasChildNodes() && childCloned.getChildNodes().isEmpty() == ! childCloned.hasChildNodes()) { result.add(passed(msg3)); } else { result.add(failed(msg3, "The children are respectively: " + "\n\t- " + newDoc + ": " + newDoc.getChildNodes() + "\n\t- " + childCloned + ": " + childCloned.getChildNodes())); } result.add("\n[i] Create a new pointer range in the cloned document"); String msg4 = "Check if in " + newDoc + " (cloned document) the methods for creating a new pointer range" + " return a range with an ID that was already present in the document, test"; Range pRange = newDoc.createPointerRange(newDoc.getAllDocuverses().iterator().next(), null, null); if (pRange == null) { result.add(failed(msg4, "The range was not created.")); } else { result.add(passed(msg4)); } return result; } @Override public String getTestName() { return "Francesco Poggi test 1"; } @Override public boolean useDocument(EARMARKDocument document) { this.document = document; return true; } }
essepuntato/EarmarkDataStructure
src/it/essepuntato/earmark/core/test/FrancescoPoggiTestOne.java
Java
apache-2.0
5,634
/* * Copyright (C) Lightbend Inc. <https://www.lightbend.com> */ package com.lightbend.lagom.internal.testkit import java.nio.file.Files import java.util.concurrent.TimeUnit import akka.persistence.cassandra.testkit.CassandraLauncher import com.google.common.io.MoreFiles import com.google.common.io.RecursiveDeleteOption import play.api.Logger import play.api.inject.ApplicationLifecycle import scala.concurrent.Future import scala.util.Try private[lagom] object CassandraTestServer { private val LagomTestConfigResource: String = "lagom-test-embedded-cassandra.yaml" private lazy val log = Logger(getClass) def run(cassandraDirectoryPrefix: String, lifecycle: ApplicationLifecycle): Int = { val cassandraDirectory = Files.createTempDirectory(cassandraDirectoryPrefix) // Shut down Cassandra and delete its temporary directory when the application shuts down lifecycle.addStopHook { () => import scala.concurrent.ExecutionContext.Implicits.global Try(CassandraLauncher.stop()) // The ALLOW_INSECURE option is required to remove the files on OSes that don't support SecureDirectoryStream // See http://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/io/MoreFiles.html#deleteRecursively-java.nio.file.Path-com.google.common.io.RecursiveDeleteOption...- Future(MoreFiles.deleteRecursively(cassandraDirectory, RecursiveDeleteOption.ALLOW_INSECURE)) } val t0 = System.nanoTime() CassandraLauncher.start( cassandraDirectory.toFile, LagomTestConfigResource, clean = false, port = 0, CassandraLauncher.classpathForResources(LagomTestConfigResource) ) log.debug(s"Cassandra started in ${TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0)} ms") CassandraLauncher.randomPort } }
lagom/lagom
testkit/core/src/main/scala/com/lightbend/lagom/internal/testkit/CassandraTestServer.scala
Scala
apache-2.0
1,815
/* Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package grpcvtgateconn import ( "flag" "io" "net" "os" "testing" "google.golang.org/grpc" "context" "vitess.io/vitess/go/vt/servenv" "vitess.io/vitess/go/vt/vtgate/grpcvtgateservice" "vitess.io/vitess/go/vt/vtgate/vtgateconn" ) // TestGRPCVTGateConn makes sure the grpc service works func TestGRPCVTGateConn(t *testing.T) { // fake service service := CreateFakeServer(t) // listen on a random port listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("Cannot listen: %v", err) } // Create a gRPC server and listen on the port server := grpc.NewServer() grpcvtgateservice.RegisterForTest(server, service) go server.Serve(listener) // Create a Go RPC client connecting to the server ctx := context.Background() client, err := dial(ctx, listener.Addr().String()) if err != nil { t.Fatalf("dial failed: %v", err) } RegisterTestDialProtocol(client) // run the test suite RunTests(t, client, service) RunErrorTests(t, service) // and clean up client.Close() } // TestGRPCVTGateConnAuth makes sure the grpc with auth plugin works func TestGRPCVTGateConnAuth(t *testing.T) { var opts []grpc.ServerOption // fake service service := CreateFakeServer(t) // listen on a random port listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("Cannot listen: %v", err) } // add auth interceptors opts = append(opts, grpc.StreamInterceptor(servenv.FakeAuthStreamInterceptor)) opts = append(opts, grpc.UnaryInterceptor(servenv.FakeAuthUnaryInterceptor)) // Create a gRPC server and listen on the port server := grpc.NewServer(opts...) grpcvtgateservice.RegisterForTest(server, service) go server.Serve(listener) authJSON := `{ "Username": "valid", "Password": "valid" }` f, err := os.CreateTemp("", "static_auth_creds.json") if err != nil { t.Fatal(err) } defer os.Remove(f.Name()) if _, err := io.WriteString(f, authJSON); err != nil { t.Fatal(err) } if err := f.Close(); err != nil { t.Fatal(err) } // Create a Go RPC client connecting to the server ctx := context.Background() flag.Set("grpc_auth_static_client_creds", f.Name()) client, err := dial(ctx, listener.Addr().String()) if err != nil { t.Fatalf("dial failed: %v", err) } RegisterTestDialProtocol(client) // run the test suite RunTests(t, client, service) RunErrorTests(t, service) // and clean up client.Close() invalidAuthJSON := `{ "Username": "invalid", "Password": "valid" }` f, err = os.CreateTemp("", "static_auth_creds.json") if err != nil { t.Fatal(err) } defer os.Remove(f.Name()) if _, err := io.WriteString(f, invalidAuthJSON); err != nil { t.Fatal(err) } if err := f.Close(); err != nil { t.Fatal(err) } // Create a Go RPC client connecting to the server ctx = context.Background() flag.Set("grpc_auth_static_client_creds", f.Name()) client, err = dial(ctx, listener.Addr().String()) if err != nil { t.Fatalf("dial failed: %v", err) } RegisterTestDialProtocol(client) conn, _ := vtgateconn.DialProtocol(context.Background(), "test", "") // run the test suite _, err = conn.Session("", nil).Execute(context.Background(), "select * from t", nil) want := "rpc error: code = Unauthenticated desc = username and password must be provided" if err == nil || err.Error() != want { t.Errorf("expected auth failure:\n%v, want\n%s", err, want) } // and clean up again client.Close() }
vitessio/vitess
go/vt/vtgate/grpcvtgateconn/conn_rpc_test.go
GO
apache-2.0
4,005
package pf.lapimonster.JsonChatAPI; import java.lang.reflect.InvocationTargetException; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import pf.lapimonster.JsonChatAPI.tools.JsonColor; import pf.lapimonster.JsonChatAPI.tools.JsonFormat; import pf.lapimonster.JsonChatAPI.tools.JsonPosition; import pf.lapimonster.JsonChatAPI.utils.NMSUtils; public class JsonMessage { private Object base; private Object u; private byte position; public JsonMessage(JsonPosition position) { try { this.base = JsonChatAPI.getInstance().getChatSerializerClass().getMethod("a", String.class).invoke(null, "{text: \"\"}"); this.position = position.work(); } catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } } public JsonMessage text(String text) { try { this.u = JsonChatAPI.getInstance().getChatSerializerClass().getMethod("a", String.class).invoke(null, "{text: \""+text+"\"}"); this.base.getClass().getMethod("addSibling", JsonChatAPI.getInstance().getIChatBaseComponentClass()).invoke(this.base, this.u); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } return this; } public JsonMessage text(String text, JsonColor color) { try { this.u = JsonChatAPI.getInstance().getChatSerializerClass().getMethod("a", String.class).invoke(null, "{text: \""+text+"\", color:\""+color.work()+"\"}"); this.base.getClass().getMethod("addSibling", JsonChatAPI.getInstance().getIChatBaseComponentClass()).invoke(this.base, this.u); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } return this; } public JsonMessage text(String text, JsonFormat format) { try { this.u = JsonChatAPI.getInstance().getChatSerializerClass().getMethod("a", String.class).invoke(null, "{text: \""+text+"\", "+format.work()+": true}"); this.base.getClass().getMethod("addSibling", JsonChatAPI.getInstance().getIChatBaseComponentClass()).invoke(this.base, this.u); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } return this; } public JsonMessage text(String text, JsonFormat[] formats) { String format = ""; for(JsonFormat fs : formats) format += fs.work()+": true, "; format = format.substring(0, format.length()-2); try { this.u = JsonChatAPI.getInstance().getChatSerializerClass().getMethod("a", String.class).invoke(null, "{text: \""+text+"\", "+format+"}"); this.base.getClass().getMethod("addSibling", JsonChatAPI.getInstance().getIChatBaseComponentClass()).invoke(this.base, this.u); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } return this; } public JsonMessage text(String text, JsonColor color, JsonFormat format) { try { this.u = JsonChatAPI.getInstance().getChatSerializerClass().getMethod("a", String.class).invoke(null, "{text: \""+text+"\", color: \""+color.toString()+"\", "+format.work()+": true}"); this.base.getClass().getMethod("addSibling", JsonChatAPI.getInstance().getChatSerializerClass()).invoke(this.base, this.u); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } return this; } public JsonMessage text(String text, JsonColor color, JsonFormat[] formats) { String format = ""; for(JsonFormat fs : formats) format += fs.work()+": true, "; format = format.substring(0, format.length()-2); try { this.u = JsonChatAPI.getInstance().getChatSerializerClass().getMethod("a", String.class).invoke(null, "{text: \""+text+"\", "+format+", color: \""+color.work()+"\"}"); this.base.getClass().getMethod("addSibling", JsonChatAPI.getInstance().getIChatBaseComponentClass()).invoke(this.base, this.u); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } return this; } public JsonMessage extra(String JsonExtra) { try { this.u = JsonChatAPI.getInstance().getChatSerializerClass().getMethod("a", String.class).invoke(null, JsonExtra); this.base.getClass().getMethod("addSibling", JsonChatAPI.getInstance().getIChatBaseComponentClass()).invoke(this.base, this.u); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } return this; } public void send(Player p) { try { Object packet = JsonChatAPI.getInstance().getPacketPlayOutChatClass().getConstructor(JsonChatAPI.getInstance().getIChatBaseComponentClass(), byte.class).newInstance(this.base, this.position); Object pConnection = NMSUtils.getNMSPlayer(p).getClass().getField("playerConnection").get(NMSUtils.getNMSPlayer(p)); pConnection.getClass().getMethod("sendPacket", JsonChatAPI.getInstance().getPacketClass()).invoke(pConnection, packet); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException | InvocationTargetException | NoSuchMethodException | InstantiationException e) { e.printStackTrace(); } } public void sendToAll() { for(Player p : Bukkit.getServer().getOnlinePlayers()) send(p); } }
LaPiMoNsTeR/JsonChatAPI
src/pf/lapimonster/JsonChatAPI/JsonMessage.java
Java
apache-2.0
5,799
import mongodb from 'mongodb'; import _ from 'lodash'; const debug = require('debug')('mongobless'); const models = []; let DB; const Model = new Function(); const isFunction = obj => typeof obj === 'function'; function extend(destination) { const sources = Array.prototype.slice.call(arguments, 1); for(let i in sources){ const source = sources[i]; Object.keys(source).forEach(function(property) { Object.defineProperty(destination, property, Object.getOwnPropertyDescriptor(source, property)); }); } return destination; } Model.bless = function(obj){ if (!obj) return; obj.__proto__ = this.prototype; obj.constructor = this; return obj; }; Model.findAll = function(...params){ const blessAll = data => data.map(obj => this.bless(obj)); const fn = params[params.length - 1]; if (isFunction(fn)) { const cb = (err, res) => { if(err) return fn(err); fn(null, blessAll(res)); }; this.collection.find(...params.slice(0, -1)).toArray(cb); return this; } return this.collection.find(...params).toArray().then(blessAll); }; Model.findOne = function(...params){ const blessOne = obj => this.bless(obj); const fn = params[params.length - 1]; if (isFunction(fn)) { const cb = (err, res) => { if(err) return fn(err); fn(null, blessOne(res)); }; this.collection.findOne(...params.slice(0, -1), cb); return this; } return this.collection.findOne(...params).then(blessOne); } Object.defineProperty(Model, 'collection', { enumerable: true , configurable: false , get: function(){return this.db.collection(this.collectionName) } }); Model.connect = function(db){ this.db = db; } Model.extendableProperties = ['connect', 'collection', 'findOne', 'findAll']; export default function MongoBless(options = {}){ return function(constructor){ if(options.collection){ if(constructor.isPersistentRoot)throw new Error(`Cannot overload collection's name for class '${constructor.name}'`); models.push(constructor); constructor.collectionName = options.collection; constructor.isPersistentRoot = true; _.each(Model.extendableProperties, prop => { Object.defineProperty(constructor, prop, Object.getOwnPropertyDescriptor(Model, prop)); }); if(!constructor.bless){ Object.defineProperty(constructor, 'bless', Object.getOwnPropertyDescriptor(Model, 'bless')); } }else{ constructor.isPersistentRoot = false; } } } MongoBless.close = cb => { if (cb) return DB.close(cb); return DB.close(); } MongoBless.bless = function(obj){ return Model.bless.bind(this)(obj); }; MongoBless.connect = function(opt, cb){ const options = _.extend({host: '127.0.0.1', port: 27017, auto_reconnect: true, poolSize: 10, w:1, strict: true, native_parser: true, verbose: true}, opt); let mongoserver; if (!options.replicaSet) mongoserver = new mongodb.Server(options.host, options.port, options); else { const replicaServers = _.map(options.replicaSet.servers, function(server){ return new mongodb.Server( server.host, server.port, server.options); }); mongoserver = new mongodb.ReplSet(replicaServers, _.extend({}, options.replicaSet.options, {rs_name: options.replicaSet.name})); } const dbconnector = new mongodb.Db(options.database, mongoserver, options); const initModels = (db) => { DB = db; for(const i in models){ models[i].connect(db) } debug("mongobless is ready for your requests ..."); return db; }; if (cb) { dbconnector.open((err, db) => { if (err) return cb(err); initModels(db); cb(null, db); }); } else { return dbconnector.open().then(initModels); } }; export const ObjectId = mongodb.ObjectID;
redpelicans/mongobless
src/index.js
JavaScript
apache-2.0
3,789
package org.apereo.cas.web.view; import org.apereo.cas.CasProtocolConstants; import org.apereo.cas.CasViewConstants; import org.apereo.cas.CipherExecutor; import org.apereo.cas.authentication.CoreAuthenticationTestUtils; import org.apereo.cas.authentication.DefaultAuthenticationAttributeReleasePolicy; import org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionPlan; import org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionStrategy; import org.apereo.cas.authentication.ProtocolAttributeEncoder; import org.apereo.cas.authentication.support.DefaultCasProtocolAttributeEncoder; import org.apereo.cas.services.ServicesManager; import org.apereo.cas.services.web.view.AbstractCasView; import org.apereo.cas.util.CollectionUtils; import org.apereo.cas.util.EncodingUtils; import org.apereo.cas.util.crypto.PrivateKeyFactoryBean; import org.apereo.cas.validation.DefaultServiceTicketValidationAuthorizersExecutionPlan; import org.apereo.cas.web.AbstractServiceValidateController; import org.apereo.cas.web.AbstractServiceValidateControllerTests; import org.apereo.cas.web.ServiceValidateConfigurationContext; import org.apereo.cas.web.ServiceValidationViewFactory; import org.apereo.cas.web.v2.ServiceValidateController; import org.apereo.cas.web.view.attributes.DefaultCas30ProtocolAttributesRenderer; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.tuple.Pair; import org.apereo.services.persondir.IPersonAttributeDao; import org.apereo.services.persondir.support.StubPersonAttributeDao; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.core.io.ClassPathResource; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.View; import org.springframework.web.servlet.support.RequestContext; import javax.crypto.Cipher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; /** * Unit tests for {@link Cas30ResponseView}. * * @author Misagh Moayyed * @since 4.0.0 */ @DirtiesContext @TestPropertySource(properties = {"cas.clearpass.cacheCredential=true", "cas.clearpass.crypto.enabled=false"}) @Slf4j @Import(Cas30ResponseViewTests.AttributeRepositoryTestConfiguration.class) public class Cas30ResponseViewTests extends AbstractServiceValidateControllerTests { @Autowired @Qualifier("serviceValidationViewFactory") protected ServiceValidationViewFactory serviceValidationViewFactory; @Autowired @Qualifier("servicesManager") protected ServicesManager servicesManager; @Override public AbstractServiceValidateController getServiceValidateControllerInstance() { val context = ServiceValidateConfigurationContext.builder() .validationSpecifications(CollectionUtils.wrapSet(getValidationSpecification())) .authenticationSystemSupport(getAuthenticationSystemSupport()) .servicesManager(getServicesManager()) .centralAuthenticationService(getCentralAuthenticationService()) .argumentExtractor(getArgumentExtractor()) .proxyHandler(getProxyHandler()) .requestedContextValidator((assertion, request) -> Pair.of(Boolean.TRUE, Optional.empty())) .authnContextAttribute("authenticationContext") .validationAuthorizers(new DefaultServiceTicketValidationAuthorizersExecutionPlan()) .renewEnabled(true) .validationViewFactory(serviceValidationViewFactory) .build(); return new ServiceValidateController(context); } protected Map<?, ?> renderView() throws Exception { val modelAndView = this.getModelAndViewUponServiceValidationWithSecurePgtUrl(); LOGGER.debug("Retrieved model and view [{}]", modelAndView.getModel()); val req = new MockHttpServletRequest(new MockServletContext()); req.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, new GenericWebApplicationContext(req.getServletContext())); val encoder = new DefaultCasProtocolAttributeEncoder(this.servicesManager, CipherExecutor.noOpOfStringToString()); val viewDelegated = new View() { @Override public String getContentType() { return MediaType.TEXT_HTML_VALUE; } @Override public void render(final Map<String, ?> map, final HttpServletRequest request, final HttpServletResponse response) { LOGGER.warn("Setting attribute [{}]", map.keySet()); map.forEach(request::setAttribute); } }; val view = getCasViewToRender(encoder, viewDelegated); val resp = new MockHttpServletResponse(); view.render(modelAndView.getModel(), req, resp); return getRenderedViewModelMap(req); } protected Map getRenderedViewModelMap(final MockHttpServletRequest req) { return (Map) req.getAttribute(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES); } protected AbstractCasView getCasViewToRender(final ProtocolAttributeEncoder encoder, final View viewDelegated) { return new Cas30ResponseView(true, encoder, servicesManager, viewDelegated, new DefaultAuthenticationAttributeReleasePolicy("attribute"), new DefaultAuthenticationServiceSelectionPlan(new DefaultAuthenticationServiceSelectionStrategy()), new DefaultCas30ProtocolAttributesRenderer()); } @Test public void verifyViewAuthnAttributes() throws Exception { val attributes = renderView(); assertTrue(attributes.containsKey(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_AUTHENTICATION_DATE)); assertTrue(attributes.containsKey(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_FROM_NEW_LOGIN)); assertTrue(attributes.containsKey(CasProtocolConstants.VALIDATION_REMEMBER_ME_ATTRIBUTE_NAME)); } @Test public void verifyPasswordAsAuthenticationAttributeCanDecrypt() throws Exception { val attributes = renderView(); assertTrue(attributes.containsKey(CasViewConstants.MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL)); val encodedPsw = (String) attributes.get(CasViewConstants.MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL); val password = decryptCredential(encodedPsw); val creds = CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(); assertEquals(password, creds.getPassword()); } @Test public void verifyProxyGrantingTicketAsAuthenticationAttributeCanDecrypt() throws Exception { val attributes = renderView(); LOGGER.trace("Attributes are [{}]", attributes.keySet()); assertTrue(attributes.containsKey(CasViewConstants.MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET)); val encodedPgt = (String) attributes.get(CasViewConstants.MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET); val pgt = decryptCredential(encodedPgt); assertNotNull(pgt); } @SneakyThrows private static String decryptCredential(final String cred) { val factory = new PrivateKeyFactoryBean(); factory.setAlgorithm("RSA"); factory.setLocation(new ClassPathResource("keys/RSA4096Private.p8")); factory.setSingleton(false); val privateKey = factory.getObject(); LOGGER.debug("Initializing cipher based on [{}]", privateKey.getAlgorithm()); val cipher = Cipher.getInstance(privateKey.getAlgorithm()); LOGGER.debug("Decoding value [{}]", cred); val cred64 = EncodingUtils.decodeBase64(cred); LOGGER.debug("Initializing decrypt-mode via private key [{}]", privateKey.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); val cipherData = cipher.doFinal(cred64); return new String(cipherData, StandardCharsets.UTF_8); } @Test public void verifyViewBinaryAttributes() throws Exception { val attributes = renderView(); assertTrue(attributes.containsKey("binaryAttribute")); val binaryAttr = attributes.get("binaryAttribute"); assertEquals("binaryAttributeValue", EncodingUtils.decodeBase64ToString(binaryAttr.toString())); } @TestConfiguration public static class AttributeRepositoryTestConfiguration { @Bean public IPersonAttributeDao attributeRepository() { val attrs = CollectionUtils.wrap("uid", CollectionUtils.wrap("uid"), "eduPersonAffiliation", CollectionUtils.wrap("developer"), "groupMembership", CollectionUtils.wrap("adopters"), "binaryAttribute", CollectionUtils.wrap("binaryAttributeValue".getBytes(StandardCharsets.UTF_8))); return new StubPersonAttributeDao((Map) attrs); } } }
rrenomeron/cas
support/cas-server-support-validation/src/test/java/org/apereo/cas/web/view/Cas30ResponseViewTests.java
Java
apache-2.0
9,642
# caridea-http Caridea is a miniscule PHP application library. This shrimpy fellow is what you'd use when you just want some helping hands and not a full-blown framework. ![](http://libreworks.com/caridea-100.png) This is its HTTP component. It includes small utilities for working with [PSR-7](http://www.php-fig.org/psr/psr-7/) HTTP requests and responses, including: * An implementation of RFC 7807, "[Problem Details for HTTP APIs](https://tools.ietf.org/html/rfc7807)". * A utility to parse common pagination parameters from the request * A utility to correctly parse query strings with multiple parameters having the same name * A utility to determine a client's preferred accepted MIME type [![Packagist](https://img.shields.io/packagist/v/caridea/http.svg)](https://packagist.org/packages/caridea/http) [![Build Status](https://travis-ci.org/libreworks/caridea-http.svg)](https://travis-ci.org/libreworks/caridea-http) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/libreworks/caridea-http/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/libreworks/caridea-http/?branch=master) [![Code Coverage](https://scrutinizer-ci.com/g/libreworks/caridea-http/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/libreworks/caridea-http/?branch=master) [![Documentation Status](http://readthedocs.org/projects/caridea-http/badge/?version=latest)](http://caridea-http.readthedocs.io/en/latest/?badge=latest) ## Installation You can install this library using Composer: ```console $ composer require caridea/http ``` * The master branch (version 3.x) of this project requires PHP 7.1 and depends on `psr/http-message`. * Version 2.x of this project requires PHP 7.0 and depends on `psr/http-message`. * Version 1.x of this project requires PHP 5.5 and depends on `psr/http-message`. ## Compliance Releases of this library will conform to [Semantic Versioning](http://semver.org). Our code is intended to comply with [PSR-1](http://www.php-fig.org/psr/psr-1/), [PSR-2](http://www.php-fig.org/psr/psr-2/), and [PSR-4](http://www.php-fig.org/psr/psr-4/). If you find any issues related to standards compliance, please send a pull request! ## Documentation * Head over to [Read the Docs](http://caridea-http.readthedocs.io/en/latest/) ## Examples Just a few quick examples. ### Problem Details We included an implementation of RFC 7807 that you can serialize to JSON or append to a PSR-7 HTTP Response. ```php use Caridea\Http\ProblemDetails; use Zend\Diactoros\Uri; $problem = new ProblemDetails( new Uri('http://example.com/problem/oops'), // type 'A weird thing happened', // title 500, // status 'It looks like the server has goofed again', // detail new Uri('http://example.com/problems/1f9a'), // instance [ // extensions 'server' => 'workerbee01.example.com', 'auth' => 'foobar' ] ); echo json_encode($problem); ``` ### Pagination Factory ```php use Zend\Diactoros\ServerRequestFactory; $request = ServerRequestFactory::fromGlobals( $_SERVER, \Caridea\Http\QueryParams::getFromServer(), // instead of $_GET ); $factory = new \Caridea\Http\PaginationFactory(); // say the Query was ?count=25&startIndex=1&sort=%2Bfoo&sort-bar // or maybe ?count=25&start=0&sort=%2Bfoo,-bar // or one of many other formats for this type of pagination settingns $pagination = $factory->create($request, 'sort'); $pagination->getMax(); // 25 $pagination->getOffset(); // 0 $pagination->getOrder(); // ['foo' => true, 'bar' => false] ``` ### Accept Types ```php // say the HTTP_ACCEPT field is text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 $types = new \Caridea\Http\AcceptTypes($_SERVER); $types->preferred(['application/xml', 'application/json']); // returns application/xml ``` ### Helper Traits Two traits are now available, `JsonHelper` and `MessageHelper`. These can be used by controller classes or dispatcher middleware. ## Third-Party The traits `JsonHelper` and `MessageHelper` (as well as their unit tests) were ported to PHP from the Labrys library under a compatible Apache 2.0 license.
libreworks/caridea-http
README.md
Markdown
apache-2.0
4,228
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import itertools import os import sys import tempfile from absl.testing import absltest import numpy as np from six.moves import cPickle from simulation_research.traffic import file_util class UtilTest(absltest.TestCase): def setUp(self): super(UtilTest, self).setUp() self._output_dir = tempfile.mkdtemp(dir=absltest.get_default_test_tmpdir()) def test_append_line_to_file(self): r"""Tests the output file. The output file contains the following. hello world (hello) "world" (hello) !!!!!!!!!!! @~#$%^&*()_+"world" aaaaaaaa bbbbbbbbbb backslash\ backslash backslash\ backslash backslash\\ backslash backslash\\\ backslash backslash\\ backslash """ input_lines = ['hello world', '(hello) "world"', '(hello) !!!!!!!!!!! @~#$%^&*()_+"world"', 'aaaaaaaa\nbbbbbbbbbb', r'backslash\ backslash', 'backslash\\ backslash', r'backslash\\ backslash', r'backslash\\\ backslash', 'backslash\\\\ backslash'] file_path = os.path.join(self._output_dir, 'test_append_line_to_file.txt') for line in input_lines: file_util.append_line_to_file(file_path, line) self.assertTrue(file_util.f_exists(file_path)) # Note that the linebreak in the input_lines[3]. target_lines = ['hello world', '(hello) "world"', '(hello) !!!!!!!!!!! @~#$%^&*()_+"world"', 'aaaaaaaa', 'bbbbbbbbbb', r'backslash\ backslash', 'backslash\\ backslash', r'backslash\\ backslash', r'backslash\\\ backslash', 'backslash\\\\ backslash'] with file_util.f_open(file_path, 'r') as actual_file: line_counter = 0 read_lines = actual_file.readlines() for line in read_lines: # Linebreak is appended to the target string. self.assertEqual(line, target_lines[line_counter] + '\n') line_counter += 1 target_line_number = len(target_lines) self.assertEqual(target_line_number, line_counter) def test_save_load_variable(self): file_path = os.path.join(self._output_dir, 'test_output_data.pkl') # Case 1: Nested dictionary. data = {'zz': 1, 'b': 234, 123: 'asdfa', 'dict': {'a': 123, 't': 123}} file_util.save_variable(file_path, data) actual_variable = file_util.load_variable(file_path) self.assertEqual(data, actual_variable) self.assertIsInstance(actual_variable, dict) # Case 2: 2-level nested dictionary. data = collections.defaultdict( lambda: collections.defaultdict(list)) data['first']['A'] = [1, 2, 3] data['first']['B'] = [1, 2, 3] data['second']['B'] = [1, 2, 3] data['second']['C'] = [1, 2, 3] data['third']['C'] = [1, 2, 3] data['third']['D'] = [1, 2, 3] data['path'] = 'asdfas/asdf/asdfasdf/' file_util.save_variable(file_path, data) actual_variable = file_util.load_variable(file_path) self.assertEqual(data, actual_variable) self.assertIsInstance(actual_variable, dict) # Case 3: Large array. If the size is too large, the test will timeout. data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] * 10000 file_util.save_variable(file_path, data) actual_variable = file_util.load_variable(file_path) self.assertListEqual(data, actual_variable) self.assertIsInstance(actual_variable, list) # Case 4: numpy array. data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] * 10 data = np.array(data) file_util.save_variable(file_path, data) actual_variable = file_util.load_variable(file_path) np.testing.assert_array_equal(data, actual_variable) self.assertIsInstance(actual_variable, np.ndarray) # Case 5: A list of tuples. x = [1, 2, 3] y = ['a', 'b', 'c'] data = zip(x, y) # Saving zip variable does not affect the iterative variable. file_util.save_variable(file_path, data) actual_variable = file_util.load_variable(file_path) # python2 treats `actual_variable` as a list, however, python3 treats it as # an iterative object. self.assertListEqual(list(actual_variable), list(data)) # Case 6: In python2, the itertools.tee cannot be saved by cPickle. However, # in python3, it can be saved. x = [1, 2, 3] y = ['a', 'b', 'c'] data = zip(x, y) data_tee, _ = itertools.tee(data) python_version = sys.version_info[0] try: file_util.save_variable(file_path, data_tee) pickle_save_correctly = True except cPickle.PicklingError: pickle_save_correctly = False self.assertTrue((pickle_save_correctly and python_version == 3) or (not pickle_save_correctly and python_version == 2)) if __name__ == '__main__': absltest.main()
google-research/google-research
simulation_research/traffic/file_util_test.py
Python
apache-2.0
5,630
/* * Copyright 2013-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.routing.v1.tcproutes; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.immutables.value.Value; /** * The payload for TCP Route responses */ @JsonDeserialize @Value.Immutable abstract class _TcpRouteConfiguration { /** * IP address of backend. */ @JsonProperty("backend_ip") abstract String getBackendIp(); /** * Backend port. */ @JsonProperty("backend_port") abstract Integer getBackendPort(); /** * External facing port for the TCP route. */ @JsonProperty("port") abstract Integer getPort(); /** * ID of the router group associated with this route. */ @JsonProperty("router_group_guid") abstract String getRouterGroupId(); /** * Time to live, in seconds. */ @JsonProperty("ttl") abstract Integer getTtl(); }
cloudfoundry/cf-java-client
cloudfoundry-client/src/main/java/org/cloudfoundry/routing/v1/tcproutes/_TcpRouteConfiguration.java
Java
apache-2.0
1,558
<html> <body><table> <tr> <td valign="top" height="150"> <font face="verdana" size="-1">This inspection reports any instances of <b><font color="#000080">public</font></b> instance variables. Constants (i.e. variables marked <b><font color="#000080">static</font></b> and <b><font color="#000080">final</font></b>) are not reported. </font></td> </tr> <tr> <td height="20"> <font face="verdana" size="-2">Powered by InspectionGadgets </font> </td> </tr> </table> </body> </html>
jexp/idea2
plugins/InspectionGadgets/src/inspectionDescriptions/PublicField.html
HTML
apache-2.0
478
d'ORModel ========= d'ORModel is an ORM for Delphi, based on models and object fields. for now, it uses the "database first" approach: all objects and metadata (delphi attributes) are generated from the database (MS SQL Server + CE, MySQL is pending). Everything is fully typed with no hard coded strings (no FieldByName('field1')!) so you can use the compiler to check your models and code! When you change the database, just regenerate the models and metadata and recompile: the compiler will gives errors when you use an old renamed field, so no nasty runtime errors :). The models and attributes can be used for all layers and tiers: - data layer, using CRUDs - bo layer, with direct using data CRUDs for loading and saving - presentation layer, using the model for a MVC implementation. Instead of datamodules with queries and hidden design time textual sql statements and fields, everything is done in code with objects. ## LINQ By using a query builder with fluent interfaces, you can create sql statements in your code which are typesafe and checked by the compiler. For example: ``` TESTCrud.NewQuery .Select ([TESTCrud.Data.ID]) .Where.FieldValue(TESTCrud.Data.Name).Equal('test'); if TESTCrud.QuerySelectSingle then MessageDlg('Record is found in database!'); ``` There are many more cool features, take a look at the unit tests for examples.
ultraware/d-ORModel
README.md
Markdown
apache-2.0
1,389
# Rinodina cornutula Zahlbr. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Rinodina cornutula Zahlbr. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Lecanoromycetes/Teloschistales/Physciaceae/Rinodina/Rinodina cornutula/README.md
Markdown
apache-2.0
181
# Phyllanthus lingulatus Beille SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Phyllanthaceae/Phyllanthus/Phyllanthus lingulatus/README.md
Markdown
apache-2.0
187
## 4.0.0 - 2019-11-20 * Upgrade internal tooling API to use Gradle 5.6.2 which adds Java 11 support * Gradle wrapper is now at Gradle 5.6.2 * Java bytecode compatibility bumped up to 1.8 to support later versions of Gradle Tooling API * Switch to using the org.jetbrains.intellij plugin for more modern plugin development * Removed old gradle-one-jar plugin in favor of shadow ## 3.0.0 - 2017-11-21 * Upgrade internal tooling API to use Gradle 3.5.1 * Add dependency resolution compatibility fixes to support Gradle 2.x, 3.x, and 4.x * Java bytecode compatibility bumped up to 1.7 to support later versions of Gradle Tooling API ## 2.1.0 - 2015-04-27 * Upgrade internal tooling API to use Gradle 2.3 #11 * Removed painful light red on blue background selection color #6 ## 2.0.2 - 2014-10-06 * Fixed some wonky Windows JAVA_HOME path behavior #5 ## 2.0.1 - 2014-09-22 * Fixed a Windows path bug with absolute file names [#5](https://github.com/rholder/gradle-view/issues/5) ## 2.0.0 - 2014-09-10 * Major rewrite of the Gradle Tooling API integration using 1.12 and custom model serialization * Added handling of multi-module project dependency graphs for all configurations * Added separate scrolling log window ## 1.0.1 - 2013-07-21 * Adjusted color for highlighting on the Darcula theme * Added toggle to switch between display of actual/replaced versions for [#3](https://github.com/rholder/gradle-view/issues/3) * Fixed handling of configurations with "No dependencies" for [#2](https://github.com/rholder/gradle-view/issues/2) * Code cleanup and preparation for the dependencyInsight task once it's available in the Gradle Tooling API ## 1.0.0 - 2012-01-03 * Initial stable release
rholder/gradle-view
HISTORY.md
Markdown
apache-2.0
1,693
package com.bazaarvoice.emodb.table.db.astyanax; import java.time.Instant; import java.time.ZonedDateTime; import java.util.Map; import static java.util.Objects.requireNonNull; /** * Wrapper around a Json Map with helper methods that facilitate type-safe access of map values. */ class JsonMap { private final Map<String, Object> _json; JsonMap(Map<String, Object> json) { _json = requireNonNull(json, "json"); } Map<String, Object> getRawJson() { return _json; } boolean containsKey(Attribute<?> key) { return key.containsKey(_json); } <T> T get(Attribute<T> key) { return key.get(_json); } static class Attribute<T> { protected final String _key; static <T> Attribute<T> create(String key) { return new Attribute<>(key); } Attribute(String key) { _key = requireNonNull(key, "key"); } String key() { return _key; } boolean containsKey(Map<String, ?> json) { return json.containsKey(_key); } T get(Map<String, ?> json) { // Skip runtime type checks here. Usually the caller will verify the type with a cast anyway. // The main purpose of this method is to ensure at compile time that an attribute isn't used // in an inconsistent way--eg. as a String in some places and as a Integer elsewhere. //noinspection unchecked return (T) json.get(_key); } } static class TimestampAttribute extends Attribute<Instant> { static Attribute<Instant> create(String key) { return new TimestampAttribute(key); } private TimestampAttribute(String key) { super(key); } @Override Instant get(Map<String, ?> json) { return parse((String) json.get(_key)); } static String format(Instant timestamp) { return timestamp != null ? timestamp.toString() : null; } static Instant parse(String string) { return string != null ? ZonedDateTime.parse(string).toInstant() : null; } } }
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/JsonMap.java
Java
apache-2.0
2,202
from django.utils import unittest from restclients.test.uwnetid.subscription import EmailForwardingTest from restclients.test.util.date_formator import formatorTest from restclients.test.hfs.idcard import HfsTest from restclients.test.library.mylibinfo import MyLibInfoTest from restclients.test.digitlib.curric import DigitLibTest from restclients.test.sws.compatible import SWSTest from restclients.test.sws.financial import SWSFinance from restclients.test.sws.notice import SWSNotice from restclients.test.sws.term import SWSTestTerm from restclients.test.sws.err404.dao import SWSTestDAO404 from restclients.test.sws.err500.dao import SWSTestDAO500 from restclients.test.sws.invalid_dao import SWSTestInvalidDAO from restclients.test.sws.file_implementation.dao import SWSTestFileDAO from restclients.test.sws.schedule_data import SWSTestScheduleData from restclients.test.sws.enrollment import SWSTestEnrollments from restclients.test.sws.section import SWSTestSectionData from restclients.test.sws.section_status import SWSTestSectionStatusData from restclients.test.sws.independent_study import SWSIndependentStudy from restclients.test.sws.instructor_no_regid import SWSMissingRegid from restclients.test.sws.registrations import SWSTestRegistrations from restclients.test.sws.campus import SWSTestCampus from restclients.test.sws.college import SWSTestCollege from restclients.test.sws.department import SWSTestDepartment from restclients.test.sws.curriculum import SWSTestCurriculum from restclients.test.sws.graderoster import SWSTestGradeRoster from restclients.test.sws.dates import SWSTestDates from restclients.test.pws.person import PWSTestPersonData from restclients.test.pws.entity import PWSTestEntityData from restclients.test.pws.idcard import TestIdCardPhoto from restclients.test.pws.err404.dao import PWSTestDAO404 from restclients.test.pws.err404.pws import PWSTest404 from restclients.test.pws.err500.dao import PWSTestDAO500 from restclients.test.pws.err500.pws import PWSTest500 from restclients.test.pws.invalid_dao import PWSTestInvalidDAO from restclients.test.pws.file_implementation.dao import PWSTestFileDAO from restclients.test.gws.group import GWSGroupBasics from restclients.test.gws.course_group import GWSCourseGroupBasics from restclients.test.gws.search import GWSGroupSearch from restclients.test.cache.none import NoCacheTest from restclients.test.cache.time import TimeCacheTest from restclients.test.cache.etag import ETagCacheTest from restclients.test.book.by_schedule import BookstoreScheduleTest from restclients.test.amazon_sqs.queues import SQSQueue from restclients.test.sms.send import SMS from restclients.test.sms.invalid_phone_number import SMSInvalidNumbers from restclients.test.nws.subscription import NWSTestSubscription from restclients.test.nws.channel import NWSTestChannel from restclients.test.nws.endpoint import NWSTestEndpoint from restclients.test.nws.message import NWSTestMessage from restclients.test.nws.person import NWSTestPerson from restclients.test.canvas.enrollments import CanvasTestEnrollment from restclients.test.canvas.accounts import CanvasTestAccounts from restclients.test.canvas.admins import CanvasTestAdmins from restclients.test.canvas.roles import CanvasTestRoles from restclients.test.canvas.courses import CanvasTestCourses from restclients.test.canvas.sections import CanvasTestSections from restclients.test.canvas.bad_sis_ids import CanvasBadSISIDs from restclients.test.canvas.terms import CanvasTestTerms from restclients.test.canvas.users import CanvasTestUsers from restclients.test.canvas.submissions import CanvasTestSubmissions from restclients.test.canvas.assignments import CanvasTestAssignments from restclients.test.canvas.quizzes import CanvasTestQuizzes from restclients.test.catalyst.gradebook import CatalystTestGradebook from restclients.test.trumba.accounts import TrumbaTestAccounts from restclients.test.trumba.calendar import TestCalendarParse from restclients.test.trumba.calendars import TrumbaTestCalendars from restclients.test.gws.trumba_group import TestGwsTrumbaGroup from restclients.test.r25.events import R25TestEvents from restclients.test.r25.spaces import R25TestSpaces from restclients.test.myplan import MyPlanTestData from restclients.test.thread import ThreadsTest from restclients.test.view import ViewTest from restclients.test.dao_implementation.mock import TestMock from restclients.test.irws import IRWSTest from restclients.test.iasystem.evaluation import IASystemTest
jeffFranklin/uw-restclients
restclients/tests.py
Python
apache-2.0
4,530
@extends('layouts.app') @section('content') <div class="row"> <div class="col-md-12"> <div class="panel"> <div class="panel-heading"> <div class="panel-title"><h4>GAME FLAVOR REPORTS</h4></div> </div><!--.panel-heading--> <div class="panel-body"> <div class="overflow-table"> <table class="col-md-12 table-bordered table-striped table-condensed"> <thead> <tr> <th>Game name</th> <th>Creator</th> <th>Creator email</th> <th>Reporter</th> <th>Reporter email</th> <th>Report comment</th> <th>Report date</th> </tr> </thead> <tbody> @foreach($gameFlavorReports as $gameFlavorReport) <td>{{$gameFlavorReport->gameFlavor->name}}</td> <td>{{$gameFlavorReport->gameFlavor->creator->name}}</td> <td>{{$gameFlavorReport->gameFlavor->creator->email}}</td> @if($gameFlavorReport->user_id != null) <td>{{$gameFlavorReport->user->name}}</td> <td>{{$gameFlavorReport->user->email}}</td> @else <td>{{$gameFlavorReport->user_name}}</td> <td>{{$gameFlavorReport->user_email}}</td> @endif <td>{{$gameFlavorReport->user_comment}}</td> <td>{{$gameFlavorReport->created_at}}</td> @endforeach </tbody> </table> </div> </div> </div> </div> </div> @endsection
scify/memori-online-games-repository
resources/views/game_flavor_report/list_all.blade.php
PHP
apache-2.0
2,204
package mock import ( "github.com/fkmhrk/OpenInvoice/v1/model/env" ) type EnvDAO struct { CreateResult env.Env GetResult env.Env GetListResult []*env.Env SaveResult error UpdateResult env.Env DeleteResult env.Env } func (d *EnvDAO) Create(key, value string) (env.Env, error) { return d.CreateResult, nil } func (d *EnvDAO) Get(key string) (env.Env, error) { return d.GetResult, nil } func (d *EnvDAO) GetList() ([]*env.Env, error) { return d.GetListResult, nil } func (d *EnvDAO) Save(list []*env.Env) error { return d.SaveResult } func (d *EnvDAO) Update(key, value string) (env.Env, error) { return d.UpdateResult, nil } func (d *EnvDAO) Delete(key string) (env.Env, error) { return d.DeleteResult, nil }
fkmhrk/OpenInvoice
go/v1/model/mock/env.go
GO
apache-2.0
738
package org.glamey.training.designmodel.strategy; /** * @author zhouyang.zhou. 2017.05.09.15. */ public interface Strategy { void algorithm(StrategyContext context); }
glameyzhou/training
distribute/src/main/java/org/glamey/training/designmodel/strategy/Strategy.java
Java
apache-2.0
175
package hangman; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.awt.event.*; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class UH implements ActionListener { JPanel p = new JPanel(),b=new JPanel(),g=new JPanel(); JFrame jf,jf2; JLabel j1 = new JLabel(), j2=new JLabel(), j3 = new JLabel(); JButton jb1 = new JButton(), jb2= new JButton(), jb3= new JButton(),jb4= new JButton(), jb5=new JButton(); Hangman hangtemp = new Hangman(); JTextField input = new JTextField(), input2 = new JTextField(); boolean wordFamily=true; Hangman hangman = new Hangman(); int length; public static void main(String[]args){ new UH().menu(); } public void menu() { j1 = new JLabel(" "); j2 = new JLabel(" "); jf = new JFrame("Evil Hangman"); jb1 = new JButton("Start"); jb2 = new JButton("Help"); jb3 = new JButton("Developers"); jb4 = new JButton("Exit"); jb5 = new JButton("Total Number of Word Family: On "); // p1 = new JPanel(); // p2 = new JPanel(); // p3 = new JPanel(); p = new JPanel() { private static final long serialVersionUID = 1L; @Override protected void paintComponent(Graphics g) { try { BufferedImage img = ImageIO.read(new File(this.getClass().getResource("menu.jpg").getPath())); g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null); } catch (IOException e) { e.printStackTrace(); } } }; p.setLayout(null); //p.add(p1); //p.add(p2); //p.add(p3); j1.setBounds(300,400,100,20); p.add(j1); jb1.setBounds(180, 370, 100, 20); p.add(jb1); jb2.setBounds(180, 400, 100, 20); p.add(jb2); jb3.setBounds(180,430,100,20); p.add(jb3); jb4.setBounds(180,460,100,20); p.add(jb4); jb5.setBounds(180,490,300,20); p.add(jb5); jf.add(p); jb1.addActionListener(this); jb2.addActionListener(this); jb3.addActionListener(this); jb4.addActionListener(this); jb5.addActionListener(this); jf.setBounds(20,20,820,620); jf.setResizable(false); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void startGame() { hangman.readD("D:\\DISK 2\\Codes\\Hangman\\src\\Hangman\\dictionary.txt"); p.setVisible(false); JPanel b = new JPanel() { private static final long serialVersionUID = 1L; @Override protected void paintComponent(Graphics g) { try { BufferedImage img = ImageIO.read(new File(this.getClass().getResource("14.jpg").getPath())); g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null); } catch (IOException e) { e.printStackTrace(); } } }; input = new JTextField(); input.setBounds(170,200,100,20); input.addActionListener(this); b.setLayout(null); j1.setBounds(170,170,1000,20); j1.setText("Input the length of the words you are choosing!"); b.add(j1); b.add(j2); b.add(input); b.add(jb4); input.setActionCommand("Length"); jf.add(b); jf.setBounds(20,20,820,620); jf.setResizable(false); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); System.out.println(input.getText()); } public void game(int count,String word, int length,Hangman hangman){ Hangman hangtemp = new Hangman(); b.setVisible(false); j2.setVisible(false); input.setVisible(false); hangman.askForLength(length); System.out.println(hangman.getWord()); final String t = String.valueOf(count); JPanel g = new JPanel() { private static final long serialVersionUID = 1L; @Override protected void paintComponent(Graphics g) { try { BufferedImage img = ImageIO.read(new File(this.getClass().getResource(t+".jpg").getPath())); g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null); } catch (IOException e) { e.printStackTrace(); } } }; if(wordFamily){ j3 = new JLabel(); j3.setBounds(170,300,1000,20); j3.setText(hangman.getWordF()+" words are in the Family! Quite deceiving eh!"); g.add(j3); } input2 = new JTextField(); input2.setBounds(170,250,100,20); input2.addActionListener(this); g.setLayout(null); j2 = new JLabel(); j1 = new JLabel(); j1.setBounds(130,220,1000,20); j2.setBounds(130,180,1000,20); j1.setText("GUESS A WORD, REMEMBER, ONLY ONE LETTER AT A TIME!"); j2.setText(word); g.add(input2); g.add(j1); g.add(j2); g.add(jb4); input2.setActionCommand("Game"); jf = new JFrame(); jf.add(g); jf.setBounds(20,20,820,620); jf.setResizable(false); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent event) { String eventName = event.getActionCommand(); if(eventName.equals("Start")){ startGame(); }else if(eventName.equals("Total Number of Word Family: On ")){ wordFamily=false; jb5.setText("Total Number of Word Family: Off "); jb5.setActionCommand("Total Number of Word Family: Off "); }else if(eventName.equals("Total Number of Word Family: Off ")){ wordFamily = true; jb5.setText("Total Number of Word Family: On "); jb5.setActionCommand("Total Number of Word Family: On "); }else if(eventName.equals("Developers")){ j1.setText("See you are pretending that you don't know these guys..."); j1.setBounds(150,400,1000,20); jb3.setText("Go Back"); jb3.setActionCommand("Go Back"); jb1.setVisible(false); jb2.setVisible(false); jb4.setVisible(false); jb5.setVisible(false); }else if(eventName.equals("Go Back")){ j1.setText(" "); jb3.setText("Developers"); jb3.setActionCommand("Developers"); jb1.setVisible(true); jb2.setVisible(true); jb4.setVisible(true); jb5.setVisible(true); } else if(eventName.equals("Quit")){ j1.setText(" "); jb2.setText("Help"); jb2.setActionCommand("Help"); jb1.setVisible(true); jb3.setVisible(true); jb4.setVisible(true); jb5.setVisible(true); jb2.setBounds(180, 400, 100, 20); }else if(eventName.equals("Help")){ j1.setText("Figure It out!"); j1.setBounds(250,400,1000,20); jb2.setText("Quit"); jb2.setActionCommand("Quit"); jb1.setVisible(false); jb3.setVisible(false); jb4.setVisible(false); jb5.setVisible(false); jb2.setBounds(100,500,100,20); }else if(eventName.equals("Exit")){ System.exit(0); }else if(eventName.equals("Length")){ try{ String in = input.getText(); int temp = Integer.parseInt(in); if(temp>=1&&temp<hangman.maxL()){ jf.setVisible(false); hangman = new Hangman(); hangman.readD("D:\\DISK 2\\Codes\\Hangman\\src\\Hangmandictionary.txt"); game(0,"_ _ _ _",temp,hangman); }else{ j2.setText("Your input is invalid, try a better looking length."); j2.setBounds(170,300+(int)Math.random()*50,1000,20); } } catch(NumberFormatException e){ j2.setText("Your input is invalid, try a better looking length."); startGame(); } }else if(eventName.equals("Game")){ boolean result=false; int count =0; while(count<14){ String temp =String.valueOf(input2.getText()).trim(); result = hangman.ifWon(temp); System.out.println(temp); if(!result) count++; String word =""; for(String str:hangman.output(temp)){ word+=str+=" "; }if(word.contains("_")) result=false; if(result){ break; } else{ // jf.setVisible(false); game(count,word,length,hangtemp); } } result(count); } } public void result(int count){ if(count==14){ j3 = new JLabel(new ImageIcon("clown.jpg")); j3.setBounds(200,200,100,300); j3.setAlignmentX(JLabel.CENTER_ALIGNMENT); g.add(j3); jf.add(g); }else{ j3.setText("Ok, you win, big deal..."); j3.setBounds(200,200,1000,20); g.add(j3); jf.add(g); } } }
STBTony/The-Evil-Hangman
UH.java
Java
apache-2.0
10,101
package se.mah.k3.grupp4; import java.text.DecimalFormat; import java.util.Calendar; //kör klockan public class ClockThread extends Thread{ private Gui2 gui2; private TestGUI testGUI; public ClockThread(Gui2 gui22) { // TODO Auto-generated constructor stub this.gui2 = gui22; } public ClockThread(TestGUI testGUI) { // TODO Auto-generated constructor stub this.testGUI=testGUI; } @Override public void run(){ DecimalFormat decimalFormat = new DecimalFormat("00"); while(true) { Calendar cal = Calendar.getInstance(); int second = cal.get(Calendar.SECOND); int minute = cal.get(Calendar.MINUTE); int hour = cal.get(Calendar.HOUR_OF_DAY); gui2.setTimeOnLabel("" + decimalFormat.format(hour) + ":" +decimalFormat.format(minute) + ":" + decimalFormat.format(second)); //testGUI.setTimeOnLabel("" + decimalFormat.format(hour) + ":" +decimalFormat.format(minute) + ":" + decimalFormat.format(second)); try { Thread.sleep(900); } catch (InterruptedException e) { e.printStackTrace(); return; } } } }
k3larra/KD405A_Lars_H
Grupparbete/src/se/mah/k3/grupp4/ClockThread.java
Java
apache-2.0
1,247
var config = require('./config.js'); console.log("config: ", config); var pack = require('./lib/package.js'); var send = require('./lib/send.js'); var inbox = require('./lib/inbox.js'); var express = require('express'); var path = require('path'); var logger = require('morgan'); var bodyParser = require('body-parser'); var http = require('http'); var FormData = require('form-data'); var fs = require('fs'); var multer = require('multer'); var autoReap = require('multer-autoreap'); autoReap.options = { reapOnError: true }; var async = require('async'); var app = express(); app.all('*', function(req, res, next) { console.log("all request"); res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With'); next(); }); app.use(multer({ dest: './uploads/' })) app.use(autoReap); app.use(logger('dev')); app.use('/docs', express.static('./swagger')); app.get('/interop', function (req, res) { res.send("Direct Node Server is up and running!!!"); }); //send new message app.post('/api/v1/send', function(req, res) { var filename = req.files.file.path; var data = fs.readFileSync(filename).toString(); var to = req.body.to; var from = req.body.from; //TODO: use patient's domain from config var subject = req.body.subject; var message = req.body.message; var memberId = "STAN01"; //console.log(data); console.log("/api/v1/send"); console.log("to: ", to); console.log("from: ", from); console.log("subject: ", subject); console.log("message: ", message); //package email var attachments = [{ 'filename': filename, 'contents': data }]; var email = { 'from': from, 'to': to, 'subject': subject, 'body': message }; console.log("email: ", email); pack(email, attachments, function(err, mime) { if (err) { res.statusCode = 500; res.send(err); } else { //send email send(config.abelian, mime, function(err) { if (err) { res.statusCode = 500; res.send(err); } else { console.log(mime.substring(0, 1000)); console.log("...skipping rest of mime envelope"); console.log("everything is ok"); res.send('OK'); } }); } }); }); //get list of messages app.get('/api/v1/inbox', function(req, res) { //takes query param memberId /doctor e.g. username/email address //var memberId = req.query.memberId || "STAN01"; inbox(config.abelian, false, function(err, response) { if (err) { res.statusCode = 500; res.send(err); } else { console.log(response); console.log("everything is ok"); res.send(response); } }) //res.status(200).end(); }); var server = app.listen(3001, function() { var host = server.address().address var port = server.address().port console.log('Listening at http://%s:%s', host, port) var mailListener = require('./lib/mail-listener'); function timerMail() { mailListener(function(err, results) { if (err) { console.error(err); } else { console.log("got mail #", results.length); //TODO: process each email into DRE for (var j = 0; j < results.length; j++) { console.log("processing email ", results[j]); //console.log(results[j].attachments[0].content.toString()); //DRE Ingest call here console.log("posting to ingest api: ", config['dre-ingest-api'] + '/api/v1/ingest'); var patKey = results[j].user; if (results[j].attachments) { var form = new FormData(); form.append('file', results[j].attachments[0].content, {filename: 'bluebutton.xml'}); form.append('patKey', patKey); form.submit(config['dre-ingest-api'] + '/api/v1/ingest', function(err, res) { //res.resume(); // for node-0.10.x }); } } } }); } //mail listener (every 30 seconds) console.log("listening for mail every 15 seconds"); setInterval(timerMail, 15000); })
amida-tech/abelian-connector
server.js
JavaScript
apache-2.0
4,686
<?php include_once 'include/session.start.inc.php'; ?> <!--metatagi, kodowanie, skrypt google analitics--> <?php include_once 'include/meta.inc.php'; ?> <title>Programowanie C++, Turbo Pascal, PHP, Systemy UNIX - FreeBSD</title> </head> <body onload="zegar();"> <div align="center"> <div id="kontener"> <div id="panel"> <div id="formularz"><?php include_once 'include/login.user.php'; ?> </div> <div id="zegar"> <script type="text/javascript" src="script.js"></script> </div> </div> <div id="gorna_czesc_kontenera"> </div> <!-- koniec div gorna czesc kontenera --> <!--środkowe menu--> <?php include_once 'include/middle.menu.inc.php'; ?> <!-- koniec div srodkowe menu--> <div id="zawartosc"> <div id="gorna_czesc_zawartosci"></div> <div id="srodkowa_czesc_zawartosci"> <div id="tekst"> <?php if (isset($_GET['page_guestbook'])) { $_GET['page_guestbook'] = filter_var($_GET['page_guestbook'], FILTER_SANITIZE_STRING); } $plik = "dane.txt"; $wskaznik = fopen($plik, "r"); $licznik = 0; if ($wskaznik) { while ($linia = (fgets($wskaznik))) { $licznik++; } $ilosc_stron = ceil($licznik/10); if (isset($_GET['page_guestbook'])) { if (($_GET['page_guestbook'] > $ilosc_stron) ) { echo "Site not exists!"; exit; } if ($_GET['page_guestbook']!=NULL) if (!is_numeric($_GET['page_guestbook'])) { echo "Site not exists!"; exit; } rewind($wskaznik); } } else echo "empty file!"; fclose($wskaznik); ?> <form action="guestbook1.php" method="post" name="form" > <input type="text" name="nick" value="nickname"/> <input type="text" name="validator" value="rok bitwy pod grunwaldem"> <textarea name="contents" cols="30" rows="5">Message</textarea> <input type="submit" value=" Send "/> </form><br><br> <?php echo "<table border='1' align='center' cellspacing='1'>"; $plik = "dane.txt"; $wskaznik = fopen($plik, "r+"); if ($wskaznik) { //$tresc = fread($wskaznik, filesize($plik)); if (isset($_GET['page_guestbook'])) filter_var($_GET['page_guestbook'], FILTER_SANITIZE_STRING); if (empty($_GET['page_guestbook'])) { $ile_petli = 0; $tablica = file($plik); for ($i=0; $i<=count($tablica); $i+=2) { if (empty($tablica)) break; if ($ile_petli >= 5) break; if ($ile_petli>=$tablica) break; if ($tablica[$i+1] == '') break; echo "<tr><td>".($i/2+1)." nick </td><td>".$tablica[$i+1]."</td></tr>"; echo "<tr><td>".($i/2+1)." tekst</td><td>".$tablica[$i+2]."</td></tr>"; $ile_petli++; } echo "</table>"; } if (isset($_GET['page_guestbook'])) { if ($_GET['page_guestbook']== '0' || $_GET['page_guestbook']== '1') { $ile_petli = 0; $tablica = file($plik); for ($i=0; $i<=count($tablica); $i+=2) { if (empty($tablica)) break; if ($ile_petli >= 5) break; if ($ile_petli>=$tablica) break; if ($tablica[$i+1] == '') break; echo "<tr><td>".($i/2+1)." nick </td><td>".$tablica[$i+1]."</td></tr>"; echo "<tr><td>".($i/2+1)." tekst</td><td>".$tablica[$i+2]."</td></tr>"; $ile_petli++; } echo "</table>"; } } //obliczanie ilości stron $licznik = 0; while ($linia = (fgets($wskaznik))) { $licznik++; } $ilosc_stron = ceil($licznik/10); if (isset($_GET['page_guestbook'])) { $odktorego = ((($_GET['page_guestbook'])*10)-10); $doktorego = $odktorego+9; } if (isset($_GET['page_guestbook'])) { if (($_GET['page_guestbook'])>=2) { $ile_petli = 0; $tablica = file($plik); for ($i = $odktorego; $i<=$doktorego; $i+=2) { if ($i>=$licznik) break; if ($ile_petli >=5 ) break; if ($tablica[$i+1] == '') break; echo "<tr><td>".($i/2+1)." nick </td><td>".$tablica[$i]."</td></tr>"; echo "<tr><td>".($i/2+1)." tekst</td><td>".$tablica[$i+1]."</td></tr>"; $ile_petli++; } echo "</table>"; } } } else echo "File not exists" ; echo "<br><br>"; //strzalki przód i tył $dwa = 2; if (isset($_GET['page_guestbook'])) { $strona_nastepna = $_GET['page_guestbook']+1; $strona_poprzednia = $_GET['page_guestbook']-1; if (($_GET['page_guestbook'])<=$ilosc_stron) { if ($_GET['page_guestbook'] >= 2) { echo "<a href='guestbook.php?page_guestbook=$strona_poprzednia'> < </a> "; } } for ($i=1; $i<=$ilosc_stron; $i++) echo "<a href='guestbook.php?page_guestbook=$i'> $i </a> "; if (($_GET['page_guestbook'])>=1 ) { if ($ilosc_stron > ($_GET['page_guestbook'])) { echo "<a href='guestbook.php?page_guestbook=$strona_nastepna'> > </a> "; } } } if (empty($_GET['page_guestbook'])) { for ($i=1; $i<=$ilosc_stron; $i++) echo "<a href='guestbook.php?page_guestbook=$i'> $i </a> "; if ($ilosc_stron > 1) echo "<a href='guestbook.php?page_guestbook=$dwa'> > </a> "; } //$trescpoprawiona = explode(" ", $tresc); //echo "<pre>".$trescpoprawiona[2]."</pre>"; //echo $linia; //$linia = fgets($wskaznik); //echo $linia; fclose($wskaznik); ?> </div> </div> <!--koniec div srodkowa czesc zawartosci--> <div id="dolna_czesc_zawartosci"></div> </div> <div id="stopka"> &copy; 2015 created by Matys </div> </div> <!-- koniec div kontener--> </div> </body> </html>
matysek83/Library
guestbook.php
PHP
apache-2.0
6,749
# Copyright 2014-2021 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Extension to scipy.linalg module developed for PBC branch. ''' import numpy as np import scipy.linalg def davidson_nosymm(matvec,size,nroots,Adiag=None): '''Davidson diagonalization method to solve A c = E c when A is not Hermitian. ''' # We don't pass args def matvec_args(vec, args): return matvec(vec) nroots = min(nroots,size) #if Adiag == None: # Adiag = matvec(numpy.ones(size)) # Currently not used: x = np.ones((size,1)) P = np.ones((size,1)) arnold = Arnoldi(matvec_args, x, P, nroots=nroots) return arnold.solve() VERBOSE = False class Arnoldi: def __init__(self,matr_multiply,xStart,inPreCon,nroots=1,tol=1e-6): self.matrMultiply = matr_multiply self.size = xStart.shape[0] self.nEigen = min(nroots, self.size) self.maxM = min(30, self.size) self.maxOuterLoop = 10 self.tol = tol # # Creating initial guess and preconditioner # self.x0 = xStart.real.copy() self.iteration = 0 self.totalIter = 0 self.converged = False self.preCon = inPreCon.copy() # # Allocating other vectors # self.allocateVecs() def solve(self): while self.converged == 0: if self.totalIter == 0: self.guessInitial() for i in range(self.maxM): if self.deflated == 1: self.currentSize = self.nEigen if self.deflated == 0 and self.totalIter > 0: self.hMult() self.push_Av() self.constructSubspace() self.solveSubspace() self.constructSol() self.computeResidual() self.checkConvergence() self.deflated = 0 if self.converged: break self.updateVecs() self.checkDeflate() self.constructDeflatedSub() self.totalIter += 1 self.currentSize += 1 print("") print("Converged in %3d cycles" % self.totalIter) self.constructAllSolV() return self.outeigs, self.outevecs def allocateVecs(self): self.subH = np.zeros( shape=(self.maxM,self.maxM), dtype=complex ) self.sol = np.zeros( shape=(self.maxM), dtype=complex ) self.dgks = np.zeros( shape=(self.maxM), dtype=complex ) self.nConv = np.zeros( shape=(self.maxM), dtype=int ) self.eigs = np.zeros( shape=(self.maxM), dtype=complex ) self.evecs = np.zeros( shape=(self.maxM,self.maxM), dtype=complex ) self.oldeigs = np.zeros( shape=(self.maxM), dtype=complex ) self.deigs = np.zeros( shape=(self.maxM), dtype=complex ) self.outeigs = np.zeros( shape=(self.nEigen), dtype=complex ) self.outevecs = np.zeros( shape=(self.size,self.nEigen), dtype=complex) self.currentSize = 0 self.Ax = np.zeros( shape=(self.size), dtype=complex ) self.res = np.zeros( shape=(self.size), dtype=complex ) self.vlist = np.zeros( shape=(self.maxM,self.size), dtype=complex ) self.cv = np.zeros( shape = (self.size), dtype = complex ) self.cAv = np.zeros( shape = (self.size), dtype = complex ) self.Avlist = np.zeros( shape=(self.maxM,self.size), dtype=complex ) self.dres = 999.9 self.resnorm = 999.9 self.cvEig = 0.1 self.ciEig = 0 self.deflated = 0 def guessInitial(self): nrm = np.linalg.norm(self.x0) self.x0 *= 1./nrm self.currentSize = self.nEigen for i in range(self.currentSize): self.vlist[i] *= 0.0 self.vlist[i,i] = 1.0 + 0.0*1j self.vlist[i] /= np.linalg.norm(self.vlist[i]) for i in range(self.currentSize): self.cv = self.vlist[i].copy() self.hMult() self.Avlist[i] = self.cAv.copy() self.constructSubspace() def hMult(self): args = 0 self.cAv = self.matrMultiply(self.cv.reshape(self.size),args) def push_Av(self): self.Avlist[self.currentSize-1] = self.cAv.reshape(self.size) def constructSubspace(self): if self.totalIter == 0 or self.deflated == 1: # construct the full block of v^*Av for i in range(self.currentSize): for j in range(self.currentSize): val = np.vdot(self.vlist[i],self.Avlist[j]) self.subH[i,j] = val else: for j in range(self.currentSize): if j <= (self.currentSize-1): val = np.vdot(self.vlist[j],self.Avlist[self.currentSize-1]) self.subH[j,self.currentSize-1] = val if j < (self.currentSize-1): val = np.vdot(self.vlist[self.currentSize-1],self.Avlist[j]) self.subH[self.currentSize-1,j] = val def solveSubspace(self): w, v = scipy.linalg.eig(self.subH[:self.currentSize,:self.currentSize]) idx = w.real.argsort() #imag_norm = np.linalg.norm(w.imag) #if imag_norm > 1e-12: # print " *************************************************** " # print " WARNING IMAGINARY EIGENVALUE OF NORM %.15g " % (imag_norm) # print " *************************************************** " #print "Imaginary norm eigenvectors = ", np.linalg.norm(v.imag) #print "Imaginary norm eigenvalue = ", np.linalg.norm(w.imag) v = v[:,idx] w = w[idx].real self.sol[:self.currentSize] = v[:,self.ciEig] self.evecs[:self.currentSize,:self.currentSize] = v self.eigs[:self.currentSize] = w[:self.currentSize] self.outeigs[:self.nEigen] = w[:self.nEigen] self.cvEig = self.eigs[self.ciEig] def constructAllSolV(self): for i in range(self.nEigen): self.sol[:] = self.evecs[:,i] self.cv = np.dot(self.vlist[:self.currentSize].transpose(),self.sol[:self.currentSize]) self.outevecs[:,i] = self.cv def constructSol(self): self.constructSolV() self.constructSolAv() def constructSolV(self): self.cv = np.dot(self.vlist[:self.currentSize].transpose(),self.sol[:self.currentSize]) def constructSolAv(self): self.cAv = np.dot(self.Avlist[:self.currentSize].transpose(),self.sol[:self.currentSize]) def computeResidual(self): self.res = self.cAv - self.cvEig * self.cv self.dres = np.vdot(self.res,self.res)**0.5 # # gram-schmidt for residual vector # for i in range(self.currentSize): self.dgks[i] = np.vdot( self.vlist[i], self.res ) self.res -= self.dgks[i]*self.vlist[i] # # second gram-schmidt to make them really orthogonal # for i in range(self.currentSize): self.dgks[i] = np.vdot( self.vlist[i], self.res ) self.res -= self.dgks[i]*self.vlist[i] self.resnorm = np.linalg.norm(self.res) self.res /= self.resnorm orthog = 0.0 for i in range(self.currentSize): orthog += np.vdot(self.res,self.vlist[i])**2.0 orthog = orthog ** 0.5 if not self.deflated: if VERBOSE: print("%3d %20.14f %20.14f %10.4g" % (self.ciEig, self.cvEig.real, self.resnorm.real, orthog.real)) #else: # print "%3d %20.14f %20.14f %20.14f (deflated)" % (self.ciEig, self.cvEig, # self.resnorm, orthog) self.iteration += 1 def updateVecs(self): self.vlist[self.currentSize] = self.res.copy() self.cv = self.vlist[self.currentSize] def checkConvergence(self): if self.resnorm < self.tol: if VERBOSE: print("Eigenvalue %3d converged! (res = %.15g)" % (self.ciEig, self.resnorm)) self.ciEig += 1 if self.ciEig == self.nEigen: self.converged = True if self.resnorm < self.tol and not self.converged: if VERBOSE: print("") print("") print("%-3s %-20s %-20s %-8s" % ("#", " Eigenvalue", " Res. Norm.", " Ortho. (should be ~0)")) def gramSchmidtCurrentVec(self,northo): for i in range(northo): self.dgks[i] = np.vdot( self.vlist[i], self.cv ) self.cv -= self.dgks[i]*self.vlist[i] #/ np.vdot(self.vlist[i],self.vlist[i]) self.cv /= np.linalg.norm(self.cv) def checkDeflate(self): if self.currentSize == self.maxM-1: self.deflated = 1 #print "deflating..." for i in range(self.nEigen): self.sol[:self.currentSize] = self.evecs[:self.currentSize,i] # Finds the "best" eigenvector for this eigenvalue self.constructSolV() # Puts this guess in self.Avlist rather than self.vlist for now... # since this would mess up self.constructSolV()'s solution self.Avlist[i] = self.cv.copy() for i in range(self.nEigen): # This is actually the "best" eigenvector v, not A*v (see above) self.cv = self.Avlist[i].copy() self.gramSchmidtCurrentVec(i) self.vlist[i] = self.cv.copy() for i in range(self.nEigen): # This is actually the "best" eigenvector v, not A*v (see above) self.cv = self.vlist[i].copy() # Use current vector cv to create cAv self.hMult() self.Avlist[i] = self.cAv.copy() def constructDeflatedSub(self): if self.deflated == 1: self.currentSize = self.nEigen self.constructSubspace()
sunqm/pyscf
pyscf/pbc/lib/arnoldi.py
Python
apache-2.0
10,549
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.multipart; import jakarta.servlet.http.HttpServletRequest; /** * A strategy interface for multipart file upload resolution in accordance * with <a href="https://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>. * Implementations are typically usable both within an application context * and standalone. * * <p>Spring provides the following concrete implementation: * <ul> * <li>{@link org.springframework.web.multipart.support.StandardServletMultipartResolver} * for the Servlet Part API * </ul> * * <p>There is no default resolver implementation used for Spring * {@link org.springframework.web.servlet.DispatcherServlet DispatcherServlets}, * as an application might choose to parse its multipart requests itself. To define * an implementation, create a bean with the id "multipartResolver" in a * {@link org.springframework.web.servlet.DispatcherServlet DispatcherServlet's} * application context. Such a resolver gets applied to all requests handled * by that {@link org.springframework.web.servlet.DispatcherServlet}. * * <p>If a {@link org.springframework.web.servlet.DispatcherServlet} detects a * multipart request, it will resolve it via the configured {@link MultipartResolver} * and pass on a wrapped {@link jakarta.servlet.http.HttpServletRequest}. Controllers * can then cast their given request to the {@link MultipartHttpServletRequest} * interface, which allows for access to any {@link MultipartFile MultipartFiles}. * Note that this cast is only supported in case of an actual multipart request. * * <pre class="code"> * public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) { * MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; * MultipartFile multipartFile = multipartRequest.getFile("image"); * ... * }</pre> * * Instead of direct access, command or form controllers can register a * {@link org.springframework.web.multipart.support.ByteArrayMultipartFileEditor} * or {@link org.springframework.web.multipart.support.StringMultipartFileEditor} * with their data binder, to automatically apply multipart content to form * bean properties. * * <p>As an alternative to using a {@link MultipartResolver} with a * {@link org.springframework.web.servlet.DispatcherServlet}, * a {@link org.springframework.web.multipart.support.MultipartFilter} can be * registered in {@code web.xml}. It will delegate to a corresponding * {@link MultipartResolver} bean in the root application context. This is mainly * intended for applications that do not use Spring's own web MVC framework. * * <p>Note: There is hardly ever a need to access the {@link MultipartResolver} * itself from application code. It will simply do its work behind the scenes, * making {@link MultipartHttpServletRequest MultipartHttpServletRequests} * available to controllers. * * @author Juergen Hoeller * @author Trevor D. Cook * @since 29.09.2003 * @see MultipartHttpServletRequest * @see MultipartFile * @see org.springframework.web.multipart.support.ByteArrayMultipartFileEditor * @see org.springframework.web.multipart.support.StringMultipartFileEditor * @see org.springframework.web.servlet.DispatcherServlet */ public interface MultipartResolver { /** * Determine if the given request contains multipart content. * <p>Will typically check for content type "multipart/form-data", but the actually * accepted requests might depend on the capabilities of the resolver implementation. * @param request the servlet request to be evaluated * @return whether the request contains multipart content */ boolean isMultipart(HttpServletRequest request); /** * Parse the given HTTP request into multipart files and parameters, * and wrap the request inside a * {@link org.springframework.web.multipart.MultipartHttpServletRequest} * object that provides access to file descriptors and makes contained * parameters accessible via the standard ServletRequest methods. * @param request the servlet request to wrap (must be of a multipart content type) * @return the wrapped servlet request * @throws MultipartException if the servlet request is not multipart, or if * implementation-specific problems are encountered (such as exceeding file size limits) * @see MultipartHttpServletRequest#getFile * @see MultipartHttpServletRequest#getFileNames * @see MultipartHttpServletRequest#getFileMap * @see jakarta.servlet.http.HttpServletRequest#getParameter * @see jakarta.servlet.http.HttpServletRequest#getParameterNames * @see jakarta.servlet.http.HttpServletRequest#getParameterMap */ MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException; /** * Cleanup any resources used for the multipart handling, * like a storage for the uploaded files. * @param request the request to cleanup resources for */ void cleanupMultipart(MultipartHttpServletRequest request); }
spring-projects/spring-framework
spring-web/src/main/java/org/springframework/web/multipart/MultipartResolver.java
Java
apache-2.0
5,625
define(function(require, exports, module){ // wrapped Hogan.js into an AMD module and also added pragmas to remove // compiler after build if it isn't needed. Source code wasn't touched // besides that. // START WRAPPED CODE // =========================================================================== /* * Copyright 2011 Twitter, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Hogan = {}; (function (Hogan, useArrayBuffer) { Hogan.Template = function (renderFunc, text, compiler, options) { this.r = renderFunc || this.r; this.c = compiler; this.options = options; this.text = text || ''; this.buf = (useArrayBuffer) ? [] : ''; } Hogan.Template.prototype = { // render: replaced by generated code. r: function (context, partials, indent) { return ''; }, // variable escaping v: hoganEscape, // triple stache t: coerceToString, render: function render(context, partials, indent) { return this.ri([context], partials || {}, indent); }, // render internal -- a hook for overrides that catches partials too ri: function (context, partials, indent) { return this.r(context, partials, indent); }, // tries to find a partial in the curent scope and render it rp: function(name, context, partials, indent) { var partial = partials[name]; if (!partial) { return ''; } if (this.c && typeof partial == 'string') { partial = this.c.compile(partial, this.options); } return partial.ri(context, partials, indent); }, // render a section rs: function(context, partials, section) { var tail = context[context.length - 1]; if (!isArray(tail)) { section(context, partials, this); return; } for (var i = 0; i < tail.length; i++) { context.push(tail[i]); section(context, partials, this); context.pop(); } }, // maybe start a section s: function(val, ctx, partials, inverted, start, end, tags) { var pass; if (isArray(val) && val.length === 0) { return false; } if (typeof val == 'function') { val = this.ls(val, ctx, partials, inverted, start, end, tags); } pass = (val === '') || !!val; if (!inverted && pass && ctx) { ctx.push((typeof val == 'object') ? val : ctx[ctx.length - 1]); } return pass; }, // find values with dotted names d: function(key, ctx, partials, returnFound) { var names = key.split('.'), val = this.f(names[0], ctx, partials, returnFound), cx = null; if (key === '.' && isArray(ctx[ctx.length - 2])) { return ctx[ctx.length - 1]; } for (var i = 1; i < names.length; i++) { if (val && typeof val == 'object' && names[i] in val) { cx = val; val = val[names[i]]; } else { val = ''; } } if (returnFound && !val) { return false; } if (!returnFound && typeof val == 'function') { ctx.push(cx); val = this.lv(val, ctx, partials); ctx.pop(); } return val; }, // find values with normal names f: function(key, ctx, partials, returnFound) { var val = false, v = null, found = false; for (var i = ctx.length - 1; i >= 0; i--) { v = ctx[i]; if (v && typeof v == 'object' && key in v) { val = v[key]; found = true; break; } } if (!found) { return (returnFound) ? false : ""; } if (!returnFound && typeof val == 'function') { val = this.lv(val, ctx, partials); } return val; }, // higher order templates ho: function(val, cx, partials, text, tags) { var compiler = this.c; var options = this.options; options.delimiters = tags; var text = val.call(cx, text); text = (text == null) ? String(text) : text.toString(); this.b(compiler.compile(text, options).render(cx, partials)); return false; }, // template result buffering b: (useArrayBuffer) ? function(s) { this.buf.push(s); } : function(s) { this.buf += s; }, fl: (useArrayBuffer) ? function() { var r = this.buf.join(''); this.buf = []; return r; } : function() { var r = this.buf; this.buf = ''; return r; }, // lambda replace section ls: function(val, ctx, partials, inverted, start, end, tags) { var cx = ctx[ctx.length - 1], t = null; if (!inverted && this.c && val.length > 0) { return this.ho(val, cx, partials, this.text.substring(start, end), tags); } t = val.call(cx); if (typeof t == 'function') { if (inverted) { return true; } else if (this.c) { return this.ho(t, cx, partials, this.text.substring(start, end), tags); } } return t; }, // lambda replace variable lv: function(val, ctx, partials) { var cx = ctx[ctx.length - 1]; var result = val.call(cx); if (typeof result == 'function') { result = coerceToString(result.call(cx)); if (this.c && ~result.indexOf("{\u007B")) { return this.c.compile(result, this.options).render(cx, partials); } } return coerceToString(result); } }; var rAmp = /&/g, rLt = /</g, rGt = />/g, rApos =/\'/g, rQuot = /\"/g, hChars =/[&<>\"\']/; function coerceToString(val) { return String((val === null || val === undefined) ? '' : val); } function hoganEscape(str) { str = coerceToString(str); return hChars.test(str) ? str .replace(rAmp,'&amp;') .replace(rLt,'&lt;') .replace(rGt,'&gt;') .replace(rApos,'&#39;') .replace(rQuot, '&quot;') : str; } var isArray = Array.isArray || function(a) { return Object.prototype.toString.call(a) === '[object Array]'; }; })(typeof exports !== 'undefined' ? exports : Hogan); //>>excludeStart('excludeHogan', pragmas.excludeHogan) (function (Hogan) { // Setup regex assignments // remove whitespace according to Mustache spec var rIsWhitespace = /\S/, rQuot = /\"/g, rNewline = /\n/g, rCr = /\r/g, rSlash = /\\/g, tagTypes = { '#': 1, '^': 2, '/': 3, '!': 4, '>': 5, '<': 6, '=': 7, '_v': 8, '{': 9, '&': 10 }; Hogan.scan = function scan(text, delimiters) { var len = text.length, IN_TEXT = 0, IN_TAG_TYPE = 1, IN_TAG = 2, state = IN_TEXT, tagType = null, tag = null, buf = '', tokens = [], seenTag = false, i = 0, lineStart = 0, otag = '{{', ctag = '}}'; function addBuf() { if (buf.length > 0) { tokens.push(new String(buf)); buf = ''; } } function lineIsWhitespace() { var isAllWhitespace = true; for (var j = lineStart; j < tokens.length; j++) { isAllWhitespace = (tokens[j].tag && tagTypes[tokens[j].tag] < tagTypes['_v']) || (!tokens[j].tag && tokens[j].match(rIsWhitespace) === null); if (!isAllWhitespace) { return false; } } return isAllWhitespace; } function filterLine(haveSeenTag, noNewLine) { addBuf(); if (haveSeenTag && lineIsWhitespace()) { for (var j = lineStart, next; j < tokens.length; j++) { if (!tokens[j].tag) { if ((next = tokens[j+1]) && next.tag == '>') { // set indent to token value next.indent = tokens[j].toString() } tokens.splice(j, 1); } } } else if (!noNewLine) { tokens.push({tag:'\n'}); } seenTag = false; lineStart = tokens.length; } function changeDelimiters(text, index) { var close = '=' + ctag, closeIndex = text.indexOf(close, index), delimiters = trim( text.substring(text.indexOf('=', index) + 1, closeIndex) ).split(' '); otag = delimiters[0]; ctag = delimiters[1]; return closeIndex + close.length - 1; } if (delimiters) { delimiters = delimiters.split(' '); otag = delimiters[0]; ctag = delimiters[1]; } for (i = 0; i < len; i++) { if (state == IN_TEXT) { if (tagChange(otag, text, i)) { --i; addBuf(); state = IN_TAG_TYPE; } else { if (text.charAt(i) == '\n') { filterLine(seenTag); } else { buf += text.charAt(i); } } } else if (state == IN_TAG_TYPE) { i += otag.length - 1; tag = tagTypes[text.charAt(i + 1)]; tagType = tag ? text.charAt(i + 1) : '_v'; if (tagType == '=') { i = changeDelimiters(text, i); state = IN_TEXT; } else { if (tag) { i++; } state = IN_TAG; } seenTag = i; } else { if (tagChange(ctag, text, i)) { tokens.push({tag: tagType, n: trim(buf), otag: otag, ctag: ctag, i: (tagType == '/') ? seenTag - ctag.length : i + otag.length}); buf = ''; i += ctag.length - 1; state = IN_TEXT; if (tagType == '{') { if (ctag == '}}') { i++; } else { cleanTripleStache(tokens[tokens.length - 1]); } } } else { buf += text.charAt(i); } } } filterLine(seenTag, true); return tokens; } function cleanTripleStache(token) { if (token.n.substr(token.n.length - 1) === '}') { token.n = token.n.substring(0, token.n.length - 1); } } function trim(s) { if (s.trim) { return s.trim(); } return s.replace(/^\s*|\s*$/g, ''); } function tagChange(tag, text, index) { if (text.charAt(index) != tag.charAt(0)) { return false; } for (var i = 1, l = tag.length; i < l; i++) { if (text.charAt(index + i) != tag.charAt(i)) { return false; } } return true; } function buildTree(tokens, kind, stack, customTags) { var instructions = [], opener = null, token = null; while (tokens.length > 0) { token = tokens.shift(); if (token.tag == '#' || token.tag == '^' || isOpener(token, customTags)) { stack.push(token); token.nodes = buildTree(tokens, token.tag, stack, customTags); instructions.push(token); } else if (token.tag == '/') { if (stack.length === 0) { throw new Error('Closing tag without opener: /' + token.n); } opener = stack.pop(); if (token.n != opener.n && !isCloser(token.n, opener.n, customTags)) { throw new Error('Nesting error: ' + opener.n + ' vs. ' + token.n); } opener.end = token.i; return instructions; } else { instructions.push(token); } } if (stack.length > 0) { throw new Error('missing closing tag: ' + stack.pop().n); } return instructions; } function isOpener(token, tags) { for (var i = 0, l = tags.length; i < l; i++) { if (tags[i].o == token.n) { token.tag = '#'; return true; } } } function isCloser(close, open, tags) { for (var i = 0, l = tags.length; i < l; i++) { if (tags[i].c == close && tags[i].o == open) { return true; } } } Hogan.generate = function (tree, text, options) { var code = 'var _=this;_.b(i=i||"");' + walk(tree) + 'return _.fl();'; if (options.asString) { return 'function(c,p,i){' + code + ';}'; } return new Hogan.Template(new Function('c', 'p', 'i', code), text, Hogan, options); } function esc(s) { return s.replace(rSlash, '\\\\') .replace(rQuot, '\\\"') .replace(rNewline, '\\n') .replace(rCr, '\\r'); } function chooseMethod(s) { return (~s.indexOf('.')) ? 'd' : 'f'; } function walk(tree) { var code = ''; for (var i = 0, l = tree.length; i < l; i++) { var tag = tree[i].tag; if (tag == '#') { code += section(tree[i].nodes, tree[i].n, chooseMethod(tree[i].n), tree[i].i, tree[i].end, tree[i].otag + " " + tree[i].ctag); } else if (tag == '^') { code += invertedSection(tree[i].nodes, tree[i].n, chooseMethod(tree[i].n)); } else if (tag == '<' || tag == '>') { code += partial(tree[i]); } else if (tag == '{' || tag == '&') { code += tripleStache(tree[i].n, chooseMethod(tree[i].n)); } else if (tag == '\n') { code += text('"\\n"' + (tree.length-1 == i ? '' : ' + i')); } else if (tag == '_v') { code += variable(tree[i].n, chooseMethod(tree[i].n)); } else if (tag === undefined) { code += text('"' + esc(tree[i]) + '"'); } } return code; } function section(nodes, id, method, start, end, tags) { return 'if(_.s(_.' + method + '("' + esc(id) + '",c,p,1),' + 'c,p,0,' + start + ',' + end + ',"' + tags + '")){' + '_.rs(c,p,' + 'function(c,p,_){' + walk(nodes) + '});c.pop();}'; } function invertedSection(nodes, id, method) { return 'if(!_.s(_.' + method + '("' + esc(id) + '",c,p,1),c,p,1,0,0,"")){' + walk(nodes) + '};'; } function partial(tok) { return '_.b(_.rp("' + esc(tok.n) + '",c,p,"' + (tok.indent || '') + '"));'; } function tripleStache(id, method) { return '_.b(_.t(_.' + method + '("' + esc(id) + '",c,p,0)));'; } function variable(id, method) { return '_.b(_.v(_.' + method + '("' + esc(id) + '",c,p,0)));'; } function text(id) { return '_.b(' + id + ');'; } Hogan.parse = function(tokens, text, options) { options = options || {}; return buildTree(tokens, '', [], options.sectionTags || []); }, Hogan.cache = {}; Hogan.compile = function(text, options) { // options // // asString: false (default) // // sectionTags: [{o: '_foo', c: 'foo'}] // An array of object with o and c fields that indicate names for custom // section tags. The example above allows parsing of {{_foo}}{{/foo}}. // // delimiters: A string that overrides the default delimiters. // Example: "<% %>" // options = options || {}; var key = text + '||' + !!options.asString; var t = this.cache[key]; if (t) { return t; } t = this.generate(this.parse(this.scan(text, options.delimiters), text, options), text, options); return this.cache[key] = t; }; })(typeof exports !== 'undefined' ? exports : Hogan); //>>excludeEnd('excludeHogan') // END WRAPPED CODE // =========================================================================== });
bfreis/awsexplorer
src/main/webapp/libs/require-plugins/require-hogan/hogan-2.0.0.js
JavaScript
apache-2.0
15,687
package me.doshou.common.entity.search.exception; /** * @author YorkChow<york.chow@actionsky.com> * @since 2014/12/28 * Time: 15:20 */ public final class InvalidSearchValueException extends SearchException { public InvalidSearchValueException(String searchProperty, String entityProperty, Object value) { this(searchProperty, entityProperty, value, null); } public InvalidSearchValueException(String searchProperty, String entityProperty, Object value, Throwable cause) { super("Invalid Search Value, searchProperty [" + searchProperty + "], " + "entityProperty [" + entityProperty + "], value [" + value + "]", cause); } }
yorkchow/doshou-web
src/main/java/me/doshou/common/entity/search/exception/InvalidSearchValueException.java
Java
apache-2.0
678
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <title>Uses of Class org.apache.poi.xslf.usermodel.XSLFImageRenderer (POI API Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.poi.xslf.usermodel.XSLFImageRenderer (POI API Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/poi/xslf/usermodel/XSLFImageRenderer.html" title="class in org.apache.poi.xslf.usermodel">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/poi/xslf/usermodel//class-useXSLFImageRenderer.html" target="_top">FRAMES</a></li> <li><a href="XSLFImageRenderer.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.poi.xslf.usermodel.XSLFImageRenderer" class="title">Uses of Class<br>org.apache.poi.xslf.usermodel.XSLFImageRenderer</h2> </div> <div class="classUseContainer">No usage of org.apache.poi.xslf.usermodel.XSLFImageRenderer</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/poi/xslf/usermodel/XSLFImageRenderer.html" title="class in org.apache.poi.xslf.usermodel">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/poi/xslf/usermodel//class-useXSLFImageRenderer.html" target="_top">FRAMES</a></li> <li><a href="XSLFImageRenderer.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright 2016 The Apache Software Foundation or its licensors, as applicable.</i> </small></p> </body> </html>
Aarhus-BSS/Aarhus-Research-Rebuilt
lib/poi-3.16-beta1/docs/apidocs/org/apache/poi/xslf/usermodel/class-use/XSLFImageRenderer.html
HTML
apache-2.0
4,378
/*************************************************************************** * Copyright 1998-2015 by authors (see AUTHORS.txt) * * * * This file is part of LuxRender. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* * See the License for the specific language governing permissions and * * limitations under the License. * ***************************************************************************/ #include "slg/textures/fresnel/fresnelcolor.h" using namespace std; using namespace luxrays; using namespace slg; //------------------------------------------------------------------------------ // Fresnel color texture //------------------------------------------------------------------------------ float FresnelColorTexture::GetFloatValue(const HitPoint &hitPoint) const { return kr->GetFloatValue(hitPoint); } Spectrum FresnelColorTexture::GetSpectrumValue(const HitPoint &hitPoint) const { return kr->GetSpectrumValue(hitPoint); } float FresnelColorTexture::Y() const { return kr->Y(); } float FresnelColorTexture::Filter() const { return kr->Filter(); } Spectrum FresnelColorTexture::Evaluate(const HitPoint &hitPoint, const float cosi) const { const Spectrum c = kr->GetSpectrumValue(hitPoint); const Spectrum n = ApproxN(c); const Spectrum k = ApproxK(c); return GeneralEvaluate(n, k, cosi); } Properties FresnelColorTexture::ToProperties(const ImageMapCache &imgMapCache) const { Properties props; const string name = GetName(); props.Set(Property("scene.textures." + name + ".type")("fresnelcolor")); props.Set(Property("scene.textures." + name + ".kr")(kr->GetName())); return props; }
DavidBluecame/LuxRays
src/slg/textures/fresnel/fresnelcolor.cpp
C++
apache-2.0
2,533
using UnityEngine; using System.Collections; namespace DragonBones { [System.Serializable] public class UnityDragonBonesData:ScriptableObject { [System.Serializable] public class TextureAtlas{ public TextAsset textureAtlasJSON; public Texture2D texture; public Material material; public Material uiMaterial; } public string dataName; public TextAsset dragonBonesJSON; public TextureAtlas[] textureAtlas; /** * @language zh_CN * 从UnityFactory中移除。 * @param disposeData */ public void RemoveFromFactory(bool disposeData=true) { UnityFactory.factory.RemoveDragonBonesData(dataName,disposeData); if(textureAtlas!=null){ foreach(TextureAtlas ta in textureAtlas){ if(ta!=null && ta.texture!=null){ UnityFactory.factory.RemoveTextureAtlasData(dataName+ta.texture.name,disposeData); } } } } } }
MadGriffonGames/BiltyBlop-Farts
Assets/Scripts/DragonBones/unity/UnityDragonBonesData.cs
C#
apache-2.0
908
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; /** * Represents a directive from the {@link org.apache.hadoop.mapred.JobTracker} * to the {@link org.apache.hadoop.mapred.TaskTracker} to launch a new task. * */ class LaunchTaskAction extends TaskTrackerAction implements Serializable { private transient Task task; public LaunchTaskAction() { super(ActionType.LAUNCH_TASK); } public LaunchTaskAction(Task task) { super(ActionType.LAUNCH_TASK); this.task = task; } public Task getTask() { return task; } public void write(DataOutput out) throws IOException { out.writeBoolean(task.isMapTask()); task.write(out); } public void readFields(DataInput in) throws IOException { boolean isMapTask = in.readBoolean(); if (isMapTask) { task = new MapTask(); } else { task = new ReduceTask(); } task.readFields(in); } }
vierja/hadoop-per-mare
src/mapred/org/apache/hadoop/mapred/LaunchTaskAction.java
Java
apache-2.0
1,813
<?php Class MenuAction extends CommonAction { public function _initialize() { parent::_initialize(); $this->dbname = MODULE_NAME; } public function index() { $list = cateTree($pid = 0, $level = 0, $this->dbname); $this->assign('list', $list); $this->display(); } public function _befor_handle(&$data) { $pid = $data['pid']; if ($pid == 0) { $data['level'] = 0; } else { //查询父的level $level = D($this->dbname)->where('id=' . $pid . '')->field('level')->limit(1)->select(); $level = $level[0]['level'] + 1; $data['level'] = $level; } return; } }
izhangh/yunwublog
webs/Lib/Action/Admin/MenuAction.class.php
PHP
apache-2.0
761
using System.Runtime.Serialization; using Umizoo.Messaging; namespace UserRegistration.ReadModel { [DataContract] public class UserAuthentication : IQuery { [DataMember] public string LoginId { get; set; } [DataMember] public string Password { get; set; } [DataMember] public string IpAddress { get; set; } } }
imyounghan/umizoo
src/Samples/UserRegistration/ReadModel/UserAuthentication.cs
C#
apache-2.0
380
/* * Copyright 2013, Arondor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ /** * @author francois * */ package com.arondor.common.reflection.api.parser;
Doloops/arondor-common-reflection
arondor-common-reflection-api/src/main/java/com/arondor/common/reflection/api/parser/package-info.java
Java
apache-2.0
692
package com.github.bingoohuang.springrediscache; import org.aopalliance.aop.Advice; import org.springframework.aop.Pointcut; import org.springframework.aop.support.AbstractPointcutAdvisor; import org.springframework.aop.support.StaticMethodMatcherPointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.lang.reflect.Method; @Component public class RedisCacheEnabledAdvisor extends AbstractPointcutAdvisor { final StaticMethodMatcherPointcut pointcut = new StaticMethodMatcherPointcut() { @Override public boolean matches(Method method, Class<?> targetClass) { return method.isAnnotationPresent(RedisCacheEnabled.class); } }; @Autowired RedisCacheEnabledInterceptor interceptor; @Override public Pointcut getPointcut() { return this.pointcut; } @Override public Advice getAdvice() { return this.interceptor; } }
bingoohuang/spring-redis-cache
src/main/java/com/github/bingoohuang/springrediscache/RedisCacheEnabledAdvisor.java
Java
apache-2.0
988
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace GiveMeTheRESTClient { /// <summary> /// Interaktionslogik für "App.xaml" /// </summary> public partial class App : Application { } }
HopfTorsten/GiveMeTheREST
GiveMeTheRESTClient/GiveMeTheRESTClient/App.xaml.cs
C#
apache-2.0
338
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id: LayoutEngineChecksFactory.java 1094690 2011-04-18 18:36:05Z vhennebert $ */ package org.apache.fop.layoutengine; import org.w3c.dom.Element; import org.apache.fop.check.ChecksFactory; /** * A factory class for creating {@link LayoutEngineCheck} instances. */ final class LayoutEngineChecksFactory extends ChecksFactory<LayoutEngineCheck> { LayoutEngineChecksFactory() { registerCheckFactory("true", new CheckFactory<LayoutEngineCheck>() { public LayoutEngineCheck createCheck(Element element) { return new TrueCheck(element); } }); registerCheckFactory("eval", new CheckFactory<LayoutEngineCheck>() { public LayoutEngineCheck createCheck(Element element) { return new EvalCheck(element); } }); registerCheckFactory("element-list", new CheckFactory<LayoutEngineCheck>() { public LayoutEngineCheck createCheck(Element element) { return new ElementListCheck(element); } }); registerCheckFactory("result", new CheckFactory<LayoutEngineCheck>() { public LayoutEngineCheck createCheck(Element element) { return new ResultCheck(element); } }); } }
pellcorp/fop
test/java/org/apache/fop/layoutengine/LayoutEngineChecksFactory.java
Java
apache-2.0
2,101
// // IntroScene.h // HelloCocos2d // // Created by Patrick Lo on 12/16/14. // Copyright Patrick Lo 2014. All rights reserved. // // ----------------------------------------------------------------------- // Importing cocos2d.h and cocos2d-ui.h, will import anything you need to start using cocos2d-v3 #import "cocos2d.h" #import "cocos2d-ui.h" // ----------------------------------------------------------------------- /** * The intro scene * Note, that scenes should now be based on CCScene, and not CCLayer, as previous versions * Main usage for CCLayer now, is to make colored backgrounds (rectangles) * */ @interface IntroScene : CCScene // ----------------------------------------------------------------------- + (IntroScene *)scene; - (id)init; // ----------------------------------------------------------------------- @end
patricklo/iOSPractice
HelloCocos2d/HelloCocos2d/Classes/IntroScene.h
C
apache-2.0
850
<div class= "container"> <div class= "col-xs-3"></div> <div class= "col-xs-3"> <select id="orderBy" data-ng-model="orderBy" class="form-control col-md-4"> <option value="" selected>Sort by Price</option> <option value="price-low-high">Price: low - high</option> <option value="price-high-low">Price: high - low</option> </select> </div> </div> <div class= "container" data-ng-click="getBookInfo(book.bookId)"> <div class= "col-xs-3"> <div class="checkbox"> <label><input type="checkbox" value="">Mystery</label> </div> <div class="checkbox"> <label><input type="checkbox" value="">Fiction</label> </div> <div class="checkbox disabled"> <label><input type="checkbox" value="" disabled>Thriller</label> </div> </div> <div class= "col-xs-9"> <div data-ng-repeat="book in (filteredItems =(books | filter:filterPrice) )|orderBy:[orderByPrice]" class="col-md-4"> <h4><strong>{{book.bookName}}</strong></h4> <img data-ng-src="{{book.bookImage}}" alt="book.bookName" class="img-rounded" height="150px" width="150px"> <p > {{book.bookAuthor}}</p> <span >Genre: </span> <span data-ng-repeat="genre in book.genre"> {{genre}}</span> <!-- <p data-ng-show="book.series"> Series: {{book.series}}</p> --> <!-- <p > {{book.pubDate | date}}</p> --> <p style="color: red"> {{book.price | currency}}</p> </div> </div> </div>
RamuIMC/AWSMavenGitProject
src/main/webapp/resources/templates/home.html
HTML
apache-2.0
1,317
package com.iboxapp.ibox.ui; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.Button; import com.iboxapp.ibox.R; public class SettingSystemActivity extends AppCompatActivity { private Toolbar mToolbar; private Button mButtonEnsure; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting_system); mToolbar = (Toolbar) findViewById(R.id.simple_toolbar); mToolbar.setTitle(getResources().getString(R.string.navigation_sys_set)); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mButtonEnsure = (Button) findViewById(R.id.activity_setting_system_sure_button); mButtonEnsure.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "设置完成", Snackbar.LENGTH_SHORT) .setAction("Action", null).show(); finish(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub if(item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } }
kellan04/IboxApp
IBOX/app/src/main/java/com/iboxapp/ibox/ui/SettingSystemActivity.java
Java
apache-2.0
1,576