code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.sky.gank.data.douban; import com.sky.gank.net.HttpUtil; import com.sky.gank.net.RetrofitService; import com.sky.gank.net.Urls; import io.reactivex.Observable; /** * 类名称: * 类功能: * 类作者:Sky * 类日期:2018/12/31 0031. **/ public class RemoteDoubanMovieDataSource implements DoubanMovieDataSource{ public static final String MOVETYPE_IN_THEATERS = "in_theaters"; public static final String MOVETYPE_TOP250 = "top250"; private static RemoteDoubanMovieDataSource sInstance; private RemoteDoubanMovieDataSource() { } public static RemoteDoubanMovieDataSource getInstance() { if (sInstance == null) { synchronized (RemoteDoubanMovieDataSource.class) { if (sInstance == null) { sInstance = new RemoteDoubanMovieDataSource(); } } } return sInstance; } @Override public Observable<DoubanMovieData> getDouBanMovies(String type,int start,int count) { return HttpUtil.getInstance() .setBaseUrl(Urls.DOUBAN_API_BASE) .create(RetrofitService.class) .getDouBanMovies(type,start,count); } @Override public Observable<DoubanMovieDetailData> getDouBanMovieDetail(String id) { return HttpUtil.getInstance() .setBaseUrl(Urls.DOUBAN_API_BASE) .create(RetrofitService.class) .getDouBanMovieDetail(id); } }
SkyZhang007/LazyCat
gankio/src/main/java/com/sky/gank/data/douban/RemoteDoubanMovieDataSource.java
Java
apache-2.0
1,499
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import unittest from textwrap import dedent from pants.backend.jvm.register import build_file_aliases as register_jvm from pants.backend.jvm.targets.exclude import Exclude from pants.backend.jvm.targets.jvm_binary import (Duplicate, JarRules, JvmBinary, ManifestEntries, Skip) from pants.base.address import BuildFileAddress from pants.base.exceptions import TargetDefinitionException from pants.base.payload_field import FingerprintedField from pants.base.target import Target from pants_test.base_test import BaseTest class JarRulesTest(unittest.TestCase): def test_jar_rule(self): dup_rule = Duplicate('foo', Duplicate.REPLACE) self.assertEquals('Duplicate(apply_pattern=foo, action=REPLACE)', repr(dup_rule)) skip_rule = Skip('foo') self.assertEquals('Skip(apply_pattern=foo)', repr(skip_rule)) def test_invalid_apply_pattern(self): with self.assertRaisesRegexp(ValueError, r'The supplied apply_pattern is not a string'): Skip(None) with self.assertRaisesRegexp(ValueError, r'The supplied apply_pattern is not a string'): Duplicate(None, Duplicate.SKIP) with self.assertRaisesRegexp(ValueError, r'The supplied apply_pattern: \) is not a valid'): Skip(r')') with self.assertRaisesRegexp(ValueError, r'The supplied apply_pattern: \) is not a valid'): Duplicate(r')', Duplicate.SKIP) def test_bad_action(self): with self.assertRaisesRegexp(ValueError, r'The supplied action must be one of'): Duplicate('foo', None) def test_duplicate_error(self): with self.assertRaisesRegexp(Duplicate.Error, r'Duplicate entry encountered for path foo'): raise Duplicate.Error('foo') def test_default(self): jar_rules = JarRules.default() self.assertTrue(4, len(jar_rules.rules)) for rule in jar_rules.rules: self.assertTrue(rule.apply_pattern.pattern.startswith(r'^META-INF')) def test_set_bad_default(self): with self.assertRaisesRegexp(ValueError, r'The default rules must be a JarRules'): JarRules.set_default(None) class JvmBinaryTest(BaseTest): @property def alias_groups(self): return register_jvm() def test_simple(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', basename='foo-base', ) ''')) target = self.target('//:foo') self.assertEquals('com.example.Foo', target.main) self.assertEquals('com.example.Foo', target.payload.main) self.assertEquals('foo-base', target.basename) self.assertEquals('foo-base', target.payload.basename) self.assertEquals([], target.deploy_excludes) self.assertEquals([], target.payload.deploy_excludes) self.assertEquals(JarRules.default(), target.deploy_jar_rules) self.assertEquals(JarRules.default(), target.payload.deploy_jar_rules) self.assertEquals({}, target.payload.manifest_entries.entries); def test_default_base(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', ) ''')) target = self.target('//:foo') self.assertEquals('foo', target.basename) def test_deploy_jar_excludes(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', deploy_excludes=[exclude(org='example.com', name='foo-lib')], ) ''')) target = self.target('//:foo') self.assertEquals([Exclude(org='example.com', name='foo-lib')], target.deploy_excludes) def test_deploy_jar_rules(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', deploy_jar_rules=jar_rules([Duplicate('foo', Duplicate.SKIP)], default_dup_action=Duplicate.FAIL) ) ''')) target = self.target('//:foo') jar_rules = target.deploy_jar_rules self.assertEquals(1, len(jar_rules.rules)) self.assertEquals('foo', jar_rules.rules[0].apply_pattern.pattern) self.assertEquals(repr(Duplicate.SKIP), repr(jar_rules.rules[0].action)) # <object object at 0x...> self.assertEquals(Duplicate.FAIL, jar_rules.default_dup_action) def test_bad_source_declaration(self): build_file = self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', source=['foo.py'], ) ''')) with self.assertRaisesRegexp(TargetDefinitionException, r'Invalid target JvmBinary.*foo.*source must be a single'): self.build_graph.inject_address_closure(BuildFileAddress(build_file, 'foo')) def test_bad_sources_declaration(self): with self.assertRaisesRegexp(Target.IllegalArgument, r'jvm_binary only supports a single "source" argument'): self.make_target('foo:foo', target_type=JvmBinary, main='com.example.Foo', sources=['foo.py']) def test_bad_main_declaration(self): build_file = self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='bar', main=['com.example.Bar'], ) ''')) with self.assertRaisesRegexp(TargetDefinitionException, r'Invalid target JvmBinary.*bar.*main must be a fully'): self.build_graph.inject_address_closure(BuildFileAddress(build_file, 'bar')) def test_bad_jar_rules(self): build_file = self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', deploy_jar_rules='invalid', ) ''')) with self.assertRaisesRegexp(TargetDefinitionException, r'Invalid target JvmBinary.*foo.*' r'deploy_jar_rules must be a JarRules specification. got str'): self.build_graph.inject_address_closure(BuildFileAddress(build_file, 'foo')) def _assert_fingerprints_not_equal(self, fields): for field in fields: for other_field in fields: if field == other_field: continue self.assertNotEquals(field.fingerprint(), other_field.fingerprint()) def test_jar_rules_field(self): field1 = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP)])) field1_same = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP)])) field2 = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.CONCAT)])) field3 = FingerprintedField(JarRules(rules=[Duplicate('bar', Duplicate.SKIP)])) field4 = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP), Duplicate('bar', Duplicate.SKIP)])) field5 = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP), Skip('foo')])) field6 = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP)], default_dup_action=Duplicate.FAIL)) field6_same = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP)], default_dup_action=Duplicate.FAIL)) field7 = FingerprintedField(JarRules(rules=[Skip('foo')])) field8 = FingerprintedField(JarRules(rules=[Skip('bar')])) field8_same = FingerprintedField(JarRules(rules=[Skip('bar')])) self.assertEquals(field1.fingerprint(), field1_same.fingerprint()) self.assertEquals(field6.fingerprint(), field6_same.fingerprint()) self.assertEquals(field8.fingerprint(), field8_same.fingerprint()) self._assert_fingerprints_not_equal([field1, field2, field3, field4, field5, field6, field7]) def test_manifest_entries(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', manifest_entries= { 'Foo-Field' : 'foo', } ) ''')) target = self.target('//:foo') self.assertTrue(isinstance(target.payload.manifest_entries, ManifestEntries)) entries = target.payload.manifest_entries.entries self.assertEquals({ 'Foo-Field' : 'foo'}, entries) def test_manifest_not_dict(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', manifest_entries= 'foo', ) ''')) with self.assertRaisesRegexp(TargetDefinitionException, r'Invalid target JvmBinary\(BuildFileAddress\(.*BUILD\), foo\)\): ' r'manifest_entries must be a dict. got str'): self.target('//:foo') def test_manifest_bad_key(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', manifest_entries= { jar(org='bad', name='bad', rev='bad') : 'foo', } ) ''')) with self.assertRaisesRegexp(ManifestEntries.ExpectedDictionaryError, r'entries must be dictionary of strings, got key bad-bad-bad type JarDependency'): self.target('//:foo') def test_manifest_entries_fingerprint(self): field1 = ManifestEntries() field2 = ManifestEntries({'Foo-Field' : 'foo'}) field2_same = ManifestEntries({'Foo-Field' : 'foo'}) field3 = ManifestEntries({'Foo-Field' : 'foo', 'Bar-Field' : 'bar'}) self.assertEquals(field2.fingerprint(), field2_same.fingerprint()) self._assert_fingerprints_not_equal([field1, field2, field3])
digwanderlust/pants
tests/python/pants_test/backend/jvm/targets/test_jvm_binary.py
Python
apache-2.0
9,783
/* * Copyright 2009-2012 The MyBatis Team * * 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.ibatis.sqlmap; import com.testdomain.ComplexBean; import java.util.HashMap; import java.util.Map; public class ComplexTypeTest extends BaseSqlMapTest { // SETUP & TEARDOWN protected void setUp() throws Exception { initSqlMap("com/ibatis/sqlmap/maps/SqlMapConfig.xml", null); initScript("com/scripts/account-init.sql"); initScript("com/scripts/order-init.sql"); initScript("com/scripts/line_item-init.sql"); } protected void tearDown() throws Exception { } public void testMapBeanMap() throws Exception { Map map = new HashMap(); ComplexBean bean = new ComplexBean(); bean.setMap(new HashMap()); bean.getMap().put("id", new Integer(1)); map.put("bean", bean); Integer id = (Integer) sqlMap.queryForObject("mapBeanMap", map); assertEquals(id, bean.getMap().get("id")); } }
c340c340/mybatis-3.2.22
src/test/java/com/ibatis/sqlmap/ComplexTypeTest.java
Java
apache-2.0
1,486
package com.orangemile.replay; import com.higherfrequencytrading.chronicle.Excerpt; public interface ReplayHandler<T> { public T parse(int id, Excerpt e); public long getTime(int id, T t); public void replay(int id, T t, long realTime, long relativeTime); }
orangemile/chronicle-replay
src/app/java/com/orangemile/replay/ReplayHandler.java
Java
apache-2.0
283
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.profile.query; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken; import static org.elasticsearch.common.xcontent.XContentParserUtils.throwUnknownField; import static org.elasticsearch.common.xcontent.XContentParserUtils.throwUnknownToken; /** * Public interface and serialization container for profiled timings of the * Collectors used in the search. Children CollectorResult's may be * embedded inside of a parent CollectorResult */ public class CollectorResult implements ToXContentObject, Writeable { public static final String REASON_SEARCH_COUNT = "search_count"; public static final String REASON_SEARCH_TOP_HITS = "search_top_hits"; public static final String REASON_SEARCH_TERMINATE_AFTER_COUNT = "search_terminate_after_count"; public static final String REASON_SEARCH_POST_FILTER = "search_post_filter"; public static final String REASON_SEARCH_MIN_SCORE = "search_min_score"; public static final String REASON_SEARCH_MULTI = "search_multi"; public static final String REASON_SEARCH_TIMEOUT = "search_timeout"; public static final String REASON_SEARCH_CANCELLED = "search_cancelled"; public static final String REASON_AGGREGATION = "aggregation"; public static final String REASON_AGGREGATION_GLOBAL = "aggregation_global"; private static final ParseField NAME = new ParseField("name"); private static final ParseField REASON = new ParseField("reason"); private static final ParseField TIME = new ParseField("time"); private static final ParseField TIME_NANOS = new ParseField("time_in_nanos"); private static final ParseField CHILDREN = new ParseField("children"); /** * A more friendly representation of the Collector's class name */ private final String collectorName; /** * A "hint" to help provide some context about this Collector */ private final String reason; /** * The total elapsed time for this Collector */ private final Long time; /** * A list of children collectors "embedded" inside this collector */ private List<CollectorResult> children; public CollectorResult(String collectorName, String reason, Long time, List<CollectorResult> children) { this.collectorName = collectorName; this.reason = reason; this.time = time; this.children = children; } /** * Read from a stream. */ public CollectorResult(StreamInput in) throws IOException { this.collectorName = in.readString(); this.reason = in.readString(); this.time = in.readLong(); int size = in.readVInt(); this.children = new ArrayList<>(size); for (int i = 0; i < size; i++) { CollectorResult child = new CollectorResult(in); this.children.add(child); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(collectorName); out.writeString(reason); out.writeLong(time); out.writeVInt(children.size()); for (CollectorResult child : children) { child.writeTo(out); } } /** * @return the profiled time for this collector (inclusive of children) */ public long getTime() { return this.time; } /** * @return a human readable "hint" about what this collector was used for */ public String getReason() { return this.reason; } /** * @return the lucene class name of the collector */ public String getName() { return this.collectorName; } /** * @return a list of children collectors */ public List<CollectorResult> getProfiledChildren() { return children; } @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder = builder.startObject() .field(NAME.getPreferredName(), getName()) .field(REASON.getPreferredName(), getReason()) .field(TIME.getPreferredName(), String.format(Locale.US, "%.10gms", getTime() / 1000000.0)) .field(TIME_NANOS.getPreferredName(), getTime()); if (!children.isEmpty()) { builder = builder.startArray(CHILDREN.getPreferredName()); for (CollectorResult child : children) { builder = child.toXContent(builder, params); } builder = builder.endArray(); } builder = builder.endObject(); return builder; } public static CollectorResult fromXContent(XContentParser parser) throws IOException { XContentParser.Token token = parser.currentToken(); ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser::getTokenLocation); String currentFieldName = null; String name = null, reason = null; long time = -1; List<CollectorResult> children = new ArrayList<>(); while((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if (NAME.match(currentFieldName)) { name = parser.text(); } else if (REASON.match(currentFieldName)) { reason = parser.text(); } else if (TIME.match(currentFieldName)) { // we need to consume this value, but we use the raw nanosecond value parser.text(); } else if (TIME_NANOS.match(currentFieldName)) { time = parser.longValue(); } else { throwUnknownField(currentFieldName, parser.getTokenLocation()); } } else if (token == XContentParser.Token.START_ARRAY) { if (CHILDREN.match(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { children.add(CollectorResult.fromXContent(parser)); } } else { throwUnknownField(currentFieldName, parser.getTokenLocation()); } } else { throwUnknownToken(token, parser.getTokenLocation()); } } return new CollectorResult(name, reason, time, children); } }
strapdata/elassandra5-rc
core/src/main/java/org/elasticsearch/search/profile/query/CollectorResult.java
Java
apache-2.0
7,878
# # Copyright (c) SAS Institute 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. # """ Watch a running build job and output changes to the screen. """ import fcntl import os import select import socket import sys import tempfile import termios import time import traceback from rmake import errors from rmake.build import buildjob, buildtrove from rmake.cmdline import query def _getUri(client): if not isinstance(client.uri, str) or client.uri.startswith('unix://'): fd, tmpPath = tempfile.mkstemp() os.close(fd) uri = 'unix://' + tmpPath else: host = socket.gethostname() uri = 'http://%s' % host tmpPath = None return uri, tmpPath def monitorJob(client, jobId, showTroveDetails=False, showBuildLogs=False, exitOnFinish=None, uri=None, serve=True, out=None, displayClass=None): if not uri: uri, tmpPath = _getUri(client) else: tmpPath = None if not displayClass: displayClass = JobLogDisplay try: display = displayClass(client, showBuildLogs=showBuildLogs, out=out, exitOnFinish=exitOnFinish) client = client.listenToEvents(uri, jobId, display, showTroveDetails=showTroveDetails, serve=serve) return client finally: if serve and tmpPath: os.remove(tmpPath) def waitForJob(client, jobId, uri=None, serve=True): if not uri: uri, tmpPath = _getUri(client) else: tmpPath = None try: display = SilentDisplay(client) display._primeOutput(jobId) return client.listenToEvents(uri, jobId, display, serve=serve) finally: if tmpPath: os.remove(tmpPath) class _AbstractDisplay(object):#xmlrpc.BasicXMLRPCStatusSubscriber): def __init__(self, client, showBuildLogs=True, out=None, exitOnFinish=True): self.client = client self.finished = False self.exitOnFinish = True # override exitOnFinish setting self.showBuildLogs = showBuildLogs if not out: out = sys.stdout self.out = out def close(self): pass def _serveLoopHook(self): pass def _msg(self, msg, *args): self.out.write('[%s] %s\n' % (time.strftime('%X'), msg)) self.out.flush() def _jobStateUpdated(self, jobId, state, status): isFinished = (state in (buildjob.JOB_STATE_FAILED, buildjob.JOB_STATE_BUILT)) if isFinished: self._setFinished() def _setFinished(self): self.finished = True def _isFinished(self): return self.finished def _shouldExit(self): return self._isFinished() and self.exitOnFinish def _primeOutput(self, jobId): job = self.client.getJob(jobId, withTroves=False) if job.isFinished(): self._setFinished() class SilentDisplay(_AbstractDisplay): pass class JobLogDisplay(_AbstractDisplay): def __init__(self, client, showBuildLogs=True, out=None, exitOnFinish=None): _AbstractDisplay.__init__(self, client, out=out, showBuildLogs=showBuildLogs, exitOnFinish=exitOnFinish) self.buildingTroves = {} def _tailBuildLog(self, jobId, troveTuple): mark = self.buildingTroves.get((jobId, troveTuple), [0])[0] self.buildingTroves[jobId, troveTuple] = [mark, True] self.out.write('Tailing %s build log:\n\n' % troveTuple[0]) def _stopTailing(self, jobId, troveTuple): mark = self.buildingTroves.get((jobId, troveTuple), [0])[0] self.buildingTroves[jobId, troveTuple] = [ mark, False ] def _serveLoopHook(self): if not self.buildingTroves: return for (jobId, troveTuple), (mark, tail) in self.buildingTroves.items(): if not tail: continue try: moreData, data, mark = self.client.getTroveBuildLog(jobId, troveTuple, mark) except: moreData = True data = '' self.out.write(data) if not moreData: del self.buildingTroves[jobId, troveTuple] else: self.buildingTroves[jobId, troveTuple][0] = mark def _jobTrovesSet(self, jobId, troveData): self._msg('[%d] - job troves set' % jobId) def _jobStateUpdated(self, jobId, state, status): _AbstractDisplay._jobStateUpdated(self, jobId, state, status) state = buildjob.stateNames[state] if self._isFinished(): self._serveLoopHook() self._msg('[%d] - State: %s' % (jobId, state)) if status: self._msg('[%d] - %s' % (jobId, status)) def _jobLogUpdated(self, jobId, state, status): self._msg('[%d] %s' % (jobId, status)) def _troveStateUpdated(self, (jobId, troveTuple), state, status): isBuilding = (state in (buildtrove.TroveState.BUILDING, buildtrove.TroveState.RESOLVING)) state = buildtrove.stateNames[state] self._msg('[%d] - %s - State: %s' % (jobId, troveTuple[0], state)) if status: self._msg('[%d] - %s - %s' % (jobId, troveTuple[0], status)) if isBuilding and self.showBuildLogs: self._tailBuildLog(jobId, troveTuple) else: self._stopTailing(jobId, troveTuple) def _troveLogUpdated(self, (jobId, troveTuple), state, status): state = buildtrove.stateNames[state] self._msg('[%d] - %s - %s' % (jobId, troveTuple[0], status)) def _trovePreparingChroot(self, (jobId, troveTuple), host, path): if host == '_local_': msg = 'Chroot at %s' % path else: msg = 'Chroot at Node %s:%s' % (host, path) self._msg('[%d] - %s - %s' % (jobId, troveTuple[0], msg)) def _primeOutput(self, jobId): logMark = 0 while True: newLogs = self.client.getJobLogs(jobId, logMark) if not newLogs: break logMark += len(newLogs) for (timeStamp, message, args) in newLogs: print '[%s] [%s] - %s' % (timeStamp, jobId, message) BUILDING = buildtrove.TroveState.BUILDING troveTups = self.client.listTrovesByState(jobId, BUILDING).get(BUILDING, []) for troveTuple in troveTups: self._tailBuildLog(jobId, troveTuple) _AbstractDisplay._primeOutput(self, jobId) def set_raw_mode(): fd = sys.stdin.fileno() oldTerm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldFlags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldFlags | os.O_NONBLOCK) return oldTerm, oldFlags def restore_terminal(oldTerm, oldFlags): fd = sys.stdin.fileno() if oldTerm: termios.tcsetattr(fd, termios.TCSAFLUSH, oldTerm) if oldFlags: fcntl.fcntl(fd, fcntl.F_SETFL, oldFlags) class _AbstractDisplay(object):#xmlrpc.BasicXMLRPCStatusSubscriber): def __init__(self, client, showBuildLogs=True, out=None): self.client = client self.finished = False self.showBuildLogs = showBuildLogs self.troveStates = {} self.troveIndex = None self.troveDislay = False self.out = OutBuffer(out) def close(self): pass def _msg(self, msg, *args): self.out.write('\r[%s] %s\n' % (time.strftime('%X'), msg)) self.out.write('(h for help)>') self.out.flush() def _jobStateUpdated(self, jobId, state, status): isFinished = (state in (buildjob.JOB_STATE_FAILED, buildjob.JOB_STATE_BUILT)) if isFinished: self._setFinished() def _setFinished(self): self.finished = True def _isFinished(self): return self.finished def _shouldExit(self): return self._isFinished() and self.exitOnFinish def _primeOutput(self, jobId): job = self.client.getJob(jobId, withTroves=False) if job.isFinished(): self._setFinished() def _dispatch(self, methodname, (callData, responseHandler, args)): if methodname.startswith('_'): raise NoSuchMethodError(methodname) else: responseHandler.sendResponse('') getattr(self, methodname)(*args) class SilentDisplay(_AbstractDisplay): def _updateBuildLog(self): pass class JobLogDisplay(_AbstractDisplay): def __init__(self, client, state, out=None): _AbstractDisplay.__init__(self, client, out) self.troveToWatch = None self.watchTroves = False self.buildingTroves = {} self.state = state self.lastLen = 0 self.promptFormat = '%(jobId)s %(name)s%(context)s - %(state)s - (%(tailing)s) ([h]elp)>' self.updatePrompt() def close(self): self.out.write('\n') self.out.flush() def _msg(self, msg, *args): self.erasePrompt() self.out.write('[%s] %s\n' % (time.strftime('%X'), msg)) self.writePrompt() def updatePrompt(self): if self.troveToWatch: if self.troveToWatch not in self.state.troves: self.troveToWatch = self.state.troves[0] state = self.state.getTroveState(*self.troveToWatch) state = buildtrove.stateNames[state] name = self.troveToWatch[1][0].split(':', 1)[0] # remove :source context = self.troveToWatch[1][3] d = dict(jobId=self.troveToWatch[0], name=name, state=state, context=(context and '{%s}' % context or '')) else: d = dict(jobId='(None)', name='(None)', state='', context='') if not self.state.jobActive(): tailing = 'Job %s' % self.state.getJobStateName() elif self.watchTroves: tailing = 'Details on' else: tailing = 'Details off' d['tailing'] = tailing self.prompt = self.promptFormat % d self.erasePrompt() self.writePrompt() def erasePrompt(self): self.out.write('\r%s\r' % (' '*self.lastLen)) def writePrompt(self): self.out.write(self.prompt) self.lastLen = len(self.prompt) self.out.flush() def setWatchTroves(self, watchTroves=True): self.watchTroves = watchTroves self.updatePrompt() def getWatchTroves(self): return self.watchTroves def setTroveToWatch(self, jobId, troveTuple): self.troveToWatch = jobId, troveTuple self.updatePrompt() def _watchTrove(self, jobId, troveTuple): if not self.watchTroves: return False return self.troveToWatch == (jobId, troveTuple) def displayTroveStates(self): if not self.troveToWatch: return self.erasePrompt() job = self.client.getJob(self.troveToWatch[0]) query.displayTrovesByState(job, out=self.out) self.writePrompt() def setPrompt(self, promptFormat): self.promptFormat = promptFormat self.updatePrompt() def updateBuildLog(self, jobId, troveTuple): if not self._watchTrove(jobId, troveTuple): return mark = self.getMark(jobId, troveTuple) if mark is None: return try: moreData, data, mark = self.client.getTroveBuildLog(jobId, troveTuple, mark) except: return if data and data != '\n': self.erasePrompt() if data[0] == '\n': # we've already got a \n because we've cleared # the prompt. data = data[1:] self.out.write(data) if data[-1] != '\n': self.out.write('\n') self.writePrompt() if not moreData: mark = None self.setMark(jobId, troveTuple, mark) def getMark(self, jobId, troveTuple): if (jobId, troveTuple) not in self.buildingTroves: # display max 80 lines of back log self.buildingTroves[jobId, troveTuple] = -80 return self.buildingTroves[jobId, troveTuple] def setMark(self, jobId, troveTuple, mark): self.buildingTroves[jobId, troveTuple] = mark def _jobTrovesSet(self, jobId, troveList): self._msg('[%d] - job troves set' % jobId) self.troveToWatch = jobId, troveList[0] self.updatePrompt() def _jobStateUpdated(self, jobId, state, status): _AbstractDisplay._jobStateUpdated(self, jobId, state, status) state = buildjob.stateNames[state] if self._isFinished() and self.troveToWatch: self.updateBuildLog(*self.troveToWatch) self._msg('[%d] - State: %s' % (jobId, state)) if status: self._msg('[%d] - %s' % (jobId, status)) self.updatePrompt() def _jobLogUpdated(self, jobId, state, status): self._msg('[%d] %s' % (jobId, status)) def _troveStateUpdated(self, (jobId, troveTuple), state, status): isBuilding = (state == buildtrove.TroveState.BUILDING) state = buildtrove.stateNames[state] if troveTuple[3]: name = '%s{%s}' % (troveTuple[0], troveTuple[3]) else: name = troveTuple[0] self._msg('[%d] - %s - State: %s' % (jobId, name, state)) if status and self._watchTrove(jobId, troveTuple): self._msg('[%d] - %s - %s' % (jobId, name, status)) self.updatePrompt() def _troveLogUpdated(self, (jobId, troveTuple), state, status): if self._watchTrove(jobId, troveTuple): state = buildtrove.stateNames[state] self._msg('[%d] - %s - %s' % (jobId, troveTuple[0], status)) def _trovePreparingChroot(self, (jobId, troveTuple), host, path): if not self._watchTrove(jobId, troveTuple): return if host == '_local_': msg = 'Chroot at %s' % path else: msg = 'Chroot at Node %s:%s' % (host, path) self._msg('[%d] - %s - %s' % (jobId, troveTuple[0], msg)) class OutBuffer(object): def __init__(self, fd): if fd is None: fd = sys.stdout.fileno() elif not isinstance(out, int): fd = out.fileno() self.fd = fd self.data = [] def write(self, data): self.data.append(data) def fileno(self): return self.fd def flush(self): while self.data: self.check() def check(self): while self.data: ready = select.select([], [self.fd], [], 0.1)[1] if not ready: return rc = os.write(self.fd, self.data[0]) if rc < len(self.data[0]): self.data[0] = self.data[0][rc:] else: self.data.pop(0) class DisplayState(object):#xmlrpc.BasicXMLRPCStatusSubscriber): def __init__(self, client): self.troves = [] self.states = {} self.buildingTroves = {} self.jobId = None self.client = client self.jobState = None def _primeOutput(self, jobId): #assert(not self.jobId) self.jobId = jobId job = self.client.getJob(jobId, withTroves=False) self.jobState = job.state if job.isBuilding() or job.isFinished() or job.isFailed(): self.updateTrovesForJob(jobId) def jobActive(self): return self.jobState in ( buildjob.JOB_STATE_STARTED, buildjob.JOB_STATE_LOADING, buildjob.JOB_STATE_LOADED, buildjob.JOB_STATE_BUILD, ) def getJobStateName(self): if self.jobState is None: return 'None' return buildjob.stateNames[self.jobState] def isFailed(self, jobId, troveTuple): return (self.getTroveState(jobId, troveTuple) == buildtrove.TroveState.FAILED) def isBuilding(self, jobId, troveTuple): return self.getTroveState(jobId, troveTuple) in ( buildtrove.TroveState.BUILDING, buildtrove.TroveState.PREPARING, buildtrove.TroveState.RESOLVING) def isFailed(self, jobId, troveTuple): # don't iterate through unbuildable - they are failures due to # secondary causes. return self.getTroveState(jobId, troveTuple) in ( buildtrove.TroveState.FAILED,) def findTroveByName(self, troveName): startsWith = None for jobId, troveTuple in sorted(self.states): if troveTuple[0].split(':', 1)[0] == troveName: # exact matches take priority return (jobId, troveTuple) elif troveTuple[0].startswith(troveName) and startsWith is None: startsWith = (jobId, troveTuple) return startsWith def getTroveState(self, jobId, troveTuple): return self.states[jobId, troveTuple] def getBuildingTroves(self): return [ x[0] for x in self.states.iteritems() if x[1] in (buildtrove.TroveState.BUILDING, buildtrove.TroveState.RESOLVING) ] def updateTrovesForJob(self, jobId): self.troves = [] self.states = {} for state, troveTupleList in self.client.listTrovesByState(jobId).items(): for troveTuple in troveTupleList: self.troves.append((jobId, troveTuple)) self.states[jobId, troveTuple] = state self.troves.sort() def _troveStateUpdated(self, (jobId, troveTuple), state, status): if (jobId, troveTuple) not in self.states: self.updateTrovesForJob(jobId) else: self.states[jobId, troveTuple] = state def _jobStateUpdated(self, jobId, state, status): self.jobState = state if self._isBuilding(): self.updateTrovesForJob(jobId) def _jobTrovesSet(self, jobId, troveList): self.updateTrovesForJob(jobId) def _isBuilding(self): return self.jobState in (buildjob.JOB_STATE_BUILD, buildjob.JOB_STATE_STARTED) def _isFinished(self): return self.jobState in ( buildjob.JOB_STATE_FAILED, buildjob.JOB_STATE_BUILT) class DisplayManager(object):#xmlrpc.BasicXMLRPCStatusSubscriber): displayClass = JobLogDisplay stateClass = DisplayState def __init__(self, client, showBuildLogs, out=None, exitOnFinish=None): self.termInfo = set_raw_mode() if out is None: out = open('/dev/tty', 'w') self.state = self.stateClass(client) self.display = self.displayClass(client, self.state, out) self.client = client self.troveToWatch = None self.troveIndex = 0 self.showBuildLogs = showBuildLogs if exitOnFinish is None: exitOnFinish = False self.exitOnFinish = exitOnFinish def _receiveEvents(self, *args, **kw): methodname = '_receiveEvents' method = getattr(self.state, methodname, None) if method: try: method(*args) except errors.uncatchableExceptions: raise except Exception, err: print 'Error in handler: %s\n%s' % (err, traceback.format_exc()) method = getattr(self.display, methodname, None) if method: try: method(*args) except errors.uncatchableExceptions: raise except Exception, err: print 'Error in handler: %s\n%s' % (err, traceback.format_exc()) return '' def getCurrentTrove(self): if self.state.troves: return self.state.troves[self.troveIndex] else: return None def _primeOutput(self, jobId): self.state._primeOutput(jobId) self.display._msg('Watching job %s' % jobId) if self.getCurrentTrove(): self.displayTrove(*self.getCurrentTrove()) def displayTrove(self, jobId, troveTuple): self.display.setTroveToWatch(jobId, troveTuple) state = self.state.getTroveState(jobId, troveTuple) state = buildtrove.stateNames[state] def _serveLoopHook(self): ready = select.select([sys.stdin], [], [], 0.1)[0] if ready: cmd = sys.stdin.read(1) if cmd == '\x1b': cmd += sys.stdin.read(2) if cmd == ' ': self.do_switch_log() elif cmd == 'n' or cmd == '\x1b[C': self.do_next() elif cmd == 'p' or cmd == '\x1b[D': self.do_prev() elif cmd == 'q': sys.exit(0) elif cmd == 'h': self.do_help() elif cmd == 'b': self.do_next_building() elif cmd == 'f': self.do_next_failed() elif cmd == 'i': self.do_info() elif cmd == 'l': self.do_log() elif cmd == 's': self.do_status() elif cmd == 'g': self.do_goto() if self.showBuildLogs: for jobId, troveTuple in self.state.getBuildingTroves(): self.display.updateBuildLog(jobId, troveTuple) def do_next(self): if not self.state.troves: return self.troveIndex = (self.troveIndex + 1) % len(self.state.troves) if self.getCurrentTrove(): self.displayTrove(*self.getCurrentTrove()) def do_next_building(self): if not self.state.troves: return startIndex = self.troveIndex self.troveIndex = (self.troveIndex + 1) % len(self.state.troves) while (not self.state.isBuilding(*self.getCurrentTrove()) and self.troveIndex != startIndex): self.troveIndex = (self.troveIndex + 1) % len(self.state.troves) if self.troveIndex != startIndex: self.displayTrove(*self.getCurrentTrove()) def do_goto(self): if not self.state.troves: print 'No troves loaded yet' return self.display.erasePrompt() restore_terminal(*self.termInfo) try: troveName = raw_input("\nName or part of name of trove: ") troveInfo = self.state.findTroveByName(troveName) if not troveInfo: print 'No trove starting with "%s"' % troveName self.display.writePrompt() return while not self.getCurrentTrove() == troveInfo: self.troveIndex = (self.troveIndex + 1) % len(self.state.troves) self.displayTrove(*self.getCurrentTrove()) finally: self.termInfo = set_raw_mode() def do_next_failed(self): if not self.state.troves: return startIndex = self.troveIndex self.troveIndex = (self.troveIndex + 1) % len(self.state.troves) while (not self.state.isFailed(*self.getCurrentTrove()) and self.troveIndex != startIndex): self.troveIndex = (self.troveIndex + 1) % len(self.state.troves) if self.troveIndex != startIndex: self.displayTrove(*self.getCurrentTrove()) def do_prev(self): if not self.state.troves: return self.troveIndex = (self.troveIndex - 1) % len(self.state.troves) if self.getCurrentTrove(): self.displayTrove(*self.getCurrentTrove()) def do_info(self): if not self.getCurrentTrove(): return jobId, troveTuple = self.getCurrentTrove() job = self.client.getJob(jobId) trove = job.getTrove(*troveTuple) dcfg = query.DisplayConfig(self.client, showTracebacks=True) self.display.setWatchTroves(False) self.display.erasePrompt() query.displayTroveDetail(dcfg, job, trove, out=self.display.out) self.display.writePrompt() def do_log(self): if not self.getCurrentTrove(): return jobId, troveTuple = self.getCurrentTrove() job = self.client.getJob(jobId) trove = job.getTrove(*troveTuple) moreData, data, mark = self.client.getTroveBuildLog(jobId, troveTuple, 0) if not data: self.display._msg('No log yet.') return fd, path = tempfile.mkstemp() os.fdopen(fd, 'w').write(data) try: os.system('less %s' % path) finally: os.remove(path) def do_help(self): print print "<space>: Turn on/off tailing of log" print "<left>/<right>: move to next/prev trove in list" print "b: move to next building trove" print "f: move to next failed trove" print "g: go to a particular trove" print "h: print help" print "i: display info for this trove" print "l: display log for this trove in less" print "q: quit" print "s: display status on all troves" def do_status(self): self.display.setWatchTroves(False) self.display.displayTroveStates() def do_switch_log(self): self.display.setWatchTroves(not self.display.getWatchTroves()) def _isFinished(self): return self.display._isFinished() def _shouldExit(self): return self._isFinished() and self.exitOnFinish def close(self): self.display.close() restore_terminal(*self.termInfo)
sassoftware/rmake3
rmake/cmdline/monitor.py
Python
apache-2.0
26,810
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FeatureNode.cs" company="PicklesDoc"> // Copyright 2011 Jeffrey Cameron // Copyright 2012-present PicklesDoc team and community contributors // // // 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. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.IO.Abstractions; using PicklesDoc.Pickles.Extensions; using PicklesDoc.Pickles.ObjectModel; namespace PicklesDoc.Pickles.DirectoryCrawler { public class FeatureNode : INode { public FeatureNode(IFileSystemInfo location, string relativePathFromRoot, Feature feature) { this.OriginalLocation = location; this.OriginalLocationUrl = location.ToUri(); this.RelativePathFromRoot = relativePathFromRoot; this.Feature = feature; } public Feature Feature { get; } public NodeType NodeType { get { return NodeType.Content; } } public string Name { get { return this.Feature.Name; } } public IFileSystemInfo OriginalLocation { get; } public Uri OriginalLocationUrl { get; } public string RelativePathFromRoot { get; } public string GetRelativeUriTo(Uri other, string newExtension) { return other.GetUriForTargetRelativeToMe(this.OriginalLocation, newExtension); } public string GetRelativeUriTo(Uri other) { return this.GetRelativeUriTo(other, ".html"); } } }
picklesdoc/pickles
src/Pickles.ObjectModel/DirectoryCrawler/FeatureNode.cs
C#
apache-2.0
2,242
package com.cody.app.business.launch; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.animation.AccelerateDecelerateInterpolator; import java.util.ArrayList; import java.util.List; /** * Created by cody.yi on 2017/9/6. * some useful information */ public class CharacterView extends android.support.v7.widget.AppCompatTextView { private Position mCurrentPosition; private int mDuration = 2000; public int getDuration() { return mDuration; } public void setDuration(int duration) { mDuration = duration; } private List<Position> mPositions = new ArrayList<>(); private AnimatorSet mAnimatorSet; public Position getLastPosition() { return mPositions.get(mPositions.size() - 1); } public Position getCurrentPosition() { return mCurrentPosition; } public List<Position> getPositions() { return mPositions; } public CharacterView addPosition(Position position) { mPositions.add(position); return this; } public CharacterView addPosition(float x, float y) { mPositions.add(new Position(x, y)); return this; } public CharacterView addLineToX(float x) { mPositions.add(new Position(x, getLastPosition().y)); return this; } public CharacterView addLineToY(float y) { mPositions.add(new Position(getLastPosition().x, y)); return this; } public CharacterView(Context context) { this(context, null); } public CharacterView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (mCurrentPosition == null) { mCurrentPosition = new Position(getX(), getY()); mPositions.clear(); addPosition(mCurrentPosition); } } public CharacterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void startAnimation() { if (mAnimatorSet == null) { mAnimatorSet = new AnimatorSet(); ValueAnimator positionAnimator = ValueAnimator.ofObject(new PositionEvaluator(), mPositions.toArray()); positionAnimator.setDuration(mDuration); positionAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mCurrentPosition = (Position) animation.getAnimatedValue(); setX(mCurrentPosition.x); setY(mCurrentPosition.y); invalidate(); } }); positionAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); ValueAnimator scaleAnimator = ValueAnimator.ofFloat(1.0f, 0.5f); scaleAnimator.setDuration(mDuration); scaleAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float scale = (float) animation.getAnimatedValue(); setPivotX(0); setScaleX(scale); setScaleY(scale); invalidate(); } }); mAnimatorSet.playTogether(positionAnimator, scaleAnimator); } if (!mAnimatorSet.isStarted()) { mAnimatorSet.start(); } } public void stopAnimation() { if (mAnimatorSet != null && mAnimatorSet.isStarted()) { mAnimatorSet.end(); } } }
codyer/CleanFramework
app/src/demo/java/com/cody/app/business/launch/CharacterView.java
Java
apache-2.0
3,979
/* * Copyright 2014-2016 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.codehaus.griffon.runtime.domain; import griffon.plugins.domain.GriffonDomainClass; import griffon.plugins.domain.GriffonDomainClassProperty; import javax.annotation.Nonnull; import java.beans.PropertyDescriptor; import static java.util.Objects.requireNonNull; /** * @author Andres Almiray */ public abstract class AbstractGriffonDomainClassProperty extends DefaultGriffonDomainProperty implements GriffonDomainClassProperty { private static final String ERROR_DOMAIN_CLASS_NULL = "Argument 'domainClass' must not be null"; private final GriffonDomainClass<?> domainClass; public AbstractGriffonDomainClassProperty(@Nonnull GriffonDomainClass<?> domainClass, @Nonnull PropertyDescriptor propertyDescriptor) { super(propertyDescriptor, requireNonNull(domainClass, ERROR_DOMAIN_CLASS_NULL).getClazz()); this.domainClass = domainClass; } @Nonnull public GriffonDomainClass<?> getDomainClass() { return domainClass; } }
griffon-plugins/griffon-domain-plugin
subprojects/griffon-domain-core/src/main/java/org/codehaus/griffon/runtime/domain/AbstractGriffonDomainClassProperty.java
Java
apache-2.0
1,607
package org.grobid.core.utilities; import org.apache.commons.lang3.StringUtils; import org.grobid.core.analyzers.GrobidAnalyzer; import org.grobid.core.exceptions.GrobidException; import org.grobid.core.layout.LayoutToken; import org.grobid.core.lexicon.Lexicon; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class for holding static methods for text processing. * * @author Patrice Lopez */ public class TextUtilities { public static final String punctuations = " •*,:;?.!)-−–\"“”‘’'`$]*\u2666\u2665\u2663\u2660\u00A0"; public static final String fullPunctuations = "(([ •*,:;?.!/))-−–‐«»„\"“”‘’'`$]*\u2666\u2665\u2663\u2660\u00A0"; public static final String restrictedPunctuations = ",:;?.!/-–«»„\"“”‘’'`*\u2666\u2665\u2663\u2660"; public static String delimiters = "\n\r\t\f\u00A0" + fullPunctuations; public static final String OR = "|"; public static final String NEW_LINE = "\n"; public static final String SPACE = " "; public static final String COMMA = ","; public static final String QUOTE = "'"; public static final String END_BRACKET = ")"; public static final String START_BRACKET = "("; public static final String SHARP = "#"; public static final String COLON = ":"; public static final String DOUBLE_QUOTE = "\""; public static final String ESC_DOUBLE_QUOTE = "&quot;"; public static final String LESS_THAN = "<"; public static final String ESC_LESS_THAN = "&lt;"; public static final String GREATER_THAN = ">"; public static final String ESC_GREATER_THAN = "&gt;"; public static final String AND = "&"; public static final String ESC_AND = "&amp;"; public static final String SLASH = "/"; // the magical DOI regular expression... static public final Pattern DOIPattern = Pattern .compile("(10\\.\\d{4,5}\\/[\\S]+[^;,.\\s])"); // a regular expression for arXiv identifiers // see https://arxiv.org/help/arxiv_identifier and https://arxiv.org/help/arxiv_identifier_for_services static public final Pattern arXivPattern = Pattern .compile("(arXiv\\s?(\\.org)?\\s?\\:\\s?\\d{4}\\s?\\.\\s?\\d{4,5}(v\\d+)?)|(arXiv\\s?(\\.org)?\\s?\\:\\s?[ a-zA-Z\\-\\.]*\\s?/\\s?\\d{7}(v\\d+)?)"); // a regular expression for identifying url pattern in text // TODO: maybe find a better regex static public final Pattern urlPattern = Pattern .compile("(?i)(https?|ftp)\\s?:\\s?//\\s?[-A-Z0-9+&@#/%?=~_()|!:,.;]*[-A-Z0-9+&@#/%=~_()|]"); /** * Replace numbers in the string by a dummy character for string distance evaluations * * @param string the string to be processed. * @return Returns the string with numbers replaced by 'X'. */ public static String shadowNumbers(String string) { int i = 0; if (string == null) return string; String res = ""; while (i < string.length()) { char c = string.charAt(i); if (Character.isDigit(c)) res += 'X'; else res += c; i++; } return res; } private static int getLastPunctuationCharacter(String section) { int res = -1; for (int i = section.length() - 1; i >= 0; i--) { if (fullPunctuations.contains("" + section.charAt(i))) { res = i; } } return res; } public static List<LayoutToken> dehyphenize(List<LayoutToken> tokens) { List<LayoutToken> output = new ArrayList<>(); for (int i = 0; i < tokens.size(); i++) { LayoutToken currentToken = tokens.get(i); //the current token is dash checking what's around if (currentToken.getText().equals("-")) { if (doesRequireDehypenisation(tokens, i)) { //Cleanup eventual additional spaces before the hypen that have been already written to the output int z = output.size() - 1; while (z >= 0 && output.get(z).getText().equals(" ")) { String tokenString = output.get(z).getText(); if (tokenString.equals(" ")) { output.remove(z); } z--; } List<Integer> breakLines = new ArrayList<>(); List<Integer> spaces = new ArrayList<>(); int j = i + 1; while (j < tokens.size() && tokens.get(j).getText().equals(" ") || tokens.get(j).getText().equals("\n")) { String tokenString = tokens.get(j).getText(); if (tokenString.equals("\n")) { breakLines.add(j); } if (tokenString.equals(" ")) { spaces.add(j); } j++; } i += breakLines.size() + spaces.size(); } else { output.add(currentToken); List<Integer> breakLines = new ArrayList<>(); List<Integer> spaces = new ArrayList<>(); int j = i + 1; while (j < tokens.size() && tokens.get(j).getText().equals("\n")) { String tokenString = tokens.get(j).getText(); if (tokenString.equals("\n")) { breakLines.add(j); } j++; } i += breakLines.size() + spaces.size(); } } else { output.add(currentToken); } } return output; } /** * Check if the current token (place i), or the hypen, needs to be removed or not. * <p> * It will check the tokens before and after. It will get to the next "non space" tokens and verify * that it's a plain word. If it's not it's keeping the hypen. * <p> * TODO: add the check on the bounding box of the next token to see whether there is really a break line. * TODO: What to do in case of a punctuation is found? */ protected static boolean doesRequireDehypenisation(List<LayoutToken> tokens, int i) { boolean forward = false; boolean backward = false; int j = i + 1; int breakLine = 0; while (j < tokens.size() && (tokens.get(j).getText().equals(" ") || tokens.get(j).getText().equals("\n"))) { String tokenString = tokens.get(j).getText(); if (tokenString.equals("\n")) { breakLine++; } j++; } if (breakLine == 0) { return false; } Pattern onlyLowercaseLetters = Pattern.compile("[a-z]+"); if (j < tokens.size()) { Matcher matcher = onlyLowercaseLetters.matcher(tokens.get(j).getText()); if (matcher.find()) { forward = true; } if (forward) { if(i < 1) { //If nothing before the hypen, but it looks like a forward hypenisation, let's trust it return forward; } int z = i - 1; while (z > 0 && tokens.get(z).getText().equals(" ")) { z--; } Matcher backwardMatcher = Pattern.compile("^[A-Za-z]+$").matcher(tokens.get(z).getText()); if (backwardMatcher.find()) { backward = true; } } } return backward; } public static String dehyphenize(String text) { GrobidAnalyzer analyser = GrobidAnalyzer.getInstance(); final List<LayoutToken> layoutTokens = analyser.tokenizeWithLayoutToken(text); return LayoutTokensUtil.toText(dehyphenize(layoutTokens)); } public static String getLastToken(String section) { String lastToken = section; int lastSpaceIndex = section.lastIndexOf(' '); //The last parenthesis cover the case 'this is a (special-one) case' // where the lastToken before the hypen should be 'special' and not '(special' /* int lastParenthesisIndex = section.lastIndexOf('('); if (lastParenthesisIndex > lastSpaceIndex) lastSpaceIndex = lastParenthesisIndex;*/ if (lastSpaceIndex != -1) { lastToken = section.substring(lastSpaceIndex + 1, section.length()); } else { lastToken = section.substring(0, section.length()); } return lastToken; } public static String getFirstToken(String section) { int firstSpaceIndex = section.indexOf(' '); if (firstSpaceIndex == 0) { return getFirstToken(section.substring(1, section.length())); } else if (firstSpaceIndex != -1) { return section.substring(0, firstSpaceIndex); } else { return section.substring(0, section.length()); } } /** * Text extracted from a PDF is usually hyphenized, which is not desirable. * This version supposes that the end of line are lost and than hyphenation * could appear everywhere. So a dictionary is used to control the recognition * of hyphen. * * @param text the string to be processed without preserved end of lines. * @return Returns the dehyphenized string. * <p> * Deprecated method, not needed anymore since the @newline are preserved thanks to the LayoutTokens * Use dehypenize */ @Deprecated public static String dehyphenizeHard(String text) { if (text == null) return null; String res = ""; text.replaceAll("\n", SPACE); StringTokenizer st = new StringTokenizer(text, "-"); boolean hyphen = false; boolean failure = false; String lastToken = null; while (st.hasMoreTokens()) { String section = st.nextToken().trim(); if (hyphen) { // we get the first token StringTokenizer st2 = new StringTokenizer(section, " ,.);!"); if (st2.countTokens() > 0) { String firstToken = st2.nextToken(); // we check if the composed token is in the lexicon String hyphenToken = lastToken + firstToken; //System.out.println(hyphenToken); /*if (lex == null) featureFactory.loadLexicon();*/ Lexicon lex = Lexicon.getInstance(); if (lex.inDictionary(hyphenToken.toLowerCase()) & !(test_digit(hyphenToken))) { // if yes, it is hyphenization res += firstToken; section = section.substring(firstToken.length(), section.length()); } else { // if not res += "-"; failure = true; } } else { res += "-"; } hyphen = false; } // we get the last token hyphen = true; lastToken = getLastToken(section); if (failure) { res += section; failure = false; } else res += SPACE + section; } res = res.replace(" . ", ". "); res = res.replace(" ", SPACE); return res.trim(); } /** * Levenstein distance between two strings * * @param s the first string to be compared. * @param t the second string to be compared. * @return Returns the Levenshtein distance. */ public static int getLevenshteinDistance(String s, String t) { //if (s == null || t == null) { // throw new IllegalArgumentException("Strings must not be null"); //} int n = s.length(); // length of s int m = t.length(); // length of t if (n == 0) { return m; } else if (m == 0) { return n; } int p[] = new int[n + 1]; //'previous' cost array, horizontally int d[] = new int[n + 1]; // cost array, horizontally int _d[]; //placeholder to assist in swapping p and d // indexes into strings s and t int i; // iterates through s int j; // iterates through t char t_j; // jth character of t int cost; // cost for (i = 0; i <= n; i++) { p[i] = i; } for (j = 1; j <= m; j++) { t_j = t.charAt(j - 1); d[0] = j; for (i = 1; i <= n; i++) { cost = s.charAt(i - 1) == t_j ? 0 : 1; // minimum of cell to the left+1, to the top+1, diagonally left and up +cost d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); } // copy current distance counts to 'previous row' distance counts _d = p; p = d; d = _d; } // our last action in the above loop was to switch d and p, so p now // actually has the most recent cost counts return p[n]; } /** * Appending nb times the char c to the a StringBuffer... */ public final static void appendN(StringBuffer buffer, char c, int nb) { for (int i = 0; i < nb; i++) { buffer.append(c); } } /** * To replace accented characters in a unicode string by unaccented equivalents: * é -> e, ü -> ue, ß -> ss, etc. following the standard transcription conventions * * @param input the string to be processed. * @return Returns the string without accent. */ public final static String removeAccents(String input) { if (input == null) return null; final StringBuffer output = new StringBuffer(); for (int i = 0; i < input.length(); i++) { switch (input.charAt(i)) { case '\u00C0': // À case '\u00C1': // Á case '\u00C2': //  case '\u00C3': // à case '\u00C5': // Ã… output.append("A"); break; case '\u00C4': // Ä case '\u00C6': // Æ output.append("AE"); break; case '\u00C7': // Ç output.append("C"); break; case '\u00C8': // È case '\u00C9': // É case '\u00CA': // Ê case '\u00CB': // Ë output.append("E"); break; case '\u00CC': // ÃŒ case '\u00CD': // Í case '\u00CE': // ÃŽ case '\u00CF': // Ï output.append("I"); break; case '\u00D0': // Ð output.append("D"); break; case '\u00D1': // Ñ output.append("N"); break; case '\u00D2': // Ã’ case '\u00D3': // Ó case '\u00D4': // Ô case '\u00D5': // Õ case '\u00D8': // Ø output.append("O"); break; case '\u00D6': // Ö case '\u0152': // Å’ output.append("OE"); break; case '\u00DE': // Þ output.append("TH"); break; case '\u00D9': // Ù case '\u00DA': // Ú case '\u00DB': // Û output.append("U"); break; case '\u00DC': // Ü output.append("UE"); break; case '\u00DD': // Ý case '\u0178': // Ÿ output.append("Y"); break; case '\u00E0': // à case '\u00E1': // á case '\u00E2': // â case '\u00E3': // ã case '\u00E5': // Ã¥ output.append("a"); break; case '\u00E4': // ä case '\u00E6': // æ output.append("ae"); break; case '\u00E7': // ç output.append("c"); break; case '\u00E8': // è case '\u00E9': // é case '\u00EA': // ê case '\u00EB': // ë output.append("e"); break; case '\u00EC': // ì case '\u00ED': // à case '\u00EE': // î case '\u00EF': // ï output.append("i"); break; case '\u00F0': // ð output.append("d"); break; case '\u00F1': // ñ output.append("n"); break; case '\u00F2': // ò case '\u00F3': // ó case '\u00F4': // ô case '\u00F5': // õ case '\u00F8': // ø output.append("o"); break; case '\u00F6': // ö case '\u0153': // Å“ output.append("oe"); break; case '\u00DF': // ß output.append("ss"); break; case '\u00FE': // þ output.append("th"); break; case '\u00F9': // ù case '\u00FA': // ú case '\u00FB': // û output.append("u"); break; case '\u00FC': // ü output.append("ue"); break; case '\u00FD': // ý case '\u00FF': // ÿ output.append("y"); break; default: output.append(input.charAt(i)); break; } } return output.toString(); } // ad hoc stopword list for the cleanField method public final static List<String> stopwords = Arrays.asList("the", "of", "and", "du", "de le", "de la", "des", "der", "an", "und"); /** * Remove useless punctuation at the end and beginning of a metadata field. * <p/> * Still experimental ! Use with care ! */ public final static String cleanField(String input0, boolean applyStopwordsFilter) { if (input0 == null) { return null; } if (input0.length() == 0) { return null; } String input = input0.replace(",,", ","); input = input.replace(", ,", ","); int n = input.length(); // characters at the end for (int i = input.length() - 1; i > 0; i--) { char c = input.charAt(i); if ((c == ',') || (c == ' ') || (c == '.') || (c == '-') || (c == '_') || (c == '/') || //(c == ')') || //(c == '(') || (c == ':')) { n = i; } else if (c == ';') { // we have to check if we have an html entity finishing if (i - 3 >= 0) { char c0 = input.charAt(i - 3); if (c0 == '&') { break; } } if (i - 4 >= 0) { char c0 = input.charAt(i - 4); if (c0 == '&') { break; } } if (i - 5 >= 0) { char c0 = input.charAt(i - 5); if (c0 == '&') { break; } } if (i - 6 >= 0) { char c0 = input.charAt(i - 6); if (c0 == '&') { break; } } n = i; } else break; } input = input.substring(0, n); // characters at the begining n = 0; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if ((c == ',') || (c == ' ') || (c == '.') || (c == ';') || (c == '-') || (c == '_') || //(c == ')') || //(c == '(') || (c == ':')) { n = i; } else break; } input = input.substring(n, input.length()).trim(); if ((input.endsWith(")")) && (input.startsWith("("))) { input = input.substring(1, input.length() - 1).trim(); } if ((input.length() > 12) && (input.endsWith("&quot;")) && (input.startsWith("&quot;"))) { input = input.substring(6, input.length() - 6).trim(); } if (applyStopwordsFilter) { boolean stop = false; while (!stop) { stop = true; for (String word : stopwords) { if (input.endsWith(SPACE + word)) { input = input.substring(0, input.length() - word.length()).trim(); stop = false; break; } } } } return input.trim(); } /** * Segment piece of text following a list of segmentation characters. * "hello, world." -> [ "hello", ",", "world", "." ] * * @param input the string to be processed. * @param input the characters creating a segment (typically space and punctuations). * @return Returns the string without accent. */ public final static List<String> segment(String input, String segments) { if (input == null) return null; ArrayList<String> result = new ArrayList<String>(); String token = null; String seg = " \n\t"; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); int ind = seg.indexOf(c); if (ind != -1) { if (token != null) { result.add(token); token = null; } } else { int ind2 = segments.indexOf(c); if (ind2 == -1) { if (token == null) token = "" + c; else token += c; } else { if (token != null) { result.add(token); token = null; } result.add("" + segments.charAt(ind2)); } } } if (token != null) result.add(token); return result; } /** * Encode a string to be displayed in HTML * <p/> * If fullHTML encode, then all unicode characters above 7 bits are converted into * HTML entitites */ public static String HTMLEncode(String string) { return HTMLEncode(string, false); } public static String HTMLEncode(String string, boolean fullHTML) { if (string == null) return null; if (string.length() == 0) return string; //string = string.replace("@BULLET", "•"); StringBuffer sb = new StringBuffer(string.length()); // true if last char was blank boolean lastWasBlankChar = false; int len = string.length(); char c; for (int i = 0; i < len; i++) { c = string.charAt(i); if (c == ' ') { // blank gets extra work, // this solves the problem you get if you replace all // blanks with &nbsp;, if you do that you loss // word breaking if (lastWasBlankChar) { lastWasBlankChar = false; //sb.append("&nbsp;"); } else { lastWasBlankChar = true; sb.append(' '); } } else { lastWasBlankChar = false; // // HTML Special Chars if (c == '"') sb.append("&quot;"); else if (c == '\'') sb.append("&apos;"); else if (c == '&') { boolean skip = false; // we don't want to recode an existing hmlt entity if (string.length() > i + 3) { char c2 = string.charAt(i + 1); char c3 = string.charAt(i + 2); char c4 = string.charAt(i + 3); if (c2 == 'a') { if (c3 == 'm') { if (c4 == 'p') { if (string.length() > i + 4) { char c5 = string.charAt(i + 4); if (c5 == ';') { skip = true; } } } } } else if (c2 == 'q') { if (c3 == 'u') { if (c4 == 'o') { if (string.length() > i + 5) { char c5 = string.charAt(i + 4); char c6 = string.charAt(i + 5); if (c5 == 't') { if (c6 == ';') { skip = true; } } } } } } else if (c2 == 'l' || c2 == 'g') { if (c3 == 't') { if (c4 == ';') { skip = true; } } } } if (!skip) { sb.append("&amp;"); } else { sb.append("&"); } } else if (c == '<') sb.append("&lt;"); else if (c == '>') sb.append("&gt;"); /*else if (c == '\n') { // warning: this can be too much html! sb.append("&lt;br/&gt;"); }*/ else { int ci = 0xffff & c; if (ci < 160) { // nothing special only 7 Bit sb.append(c); } else { if (fullHTML) { // Not 7 Bit use the unicode system sb.append("&#"); sb.append(Integer.valueOf(ci).toString()); sb.append(';'); } else sb.append(c); } } } } return sb.toString(); } public static String normalizeRegex(String string) { string = string.replace("&", "\\\\&"); string = string.replace("&", "\\\\&"); string = string.replace("+", "\\\\+"); return string; } /* * To convert the InputStream to String we use the BufferedReader.readLine() * method. We iterate until the BufferedReader return null which means * there's no more data to read. Each line will appended to a StringBuilder * and returned as String. */ static public String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { // e.printStackTrace(); throw new GrobidException("An exception occured while running Grobid.", e); } finally { try { is.close(); } catch (IOException e) { // e.printStackTrace(); throw new GrobidException("An exception occured while running Grobid.", e); } } return sb.toString(); } /** * Count the number of digit in a given string. * * @param text the string to be processed. * @return Returns the number of digit chracaters in the string... */ static public int countDigit(String text) { int count = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (Character.isDigit(c)) count++; } return count; } /** * Map special ligature and characters coming from the pdf */ static public String clean(String token) { if (token == null) return null; if (token.length() == 0) return token; String res = ""; int i = 0; while (i < token.length()) { switch (token.charAt(i)) { // ligature case '\uFB00': { res += "ff"; break; } case '\uFB01': { res += "fi"; break; } case '\uFB02': { res += "fl"; break; } case '\uFB03': { res += "ffi"; break; } case '\uFB04': { res += "ffl"; break; } case '\uFB06': { res += "st"; break; } case '\uFB05': { res += "ft"; break; } case '\u00E6': { res += "ae"; break; } case '\u00C6': { res += "AE"; break; } case '\u0153': { res += "oe"; break; } case '\u0152': { res += "OE"; break; } // quote case '\u201C': { res += "\""; break; } case '\u201D': { res += "\""; break; } case '\u201E': { res += "\""; break; } case '\u201F': { res += "\""; break; } case '\u2019': { res += "'"; break; } case '\u2018': { res += "'"; break; } // bullet uniformity case '\u2022': { res += "•"; break; } case '\u2023': { res += "•"; break; } case '\u2043': { res += "•"; break; } case '\u204C': { res += "•"; break; } case '\u204D': { res += "•"; break; } case '\u2219': { res += "•"; break; } case '\u25C9': { res += "•"; break; } case '\u25D8': { res += "•"; break; } case '\u25E6': { res += "•"; break; } case '\u2619': { res += "•"; break; } case '\u2765': { res += "•"; break; } case '\u2767': { res += "•"; break; } case '\u29BE': { res += "•"; break; } case '\u29BF': { res += "•"; break; } // asterix case '\u2217': { res += " * "; break; } // typical author/affiliation markers case '\u2020': { res += SPACE + '\u2020'; break; } case '\u2021': { res += SPACE + '\u2021'; break; } case '\u00A7': { res += SPACE + '\u00A7'; break; } case '\u00B6': { res += SPACE + '\u00B6'; break; } case '\u204B': { res += SPACE + '\u204B'; break; } case '\u01C2': { res += SPACE + '\u01C2'; break; } // default default: { res += token.charAt(i); break; } } i++; } return res; } public static String formatTwoDecimals(double d) { NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); DecimalFormat df = (DecimalFormat) nf; df.applyPattern("#.##"); return df.format(d); } public static String formatFourDecimals(double d) { NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); DecimalFormat df = (DecimalFormat) nf; df.applyPattern("#.####"); return df.format(d); } public static boolean isAllUpperCase(String text) { for (int i = 0; i < text.length(); i++) { if (!Character.isUpperCase(text.charAt(i))) { return false; } } return true; } public static boolean isAllLowerCase(String text) { for (int i = 0; i < text.length(); i++) { if (!Character.isLowerCase(text.charAt(i))) { return false; } } return true; } public static List<String> generateEmailVariants(String firstName, String lastName) { // current heuristics: // "First Last" // "First L" // "F Last" // "First" // "Last" // "Last First" // "Last F" List<String> variants = new ArrayList<String>(); if (lastName != null) { variants.add(lastName); if (firstName != null) { variants.add(firstName + SPACE + lastName); variants.add(lastName + SPACE + firstName); if (firstName.length() > 1) { String firstInitial = firstName.substring(0, 1); variants.add(firstInitial + SPACE + lastName); variants.add(lastName + SPACE + firstInitial); } if (lastName.length() > 1) { String lastInitial = lastName.substring(0, 1); variants.add(firstName + SPACE + lastInitial); } } } else { if (firstName != null) { variants.add(firstName); } } return variants; } /** * This is a re-implementation of the capitalizeFully of Apache commons lang, because it appears not working * properly. * <p/> * Convert a string so that each word is made up of a titlecase character and then a series of lowercase * characters. Words are defined as token delimited by one of the character in delimiters or the begining * of the string. */ public static String capitalizeFully(String input, String delimiters) { if (input == null) { return null; } //input = input.toLowerCase(); String output = ""; boolean toUpper = true; for (int c = 0; c < input.length(); c++) { char ch = input.charAt(c); if (delimiters.indexOf(ch) != -1) { toUpper = true; output += ch; } else { if (toUpper == true) { output += Character.toUpperCase(ch); toUpper = false; } else { output += Character.toLowerCase(ch); } } } return output; } public static String wordShape(String word) { StringBuilder shape = new StringBuilder(); for (char c : word.toCharArray()) { if (Character.isLetter(c)) { if (Character.isUpperCase(c)) { shape.append("X"); } else { shape.append("x"); } } else if (Character.isDigit(c)) { shape.append("d"); } else { shape.append(c); } } StringBuilder finalShape = new StringBuilder().append(shape.charAt(0)); String suffix = ""; if (word.length() > 2) { suffix = shape.substring(shape.length() - 2); } else if (word.length() > 1) { suffix = shape.substring(shape.length() - 1); } StringBuilder middle = new StringBuilder(); if (shape.length() > 3) { char ch = shape.charAt(1); for (int i = 1; i < shape.length() - 2; i++) { middle.append(ch); while (ch == shape.charAt(i) && i < shape.length() - 2) { i++; } ch = shape.charAt(i); } if (ch != middle.charAt(middle.length() - 1)) { middle.append(ch); } } return finalShape.append(middle).append(suffix).toString(); } public static String wordShapeTrimmed(String word) { StringBuilder shape = new StringBuilder(); for (char c : word.toCharArray()) { if (Character.isLetter(c)) { if (Character.isUpperCase(c)) { shape.append("X"); } else { shape.append("x"); } } else if (Character.isDigit(c)) { shape.append("d"); } else { shape.append(c); } } StringBuilder middle = new StringBuilder(); char ch = shape.charAt(0); for (int i = 0; i < shape.length(); i++) { middle.append(ch); while (ch == shape.charAt(i) && i < shape.length() - 1) { i++; } ch = shape.charAt(i); } if (ch != middle.charAt(middle.length() - 1)) { middle.append(ch); } return middle.toString(); } /** * Give the punctuation profile of a line, i.e. the concatenation of all the punctuations * occuring in the line. * * @param line the string corresponding to a line * @return the punctuation profile as a string, empty string is no punctuation * @throws Exception */ public static String punctuationProfile(String line) { String profile = ""; if ((line == null) || (line.length() == 0)) { return profile; } for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c == ' ') { continue; } if (fullPunctuations.indexOf(c) != -1) profile += c; } return profile; } /** * Return the number of token in a line given an existing global tokenization and a current * start position of the line in this global tokenization. * * @param line the string corresponding to a line * @param currentLinePos position of the line in the tokenization * @param tokenization the global tokenization where the line appears * @return the punctuation profile as a string, empty string is no punctuation * @throws Exception */ public static int getNbTokens(String line, int currentLinePos, List<String> tokenization) throws Exception { if ((line == null) || (line.length() == 0)) return 0; String currentToken = tokenization.get(currentLinePos); while ((currentLinePos < tokenization.size()) && (currentToken.equals(" ") || currentToken.equals("\n"))) { currentLinePos++; currentToken = tokenization.get(currentLinePos); } if (!line.trim().startsWith(currentToken)) { System.out.println("out of sync. : " + currentToken); throw new IllegalArgumentException("line start does not match given tokenization start"); } int nbTokens = 0; int posMatch = 0; // current position in line for (int p = currentLinePos; p < tokenization.size(); p++) { currentToken = tokenization.get(p); posMatch = line.indexOf(currentToken, posMatch); if (posMatch == -1) break; nbTokens++; } return nbTokens; } /** * Ensure that special XML characters are correctly encoded. */ public static String trimEncodedCharaters(String string) { return string.replaceAll("&amp\\s+;", "&amp;"). replaceAll("&quot\\s+;|&amp;quot\\s*;", "&quot;"). replaceAll("&lt\\s+;|&amp;lt\\s*;", "&lt;"). replaceAll("&gt\\s+;|&amp;gt\\s*;", "&gt;"). replaceAll("&apos\\s+;|&amp;apos\\s*;", "&apos;"); } public static boolean filterLine(String line) { boolean filter = false; if ((line == null) || (line.length() == 0)) filter = true; else if (line.contains("@IMAGE") || line.contains("@PAGE")) { filter = true; } else if (line.contains(".pbm") || line.contains(".ppm") || line.contains(".svg") || line.contains(".jpg") || line.contains(".png")) { filter = true; } return filter; } /** * The equivalent of String.replaceAll() for StringBuilder */ public static StringBuilder replaceAll(StringBuilder sb, String regex, String replacement) { Pattern pattern = Pattern.compile(regex); Matcher m = pattern.matcher(sb); int start = 0; while (m.find(start)) { sb.replace(m.start(), m.end(), replacement); start = m.start() + replacement.length(); } return sb; } /** * Return the prefix of a string. */ public static String prefix(String s, int count) { if (s == null) { return null; } if (s.length() < count) { return s; } return s.substring(0, count); } /** * Return the suffix of a string. */ public static String suffix(String s, int count) { if (s == null) { return null; } if (s.length() < count) { return s; } return s.substring(s.length() - count); } public static String JSONEncode(String json) { // we assume all json string will be bounded by double quotes return json.replaceAll("\"", "\\\"").replaceAll("\n", "\\\n"); } public static String strrep(char c, int times) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(c); } return builder.toString(); } public static int getOccCount(String term, String string) { return StringUtils.countMatches(term, string); } /** * Test for the current string contains at least one digit. * * @param tok the string to be processed. * @return true if contains a digit */ public static boolean test_digit(String tok) { if (tok == null) return false; if (tok.length() == 0) return false; char a; for (int i = 0; i < tok.length(); i++) { a = tok.charAt(i); if (Character.isDigit(a)) return true; } return false; } /** * Useful for recognising an acronym candidate: check if a text is only * composed of upper case, dot and digit characters */ public static boolean isAllUpperCaseOrDigitOrDot(String text) { for (int i = 0; i < text.length(); i++) { final char charAt = text.charAt(i); if (!Character.isUpperCase(charAt) && !Character.isDigit(charAt) && charAt != '.') { return false; } } return true; } }
alexduch/grobid
grobid-core/src/main/java/org/grobid/core/utilities/TextUtilities.java
Java
apache-2.0
47,103
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Sandbox.Game.Entities.Cube; using Sandbox.ModAPI; using Sandbox.ModAPI.Interfaces; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NLog; using Sandbox.ModAPI.Interfaces.Terminal; namespace Torch.Server.ViewModels.Blocks { public static class BlockViewModelGenerator { private static Dictionary<Type, Type> _cache = new Dictionary<Type, Type>(); private static AssemblyName _asmName; private static ModuleBuilder _mb; private static AssemblyBuilder _ab; private static Logger _log = LogManager.GetLogger("Generator"); static BlockViewModelGenerator() { _asmName = new AssemblyName("Torch.Server.ViewModels.Generated"); _ab = AppDomain.CurrentDomain.DefineDynamicAssembly(_asmName, AssemblyBuilderAccess.RunAndSave); _mb = _ab.DefineDynamicModule(_asmName.Name); } public static void GenerateModels() { foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic)) { foreach (var type in assembly.ExportedTypes.Where(t => t.IsSubclassOf(typeof(MyTerminalBlock)))) { GenerateModel(type); } } _ab.Save("Generated.dll", PortableExecutableKinds.ILOnly, ImageFileMachine.AMD64); } public static Type GenerateModel(Type blockType, bool force = false) { if (_cache.ContainsKey(blockType) && !force) return _cache[blockType]; var propertyList = new List<ITerminalProperty>(); MyTerminalControlFactoryHelper.Static.GetProperties(blockType, propertyList); var getPropertyMethod = blockType.GetMethod("GetProperty", new[] {typeof(string)}); var getValueMethod = typeof(ITerminalProperty<>).GetMethod("GetValue"); var setValueMethod = typeof(ITerminalProperty<>).GetMethod("SetValue"); var tb = _mb.DefineType($"{_asmName.Name}.{blockType.Name}ViewModel", TypeAttributes.Class | TypeAttributes.Public); var blockField = tb.DefineField("_block", blockType, FieldAttributes.Private); var ctor = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] {blockType}); var ctorIl = ctor.GetILGenerator(); ctorIl.Emit(OpCodes.Ldarg_0); ctorIl.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)); ctorIl.Emit(OpCodes.Ldarg_0); ctorIl.Emit(OpCodes.Ldarg_1); ctorIl.Emit(OpCodes.Stfld, blockField); ctorIl.Emit(OpCodes.Ret); for (var i = 0; i < propertyList.Count; i++) { var prop = propertyList[i]; var propType = prop.GetType(); Type propGenericArg = null; foreach (var iface in propType.GetInterfaces()) { if (iface.IsGenericType && iface.GetGenericTypeDefinition() == typeof(ITerminalProperty<>)) propGenericArg = iface.GenericTypeArguments[0]; } if (propGenericArg == null) { _log.Error($"Property {prop.Id} does not implement {typeof(ITerminalProperty<>).Name}"); return null; } _log.Info($"GENERIC ARG: {propGenericArg.Name}"); var pb = tb.DefineProperty($"{prop.Id}", PropertyAttributes.HasDefault, propGenericArg, null); var getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig; var getter = tb.DefineMethod($"get_{prop.Id}", getSetAttr, propGenericArg, Type.EmptyTypes); { var getterIl = getter.GetILGenerator(); var propLoc = getterIl.DeclareLocal(propType); getterIl.Emit(OpCodes.Ldarg_0); getterIl.Emit(OpCodes.Ldfld, blockField); getterIl.Emit(OpCodes.Ldstr, prop.Id); getterIl.EmitCall(OpCodes.Callvirt, getPropertyMethod, null); getterIl.Emit(OpCodes.Stloc, propLoc); getterIl.Emit(OpCodes.Ldloc, propLoc); getterIl.Emit(OpCodes.Ldarg_0); getterIl.Emit(OpCodes.Ldfld, blockField); getterIl.EmitCall(OpCodes.Callvirt, getValueMethod, null); getterIl.Emit(OpCodes.Ret); pb.SetGetMethod(getter); } var setter = tb.DefineMethod($"set_{prop.Id}", getSetAttr, null, Type.EmptyTypes); { var setterIl = setter.GetILGenerator(); var propLoc = setterIl.DeclareLocal(propType); setterIl.Emit(OpCodes.Ldarg_0); setterIl.Emit(OpCodes.Stfld, blockField); setterIl.EmitCall(OpCodes.Callvirt, getPropertyMethod, null); setterIl.Emit(OpCodes.Stloc, propLoc); setterIl.Emit(OpCodes.Ldarg_1); setterIl.Emit(OpCodes.Ldarg_0); setterIl.Emit(OpCodes.Ldfld, blockField); setterIl.EmitCall(OpCodes.Callvirt, setValueMethod, null); setterIl.Emit(OpCodes.Ret); pb.SetSetMethod(setter); } } var vmType = tb.CreateType(); _cache.Add(blockType, vmType); return vmType; } } }
TorchAPI/Torch
Torch.Server/ViewModels/Entities/Blocks/BlockViewModelGenerator.cs
C#
apache-2.0
5,844
# A basic web server using sockets import socket PORT = 8090 MAX_OPEN_REQUESTS = 5 def process_client(clientsocket): print(clientsocket) data = clientsocket.recv(1024) print(data) web_contents = "<h1>Received</h1>" f = open("myhtml.html", "r") web_contents = f.read() f.close() web_headers = "HTTP/1.1 200" web_headers += "\n" + "Content-Type: text/html" web_headers += "\n" + "Content-Length: %i" % len(str.encode(web_contents)) clientsocket.send(str.encode(web_headers + "\n\n" + web_contents)) clientsocket.close() # create an INET, STREAMing socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the socket to a public host, and a well-known port hostname = socket.gethostname() ip = socket.gethostbyname(hostname) # Let's use better the local interface name hostname = "10.10.104.17" try: serversocket.bind((ip, PORT)) # become a server socket # MAX_OPEN_REQUESTS connect requests before refusing outside connections serversocket.listen(MAX_OPEN_REQUESTS) while True: # accept connections from outside print ("Waiting for connections at %s %i" % (hostname, PORT)) (clientsocket, address) = serversocket.accept() # now do something with the clientsocket # in this case, we'll pretend this is a non threaded server process_client(clientsocket) except socket.error: print("Problemas using port %i. Do you have permission?" % PORT)
acs-test/openfda
PER_2017-18/clientServer/P1/server_web.py
Python
apache-2.0
1,505
// // System.IO.BufferedStream // // Author: // Matt Kimball (matt@kimball.net) // Ville Palo <vi64pa@kolumbus.fi> // // Copyright (C) 2004 Novell (http://www.novell.com) // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Globalization; using System.Runtime.InteropServices; namespace System.IO { [ComVisible (true)] public sealed class BufferedStream : Stream { Stream m_stream; byte[] m_buffer; int m_buffer_pos; int m_buffer_read_ahead; bool m_buffer_reading; private bool disposed = false; public BufferedStream (Stream stream) : this (stream, 4096) { } public BufferedStream (Stream stream, int bufferSize) { if (stream == null) throw new ArgumentNullException ("stream"); // LAMESPEC: documented as < 0 if (bufferSize <= 0) throw new ArgumentOutOfRangeException ("bufferSize", "<= 0"); if (!stream.CanRead && !stream.CanWrite) { throw new ObjectDisposedException ("Cannot access a closed Stream."); } m_stream = stream; m_buffer = new byte [bufferSize]; } public override bool CanRead { get { return m_stream.CanRead; } } public override bool CanWrite { get { return m_stream.CanWrite; } } public override bool CanSeek { get { return m_stream.CanSeek; } } public override long Length { get { Flush (); return m_stream.Length; } } public override bool CanTimeout { get { return m_stream.CanTimeout; } } public override int ReadTimeout { get { return m_stream.ReadTimeout; } set { m_stream.ReadTimeout = value; } } public override int WriteTimeout { get { return m_stream.WriteTimeout; } set { m_stream.WriteTimeout = value; } } public override long Position { get { CheckObjectDisposedException (); return m_stream.Position - m_buffer_read_ahead + m_buffer_pos; } set { if (value < Position && (Position - value <= m_buffer_pos) && m_buffer_reading) { m_buffer_pos -= (int) (Position - value); } else if (value > Position && (value - Position < m_buffer_read_ahead - m_buffer_pos) && m_buffer_reading) { m_buffer_pos += (int) (value - Position); } else { Flush(); m_stream.Position = value; } } } protected override void Dispose (bool disposing) { if (disposed) return; if (m_buffer != null) Flush(); m_stream.Close(); m_buffer = null; disposed = true; } public override void Flush () { CheckObjectDisposedException (); if (m_buffer_reading) { if (CanSeek) m_stream.Position = Position; } else if (m_buffer_pos > 0) { m_stream.Write(m_buffer, 0, m_buffer_pos); } m_buffer_read_ahead = 0; m_buffer_pos = 0; } public override long Seek (long offset, SeekOrigin origin) { CheckObjectDisposedException (); if (!CanSeek) { throw new NotSupportedException ("Non seekable stream."); } Flush (); return m_stream.Seek (offset, origin); } public override void SetLength (long value) { CheckObjectDisposedException (); if (value < 0) throw new ArgumentOutOfRangeException ("value must be positive"); if (!m_stream.CanWrite && !m_stream.CanSeek) throw new NotSupportedException ("the stream cannot seek nor write."); if ((m_stream == null) || (!m_stream.CanRead && !m_stream.CanWrite)) throw new IOException ("the stream is not open"); m_stream.SetLength(value); if (Position > value) Position = value; } public override int ReadByte () { CheckObjectDisposedException (); if (!m_stream.CanRead) { throw new NotSupportedException("Cannot read from stream"); } if (!m_buffer_reading) { Flush (); m_buffer_reading = true; } if (1 <= m_buffer_read_ahead - m_buffer_pos) { return m_buffer [m_buffer_pos++]; } else { if (m_buffer_pos >= m_buffer_read_ahead) { m_buffer_pos = 0; m_buffer_read_ahead = 0; } m_buffer_read_ahead = m_stream.Read (m_buffer, 0, m_buffer.Length); if (1 <= m_buffer_read_ahead) { return m_buffer [m_buffer_pos++]; } else { return -1; } } } public override void WriteByte (byte value) { CheckObjectDisposedException (); if (!m_stream.CanWrite) { throw new NotSupportedException ("Cannot write to stream"); } if (m_buffer_reading) { Flush (); m_buffer_reading = false; } else // reordered to avoid possible integer overflow if (m_buffer_pos >= m_buffer.Length - 1) { Flush (); } m_buffer [m_buffer_pos++] = value; } public override int Read ([In,Out] byte[] array, int offset, int count) { if (array == null) throw new ArgumentNullException ("array"); CheckObjectDisposedException (); if (!m_stream.CanRead) { throw new NotSupportedException ("Cannot read from stream"); } if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "< 0"); // re-ordered to avoid possible integer overflow if (array.Length - offset < count) throw new ArgumentException ("array.Length - offset < count"); if (!m_buffer_reading) { Flush(); m_buffer_reading = true; } if (count <= m_buffer_read_ahead - m_buffer_pos) { Buffer.BlockCopy (m_buffer, m_buffer_pos, array, offset, count); m_buffer_pos += count; if (m_buffer_pos == m_buffer_read_ahead) { m_buffer_pos = 0; m_buffer_read_ahead = 0; } return count; } int ret = m_buffer_read_ahead - m_buffer_pos; Buffer.BlockCopy (m_buffer, m_buffer_pos, array, offset, ret); m_buffer_pos = 0; m_buffer_read_ahead = 0; offset += ret; count -= ret; if (count >= m_buffer.Length) { ret += m_stream.Read (array, offset, count); } else { m_buffer_read_ahead = m_stream.Read (m_buffer, 0, m_buffer.Length); if (count < m_buffer_read_ahead) { Buffer.BlockCopy (m_buffer, 0, array, offset, count); m_buffer_pos = count; ret += count; } else { Buffer.BlockCopy (m_buffer, 0, array, offset, m_buffer_read_ahead); ret += m_buffer_read_ahead; m_buffer_read_ahead = 0; } } return ret; } public override void Write (byte[] array, int offset, int count) { if (array == null) throw new ArgumentNullException ("array"); CheckObjectDisposedException (); if (!m_stream.CanWrite) { throw new NotSupportedException ("Cannot write to stream"); } if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "< 0"); // avoid possible integer overflow if (array.Length - offset < count) throw new ArgumentException ("array.Length - offset < count"); if (m_buffer_reading) { Flush(); m_buffer_reading = false; } // reordered to avoid possible integer overflow if (m_buffer_pos >= m_buffer.Length - count) { Flush (); m_stream.Write (array, offset, count); } else { Buffer.BlockCopy (array, offset, m_buffer, m_buffer_pos, count); m_buffer_pos += count; } } private void CheckObjectDisposedException () { if (disposed) { throw new ObjectDisposedException ("BufferedStream", "Stream is closed"); } } } }
dot42/api
System/IO/BufferedStream.cs
C#
apache-2.0
8,437
(function () { 'use strict'; angular.module('app.bankmaintenance').run(appRun); /* @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return [ { state: 'app.listBanks', config: { url: '/listBanks', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/profiles/ListBanks.html', controller: 'ControllerListBanks as vm' } } } }, { state: 'app.addBank', config: { url: '/addBank', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/profiles/BankDetail.html', controller: 'ControllerAddBank as vm' } } } }, { state: 'app.viewBank', config: { url: '/viewBank', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/profiles/BankDetail.html', controller: 'ControllerViewBank as vm', } }, params: { rid: true }, resolve: { organizationDetails: getBankDetailsResolve } } }, { state: 'app.editBank', config: { url: '/editBank', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/profiles/BankDetail.html', controller: 'ControllerEditBank as vm', } }, params: { rid: true }, resolve: { organizationDetails: getBankDetailsResolve } } }, { state: 'app.listBanksForSelection', config: { url: '/listBanksForSelection', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/listBanksForSelection.html', controller: 'ControllerListBanksForSelection as vm' } }, params : { targetUIState: null } } }, { state: 'app.listBankUsers', config: { url: '/listBankUsers', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userprofiles/listBankUsers.html', controller: 'ControllerListBankUsers as vm' } }, params : { selectedOrgId: null } } }, { state: 'app.addBankUser', config: { url: '/addBankUser', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userprofiles/BankUserDetail.html', controller: 'ControllerAddBankUser as vm' } }, params : { selectedOrgId: null } } }, { state: 'app.viewBankUser', config: { url: '/viewBankUser', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userprofiles/BankUserDetail.html', controller: 'ControllerViewBankUser as vm', } }, params: { rid: true }, resolve: { userDetails: getBankUserDetailsResolve } } }, { state: 'app.editBankUser', config: { url: '/editBankUser', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userprofiles/BankUserDetail.html', controller: 'ControllerEditBankUser as vm', } }, params: { rid: true }, resolve: { userDetails: getBankUserDetailsResolve } } }, { state: 'app.listBankPermissions', config: { url: '/listBankPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/permissions/listBankPermissions.html', controller: 'ControllerListBankPermissions as vm' } } } }, { state: 'app.editBankPermissions', config: { url: '/editBankPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/permissions/BankPermissionsDetail.html', controller: 'ControllerEditBankPermissions as vm', } }, params: { orgId: true }, resolve: { organizationRoles: getOrganizationRolesResolve } } }, { state: 'app.viewBankPermissions', config: { url: '/viewBankPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/permissions/BankPermissionsDetail.html', controller: 'ControllerViewBankPermissions as vm', } }, params: { orgId: true }, resolve: { organizationRoles: getOrganizationRolesResolve } } }, //BANK USER PERMISSION ROUTING { state: 'app.listBankUsersPermissions', config: { url: '/listBankUsersPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userpermissions/ListBankUsersPermissions.html', controller: 'ControllerListBankUsersPermissions as vm' } }, params : { selectedOrgId: null } } }, { state: 'app.editBankUserPermissions', config: { url: '/editBankUserPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userpermissions/BankUserPermissionsDetail.html', controller: 'ControllerEditBankUserPermissions as vm', } }, params: { userId: true }, resolve: { userRoles: getBankUserRolesResolve } } }, { state: 'app.viewBankUserPermissions', config: { url: '/viewBankUserPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userpermissions/BankUserPermissionsDetail.html', controller: 'ControllerViewBankUserPermissions as vm', } }, params: { userId: true }, resolve: { userRoles: getBankUserRolesResolve } } } ]; } function getBankUserDetailsResolve(UserService, $stateParams) { 'ngInject'; return UserService.getUserDetails($stateParams.rid); } function getBankDetailsResolve(OrganizationService, $stateParams) { 'ngInject'; return OrganizationService.getOrganizationDetails($stateParams.rid); } function getOrganizationRolesResolve(OrganizationRoleService, $stateParams) { 'ngInject'; return OrganizationRoleService.getOrganizationRoles($stateParams.orgId); } function getBankUserRolesResolve(UserRoleService, $stateParams) { 'ngInject'; return UserRoleService.getUserRoles($stateParams.userId); } })();
blessonkavala/cp
cashportal/src/main/resources/static/app/modules/bankmaintenance/bankmaintenance.route.js
JavaScript
apache-2.0
9,943
package com.github.xiaofei_dev.suspensionnotification.util.bean; public class HomeData { private boolean isClickHome; private boolean isClickMenu; public boolean isClickHome() { return isClickHome; } public void setClickHome(boolean clickHome) { isClickHome = clickHome; } public boolean isClickMenu() { return isClickMenu; } public void setClickMenu(boolean clickMenu) { isClickMenu = clickMenu; } }
xiaofei-dev/SuspendNotification
app/src/main/java/com/github/xiaofei_dev/suspensionnotification/util/bean/HomeData.java
Java
apache-2.0
480
/* * Copyright (C) 2018 Nagisa Sekiguchi * * 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 "json.h" // helper macro definition. #define RET(k) \ do { \ kind = JSONTokenKind::k; \ goto END; \ } while (false) #define REACH_EOS() \ do { \ if (this->isEnd()) { \ goto EOS; \ } else { \ ERROR(); \ } \ } while (false) #define UPDATE_LN() this->updateNewline(startPos) #define SKIP() goto INIT #define ERROR() \ do { \ RET(INVALID); \ } while (false) namespace ydsh::json { JSONTokenKind JSONLexer::nextToken(Token &token) { /*!re2c re2c:define:YYCTYPE = "unsigned char"; re2c:define:YYCURSOR = this->cursor; re2c:define:YYLIMIT = this->limit; re2c:define:YYMARKER = this->marker; re2c:define:YYCTXMARKER = this->ctxMarker; re2c:define:YYFILL:naked = 1; re2c:define:YYFILL@len = #; re2c:define:YYFILL = "if(!this->fill(#)) { REACH_EOS(); }"; re2c:yyfill:enable = 0; re2c:indent:top = 1; re2c:indent:string = " "; INT = "0" | [1-9] [0-9]*; FRAC = "." [0-9]+; EXP = [eE] [+-] [0-9]+; UNESCAPED = [\x20\x21\x23-\x5B\x5D-\U0010FFFF]; HEX = [0-9a-fA-F]; CHAR = UNESCAPED | "\\" ( ["\\/bfnrt] | "u" HEX{4} ); */ INIT: unsigned int startPos = this->getPos(); JSONTokenKind kind = JSONTokenKind::INVALID; /*!re2c "true" { RET(TRUE); } "false" { RET(FALSE); } "null" { RET(NIL); } "-"? INT FRAC? EXP? { RET(NUMBER); } ["] CHAR* ["] { RET(STRING); } "[" { RET(ARRAY_OPEN); } "]" { RET(ARRAY_CLOSE); } "{" { RET(OBJECT_OPEN); } "}" { RET(OBJECT_CLOSE); } "," { RET(COMMA); } ":" { RET(COLON); } [ \t\r\n]+ { UPDATE_LN(); SKIP(); } "\000" { REACH_EOS(); } * { RET(INVALID); } */ END: token.pos = startPos; token.size = this->getPos() - startPos; return kind; EOS: token.pos = this->getUsedSize(); token.size = 0; this->cursor--; return JSONTokenKind::EOS; } } // namespace ydsh::json
sekiguchi-nagisa/ydsh
tools/json/lexer.re2c.cpp
C++
apache-2.0
3,899
<?php require 'connect_database.php'; echo " you are in ajex checking "; if(isset($_POST["firstname"]) && $_POST["firstname"] != ""){ $username =$_POST['firstname']; echo " you are in ajex checking 2 "; if (strlen($username) < 4 ) { echo 'Too short(4-15)'; exit(); } else if(strlen($username) > 15){ echo 'Too long(4-15)'; exit(); } else if (is_numeric($username[0])) { echo 'First character must be a letter'; exit(); } else { echo '<strong>' . $username . '</strong> is OK'; exit(); } } if(isset($_POST["email"]) && $_POST["email"] != ""){ $username =$_POST['email']; $sql_uname_check = mysql_query("SELECT email FROM usr_data where email='$username'"); $uname_check = mysql_num_rows($sql_uname_check); if (is_numeric($username[0])) { echo 'First character must be a letter'; exit(); } else if (!preg_match("/.[@]/", $username)){ echo 'Not a valid email'; exit(); } else if (mysql_num_rows($sql_uname_check) < 1) { echo '<strong>' . $username . '</strong> is OK'; exit(); } else { echo '<strong>' . $username . '</strong> Already Exist'; exit(); } } if(isset($_POST["password"]) && $_POST["password"] != ""){ $username =$_POST['password']; if (strlen($username) < 6 ) { echo 'Too short (minimum 6 character)'; exit(); } else if (!preg_match("/[0-9]/", $username)){ echo 'Must contain a number'; exit(); } else if (!preg_match("/.[!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]/", $username)){ echo 'Must contain a special character'; exit(); } else { echo 'ok'; exit(); } } if(isset($_POST["confirmpassword"]) && $_POST["confirmpassword"] != ""){ $confirmpassword=$_POST['confirmpassword']; echo "Matched"; } ?>
siddimania/LebroDenken.com
public_html/simplified/php/ajaxchecking.php
PHP
apache-2.0
2,360
var extend = require('node.extend'); var PersistentCollection = require('./persistent-collection'); var preference = require('../model/preference'); var preferences = extend(true, {}, new PersistentCollection(), function() { "use strict"; return { collectionName: 'preferences', fieldDefinition: preference }; }()); module.exports = preferences;
stamp-web/stamp-webservices
app/services/preferences.js
JavaScript
apache-2.0
376
# -*- coding: utf-8 -*- # Copyright 2022 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 # # 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 .inventory import ( GetInventoryRequest, Inventory, ListInventoriesRequest, ListInventoriesResponse, InventoryView, ) from .os_policy import OSPolicy from .os_policy_assignment_reports import ( GetOSPolicyAssignmentReportRequest, ListOSPolicyAssignmentReportsRequest, ListOSPolicyAssignmentReportsResponse, OSPolicyAssignmentReport, ) from .os_policy_assignments import ( CreateOSPolicyAssignmentRequest, DeleteOSPolicyAssignmentRequest, GetOSPolicyAssignmentRequest, ListOSPolicyAssignmentRevisionsRequest, ListOSPolicyAssignmentRevisionsResponse, ListOSPolicyAssignmentsRequest, ListOSPolicyAssignmentsResponse, OSPolicyAssignment, OSPolicyAssignmentOperationMetadata, UpdateOSPolicyAssignmentRequest, ) from .osconfig_common import FixedOrPercent from .patch_deployments import ( CreatePatchDeploymentRequest, DeletePatchDeploymentRequest, GetPatchDeploymentRequest, ListPatchDeploymentsRequest, ListPatchDeploymentsResponse, MonthlySchedule, OneTimeSchedule, PatchDeployment, PausePatchDeploymentRequest, RecurringSchedule, ResumePatchDeploymentRequest, UpdatePatchDeploymentRequest, WeekDayOfMonth, WeeklySchedule, ) from .patch_jobs import ( AptSettings, CancelPatchJobRequest, ExecStep, ExecStepConfig, ExecutePatchJobRequest, GcsObject, GetPatchJobRequest, GooSettings, Instance, ListPatchJobInstanceDetailsRequest, ListPatchJobInstanceDetailsResponse, ListPatchJobsRequest, ListPatchJobsResponse, PatchConfig, PatchInstanceFilter, PatchJob, PatchJobInstanceDetails, PatchRollout, WindowsUpdateSettings, YumSettings, ZypperSettings, ) from .vulnerability import ( CVSSv3, GetVulnerabilityReportRequest, ListVulnerabilityReportsRequest, ListVulnerabilityReportsResponse, VulnerabilityReport, ) __all__ = ( "GetInventoryRequest", "Inventory", "ListInventoriesRequest", "ListInventoriesResponse", "InventoryView", "OSPolicy", "GetOSPolicyAssignmentReportRequest", "ListOSPolicyAssignmentReportsRequest", "ListOSPolicyAssignmentReportsResponse", "OSPolicyAssignmentReport", "CreateOSPolicyAssignmentRequest", "DeleteOSPolicyAssignmentRequest", "GetOSPolicyAssignmentRequest", "ListOSPolicyAssignmentRevisionsRequest", "ListOSPolicyAssignmentRevisionsResponse", "ListOSPolicyAssignmentsRequest", "ListOSPolicyAssignmentsResponse", "OSPolicyAssignment", "OSPolicyAssignmentOperationMetadata", "UpdateOSPolicyAssignmentRequest", "FixedOrPercent", "CreatePatchDeploymentRequest", "DeletePatchDeploymentRequest", "GetPatchDeploymentRequest", "ListPatchDeploymentsRequest", "ListPatchDeploymentsResponse", "MonthlySchedule", "OneTimeSchedule", "PatchDeployment", "PausePatchDeploymentRequest", "RecurringSchedule", "ResumePatchDeploymentRequest", "UpdatePatchDeploymentRequest", "WeekDayOfMonth", "WeeklySchedule", "AptSettings", "CancelPatchJobRequest", "ExecStep", "ExecStepConfig", "ExecutePatchJobRequest", "GcsObject", "GetPatchJobRequest", "GooSettings", "Instance", "ListPatchJobInstanceDetailsRequest", "ListPatchJobInstanceDetailsResponse", "ListPatchJobsRequest", "ListPatchJobsResponse", "PatchConfig", "PatchInstanceFilter", "PatchJob", "PatchJobInstanceDetails", "PatchRollout", "WindowsUpdateSettings", "YumSettings", "ZypperSettings", "CVSSv3", "GetVulnerabilityReportRequest", "ListVulnerabilityReportsRequest", "ListVulnerabilityReportsResponse", "VulnerabilityReport", )
googleapis/python-os-config
google/cloud/osconfig_v1/types/__init__.py
Python
apache-2.0
4,373
<?php /////////////////////////////////////////////////////////////////////////////// // // © Copyright f-project.net 2010-present. // // 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. // /////////////////////////////////////////////////////////////////////////////// namespace fproject\amf\auth; class AuthResult { /** * General Failure */ const FAILURE = 0; /** * Failure due to identity not being found. */ const FAILURE_IDENTITY_NOT_FOUND = -1; /** * Failure due to identity being ambiguous. */ const FAILURE_IDENTITY_AMBIGUOUS = -2; /** * Failure due to invalid credential being supplied. */ const FAILURE_CREDENTIAL_INVALID = -3; /** * Failure due to uncategorized reasons. */ const FAILURE_UNCATEGORIZED = -4; /** * Authentication success. */ const SUCCESS = 1; /** * Authentication result code * * @var int */ protected $_code; /** * The identity used in the authentication attempt * * @var mixed */ protected $_identity; /** * An array of string reasons why the authentication attempt was unsuccessful * * If authentication was successful, this should be an empty array. * * @var array */ protected $_messages; /** * Sets the result code, identity, and failure messages * * @param int $code * @param mixed $identity * @param array $messages */ public function __construct($code, $identity, array $messages = array()) { $code = (int) $code; if ($code < self::FAILURE_UNCATEGORIZED) { $code = self::FAILURE; } elseif ($code > self::SUCCESS ) { $code = 1; } $this->_code = $code; $this->_identity = $identity; $this->_messages = $messages; } /** * Returns whether the result represents a successful authentication attempt * * @return boolean */ public function isValid() { return ($this->_code > 0) ? true : false; } /** * getCode() - Get the result code for this authentication attempt * * @return int */ public function getCode() { return $this->_code; } /** * Returns the identity used in the authentication attempt * * @return mixed */ public function getIdentity() { return $this->_identity; } /** * Returns an array of string reasons why the authentication attempt was unsuccessful * * If authentication was successful, this method returns an empty array. * * @return array */ public function getMessages() { return $this->_messages; } }
fproject/phpamf
fproject/amf/auth/AuthResult.php
PHP
apache-2.0
3,363
package com.ksa.system.initialize.convert; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import com.ksa.context.ServiceContextUtils; import com.ksa.dao.security.RoleDao; import com.ksa.model.ModelUtils; import com.ksa.model.security.Role; import com.ksa.model.security.User; import com.ksa.service.security.SecurityService; import com.ksa.system.initialize.model.YongHu; import com.ksa.util.StringUtils; public class UserConverter { // 供别的转换器使用的 合作伙伴缓存 private static Map<String, User> userMap = new HashMap<String, User>(); public static Map<String, User> getUserMap() { return userMap; } public static void doConvert( SqlSession session ) { List<YongHu> list = getAllYongHu( session ); Map<String, Role> map = getRoleMap(); SecurityService service = ServiceContextUtils.getService( SecurityService.class ); // 保存用户 for( YongHu yh : list ) { User user = new User(); user.setId( yh.getId() ); user.setEmail( yh.getEmail() ); user.setName( yh.getUsername() ); user.setPassword( yh.getPassword() ); user.setTelephone( yh.getTelephone() ); if( map.containsKey( yh.getRole() ) ) { service.createUser( user, new String[]{ map.get( yh.getRole() ).getId() } ); } else { service.createUser( user ); } userMap.put( user.getName(), user ); } } /** * 插入已被删除但是业务中使用的用户 */ private static User createdDeletedUser( String userName ) { SecurityService service = ServiceContextUtils.getService( SecurityService.class ); User user = new User(); user.setId( ModelUtils.generateRandomId() ); user.setName( userName ); user.setEmail( "" ); user.setLocked( true ); user.setTelephone( "" ); user.setPassword( "123456" ); user = service.createUser( user ); userMap.put( userName, user ); return user; } public static User getUser( String name ) { if( ! StringUtils.hasText( name ) ) { return null; } User user = userMap.get( name ); if( user != null ) { return user; } else { user = createdDeletedUser( name ); return user; } } private static Map<String, Role> getRoleMap() { List<Role> roles = ServiceContextUtils.getService( RoleDao.class ).selectAllRole(); Map<String, Role> map = new HashMap<String, Role>(); for(Role role : roles) { map.put( role.getName(), role ); } return map; } private static List<YongHu> getAllYongHu( SqlSession session ) { return session.selectList( "select-init-yonghu" ); } }
whitesource/fs-agent
test_input/ksa/ksa-web-root/ksa-system-web/src/main/java/com/ksa/system/initialize/convert/UserConverter.java
Java
apache-2.0
3,005
<?php /** * * Contains the Currency class * Intended for use with Laravel >=5.1 * * @author Chris Rasmussen, digitalformula.net * @category Libraries & Utilities * @license Apache License, Version 2.0 * @package DigitalFormula\Utilities * */ namespace DigitalFormula\Utilities; use Log; use Sentinel; /** * * The Currency class * Intended for use with Laravel >=5.1 * * @author Chris Rasmussen, digitalformula.net * @category Libraries & Utilities * @license Apache License, Version 2.0 * @package DigitalFormula\Utilities * */ class Currency { /** * Perform a real-time currency conversion using CurrencyLayer API * * @param $amount * @param $from * @param $to * @return int|string */ public static function CurrencyLayerConversion( $amount, $from, $to ) { if( $from == $to ) { return $amount; } else { try { $endpoint = 'convert'; $access_key = env( 'CURRENCY_LAYER_ACCESS_KEY' ); $ch = curl_init( 'https://apilayer.net/api/' . $endpoint . '?access_key=' . $access_key . '&from=' . $from . '&to=' . $to . '&amount=' . $amount . '' ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $json = curl_exec($ch); curl_close($ch); $conversionResult = json_decode($json, true); switch( $conversionResult[ 'success' ] ) { case true: return number_format( $conversionResult['result'], 2 ); break; case false; Log::error( $conversionResult[ 'error' ][ 'info' ], [ 'email' => Sentinel::getUser()->email, 'from' => $from, 'to' => $to ] ); return 0; break; } } catch ( Exception $e ) { $message = $e->getMessage(); Log::error( $message, [ 'email' => Sentinel::getUser()->email, 'from' => $from, 'to' => $to ] ); return 0; } } } /* CurrencyLayerConversion */ } /* Currency */
digitalformula/utilities
src/DigitalFormula/Utilities/Currency.php
PHP
apache-2.0
2,209
package nds_api.fs.btx0; import nds_api.RomMapping; import java.io.IOException; /** * * Reads data to translate to a {@link BasicTexture}. * * @author Whis * */ public final class BasicTextureReader { /** * The expected BTX0 file extension. */ private static final String BTX0_EXT = "BTX0"; /** * The {@link RomMapping} to read from. */ private final RomMapping mapping; /** * Creates a new {@link BasicTextureReader}. */ public BasicTextureReader(RomMapping mapping) { this.mapping = mapping; } public BasicTexture read() throws IOException { String stamp = mapping.readString(BTX0_EXT.length()); if (!stamp.equals(BTX0_EXT)) { throw new IOException(); } return new BasicTexture(null, null); } }
sinoz/nds-api
src/main/java/nds_api/fs/btx0/BasicTextureReader.java
Java
apache-2.0
828
/* * Copyright 2015 Suprema(biostar2@suprema.co.kr) * * 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.supremainc.biostar2.adapter.base; import android.app.Activity; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection; import com.supremainc.biostar2.R; import com.supremainc.biostar2.meta.Setting; import com.supremainc.biostar2.sdk.models.v1.permission.CloudRole; import com.supremainc.biostar2.sdk.models.v1.permission.CloudRoles; import com.supremainc.biostar2.sdk.provider.PermissionDataProvider; import com.supremainc.biostar2.widget.popup.Popup; import com.supremainc.biostar2.widget.popup.Popup.OnPopupClickListener; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public abstract class BasePermissionAdapter extends BaseListAdapter<CloudRole> { protected static final int FIRST_LIMIT = 50; protected boolean mIsLastItemVisible = false; protected int mLimit = FIRST_LIMIT; protected int mOffset = 0; protected PermissionDataProvider mPermissionDataProvider; private Callback<CloudRoles> mItemListener = new Callback<CloudRoles>() { @Override public void onFailure(Call<CloudRoles> call, Throwable t) { if (isIgnoreCallback(call, true)) { return; } showRetryPopup(t.getMessage(), new OnPopupClickListener() { @Override public void OnNegative() { } @Override public void OnPositive() { showWait(null); mHandler.removeCallbacks(mRunGetItems); mHandler.post(mRunGetItems); } }); } @Override public void onResponse(Call<CloudRoles> call, Response<CloudRoles> response) { if (isIgnoreCallback(call, response, true)) { return; } if (isInvalidResponse(response, false, false)) { mItemListener.onFailure(call, new Throwable(getResponseErrorMessage(response))); return; } CloudRoles cloudRoles = response.body(); if (cloudRoles.records == null || cloudRoles.records.size() < 1) { if (mItems == null || mItems.size() < 1) { mTotal = 0; mOnItemsListener.onNoneData(); } else { mTotal = mItems.size(); mOnItemsListener.onSuccessNull(mItems.size()); } return; } if (mItems == null) { mItems = new ArrayList<CloudRole>(); CloudRole none = new CloudRole(); none.code = Setting.NONE_ITEM; none.description = mActivity.getString(R.string.none); mItems.add(none); } else { mItems.clear(); CloudRole none = new CloudRole(); none.code = Setting.NONE_ITEM; none.description = mActivity.getString(R.string.none); mItems.add(none); } if (mOnItemsListener != null) { mOnItemsListener.onTotalReceive(cloudRoles.total); } for (CloudRole ListCard : cloudRoles.records) { mItems.add(ListCard); } setData(mItems); mOffset = mItems.size(); mTotal = cloudRoles.total; } }; private Runnable mRunGetItems = new Runnable() { @Override public void run() { if (isInValidCheck()) { return; } if (isMemoryPoor()) { dismissWait(); mToastPopup.show(mActivity.getString(R.string.memory_poor), null); return; } request(mPermissionDataProvider.getCloudRoles(mItemListener)); } }; public BasePermissionAdapter(Activity context, ArrayList<CloudRole> items, ListView listView, OnItemClickListener itemClickListener, Popup popup, OnItemsListener onItemsListener) { super(context, items, listView, itemClickListener, popup, onItemsListener); mPermissionDataProvider = PermissionDataProvider.getInstance(context); setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && mIsLastItemVisible && mTotal - 1 > mOffset) { if (mPopup != null) { mPopup.showWait(true); } mHandler.removeCallbacks(mRunGetItems); mHandler.postDelayed(mRunGetItems, 100); } else { if (mPopup != null) { mPopup.dismissWiat(); } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { mIsLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount); } }); } @Override public void getItems(String query) { mQuery = query; mOffset = 0; mTotal = 0; mLimit = FIRST_LIMIT; mHandler.removeCallbacks(mRunGetItems); clearRequest(); showWait(SwipyRefreshLayoutDirection.TOP); if (mItems != null) { mItems.clear(); notifyDataSetChanged(); } mHandler.postDelayed(mRunGetItems, 500); } }
BioStar2/BioStar2Android
BioStar2Android/BioStar2Client/src/main/java/com/supremainc/biostar2/adapter/base/BasePermissionAdapter.java
Java
apache-2.0
6,611
package cn.iam007.app.mall; import java.util.ArrayList; import android.annotation.TargetApi; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.AlphaAnimation; import android.widget.TextView; import cn.iam007.app.common.utils.logging.LogUtil; import cn.iam007.app.mall.base.BaseActivity; import cn.iam007.app.mall.home.MyFragmentPagerAdapter; import com.baidu.mobstat.StatService; public class TestMainActivity extends BaseActivity { private MyFragmentPagerAdapter mMyFragmentPagerAdapter; private ViewPager mPager; @Override protected int getFlag() { return FLAG_SEARCH_VIEW | FLAG_DISABLE_HOME_AS_UP; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private View mRecommentBtn = null; private View mLiveBtn = null; private View mGameBtn = null; private View mAccountBtn = null; private MyFragmentPagerAdapter mFragmentPagerAdapter; private int mPanelTitleNormalColor = 0; private int mPanelTitleSelectedColor = 0; private ArrayList<TextView> mPanelTitles = new ArrayList<TextView>(); private ArrayList<View> mPanelImageNormal = new ArrayList<View>(); private ArrayList<View> mPanelImageSelected = new ArrayList<View>(); /* * 初始化ViewPager */ public void initView() { mPager = (ViewPager) findViewById(R.id.viewpager); // 给ViewPager设置适配器 mFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager()); mPager.setOffscreenPageLimit(mFragmentPagerAdapter.getCount());// mPager.setAdapter(mFragmentPagerAdapter); mPager.setOnPageChangeListener(new MyOnPageChangeListener()); mRecommentBtn = findViewById(R.id.recomment_btn); mRecommentBtn.setOnClickListener(mBtnClickListener); mPanelImageNormal.add(findViewById(R.id.recomment_img)); mPanelImageSelected.add(findViewById(R.id.recomment_img_selected)); mPanelTitles.add((TextView) findViewById(R.id.recommend_title)); mLiveBtn = findViewById(R.id.live_btn); mLiveBtn.setOnClickListener(mBtnClickListener); mPanelImageNormal.add(findViewById(R.id.live_img)); mPanelImageSelected.add(findViewById(R.id.live_img_selected)); mPanelTitles.add((TextView) findViewById(R.id.live_title)); mGameBtn = findViewById(R.id.game_btn); mGameBtn.setOnClickListener(mBtnClickListener); mPanelImageNormal.add(findViewById(R.id.game_img)); mPanelImageSelected.add(findViewById(R.id.game_img_selected)); mPanelTitles.add((TextView) findViewById(R.id.game_title)); mAccountBtn = findViewById(R.id.account_btn); mAccountBtn.setOnClickListener(mBtnClickListener); mPanelImageNormal.add(findViewById(R.id.account_img)); mPanelImageSelected.add(findViewById(R.id.account_img_selected)); mPanelTitles.add((TextView) findViewById(R.id.account_title)); setCurrentPage(0);// 设置当前显示标签页为第一页 mPanelTitleNormalColor = getResources().getColor(R.color.panel_title_normal_color); mPanelTitleSelectedColor = getResources().getColor(R.color.panel_title_selected_color); } private OnClickListener mBtnClickListener = new OnClickListener() { @Override public void onClick(View v) { int id = v.getId(); int pageIndex = -1; if (id == R.id.recomment_btn) { pageIndex = 0; } else if (id == R.id.live_btn) { pageIndex = 1; } else if (id == R.id.game_btn) { pageIndex = 2; } else if (id == R.id.account_btn) { pageIndex = 3; } if (pageIndex >= 0 && pageIndex < mFragmentPagerAdapter.getCount()) { setCurrentPage(pageIndex); } } }; @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setViewAlpha(View view, float alpha) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { view.setAlpha(alpha); } else { AlphaAnimation alphaAnim = new AlphaAnimation(alpha, alpha); alphaAnim.setDuration(0); // Make animation instant alphaAnim.setFillAfter(true); // Tell it to persist after the animation ends view.startAnimation(alphaAnim); } } private boolean mBackFromOtherPlace = false; @Override protected void onResume() { super.onResume(); if (mCurrentPageIndex >= 0 && mBackFromOtherPlace) { StatService.onPageStart(this, "fragment:" + mCurrentPageIndex); LogUtil.d("service", "page start " + mCurrentPageIndex); } mBackFromOtherPlace = false; } @Override protected void onPause() { super.onPause(); mBackFromOtherPlace = true; if (mCurrentPageIndex >= 0) { LogUtil.d("service", "page end " + mCurrentPageIndex); StatService.onPageEnd(this, "fragment:" + mCurrentPageIndex); } } private int mCurrentPageIndex = -1; private void setCurrentPage(int index) { if (mCurrentPageIndex != index) { if (mCurrentPageIndex >= 0) { LogUtil.d("service", "page end " + mCurrentPageIndex); StatService.onPageEnd(this, "fragment:" + mCurrentPageIndex); } LogUtil.d("service", "page start " + index); StatService.onPageStart(this, "fragment:" + index); mCurrentPageIndex = index; } if (index >= 0 && index < mFragmentPagerAdapter.getCount()) { mPager.setCurrentItem(index, false); mAccountBtn.setSelected(false); mGameBtn.setSelected(false); mLiveBtn.setSelected(false); mRecommentBtn.setSelected(false); for (int i = 0; i < mPanelImageNormal.size(); i++) { if (i != index) { setViewAlpha(mPanelImageNormal.get(i), 1); setViewAlpha(mPanelImageSelected.get(i), 0); mPanelTitles.get(i).setTextColor(mPanelTitleNormalColor); } else { setViewAlpha(mPanelImageNormal.get(i), 0); setViewAlpha(mPanelImageSelected.get(i), 1); mPanelTitles.get(i).setTextColor(mPanelTitleSelectedColor); } } switch (index) { case 0: mRecommentBtn.setSelected(true); break; case 1: mLiveBtn.setSelected(true); break; case 2: mGameBtn.setSelected(true); break; case 3: mAccountBtn.setSelected(true); break; default: break; } } } private void changePanelDisplay( int position, float positionOffset, int positionOffsetPixels) { if (positionOffset < 0.0000001) { setCurrentPage(position); return; } changePanelTitleColor(position, positionOffset, positionOffsetPixels); changePanelImage(position, positionOffset, positionOffsetPixels); } private void changePanelImage( int position, float positionOffset, int positionOffsetPixels) { setViewAlpha(mPanelImageNormal.get(position), positionOffset); setViewAlpha(mPanelImageSelected.get(position), 1 - positionOffset); setViewAlpha(mPanelImageNormal.get(position + 1), 1 - positionOffset); setViewAlpha(mPanelImageSelected.get(position + 1), positionOffset); } private void changePanelTitleColor( int position, float positionOffset, int positionOffsetPixels) { /* * 根据viewerpager渐变修改文字的颜色 */ int normalColorRed = Color.red(mPanelTitleNormalColor); int normalColorBlue = Color.blue(mPanelTitleNormalColor); int normalColorGreen = Color.green(mPanelTitleNormalColor); int selectedColorRed = Color.red(mPanelTitleSelectedColor); int selectedColorBlue = Color.blue(mPanelTitleSelectedColor); int selectedColorGreen = Color.green(mPanelTitleSelectedColor); // 设置左边item的title int leftRed = (int) ((1.0 - positionOffset) * selectedColorRed + positionOffset * normalColorRed); int leftBlue = (int) ((1.0 - positionOffset) * selectedColorBlue + positionOffset * normalColorBlue); int leftGreen = (int) ((1.0 - positionOffset) * selectedColorGreen + positionOffset * normalColorGreen); mPanelTitles.get(position).setTextColor(Color.argb(255, leftRed, leftGreen, leftBlue)); // 设置右边item的title int rightRed = (int) ((1.0 - positionOffset) * normalColorRed + positionOffset * selectedColorRed); int rightBlue = (int) ((1.0 - positionOffset) * normalColorBlue + positionOffset * selectedColorBlue); int rightGreen = (int) ((1.0 - positionOffset) * normalColorGreen + positionOffset * selectedColorGreen); mPanelTitles.get(position + 1).setTextColor(Color.argb(255, rightRed, rightGreen, rightBlue)); } private class MyOnPageChangeListener implements OnPageChangeListener { @Override public void onPageScrollStateChanged(int state) { debug("onPageScrollStateChanged:" + state); } @Override public void onPageScrolled( int position, float positionOffset, int positionOffsetPixels) { changePanelDisplay(position, positionOffset, positionOffsetPixels); } @Override public void onPageSelected(int position) { setCurrentPage(position); debug("onPageSelected:" + position); } } }
jiangerji/iam007-mobile-android
src/cn/iam007/app/mall/TestMainActivity.java
Java
apache-2.0
10,705
// Copyright 2016-2022 The Libsacloud 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 main import ( "log" "path/filepath" "github.com/sacloud/libsacloud/v2/internal/define" "github.com/sacloud/libsacloud/v2/internal/tools" ) const destination = "sacloud/zz_api_ops.go" func init() { log.SetFlags(0) log.SetPrefix("gen-api-op: ") } func main() { outputPath := destination tools.WriteFileWithTemplate(&tools.TemplateConfig{ OutputPath: filepath.Join(tools.ProjectRootPath(), outputPath), Template: tmpl, Parameter: define.APIs, }) log.Printf("generated: %s\n", outputPath) } const tmpl = `// generated by 'github.com/sacloud/libsacloud/internal/tools/gen-api-op'; DO NOT EDIT package sacloud import ( "context" "github.com/sacloud/libsacloud/v2/pkg/mutexkv" "github.com/sacloud/libsacloud/v2/sacloud/types" ) var apiLocker = mutexkv.NewMutexKV() func init() { {{ range . }} SetClientFactoryFunc("{{.TypeName}}", func(caller APICaller) interface{} { return &{{ .TypeName }}Op { Client: caller, PathSuffix: "{{.GetPathSuffix}}", PathName: "{{.GetPathName}}", } }) {{ end -}} } {{ range . }}{{ $typeName := .TypeName }}{{$resource := .}} /************************************************* * {{$typeName}}Op *************************************************/ // {{ .TypeName }}Op implements {{ .TypeName }}API interface type {{ .TypeName }}Op struct{ // Client APICaller Client APICaller // PathSuffix is used when building URL PathSuffix string // PathName is used when building URL PathName string } // New{{ $typeName}}Op creates new {{ $typeName}}Op instance func New{{ $typeName}}Op(caller APICaller) {{ $typeName}}API { return GetClientFactoryFunc("{{$typeName}}")(caller).({{$typeName}}API) } {{ range .Operations }}{{$returnErrStatement := .ReturnErrorStatement}}{{ $operationName := .MethodName }} // {{ .MethodName }} is API call func (o *{{ $typeName }}Op) {{ .MethodName }}(ctx context.Context{{if not $resource.IsGlobal}}, zone string{{end}}{{ range .Arguments }}, {{ .ArgName }} {{ .TypeName }}{{ end }}) {{.ResultsStatement}} { // build request URL pathBuildParameter := map[string]interface{}{ "rootURL": SakuraCloudAPIRoot, "pathSuffix": o.PathSuffix, "pathName": o.PathName, {{- if $resource.IsGlobal }} "zone": APIDefaultZone, {{- else }} "zone": zone, {{- end }} {{- range .Arguments }} "{{.PathFormatName}}": {{.Name}}, {{- end }} } url, err := buildURL("{{.GetPathFormat}}", pathBuildParameter) if err != nil { return {{ $returnErrStatement }} } {{ if .LockKeyFormat -}} lockKey, err := buildURL("{{.LockKeyFormat}}", pathBuildParameter) if err != nil { return {{ $returnErrStatement }} } apiLocker.Lock(lockKey) defer apiLocker.Unlock(lockKey) {{ end -}} // build request body var body interface{} {{ if .HasRequestEnvelope -}} v, err := o.transform{{.MethodName}}Args({{ range .Arguments }}{{ .ArgName }},{{ end }}) if err != nil { return {{ $returnErrStatement }} } body = v {{ end }} // do request {{ if .HasResponseEnvelope -}} data, err := o.Client.Do(ctx, "{{.Method}}", url, body) {{ else -}} _, err = o.Client.Do(ctx, "{{.Method}}", url, body) {{ end -}} if err != nil { return {{ $returnErrStatement }} } // build results {{ if .HasResponseEnvelope -}} results, err := o.transform{{.MethodName}}Results(data) if err != nil { return {{ $returnErrStatement }} } return {{ .ReturnStatement }} {{ else }} return nil {{ end -}} } {{ end -}} {{ end -}} `
sacloud/libsacloud
v2/internal/tools/gen-api-op/main.go
GO
apache-2.0
4,040
package com.google.api.ads.adwords.jaxws.v201406.cm; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for CampaignSharedSetError.Reason. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="CampaignSharedSetError.Reason"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="CAMPAIGN_SHARED_SET_DOES_NOT_EXIST"/> * &lt;enumeration value="SHARED_SET_NOT_ACTIVE"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "CampaignSharedSetError.Reason") @XmlEnum public enum CampaignSharedSetErrorReason { CAMPAIGN_SHARED_SET_DOES_NOT_EXIST, SHARED_SET_NOT_ACTIVE, UNKNOWN; public String value() { return name(); } public static CampaignSharedSetErrorReason fromValue(String v) { return valueOf(v); } }
nafae/developer
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/cm/CampaignSharedSetErrorReason.java
Java
apache-2.0
1,010
package com.thaiopensource.relaxng.parse; public interface Parseable <P, NC, L, EA, CL extends CommentList <L>, A extends Annotations <L, EA, CL>> extends SubParser <P, NC, L, EA, CL, A> { P parse (SchemaBuilder <P, NC, L, EA, CL, A> f, Scope <P, L, EA, CL, A> scope) throws BuildException, IllegalSchemaException; }
lsimons/phloc-schematron-standalone
phloc-schematron/jing/src/main/java/com/thaiopensource/relaxng/parse/Parseable.java
Java
apache-2.0
505
import React from 'react' import GenericField from './genericfield' import {object_is_equal, map_drop} from 'app/utils' import PropTypes from 'prop-types' import uuid4 from 'uuid/v4' class GenericForm extends React.Component{ constructor(props){ super(props) this.state = this.getInitialState(props) this.state.form_id = uuid4() this.updateForm = _.debounce(this.updateForm, 100) } getInitialState(props){ props = props || this.props let state={}; (props.fields || []).map((f) => { if (f.name){ let v = f.value if (v == undefined){ if (f.default == undefined) v = "" else v = f.default } state[f.name]=v } }) if (props.data){ Object.keys(props.data).map( (k) => { if (k){ state[k]=props.data[k] }}) } return state } setValue(k, v){ let update = {[k]: v } this.setState( update ) let nstate=Object.assign({}, this.state, update ) // looks like react delays state change, I need it now //console.log(nstate, this.props) this.updateForm() } componentWillReceiveProps(newprops){ if (!object_is_equal(newprops.fields, this.props.fields) || !object_is_equal(newprops.data, this.props.data)){ this.setState( this.getInitialState(newprops) ) } } componentDidMount(){ let fields = {}; (this.props.fields || []).map((f) => { if (f.validation) fields[f.name]=f.validation }) $(this.refs.form).form({ on: 'blur', fields }).on('submit', function(ev){ ev.preventDefault() }) this.updateForm() } updateForm(){ if (this.props.updateForm){ const data = map_drop(this.state, ["form_id"]) this.props.updateForm(data) } } render(){ const props=this.props return ( <form ref="form" className={`ui form ${props.className || ""}`} onSubmit={(ev) => { ev.preventDefault(); props.onSubmit && props.onSubmit(ev) }}> {(props.fields || []).map((f, i) => ( <GenericField {...f} key={f.name || i} setValue={(v) => this.setValue(f.name, v)} value={this.state[f.name]} fields={props.fields} form_data={this.state} /> ))} {props.children} </form> ) } } GenericForm.propTypes = { fields: PropTypes.arrayOf( PropTypes.shape({ label: PropTypes.string, name: PropTypes.string, description: PropTypes.string, type: PropTypes.string, value: PropTypes.oneOfType([PropTypes.string, PropTypes.Boolean]), params: PropTypes.string, }).isRequired).isRequired, data: PropTypes.object, updateForm: PropTypes.func.isRequired } export default GenericForm
serverboards/serverboards
frontend/app/js/components/genericform/index.js
JavaScript
apache-2.0
2,808
'use strict'; var chai = require('chai'); var supertest = require('supertest'); var api = supertest('https://apis-bank-dev.apigee.net'); // supertest init; chai.should(); describe('/branches', function() { describe('get', function() { it('should respond with 200 OK', function(done) { this.timeout(0); api.get('/apis/v1/locations/branches') .expect(200) .end(function(err, res) { if (err) return done(err); done(); }); }); }); });
siriscac/apigee-ci-demo
tests/branches-test.js
JavaScript
apache-2.0
488
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.psi.util; import com.intellij.openapi.util.Getter; import com.intellij.openapi.util.RecursionGuard; import org.jetbrains.annotations.NotNull; /** * A wrapper object that holds a computation ({@link #getValueProvider()}) and caches the result of the computation. * The recommended way of creation is to use one of {@link CachedValuesManager#getCachedValue} methods.<p></p> * * When {@link #getValue()} is invoked the first time, the computation is run and its result is returned and remembered internally. * In subsequent invocations, the result will be reused to avoid running the same code again and again.<p/> * * The computation will be re-run in the following circumstances: * <ol> * <li/>Garbage collector collects the result cached internally (it's kept via a {@link java.lang.ref.SoftReference}). * <li/>IDEA determines that cached value is outdated because some its dependencies are changed. See * {@link CachedValueProvider.Result#getDependencyItems()} * </ol> * * The implementation is thread-safe but not atomic, i.e. if several threads request the cached value simultaneously, the computation may * be run concurrently on more than one thread. Due to this and unpredictable garbage collection, * cached value providers shouldn't have side effects.<p></p> * * <b>Result equivalence</b>: CachedValue might return a different result even if the previous one * is still reachable and not garbage-collected, and dependencies haven't changed. Therefore CachedValue results * should be equivalent and interchangeable if they're called multiple times. Examples: * <ul> * <li>If PSI declarations are cached, {@link #equals} or at least {@link com.intellij.psi.PsiManager#areElementsEquivalent} * should hold for results from the same CachedValue.</li> * <li>{@link com.intellij.psi.ResolveResult} objects should have equivalent {@code getElement()} values.</li> * <li>Cached arrays or lists should have the same number of elements, and they also should be equivalent and come in the same order.</li> * <li>If the result object's class has a meaningful {@link #equals} method, it should hold.</li> * </ul> * This is enforced at runtime by occasional checks in {@link com.intellij.util.IdempotenceChecker#checkEquivalence(Object, Object, Class)}. * See that method's documentation for further information and advice, when a failure happens.<p></p> * * <b>Context-independence</b>: if you store the CachedValue in a field or user data of some object {@code X}, then its {@link CachedValueProvider} * may only depend on X and parts of global system state that don't change while {@code X} is alive and valid (e.g. application/project components/services). * Otherwise re-invoking the CachedValueProvider after invalidation would use outdated data and produce incorrect results, * possibly causing exceptions in places far, far away. In particular, the provider may not capture: * <ul> * <li>Parameters of a method where CachedValue is created, except for {@code X} itself. Example: * <pre> * PsiElement resolve(PsiElement e, boolean incompleteCode) { * return CachedValuesManager.getCachedValue(e, () -> doResolve(e, incompleteCode)); // WRONG!!! * } * </pre> * * </li> * <li>"this" object creating the CachedValue, if {@code X} can outlive it, * or if there can be several non-equivalent instances of "this"-object's class all creating a cached value for the same place</li> * <li>Thread-locals at the moment of creation. If you use them (either directly or via {@link RecursionGuard#currentStack()}), * please try not to. If you really have to, also use {@link RecursionGuard#prohibitResultCaching(Object)} * to ensure values depending on unstable data won't be cached.</li> * <li>PSI elements around {@code X}, when {@code X} is a {@link com.intellij.psi.PsiElement} itself, * as they can change during the lifetime of that PSI element. Example: * <pre> * PsiMethod[] methods = psiClass.getMethods(); * return CachedValuesManager.getCachedValue(psiClass, () -> calculateSomeResult(methods)); // WRONG!!! * </pre> * </ul> * </ul> * This is enforced at runtime by occasional checks in {@link com.intellij.util.CachedValueStabilityChecker}. * See that class's documentation for further information and advice, when a failure happens.<p></p> * * <b>Recursion prevention</b>: The same cached value provider can be re-entered recursively on the same thread, * if the computation is inherently cyclic. Note that this is likely to result in {@link StackOverflowError}, * so avoid such situations at all cost. If there's no other way, use * {@link com.intellij.openapi.util.RecursionManager#doPreventingRecursion} instead of custom thread-locals to help get out of the endless loop. Please ensure this call happens inside * the {@link CachedValueProvider}, not outside {@link CachedValue#getValue()} call. Otherwise you might get no caching at all, because * CachedValue uses {@link RecursionGuard.StackStamp#mayCacheNow()} to prevent caching incomplete values, and even the top-level * call would be considered incomplete if it happens inside {@code doPreventingRecursion}. * * @param <T> The type of the computation result. * * @see CachedValueProvider * @see CachedValuesManager */ public interface CachedValue<T> { /** * @return cached value if it's already computed and not outdated, newly computed value otherwise */ T getValue(); /** * @return the object calculating the value to cache */ @NotNull CachedValueProvider<T> getValueProvider(); /** * @return whether there is a cached result inside this object and it's not outdated */ boolean hasUpToDateValue(); /** * @return if {@link #hasUpToDateValue()}, then a wrapper around the cached value, otherwise null. */ Getter<T> getUpToDateOrNull(); }
paplorinc/intellij-community
platform/core-api/src/com/intellij/psi/util/CachedValue.java
Java
apache-2.0
6,496
/* Copyright 2018 The Kubernetes 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 spyglass import ( "bytes" "errors" "fmt" "io" "net/url" "strings" "k8s.io/test-infra/prow/kube" "k8s.io/test-infra/prow/spyglass/lenses" ) type jobAgent interface { GetProwJob(job string, id string) (kube.ProwJob, error) GetJobLog(job string, id string) ([]byte, error) GetJobLogTail(job string, id string, n int64) ([]byte, error) } // PodLogArtifact holds data for reading from a specific pod log type PodLogArtifact struct { name string buildID string sizeLimit int64 jobAgent } var ( errInsufficientJobInfo = errors.New("insufficient job information provided") errInvalidSizeLimit = errors.New("sizeLimit must be a 64-bit integer greater than 0") ) // NewPodLogArtifact creates a new PodLogArtifact func NewPodLogArtifact(jobName string, buildID string, sizeLimit int64, ja jobAgent) (*PodLogArtifact, error) { if jobName == "" { return nil, errInsufficientJobInfo } if buildID == "" { return nil, errInsufficientJobInfo } if sizeLimit < 0 { return nil, errInvalidSizeLimit } return &PodLogArtifact{ name: jobName, buildID: buildID, sizeLimit: sizeLimit, jobAgent: ja, }, nil } // CanonicalLink returns a link to where pod logs are streamed func (a *PodLogArtifact) CanonicalLink() string { q := url.Values{ "job": []string{a.name}, "id": []string{a.buildID}, } u := url.URL{ Path: "/log", RawQuery: q.Encode(), } return u.String() } // JobPath gets the path within the job for the pod log. Always returns build-log.txt. // This is because the pod log becomes the build log after the job artifact uploads // are complete, which should be used instead of the pod log. func (a *PodLogArtifact) JobPath() string { return "build-log.txt" } // ReadAt implements reading a range of bytes from the pod logs endpoint func (a *PodLogArtifact) ReadAt(p []byte, off int64) (n int, err error) { logs, err := a.jobAgent.GetJobLog(a.name, a.buildID) if err != nil { return 0, fmt.Errorf("error getting pod log: %v", err) } r := bytes.NewReader(logs) readBytes, err := r.ReadAt(p, off) if err == io.EOF { return readBytes, io.EOF } if err != nil { return 0, fmt.Errorf("error reading pod logs: %v", err) } return readBytes, nil } // ReadAll reads all available pod logs, failing if they are too large func (a *PodLogArtifact) ReadAll() ([]byte, error) { size, err := a.Size() if err != nil { return nil, fmt.Errorf("error getting pod log size: %v", err) } if size > a.sizeLimit { return nil, lenses.ErrFileTooLarge } logs, err := a.jobAgent.GetJobLog(a.name, a.buildID) if err != nil { return nil, fmt.Errorf("error getting pod log: %v", err) } return logs, nil } // ReadAtMost reads at most n bytes func (a *PodLogArtifact) ReadAtMost(n int64) ([]byte, error) { logs, err := a.jobAgent.GetJobLog(a.name, a.buildID) if err != nil { return nil, fmt.Errorf("error getting pod log: %v", err) } reader := bytes.NewReader(logs) var byteCount int64 var p []byte for byteCount < n { b, err := reader.ReadByte() if err == io.EOF { return p, io.EOF } if err != nil { return nil, fmt.Errorf("error reading pod log: %v", err) } p = append(p, b) byteCount++ } return p, nil } // ReadTail reads the last n bytes of the pod log func (a *PodLogArtifact) ReadTail(n int64) ([]byte, error) { logs, err := a.jobAgent.GetJobLogTail(a.name, a.buildID, n) if err != nil { return nil, fmt.Errorf("error getting pod log tail: %v", err) } size := int64(len(logs)) var off int64 if n > size { off = 0 } else { off = size - n } p := make([]byte, n) readBytes, err := bytes.NewReader(logs).ReadAt(p, off) if err != nil && err != io.EOF { return nil, fmt.Errorf("error reading pod log tail: %v", err) } return p[:readBytes], nil } // Size gets the size of the pod log. Note: this function makes the same network call as reading the entire file. func (a *PodLogArtifact) Size() (int64, error) { logs, err := a.jobAgent.GetJobLog(a.name, a.buildID) if err != nil { return 0, fmt.Errorf("error getting size of pod log: %v", err) } return int64(len(logs)), nil } // isProwJobSource returns true if the provided string is a valid Prowjob source and false otherwise func isProwJobSource(src string) bool { return strings.HasPrefix(src, "prowjob/") }
kargakis/test-infra
prow/spyglass/podlogartifact.go
GO
apache-2.0
4,865
package edu.stanford.futuredata.macrobase.analysis.classify.stats; import edu.stanford.futuredata.macrobase.util.MacrobaseInternalError; /** * Performs linear interpolation in a lazy manner: interpolation does not actually * occur until an evaluation is requested. */ public class LinearInterpolator { private double[] x; private double[] y; /** * @param x Should be sorted in non-descending order. Assumed to not be very large. */ public LinearInterpolator(double[] x, double[] y) throws IllegalArgumentException { if (x.length != y.length) { throw new IllegalArgumentException("X and Y must be the same length"); } if (x.length == 1) { throw new IllegalArgumentException("X must contain more than one value"); } this.x = x; this.y = y; } public double evaluate(double value) throws MacrobaseInternalError { if ((value > x[x.length - 1]) || (value < x[0])) { return Double.NaN; } for (int i = 0; i < x.length; i++) { if (value == x[i]) { return y[i]; } if (value >= x[i+1]) { continue; } double dx = x[i+1] - x[i]; double dy = y[i+1] - y[i]; double slope = dy / dx; double intercept = y[i] - x[i] * slope; return slope * value + intercept; } throw new MacrobaseInternalError("Linear interpolator implemented incorrectly"); } }
kexinrong/macrobase
lib/src/main/java/edu/stanford/futuredata/macrobase/analysis/classify/stats/LinearInterpolator.java
Java
apache-2.0
1,539
package com.google.api.ads.dfp.jaxws.v201403; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * A {@code CreativePlaceholder} describes a slot that a creative is expected to * fill. This is used primarily to help in forecasting, and also to validate * that the correct creatives are associated with the line item. A * {@code CreativePlaceholder} must contain a size, and it can optionally * contain companions. Companions are only valid if the line item's environment * type is {@link EnvironmentType#VIDEO_PLAYER}. * * * <p>Java class for CreativePlaceholder complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CreativePlaceholder"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="size" type="{https://www.google.com/apis/ads/publisher/v201403}Size" minOccurs="0"/> * &lt;element name="companions" type="{https://www.google.com/apis/ads/publisher/v201403}CreativePlaceholder" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="appliedLabels" type="{https://www.google.com/apis/ads/publisher/v201403}AppliedLabel" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="effectiveAppliedLabels" type="{https://www.google.com/apis/ads/publisher/v201403}AppliedLabel" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="expectedCreativeCount" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="creativeSizeType" type="{https://www.google.com/apis/ads/publisher/v201403}CreativeSizeType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CreativePlaceholder", propOrder = { "size", "companions", "appliedLabels", "effectiveAppliedLabels", "id", "expectedCreativeCount", "creativeSizeType" }) public class CreativePlaceholder { protected Size size; protected List<CreativePlaceholder> companions; protected List<AppliedLabel> appliedLabels; protected List<AppliedLabel> effectiveAppliedLabels; protected Long id; protected Integer expectedCreativeCount; protected CreativeSizeType creativeSizeType; /** * Gets the value of the size property. * * @return * possible object is * {@link Size } * */ public Size getSize() { return size; } /** * Sets the value of the size property. * * @param value * allowed object is * {@link Size } * */ public void setSize(Size value) { this.size = value; } /** * Gets the value of the companions property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the companions property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCompanions().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CreativePlaceholder } * * */ public List<CreativePlaceholder> getCompanions() { if (companions == null) { companions = new ArrayList<CreativePlaceholder>(); } return this.companions; } /** * Gets the value of the appliedLabels property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the appliedLabels property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAppliedLabels().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AppliedLabel } * * */ public List<AppliedLabel> getAppliedLabels() { if (appliedLabels == null) { appliedLabels = new ArrayList<AppliedLabel>(); } return this.appliedLabels; } /** * Gets the value of the effectiveAppliedLabels property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the effectiveAppliedLabels property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEffectiveAppliedLabels().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AppliedLabel } * * */ public List<AppliedLabel> getEffectiveAppliedLabels() { if (effectiveAppliedLabels == null) { effectiveAppliedLabels = new ArrayList<AppliedLabel>(); } return this.effectiveAppliedLabels; } /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public Long getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } /** * Gets the value of the expectedCreativeCount property. * * @return * possible object is * {@link Integer } * */ public Integer getExpectedCreativeCount() { return expectedCreativeCount; } /** * Sets the value of the expectedCreativeCount property. * * @param value * allowed object is * {@link Integer } * */ public void setExpectedCreativeCount(Integer value) { this.expectedCreativeCount = value; } /** * Gets the value of the creativeSizeType property. * * @return * possible object is * {@link CreativeSizeType } * */ public CreativeSizeType getCreativeSizeType() { return creativeSizeType; } /** * Sets the value of the creativeSizeType property. * * @param value * allowed object is * {@link CreativeSizeType } * */ public void setCreativeSizeType(CreativeSizeType value) { this.creativeSizeType = value; } }
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201403/CreativePlaceholder.java
Java
apache-2.0
7,288
// Copyright 2020 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 // // 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 "google/cloud/pubsub/internal/publisher_stub.h" #include "google/cloud/grpc_error_delegate.h" namespace google { namespace cloud { namespace pubsub_internal { inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS { class DefaultPublisherStub : public PublisherStub { public: explicit DefaultPublisherStub( std::unique_ptr<google::pubsub::v1::Publisher::StubInterface> grpc_stub) : grpc_stub_(std::move(grpc_stub)) {} ~DefaultPublisherStub() override = default; StatusOr<google::pubsub::v1::Topic> CreateTopic( grpc::ClientContext& context, google::pubsub::v1::Topic const& request) override { google::pubsub::v1::Topic response; auto status = grpc_stub_->CreateTopic(&context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::pubsub::v1::ListTopicsResponse> ListTopics( grpc::ClientContext& context, google::pubsub::v1::ListTopicsRequest const& request) override { google::pubsub::v1::ListTopicsResponse response; auto status = grpc_stub_->ListTopics(&context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } Status DeleteTopic( grpc::ClientContext& context, google::pubsub::v1::DeleteTopicRequest const& request) override { google::protobuf::Empty response; auto status = grpc_stub_->DeleteTopic(&context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return {}; } private: std::unique_ptr<google::pubsub::v1::Publisher::StubInterface> grpc_stub_; }; std::shared_ptr<PublisherStub> CreateDefaultPublisherStub( pubsub::ConnectionOptions const& options, int channel_id) { auto channel_arguments = options.CreateChannelArguments(); // Newer versions of gRPC include a macro (`GRPC_ARG_CHANNEL_ID`) but use // its value here to allow compiling against older versions. channel_arguments.SetInt("grpc.channel_id", channel_id); auto channel = grpc::CreateCustomChannel( options.endpoint(), options.credentials(), channel_arguments); auto grpc_stub = google::pubsub::v1::Publisher::NewStub(grpc::CreateCustomChannel( options.endpoint(), options.credentials(), channel_arguments)); return std::make_shared<DefaultPublisherStub>(std::move(grpc_stub)); } } // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS } // namespace pubsub_internal } // namespace cloud } // namespace google
googleapis/google-cloud-cpp-pubsub
google/cloud/pubsub/internal/publisher_stub.cc
C++
apache-2.0
3,152
package org.fogbeam.experimental.blackboard.concurrencystuff.jtp.hyde.chapter11; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import javax.swing.JComponent; public class Squish extends JComponent { private static final long serialVersionUID = 1L; private Image[] frameList; private long msPerFrame; private volatile int currFrame; private Thread internalThread; private volatile boolean noStopRequested = true; public Squish( int width, int height, long msPerCycle, int framesPerSec, Color fgColor ) { setPreferredSize( new Dimension( width, height ) ); int framesPerCycle = (int) ( (framesPerSec * msPerCycle ) / 1000 ); msPerFrame = 1000L / framesPerSec; frameList = buildImages( width, height, fgColor, framesPerCycle ); currFrame = 0; Runnable r = new Runnable() { @Override public void run() { try { runWork(); } catch( Exception e ) { e.printStackTrace(); } } }; internalThread = new Thread( r ); internalThread.start(); } private Image[] buildImages( int width, int height, Color fgColor, int count ) { BufferedImage[] images = new BufferedImage[count]; for( int i = 0; i < count; i++ ) { images[i] = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB ); double xShape = 0.0; double yShape = ( (double) (i*height) ) / ( (double)count ); double wShape = width; double hShape = 2.0 * (height - yShape ); Ellipse2D shape = new Ellipse2D.Double( xShape, yShape, wShape, hShape ); Graphics2D g2 = images[i].createGraphics(); g2.setColor( fgColor ); g2.fill( shape ); g2.dispose(); } return images; } private void runWork() { while( noStopRequested ) { currFrame = (currFrame + 1 ) % frameList.length; repaint(); try { Thread.sleep( msPerFrame ); } catch( InterruptedException e ) { // reassert interrupt and continue on Thread.currentThread().interrupt(); } } } @Override public void paint( Graphics g ) { g.drawImage( frameList[currFrame], 0, 0, this ); } public void stopRequest() { noStopRequested = false; internalThread.interrupt(); } public boolean isAlive() { return internalThread.isAlive(); } }
mindcrime/AISandbox
blackboard/src/main/java/org/fogbeam/experimental/blackboard/concurrencystuff/jtp/hyde/chapter11/Squish.java
Java
apache-2.0
2,409
//region Copyright /*Copyright 2015-2016 尚尔路(sel8616@gmail.com/philshang@163.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. */ //endregion package capframework.http.constant; public class Regular { public static final String PAGE_DIRECTORY = "^/([A-Za-z0-9][A-Za-z0-9_\\-]{0,254}/){0,10}$"; public static final String PAGE_NAME = "^[A-Za-z0-9][A-Za-z0-9_\\-]{0,254}\\.[A-Za-z]{1,4}$"; public static final String ACTION_PATH = "^/{0,1}|/([A-Za-z0-9][A-Za-z0-9_\\-]{0,254}/)*([A-Za-z0-9][A-Za-z0-9_\\-]{0,254})$"; public static final String INTERCEPTOR_EXCLUDES = "^[A-Za-z0-9_/]{1,255}$"; }
cap-framework/cap-http
src/main/java/capframework/http/constant/Regular.java
Java
apache-2.0
1,095
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.xml.util; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.codeInspection.XmlInspectionGroupNames; import com.intellij.codeInspection.XmlSuppressableInspectionTool; import com.intellij.lang.ASTNode; import com.intellij.lang.xml.XMLLanguage; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.xml.XmlChildRole; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlTokenType; import com.intellij.util.IncorrectOperationException; import com.intellij.xml.XmlBundle; import com.intellij.xml.XmlExtension; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; /** * @author Maxim Mossienko */ public class CheckTagEmptyBodyInspection extends XmlSuppressableInspectionTool { @Override public boolean isEnabledByDefault() { return true; } @Override @NotNull public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new XmlElementVisitor() { @Override public void visitXmlTag(final XmlTag tag) { if (!CheckEmptyTagInspection.isTagWithEmptyEndNotAllowed(tag)) { final ASTNode child = XmlChildRole.START_TAG_END_FINDER.findChild(tag.getNode()); if (child != null) { final ASTNode node = child.getTreeNext(); if (node != null && node.getElementType() == XmlTokenType.XML_END_TAG_START) { holder.registerProblem( tag, XmlBundle.message("xml.inspections.tag.empty.body"), isCollapsibleTag(tag) ? new Fix(tag) : null ); } } } } }; } static boolean isCollapsibleTag(final XmlTag tag) { final String name = StringUtil.toLowerCase(tag.getName()); return tag.getLanguage() == XMLLanguage.INSTANCE || "link".equals(name) || "br".equals(name) || "meta".equals(name) || "img".equals(name) || "input".equals(name) || "hr".equals(name) || XmlExtension.isCollapsible(tag); } @Override @NotNull public String getGroupDisplayName() { return XmlInspectionGroupNames.XML_INSPECTIONS; } @Override @NotNull @NonNls public String getShortName() { return "CheckTagEmptyBody"; } public static class Fix extends CollapseTagIntention { private final SmartPsiElementPointer<XmlTag> myPointer; public Fix(XmlTag tag) { myPointer = SmartPointerManager.getInstance(tag.getProject()).createSmartPsiElementPointer(tag); } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { XmlTag tag = myPointer.getElement(); if (tag == null) { return; } applyFix(project, tag); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { return true; } } }
leafclick/intellij-community
xml/xml-analysis-impl/src/com/intellij/xml/util/CheckTagEmptyBodyInspection.java
Java
apache-2.0
3,650
package com.muses.data.model; import java.util.ArrayList; import java.util.List; public class AdminDataRecordExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table suood_admin * * @mbggenerated */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table suood_admin * * @mbggenerated */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table suood_admin * * @mbggenerated */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ public AdminDataRecordExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table suood_admin * * @mbggenerated */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table suood_admin * * @mbggenerated */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andAdminIdIsNull() { addCriterion("admin_id is null"); return (Criteria) this; } public Criteria andAdminIdIsNotNull() { addCriterion("admin_id is not null"); return (Criteria) this; } public Criteria andAdminIdEqualTo(Integer value) { addCriterion("admin_id =", value, "adminId"); return (Criteria) this; } public Criteria andAdminIdNotEqualTo(Integer value) { addCriterion("admin_id <>", value, "adminId"); return (Criteria) this; } public Criteria andAdminIdGreaterThan(Integer value) { addCriterion("admin_id >", value, "adminId"); return (Criteria) this; } public Criteria andAdminIdGreaterThanOrEqualTo(Integer value) { addCriterion("admin_id >=", value, "adminId"); return (Criteria) this; } public Criteria andAdminIdLessThan(Integer value) { addCriterion("admin_id <", value, "adminId"); return (Criteria) this; } public Criteria andAdminIdLessThanOrEqualTo(Integer value) { addCriterion("admin_id <=", value, "adminId"); return (Criteria) this; } public Criteria andAdminIdIn(List<Integer> values) { addCriterion("admin_id in", values, "adminId"); return (Criteria) this; } public Criteria andAdminIdNotIn(List<Integer> values) { addCriterion("admin_id not in", values, "adminId"); return (Criteria) this; } public Criteria andAdminIdBetween(Integer value1, Integer value2) { addCriterion("admin_id between", value1, value2, "adminId"); return (Criteria) this; } public Criteria andAdminIdNotBetween(Integer value1, Integer value2) { addCriterion("admin_id not between", value1, value2, "adminId"); return (Criteria) this; } public Criteria andAdminNameIsNull() { addCriterion("admin_name is null"); return (Criteria) this; } public Criteria andAdminNameIsNotNull() { addCriterion("admin_name is not null"); return (Criteria) this; } public Criteria andAdminNameEqualTo(String value) { addCriterion("admin_name =", value, "adminName"); return (Criteria) this; } public Criteria andAdminNameNotEqualTo(String value) { addCriterion("admin_name <>", value, "adminName"); return (Criteria) this; } public Criteria andAdminNameGreaterThan(String value) { addCriterion("admin_name >", value, "adminName"); return (Criteria) this; } public Criteria andAdminNameGreaterThanOrEqualTo(String value) { addCriterion("admin_name >=", value, "adminName"); return (Criteria) this; } public Criteria andAdminNameLessThan(String value) { addCriterion("admin_name <", value, "adminName"); return (Criteria) this; } public Criteria andAdminNameLessThanOrEqualTo(String value) { addCriterion("admin_name <=", value, "adminName"); return (Criteria) this; } public Criteria andAdminNameLike(String value) { addCriterion("admin_name like", value, "adminName"); return (Criteria) this; } public Criteria andAdminNameNotLike(String value) { addCriterion("admin_name not like", value, "adminName"); return (Criteria) this; } public Criteria andAdminNameIn(List<String> values) { addCriterion("admin_name in", values, "adminName"); return (Criteria) this; } public Criteria andAdminNameNotIn(List<String> values) { addCriterion("admin_name not in", values, "adminName"); return (Criteria) this; } public Criteria andAdminNameBetween(String value1, String value2) { addCriterion("admin_name between", value1, value2, "adminName"); return (Criteria) this; } public Criteria andAdminNameNotBetween(String value1, String value2) { addCriterion("admin_name not between", value1, value2, "adminName"); return (Criteria) this; } public Criteria andAdminPasswordIsNull() { addCriterion("admin_password is null"); return (Criteria) this; } public Criteria andAdminPasswordIsNotNull() { addCriterion("admin_password is not null"); return (Criteria) this; } public Criteria andAdminPasswordEqualTo(String value) { addCriterion("admin_password =", value, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordNotEqualTo(String value) { addCriterion("admin_password <>", value, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordGreaterThan(String value) { addCriterion("admin_password >", value, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordGreaterThanOrEqualTo(String value) { addCriterion("admin_password >=", value, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordLessThan(String value) { addCriterion("admin_password <", value, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordLessThanOrEqualTo(String value) { addCriterion("admin_password <=", value, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordLike(String value) { addCriterion("admin_password like", value, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordNotLike(String value) { addCriterion("admin_password not like", value, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordIn(List<String> values) { addCriterion("admin_password in", values, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordNotIn(List<String> values) { addCriterion("admin_password not in", values, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordBetween(String value1, String value2) { addCriterion("admin_password between", value1, value2, "adminPassword"); return (Criteria) this; } public Criteria andAdminPasswordNotBetween(String value1, String value2) { addCriterion("admin_password not between", value1, value2, "adminPassword"); return (Criteria) this; } public Criteria andAdminLoginTimeIsNull() { addCriterion("admin_login_time is null"); return (Criteria) this; } public Criteria andAdminLoginTimeIsNotNull() { addCriterion("admin_login_time is not null"); return (Criteria) this; } public Criteria andAdminLoginTimeEqualTo(Integer value) { addCriterion("admin_login_time =", value, "adminLoginTime"); return (Criteria) this; } public Criteria andAdminLoginTimeNotEqualTo(Integer value) { addCriterion("admin_login_time <>", value, "adminLoginTime"); return (Criteria) this; } public Criteria andAdminLoginTimeGreaterThan(Integer value) { addCriterion("admin_login_time >", value, "adminLoginTime"); return (Criteria) this; } public Criteria andAdminLoginTimeGreaterThanOrEqualTo(Integer value) { addCriterion("admin_login_time >=", value, "adminLoginTime"); return (Criteria) this; } public Criteria andAdminLoginTimeLessThan(Integer value) { addCriterion("admin_login_time <", value, "adminLoginTime"); return (Criteria) this; } public Criteria andAdminLoginTimeLessThanOrEqualTo(Integer value) { addCriterion("admin_login_time <=", value, "adminLoginTime"); return (Criteria) this; } public Criteria andAdminLoginTimeIn(List<Integer> values) { addCriterion("admin_login_time in", values, "adminLoginTime"); return (Criteria) this; } public Criteria andAdminLoginTimeNotIn(List<Integer> values) { addCriterion("admin_login_time not in", values, "adminLoginTime"); return (Criteria) this; } public Criteria andAdminLoginTimeBetween(Integer value1, Integer value2) { addCriterion("admin_login_time between", value1, value2, "adminLoginTime"); return (Criteria) this; } public Criteria andAdminLoginTimeNotBetween(Integer value1, Integer value2) { addCriterion("admin_login_time not between", value1, value2, "adminLoginTime"); return (Criteria) this; } public Criteria andAdminLoginNumIsNull() { addCriterion("admin_login_num is null"); return (Criteria) this; } public Criteria andAdminLoginNumIsNotNull() { addCriterion("admin_login_num is not null"); return (Criteria) this; } public Criteria andAdminLoginNumEqualTo(Integer value) { addCriterion("admin_login_num =", value, "adminLoginNum"); return (Criteria) this; } public Criteria andAdminLoginNumNotEqualTo(Integer value) { addCriterion("admin_login_num <>", value, "adminLoginNum"); return (Criteria) this; } public Criteria andAdminLoginNumGreaterThan(Integer value) { addCriterion("admin_login_num >", value, "adminLoginNum"); return (Criteria) this; } public Criteria andAdminLoginNumGreaterThanOrEqualTo(Integer value) { addCriterion("admin_login_num >=", value, "adminLoginNum"); return (Criteria) this; } public Criteria andAdminLoginNumLessThan(Integer value) { addCriterion("admin_login_num <", value, "adminLoginNum"); return (Criteria) this; } public Criteria andAdminLoginNumLessThanOrEqualTo(Integer value) { addCriterion("admin_login_num <=", value, "adminLoginNum"); return (Criteria) this; } public Criteria andAdminLoginNumIn(List<Integer> values) { addCriterion("admin_login_num in", values, "adminLoginNum"); return (Criteria) this; } public Criteria andAdminLoginNumNotIn(List<Integer> values) { addCriterion("admin_login_num not in", values, "adminLoginNum"); return (Criteria) this; } public Criteria andAdminLoginNumBetween(Integer value1, Integer value2) { addCriterion("admin_login_num between", value1, value2, "adminLoginNum"); return (Criteria) this; } public Criteria andAdminLoginNumNotBetween(Integer value1, Integer value2) { addCriterion("admin_login_num not between", value1, value2, "adminLoginNum"); return (Criteria) this; } public Criteria andAdminIsSuperIsNull() { addCriterion("admin_is_super is null"); return (Criteria) this; } public Criteria andAdminIsSuperIsNotNull() { addCriterion("admin_is_super is not null"); return (Criteria) this; } public Criteria andAdminIsSuperEqualTo(Boolean value) { addCriterion("admin_is_super =", value, "adminIsSuper"); return (Criteria) this; } public Criteria andAdminIsSuperNotEqualTo(Boolean value) { addCriterion("admin_is_super <>", value, "adminIsSuper"); return (Criteria) this; } public Criteria andAdminIsSuperGreaterThan(Boolean value) { addCriterion("admin_is_super >", value, "adminIsSuper"); return (Criteria) this; } public Criteria andAdminIsSuperGreaterThanOrEqualTo(Boolean value) { addCriterion("admin_is_super >=", value, "adminIsSuper"); return (Criteria) this; } public Criteria andAdminIsSuperLessThan(Boolean value) { addCriterion("admin_is_super <", value, "adminIsSuper"); return (Criteria) this; } public Criteria andAdminIsSuperLessThanOrEqualTo(Boolean value) { addCriterion("admin_is_super <=", value, "adminIsSuper"); return (Criteria) this; } public Criteria andAdminIsSuperIn(List<Boolean> values) { addCriterion("admin_is_super in", values, "adminIsSuper"); return (Criteria) this; } public Criteria andAdminIsSuperNotIn(List<Boolean> values) { addCriterion("admin_is_super not in", values, "adminIsSuper"); return (Criteria) this; } public Criteria andAdminIsSuperBetween(Boolean value1, Boolean value2) { addCriterion("admin_is_super between", value1, value2, "adminIsSuper"); return (Criteria) this; } public Criteria andAdminIsSuperNotBetween(Boolean value1, Boolean value2) { addCriterion("admin_is_super not between", value1, value2, "adminIsSuper"); return (Criteria) this; } public Criteria andAdminGidIsNull() { addCriterion("admin_gid is null"); return (Criteria) this; } public Criteria andAdminGidIsNotNull() { addCriterion("admin_gid is not null"); return (Criteria) this; } public Criteria andAdminGidEqualTo(Short value) { addCriterion("admin_gid =", value, "adminGid"); return (Criteria) this; } public Criteria andAdminGidNotEqualTo(Short value) { addCriterion("admin_gid <>", value, "adminGid"); return (Criteria) this; } public Criteria andAdminGidGreaterThan(Short value) { addCriterion("admin_gid >", value, "adminGid"); return (Criteria) this; } public Criteria andAdminGidGreaterThanOrEqualTo(Short value) { addCriterion("admin_gid >=", value, "adminGid"); return (Criteria) this; } public Criteria andAdminGidLessThan(Short value) { addCriterion("admin_gid <", value, "adminGid"); return (Criteria) this; } public Criteria andAdminGidLessThanOrEqualTo(Short value) { addCriterion("admin_gid <=", value, "adminGid"); return (Criteria) this; } public Criteria andAdminGidIn(List<Short> values) { addCriterion("admin_gid in", values, "adminGid"); return (Criteria) this; } public Criteria andAdminGidNotIn(List<Short> values) { addCriterion("admin_gid not in", values, "adminGid"); return (Criteria) this; } public Criteria andAdminGidBetween(Short value1, Short value2) { addCriterion("admin_gid between", value1, value2, "adminGid"); return (Criteria) this; } public Criteria andAdminGidNotBetween(Short value1, Short value2) { addCriterion("admin_gid not between", value1, value2, "adminGid"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table suood_admin * * @mbggenerated do_not_delete_during_merge */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table suood_admin * * @mbggenerated */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
suood/muses-mainproject
muses-manage-mapper/src/main/java/com/muses/data/model/AdminDataRecordExample.java
Java
apache-2.0
23,831
/******************************************************************************* * Copyright (c) 2005 - 2013 Nos Doughty * * 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.llaith.toolkit.core.pump.impl; import com.google.common.collect.Iterables; import org.llaith.toolkit.core.pump.Chunk; import org.llaith.toolkit.core.pump.Sink; import org.llaith.toolkit.common.guard.Guard; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Queue; /** * Very simple implementation of a sink buffer. */ public class BufferSink<T> implements Sink<T> { private static final Logger Log = LoggerFactory.getLogger(BufferSink.class); private final Queue<T> queue; public BufferSink(final Queue<T> queue) { this.queue = Guard.notNull(queue); } @Override public void put(final Chunk<T> chunk) { if (chunk != null) Iterables.addAll(this.queue,chunk); // not offer() } @Override public void close() throws RuntimeException { if (!this.queue.isEmpty()) Log.warn( "BufferSink is closing with "+ this.queue.size()+ " elements in the queued."); } }
llaith/toolkit
toolkit-core/src/main/java/org/llaith/toolkit/core/pump/impl/BufferSink.java
Java
apache-2.0
1,784
package net.hamnaberg.jsonstat; import net.hamnaberg.funclite.Optional; import java.util.*; public final class Category implements Iterable<String> { private final Map<String, String> labels = new LinkedHashMap<>(); private final Map<String, Integer> indices = new LinkedHashMap<>(); private final Map<String, List<String>> children = new LinkedHashMap<>(); public Category(Map<String, Integer> indices, Map<String, String> labels, Map<String, List<String>> children) { this.indices.putAll(indices); this.labels.putAll(labels); this.children.putAll(children); } public int getIndex(String id) { Integer integer = indices.get(id); if (integer == null) { return 0; } return integer; } public Optional<String> getLabel(String id) { return Optional.fromNullable(labels.get(id)); } public List<String> getChild(String id) { return children.containsKey(id) ? children.get(id) : Collections.<String>emptyList(); } @Override public Iterator<String> iterator() { if (!indices.isEmpty()) { return indices.keySet().iterator(); } else { return labels.keySet().iterator(); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Category category = (Category) o; if (!children.equals(category.children)) return false; if (!indices.equals(category.indices)) return false; if (!labels.equals(category.labels)) return false; return true; } @Override public int hashCode() { int result = labels.hashCode(); result = 31 * result + indices.hashCode(); result = 31 * result + children.hashCode(); return result; } }
hamnis/json-stat.java
src/main/java/net/hamnaberg/jsonstat/Category.java
Java
apache-2.0
1,899
/* * Copyright © 2008-2009 Esko Luontola, www.orfjackal.net * * 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 net.orfjackal.pommac.util; import jdave.Specification; import jdave.junit4.JDaveRunner; import net.orfjackal.pommac.TestUtil; import org.junit.runner.RunWith; import java.io.*; import java.util.zip.*; /** * @author Esko Luontola * @since 29.2.2008 */ @SuppressWarnings({"FieldCanBeLocal"}) @RunWith(JDaveRunner.class) public class ZipUtilSpec extends Specification<Object> { private File workDir; public void create() { workDir = TestUtil.createWorkDir(); } public void destroy() { TestUtil.deleteWorkDir(); } public class ExtractingFilesFromAZipArchive { private File outputDir; private File archive; private File unpackedEmptyDir; private File unpackedFileA; private File unpackedDir; private File unpackedFileB; public void create() throws IOException { archive = new File(workDir, "archive.zip"); outputDir = new File(workDir, "output"); outputDir.mkdir(); unpackedEmptyDir = new File(outputDir, "emptyDir"); unpackedFileA = new File(outputDir, "fileA.txt"); unpackedDir = new File(outputDir, "dir"); unpackedFileB = new File(unpackedDir, "fileB.txt"); ZipEntry emptyDir = new ZipEntry("emptyDir/foo/"); ZipEntry fileA = new ZipEntry("fileA.txt"); ZipEntry fileB = new ZipEntry("dir/fileB.txt"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive)); out.putNextEntry(emptyDir); out.putNextEntry(fileA); out.write("alpha".getBytes()); out.putNextEntry(fileB); out.write("beta".getBytes()); out.close(); specify(archive.exists()); specify(outputDir.listFiles(), does.containExactly()); ZipUtil.unzip(archive, outputDir); specify(archive.exists()); } public void willUnpackDirectories() { specify(unpackedEmptyDir.exists()); specify(unpackedEmptyDir.isDirectory()); } public void willUnpackFiles() { specify(unpackedFileA.exists()); specify(unpackedFileA.isFile()); specify(FileUtil.contentsOf(unpackedFileA), does.equal("alpha")); } public void willUnpackFilesInDirectories() { specify(unpackedDir.exists()); specify(unpackedDir.isDirectory()); specify(unpackedFileB.exists()); specify(unpackedFileB.isFile()); specify(FileUtil.contentsOf(unpackedFileB), does.equal("beta")); } } }
orfjackal/pommac
src/test/java/net/orfjackal/pommac/util/ZipUtilSpec.java
Java
apache-2.0
3,286
package com.monkeysarmy.fit.ui.debug; import android.view.View; import android.view.ViewGroup; /** * A {@link android.view.ViewGroup.OnHierarchyChangeListener hierarchy change listener} which recursively * monitors an entire tree of views. */ public final class HierarchyTreeChangeListener implements ViewGroup.OnHierarchyChangeListener { /** * Wrap a regular {@link android.view.ViewGroup.OnHierarchyChangeListener hierarchy change listener} with one * that monitors an entire tree of views. */ public static HierarchyTreeChangeListener wrap(ViewGroup.OnHierarchyChangeListener delegate) { return new HierarchyTreeChangeListener(delegate); } private final ViewGroup.OnHierarchyChangeListener delegate; private HierarchyTreeChangeListener(ViewGroup.OnHierarchyChangeListener delegate) { if (delegate == null) { throw new NullPointerException("Delegate must not be null."); } this.delegate = delegate; } @Override public void onChildViewAdded(View parent, View child) { delegate.onChildViewAdded(parent, child); if (child instanceof ViewGroup) { ViewGroup childGroup = (ViewGroup) child; childGroup.setOnHierarchyChangeListener(this); for (int i = 0; i < childGroup.getChildCount(); i++) { onChildViewAdded(childGroup, childGroup.getChildAt(i)); } } } @Override public void onChildViewRemoved(View parent, View child) { if (child instanceof ViewGroup) { ViewGroup childGroup = (ViewGroup) child; for (int i = 0; i < childGroup.getChildCount(); i++) { onChildViewRemoved(childGroup, childGroup.getChildAt(i)); } childGroup.setOnHierarchyChangeListener(null); } delegate.onChildViewRemoved(parent, child); } }
niqo01/monkey
src/internalDebug/java/com/monkeysarmy/fit/ui/debug/HierarchyTreeChangeListener.java
Java
apache-2.0
1,757
<?php /** * Pixelcrush CDN Prestashop Module * * Copyright 2017 Imagenii, 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 Pixelcrush * @copyright Copyright (c) 2017 Imagenii Inc. All rights reserved * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2 * */ if (!defined('_PS_VERSION_')) { exit; } require_once(dirname(__FILE__) . '/classes/PSCache.php'); require_once(dirname(__FILE__) . '/classes/ApiClient.php'); class Pixelcrush extends Module { public $config; /* @var \pixelcrush\ApiClient*/ public $client; /* @var \pixelcrush\PSCache*/ public $cache; public $user_cloud; public $cloud_filters_hash; public $images_types_hash; public $bootstrap; public function __construct() { $this->name = 'pixelcrush'; $this->tab = 'administration'; $this->version = '1.3.1'; $this->author = 'pixelcrush.io'; $this->bootstrap = true; $this->need_instance = 1; $this->module_key = 'f06ff8e65629b4d85e63752cfbf1d457'; $this->displayName = $this->l('Pixelcrush CDN'); $this->description = $this->l('Make your shop extremely faster and forget managing images.'); $this->client = $this->getClient(); $this->cache = new \pixelcrush\PSCache(); $this->ps_versions_compliancy = array('min' => '1.7', 'max' => '1.7.9.9'); parent::__construct(); } /** * @return bool * @throws \RuntimeException * @throws PrestaShopException */ public function install() { // Assets directory is not available in PS 1.7 for example if (version_compare(_PS_VERSION_, '1.7.0', '>=')) { $this->checkOverrideDirectory('assets'); } return parent::install() && $this->registerHook('actionObjectImageTypeAddAfter') && $this->registerHook('actionObjectImageTypeUpdateAfter') && $this->registerHook('actionObjectImageTypeDeleteAfter') && $this->registerHook('displayBackOfficeHeader'); } /** * @param $dirname * @throws \RuntimeException */ public function checkOverrideDirectory($dirname) { $full_path = _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'override' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . $dirname; // check if dir exists first, then try to create AND check if creation succeeded if (!is_dir($full_path) && !mkdir($full_path) && !is_dir($full_path)) { throw new \RuntimeException(sprintf('Directory "%s" was not created', $full_path)); } umask(0000); if (!file_exists($full_path.'/index.php') && is_writable($full_path)) { copy(dirname(__FILE__).'/index.php', $full_path.'/index.php'); } } public function uninstall() { return parent::uninstall() && Configuration::deleteByName('PIXELCRUSH_ENABLE_IMAGES') && Configuration::deleteByName('PIXELCRUSH_ENABLE_STATICS') && Configuration::deleteByName('PIXELCRUSH_USER_ACCOUNT') && Configuration::deleteByName('PIXELCRUSH_API_SECRET') && Configuration::deleteByName('PIXELCRUSH_FILTERS_PREFIX') && Configuration::deleteByName('PIXELCRUSH_FILL_BACKGROUND') && Configuration::deleteByName('PIXELCRUSH_URL_PROTOCOL'); } public function getContent() { $output = ''; if (Tools::isSubmit('submit'.$this->name) && Tools::getIsset('PIXELCRUSH_ENABLE_IMAGES') && Tools::getIsset('PIXELCRUSH_ENABLE_STATICS') ) { $submit = (object)array( 'enable_images' => Tools::getValue('PIXELCRUSH_ENABLE_IMAGES'), 'enable_statics' => Tools::getValue('PIXELCRUSH_ENABLE_STATICS'), 'user_account' => Tools::getValue('PIXELCRUSH_USER_ACCOUNT'), 'api_secret' => Tools::getValue('PIXELCRUSH_API_SECRET'), 'filters_prefix' => Tools::getValue('PIXELCRUSH_FILTERS_PREFIX'), 'fill_background' => Tools::getValue('PIXELCRUSH_FILL_BACKGROUND'), 'url_protocol' => Tools::getValue('PIXELCRUSH_URL_PROTOCOL') ); if ($this->validateConfig($submit)) { // We need to re-initialize config and errors in case the user has changed its user-apiKey to reAuth $this->client = null; $this->config = null; $this->_errors = array(); $this->user_cloud = null; $error = false; $this->setConfig($submit); // Submit/Reset Existing Filters if (!$this->resetCdnFilters((bool)Tools::getValue('reset_filters_checked'))) { $error = true; $output .= $this->displayError($this->_errors); } elseif (!$this->client->domainExists($this->client->domain())) { $error = true; $output .= $this->displayError('The user-id domain cannot be found, please check the value'); } // If some error was detected, we disable the system, just in case if ($error) { Configuration::updateValue('PIXELCRUSH_ENABLE_IMAGES', false); Configuration::updateValue('PIXELCRUSH_ENABLE_STATICS', false); } $output .= $this->displayConfirmation($this->l('Settings updated')); } else { $output .= $this->displayError('You need to correctly fill all mandatory fields.'); } } return $output.$this->displayForm(); } public function setConfig($config) { Configuration::updateValue('PIXELCRUSH_ENABLE_IMAGES', $config->enable_images); Configuration::updateValue('PIXELCRUSH_ENABLE_STATICS', $config->enable_statics); Configuration::updateValue('PIXELCRUSH_USER_ACCOUNT', $config->user_account); Configuration::updateValue('PIXELCRUSH_API_SECRET', $config->api_secret); Configuration::updateValue('PIXELCRUSH_FILTERS_PREFIX', $config->filters_prefix); Configuration::updateValue('PIXELCRUSH_FILL_BACKGROUND', $config->fill_background); Configuration::updateValue('PIXELCRUSH_URL_PROTOCOL', $config->url_protocol); } public function validateConfig($config) { $UUIDv4_format = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i'; if (!is_object($config) || empty($config)) { return false; } if ($config->fill_background === '') { $config->fill_background = '#FFFFFF'; } $is_valid = true; $is_valid &= (int)$config->enable_images === 1 || (int)$config->enable_images === 0; $is_valid &= (int)$config->enable_statics === 1 || (int)$config->enable_statics === 0; $is_valid &= Tools::strlen($config->user_account) >= 3; $is_valid &= Tools::strlen($config->api_secret) === 36 && preg_match($UUIDv4_format, $config->api_secret) === 1; $is_valid &= Tools::strlen($config->filters_prefix) > 0; $is_valid &= preg_match('|^#([A-Fa-f0-9]{3}){1,2}$|', $config->fill_background) === 1; $is_valid &= $config->url_protocol === '' || $config->url_protocol === 'http://' || $config->url_protocol === 'https://'; return $is_valid; } public function displayForm() { $fields_form = array(); // Init Fields form array $fields_form[0]['form'] = array( 'legend' => array( 'title' => $this->l('Pixelcrush Settings'), ), 'input' => array( array( 'type' => version_compare(_PS_VERSION_, '1.6.0', '<') ? 'radio' : 'switch', 'label' => $this->l('Enable Image CDN'), 'name' => 'PIXELCRUSH_ENABLE_IMAGES', 'required' => true, 'is_bool' => true, 'values' => array( array( 'id' => 'active_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'active_off', 'value' => 0, 'label' => $this->l('No') ) ), 'lang' => false, ), array( 'type' => (version_compare(_PS_VERSION_, '1.6.0', '<') ? 'radio' : 'switch'), 'label' => $this->l('Enable Static CDN (.js / .css / fonts files)'), 'name' => 'PIXELCRUSH_ENABLE_STATICS', 'required' => true, 'is_bool' => true, 'values' => array( array( 'id' => 'active_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'active_off', 'value' => 0, 'label' => $this->l('No') ) ), 'lang' => false ), array( 'type' => 'text', 'label' => $this->l('User Account'), 'name' => 'PIXELCRUSH_USER_ACCOUNT', 'class' => 'col-sm-30', 'size' => 24, 'required' => true, 'lang' => false, ), array( 'type' => 'text', 'label' => $this->l('Api Secret'), 'name' => 'PIXELCRUSH_API_SECRET', 'size' => 36, 'class' => 'col-sm-30', 'required' => true, 'lang' => false, ), array( 'type' => 'text', 'label' => $this->l('Filter Alias Prefix'), 'name' => 'PIXELCRUSH_FILTERS_PREFIX', 'class' => 'col-sm-30', 'size' => 12, 'required' => true, 'lang' => false, ), array( 'type' => 'checkbox', 'label' => $this->l('Reset Existing Filters'), 'desc' => $this->l('If this option is checked, any existing filter on your pixelcrush account will be deleted before uploading the actual ones.'), 'name' => 'reset_filters', 'values' => array( 'query' => array( array( 'id' => 'checked', 'name' => '', 'val' => '1' ), ), 'id' => 'id', 'name' => 'name' ) ), array( 'type' => 'select', 'label' => $this->l('Add protocol to proxied url:'), 'desc' => $this->l('Adds protocol to original resource url. If this is not set pixelcrush will access the resources using always http.'), 'name' => 'PIXELCRUSH_URL_PROTOCOL', 'required' => true, 'options' => array( 'id' => 'id_option', 'name' => 'name', 'query' => array( array( 'id_option' => '', 'name' => 'Without Protocol' ), array( 'id_option' => 'http://', 'name' => 'http://' ), array( 'id_option' => 'https://', 'name' => 'https://' ), ) ) ), array( 'type' => 'color', 'label' => $this->l('Fill Background'), 'name' => 'PIXELCRUSH_FILL_BACKGROUND', 'lang' => false, 'size' => 15, 'desc' => $this->l('Use color picker for color.'), 'required' => false ), ), 'submit' => array( 'title' => $this->l('Save'), 'class' => 'btn btn-default pull-right' ) ); // Adds logo on top of the configuration form for PS 1.6+ if (version_compare(_PS_VERSION_, '1.6.0', '>=')) { $img = array( 'type' => 'html', 'name' => 'PIXELCRUSH_logo', 'html_content' => '<img id="pixelcrush-logo-hd" ' .'src="../modules/pixelcrush/views/img/pixelcrush-logo.png" />' ); array_unshift($fields_form[0]['form']['input'], $img); } $helper = new HelperForm(); // Module, token and currentIndex $helper->module = $this; $helper->name_controller = $this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name; // Language $helper->default_form_language = $this->context->language->id; $helper->allow_employee_form_lang = $this->context->language->id; // Title and toolbar $helper->title = $this->displayName; $helper->show_toolbar = true; $helper->toolbar_scroll = true; $helper->submit_action = 'submit'.$this->name; $helper->toolbar_btn = array( 'save' => array( 'desc' => $this->l('Save'), 'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name. '&token='.Tools::getAdminTokenLite('AdminModules'), ), 'back' => array( 'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'), 'desc' => $this->l('Back to list') ) ); // Load current values $helper->fields_value['PIXELCRUSH_ENABLE_IMAGES'] = Configuration::get('PIXELCRUSH_ENABLE_IMAGES'); $helper->fields_value['PIXELCRUSH_ENABLE_STATICS'] = Configuration::get('PIXELCRUSH_ENABLE_STATICS'); $helper->fields_value['PIXELCRUSH_USER_ACCOUNT'] = Configuration::get('PIXELCRUSH_USER_ACCOUNT'); $helper->fields_value['PIXELCRUSH_API_SECRET'] = Configuration::get('PIXELCRUSH_API_SECRET'); $helper->fields_value['PIXELCRUSH_FILTERS_PREFIX'] = Configuration::get('PIXELCRUSH_FILTERS_PREFIX'); $helper->fields_value['PIXELCRUSH_FILL_BACKGROUND'] = Configuration::get('PIXELCRUSH_FILL_BACKGROUND'); $helper->fields_value['PIXELCRUSH_URL_PROTOCOL'] = Configuration::get('PIXELCRUSH_URL_PROTOCOL'); return $helper->generateForm($fields_form); } /** * @throws PrestaShopDatabaseException */ public function loadImagesTypeHashes() { $this->images_types_hash = array(); foreach (array('products', 'categories', 'manufacturers', 'suppliers') as $type) { $type_hash = array(); foreach (ImageType::getImagesTypes($type) as $image_type) { $type_hash[ $image_type['name'] ] = $image_type; } $this->images_types_hash[ $type ] = $type_hash; } } public function loadCloudFiltersHash(array $cloud_cdn_filters) { $this->cloud_filters_hash = array(); foreach ($cloud_cdn_filters as $filter) { $this->cloud_filters_hash[ $filter->name ] = $filter; } } public function rezFilter($width, $height) { $bg = str_replace('#', '', Configuration::get('PIXELCRUSH_FILL_BACKGROUND')); $filter = sprintf('rz(o=f,w=' . $width . ',h=' . $height . ',b=%s)', (string)$bg); return $filter; } public function psFilterMap($entity, $type) { $filter_prefix = Configuration::get('PIXELCRUSH_FILTERS_PREFIX'); if (!empty($filter_prefix)) { return $filter_prefix . '_' . Tools::substr($entity, 0, 2) . '_' . $type; } return Tools::substr($entity, 0, 2) . '_' . $type; } /** * @return array * @throws PrestaShopDatabaseException */ public function imageTypesAsFilters() { if ($this->images_types_hash === null) { $this->loadImagesTypeHashes(); } $filters = array(); foreach (array('products', 'categories', 'manufacturers', 'suppliers') as $entity) { foreach ($this->images_types_hash[$entity] as $image_type) { $filter = (object)array ( 'name' => $this->psFilterMap($entity, $image_type['name']), 'filter' => $this->rezFilter($image_type['width'], $image_type['height']), 'nf' => null, 'ttl' => null, ); $filters[] = $filter; } } return $filters; } /** * @return mixed|null */ public function getUserCloud() { // if already loaded in this pageview if ($this->user_cloud !== null) { return $this->user_cloud; } // is cached by our class $this->user_cloud = $this->cache->get('PIXELCRUSH_USER_CLOUD'); if ($this->user_cloud !== null) { return $this->user_cloud; } // else, get it from API try { if ($this->apiIsCallable()) { // Cached results not valid anymore, we need to get them from user cloud and cache them again $this->user_cloud = $this->client->userCloud(); $this->cache->set('PIXELCRUSH_USER_CLOUD', $this->user_cloud, 24*3600); return $this->user_cloud; } } catch (Exception $e) { $this->logError($e->getMessage()); } return null; } /** * @param $msg */ private function logError($msg) { if (_PS_MODE_DEV_) { \Tools::error_log($msg); } elseif (version_compare(_PS_VERSION_, '1.6.0', '>=')) { \PrestaShopLogger::addLog($msg); } else { \Logger::addLog($msg); } } /** * @param $url * @param $entity * @param $type * @return string * @throws PrestaShopDatabaseException */ public function pixelcrushProxy($url, $entity, $type) { $params = array(); $filter = null; $user_cloud = $this->getUserCloud(); if ($user_cloud !== null && $this->cloud_filters_hash === null) { $this->loadCloudFiltersHash($this->user_cloud->cdn->filters); } // Using cloud filters if available if (isset($this->cloud_filters_hash[$this->psFilterMap($entity, $type)])) { $filter = $this->cloud_filters_hash[$this->psFilterMap($entity, $type)]; } // Ensure we have backup local image types just in case all/any cloud filter fails if ($this->images_types_hash === null) { $this->loadImagesTypeHashes(); } // Using hashed local image types if cloud is not available or has invalid value if ($filter === null && !empty($entity) && !empty($type)) { $image_type = $this->images_types_hash[$entity][$type]; $params['f'] = $this->rezFilter($image_type['width'], $image_type['height']); } // Ensure clients exists and build the url with the available data (cloud filter name or local resizing values) if ($this->client !== null) { return $this->client->imgProxiedUrl($url, $params, $filter, $this->config->url_protocol); } return $url; } public function cdnProxy($local_uri, $remote_uri, $newAssetManager = false) { $cdn_uri = null; if ($this->getClient() && @filemtime($local_uri) && @filesize($local_uri)) { $pixelcrush_proxy = $this->client->domain().'/cdn/'; $pixelcrush_ts = '?ttl='.filemtime($local_uri); if ($newAssetManager) { // 1.7: AbstractAssetManager $url = preg_replace('(^https?://)', '', ltrim(__PS_BASE_URI__.$remote_uri, '/')); $cdn_uri = $pixelcrush_proxy. Configuration::get('PIXELCRUSH_URL_PROTOCOL'). $url. $pixelcrush_ts; } else { // Legacy 1.7 / 1.6 / 1.5 Media $cdn_uri = $pixelcrush_proxy . Configuration::get('PIXELCRUSH_URL_PROTOCOL') . Tools::getShopDomain() . __PS_BASE_URI__ . ltrim($remote_uri, '/') . $pixelcrush_ts; } } return ($cdn_uri ?: $remote_uri); } public function isConfigured() { if (!empty($this->config->id) && !empty($this->config->api_secret_key)) { return true; } $this->config = (object)array( 'enable_images' => Configuration::get('PIXELCRUSH_ENABLE_IMAGES', false), 'enable_statics' => Configuration::get('PIXELCRUSH_ENABLE_STATICS', false), 'id' => Configuration::get('PIXELCRUSH_USER_ACCOUNT'), 'api_secret_key' => Configuration::get('PIXELCRUSH_API_SECRET'), 'rz_bg' => Configuration::get('PIXELCRUSH_FILL_BACKGROUND'), 'filters_prefix' => Configuration::get('PIXELCRUSH_FILTERS_PREFIX'), 'url_protocol' => Configuration::get('PIXELCRUSH_URL_PROTOCOL'), ); return !empty($this->config->id) && !empty($this->config->api_secret_key); } public function hookDisplayBackOfficeHeader(array $params) { // Load js/css styling files strictly only when user is on the configure module page if ($this->context->controller->controller_name === 'AdminModules' && Tools::getIsset('configure') && Tools::getValue('configure') === 'pixelcrush' ) { if (version_compare(_PS_VERSION_, '1.6.0', '<')) { $this->context->controller->addJS($this->_path . 'views/js/pixelcrush-bo.js'); } $this->context->controller->addCSS($this->_path . 'views/css/pixelcrush-bo.css'); } } public function hookActionObjectImageTypeAddAfter(array $params) { $this->processImageActionsHook($params); } public function hookActionObjectImageTypeDeleteAfter(array $params) { $this->processImageActionsHook($params); } public function hookActionObjectImageTypeUpdateAfter(array $params) { $this->processImageActionsHook($params); } public function processImageActionsHook($params) { if (isset($params['object'])) { if ($params['object'] instanceof ImageType) { if (!$this->resetCdnFilters(false)) { // Show (probably auth) error on admin image size form $this->context->controller->errors = $this->getErrors(); } } } } /** * @param bool $reset_existing * @return bool */ public function resetCdnFilters($reset_existing = true) { if ($this->apiIsCallable(false)) { try { // Ignore cached cloud, we need current account data to process $user_cloud = $this->client->userCloud(); if ($reset_existing) { foreach ($user_cloud->cdn->filters as $filter) { if (!empty($filter->name)) { $this->client->userCdnFilterDelete($filter->name); } } } // Get actual image sizes configuration and upload as filters foreach ($this->imageTypesAsFilters() as $filter) { $this->client->userCdnFilterUpsert($filter); } // User cloud has new data: update cache. TTL has already been updated by apiIsCallable() $this->user_cloud = $user_cloud; $this->cache->set('PIXELCRUSH_USER_CLOUD', $this->user_cloud, 24*3600); return true; } catch (Exception $e) { $this->_errors[] = $e->getMessage(); } } return false; } public function apiIsCallable($use_cache = true) { $client = $this->getClient(); if (!$client) { return false; } // being PHP 5.3 compatible is hard, we need to trick anonymous functions to be able to use $this vars. $errors_array = $this->_errors; $auth_api = function () use ($client, &$errors_array) { $ok = false; try { // Get client auth $ok = $client->userAuth(); } catch (Exception $e) { $errors_array[] = $e->getMessage(); } return $ok; }; $cached_value = null; if ($use_cache) { $cached_value = $this->cache->get('PIXELCRUSH_API_CHECK_VALID'); } $is_callable = $cached_value !== null ? (bool)$cached_value : $auth_api(); if ($is_callable) { $value = '1'; $ttl = 24*3600; } else { $value = '0'; $ttl = 300; } $this->cache->set('PIXELCRUSH_API_CHECK_VALID', $value, $ttl); return $is_callable; } public function getClient() { if ($this->isConfigured()) { if ($this->client === null) { try { $this->client = new \pixelcrush\ApiClient($this->config->id, $this->config->api_secret_key); } catch (Exception $e) { $this->_errors[] = $e->getMessage(); } } } return $this->client; } }
Pixelcrush/pixelcrush-prestashop
pixelcrush/pixelcrush.php
PHP
apache-2.0
27,758
/* * Copyright 2014 JBoss 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. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // 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: 2014.12.18 at 03:02:22 PM EST // package org.oasis_open.docs.s_ramp.ns.s_ramp_v1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.io.Serializable; /** * <p>Java class for PolicyExpression complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PolicyExpression"> * &lt;complexContent> * &lt;extension base="{http://docs.oasis-open.org/s-ramp/ns/s-ramp-v1.0}DerivedArtifactType"> * &lt;anyAttribute/> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PolicyExpression") public class PolicyExpression extends DerivedArtifactType implements Serializable { private static final long serialVersionUID = -2660664082872937248L; }
ArtificerRepo/s-ramp-tck
src/main/java/org/oasis_open/docs/s_ramp/ns/s_ramp_v1/PolicyExpression.java
Java
apache-2.0
1,851
package com.mazebert.error; public abstract class Error extends RuntimeException { public Error(String message) { super(message); } public Error(String message, Throwable cause) { super(message, cause); } public abstract int getStatusCode(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Error error = (Error) o; return getMessage() != null ? getMessage().equals(error.getMessage()) : error.getMessage() == null; } @Override public int hashCode() { return getMessage() != null ? getMessage().hashCode() : 0; } }
casid/mazebert-ladder
src/main/java/com/mazebert/error/Error.java
Java
apache-2.0
705
package com.pointr.tensorflow.api; import static com.pointr.tensorflow.api.TensorFlowIf.*; public class PcieDMAServer extends DMAServerBase implements TensorFlowIf.DMAServer { public PcieDMAServer() { String parentDir = System.getenv("GITDIR") + "/tfdma"; String ext = System.getProperty("os.name").equals("Mac OS X") ? ".dylib" : ".so"; String libpath = String.format("%s/%s%s",parentDir,"src/main/cpp/dmaserver",ext); Logger.info("Loading DMA native library " + libpath + " .."); try { System.load(libpath); } catch(Exception e) { Logger.error("Unable to load native library %s: %s".format( libpath, e.getMessage()),e); } } @Override public String setupChannel(String setupJson) { super.setupChannel(setupJson); return setupChannelN(setupJson); } @Override public String register(DMACallback callbackIf) { super.register(callbackIf); return registerN(callbackIf); } @Override public String prepareWrite(String configJson) { super.prepareWrite(configJson); return prepareWriteN(configJson); } @Override public DMAStructures.WriteResultStruct write(String configJson, byte[] dataPtr) { super.write(configJson, dataPtr); return writeN(configJson, dataPtr); } @Override public DMAStructures.WriteResultStruct completeWrite(String configJson) { super.completeWrite(configJson); return completeWriteN(configJson); } @Override public String prepareRead(String configJson) { super.prepareRead(configJson); return prepareReadN(configJson); } @Override public DMAStructures.ReadResultStruct read(String configJson) { super.read(configJson); return readN(configJson); } @Override public DMAStructures.ReadResultStruct completeRead(String configJson) { super.completeRead(configJson); return completeReadN(configJson); } @Override public String shutdownChannel(String shutdownJson) { super.shutdownChannel(shutdownJson); return shutdownChannelN(shutdownJson); } @Override public byte[] readLocal(byte[] dataPtr) { super.readLocal(dataPtr); return readLocalN(dataPtr); } native String setupChannelN(String setupJson); native String registerN(DMACallback callbackIf); native String prepareWriteN(String configJson); native DMAStructures.WriteResultStruct writeN(String configJson, byte[] dataPtr); native DMAStructures.WriteResultStruct completeWriteN(String configJson); native String prepareReadN(String configJson); native DMAStructures.ReadResultStruct readN(String configJson); native DMAStructures.ReadResultStruct completeReadN(String configJson); native String shutdownChannelN(String shutdownJson); native byte[] readLocalN(byte[] dataPtr); }
OpenChaiSpark/OCspark
tfdma/src/main/java/com/pointr/tensorflow/api/PcieDMAServer.java
Java
apache-2.0
2,774
/* * Copyright 2014-present Facebook, 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. */ package com.facebook.buck.cxx; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.step.Step; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import java.io.IOException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.ReadOnlyBufferException; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Arrays; /** * Scrub any non-deterministic meta-data from the given archive (e.g. timestamp, UID, GID). */ public class ArchiveScrubberStep implements Step { private static final byte[] FILE_MAGIC = {0x60, 0x0A}; private final Path archive; private final byte[] expectedGlobalHeader; public ArchiveScrubberStep( Path archive, byte[] expectedGlobalHeader) { this.archive = archive; this.expectedGlobalHeader = expectedGlobalHeader; } private byte[] getBytes(ByteBuffer buffer, int len) { byte[] bytes = new byte[len]; buffer.get(bytes); return bytes; } private int getDecimalStringAsInt(ByteBuffer buffer, int len) { byte[] bytes = getBytes(buffer, len); String str = new String(bytes, Charsets.US_ASCII); return Integer.parseInt(str.trim()); } private void putSpaceLeftPaddedString(ByteBuffer buffer, int len, String value) { Preconditions.checkState(value.length() <= len); value = Strings.padStart(value, len, ' '); buffer.put(value.getBytes(Charsets.US_ASCII)); } private void putIntAsOctalString(ByteBuffer buffer, int len, int value) { putSpaceLeftPaddedString(buffer, len, String.format("0%o", value)); } private void putIntAsDecimalString(ByteBuffer buffer, int len, int value) { putSpaceLeftPaddedString(buffer, len, String.format("%d", value)); } private void checkArchive(boolean expression, String msg) throws ArchiveException { if (!expression) { throw new ArchiveException(msg); } } /** * Efficiently modifies the archive backed by the given buffer to remove any non-deterministic * meta-data such as timestamps, UIDs, and GIDs. * @param archive a {@link ByteBuffer} wrapping the contents of the archive. */ @SuppressWarnings("PMD.AvoidUsingOctalValues") private void scrubArchive(ByteBuffer archive) throws ArchiveException { try { // Grab the global header chunk and verify it's accurate. byte[] globalHeader = getBytes(archive, this.expectedGlobalHeader.length); checkArchive( Arrays.equals(this.expectedGlobalHeader, globalHeader), "invalid global header"); // Iterate over all the file meta-data entries, injecting zero's for timestamp, // UID, and GID. while (archive.hasRemaining()) { /* File name */ getBytes(archive, 16); // Inject 0's for the non-deterministic meta-data entries. /* File modification timestamp */ putIntAsDecimalString(archive, 12, 0); /* Owner ID */ putIntAsDecimalString(archive, 6, 0); /* Group ID */ putIntAsDecimalString(archive, 6, 0); /* File mode */ putIntAsOctalString(archive, 8, 0100644); int fileSize = getDecimalStringAsInt(archive, 10); // Lastly, grab the file magic entry and verify it's accurate. byte[] fileMagic = getBytes(archive, 2); checkArchive( Arrays.equals(FILE_MAGIC, fileMagic), "invalid file magic"); // Skip the file data. archive.position(archive.position() + fileSize + fileSize % 2); } // Convert any low-level exceptions to `ArchiveExceptions`s. } catch (BufferUnderflowException | ReadOnlyBufferException e) { throw new ArchiveException(e.getMessage()); } } private FileChannel readWriteChannel(Path path) throws IOException { return FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE); } @Override public int execute(ExecutionContext context) throws InterruptedException { Path archivePath = context.getProjectFilesystem().resolve(archive); try { try (FileChannel channel = readWriteChannel(archivePath)) { MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size()); scrubArchive(map); } } catch (IOException | ArchiveException e) { context.logError(e, "Error scrubbing non-deterministic metadata from %s", archivePath); return 1; } return 0; } @Override public String getShortName() { return "archive-scrub"; } @Override public String getDescription(ExecutionContext context) { return "archive-scrub"; } @SuppressWarnings("serial") public static class ArchiveException extends Exception { public ArchiveException(String msg) { super(msg); } } }
MarkRunWu/buck
src/com/facebook/buck/cxx/ArchiveScrubberStep.java
Java
apache-2.0
5,492
import React from 'react'; import { screen } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import '__mock__/stripesCore.mock'; import renderWithRouter from 'helpers/renderWithRouter'; import account from 'fixtures/account'; import openLoans from 'fixtures/openLoans'; import okapiCurrentUser from 'fixtures/okapiCurrentUser'; import AccountDetails from './AccountDetails'; jest.mock('../../components/Accounts/Actions/FeeFineActions', () => () => <></>); jest.unmock('@folio/stripes/components'); const history = createMemoryHistory(); const props = { history, location: history.location, match: { params: { } }, isLoading: false, resources: { feefineshistory: { records: [] }, accountActions: {}, accounts: {}, feefineactions: {}, loans: {}, user: { update: jest.fn(), }, }, mutator: { activeRecord: { update: jest.fn(), }, feefineactions: { POST: jest.fn(), }, accountActions: { GET: jest.fn(), }, user: { update: jest.fn(), } }, num: 42, user: { id: '123' }, patronGroup: { group: 'Shiny happy people' }, itemDetails: {}, stripes: { hasPerm: () => true, }, account, owedAmount: 45.67, intl: {}, okapi: { url: 'https://localhost:9130', tenant: 'diku', okapiReady: true, authFailure: [], bindings: {}, currentUser: okapiCurrentUser, }, }; const accountWithLoan = { ...account, barcode: openLoans[0].item.barcode, loanId: openLoans[0].id, }; const accountWithAnonymizedLoan = { ...account, barcode: 'b612', }; const loanResources = { ...props.resources, loans: { records: openLoans, } }; const renderAccountDetails = (extraProps = {}) => renderWithRouter( <AccountDetails {...props} {...extraProps} /> ); afterEach(() => jest.clearAllMocks()); describe('Account Details', () => { test('without loan', () => { renderAccountDetails({ account }); expect(screen.getByTestId('loan-details')).toHaveTextContent(/-$/); }); test('with loan', () => { renderAccountDetails({ account: accountWithLoan, resources: loanResources }); expect(screen.getByTestId('loan-details')).toHaveTextContent(/ui-users.details.field.loan$/); }); test('with anonymized loan', () => { renderAccountDetails({ account: accountWithAnonymizedLoan, resources: loanResources }); expect(screen.getByTestId('loan-details')).toHaveTextContent(/ui-users.details.label.loanAnonymized$/); }); });
folio-org/ui-users
src/views/AccountDetails/AccountDetails.test.js
JavaScript
apache-2.0
2,518
#ifndef APIENDPOINT_HPP_7PXYTQE5 #define APIENDPOINT_HPP_7PXYTQE5 #include <utility> namespace dota2 { template<typename Backend> class APIEndpoint { public: template<typename T> APIEndpoint(T &&backend) : backend(std::forward<T>(backend)) { } template<typename Request> typename Request::obj query(const Request &request) { return backend.query(request); } protected: Backend backend; }; } // namespace dota2 #endif /* end of include guard: APIENDPOINT_HPP_7PXYTQE5 */
UnrealQuester/dota2Cmd
include/dota2api/apiendpoint.hpp
C++
apache-2.0
622
/** * Copyright (C) 2015 Red Hat, 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. */ package io.fabric8.crd.generator.v1; import com.fasterxml.jackson.databind.JsonNode; import io.fabric8.crd.example.annotated.Annotated; import io.fabric8.crd.example.basic.Basic; import io.fabric8.crd.example.extraction.IncorrectExtraction; import io.fabric8.crd.example.extraction.IncorrectExtraction2; import io.fabric8.crd.example.json.ContainingJson; import io.fabric8.crd.example.extraction.Extraction; import io.fabric8.crd.example.person.Person; import io.fabric8.crd.generator.utils.Types; import io.fabric8.kubernetes.api.model.apiextensions.v1.JSONSchemaProps; import io.sundr.model.TypeDef; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; class JsonSchemaTest { @Test void shouldCreateJsonSchemaFromClass() { TypeDef person = Types.typeDefFrom(Person.class); JSONSchemaProps schema = JsonSchema.from(person); assertNotNull(schema); Map<String, JSONSchemaProps> properties = schema.getProperties(); assertEquals(7, properties.size()); final List<String> personTypes = properties.get("type").getEnum().stream().map(JsonNode::asText) .collect(Collectors.toList()); assertEquals(2, personTypes.size()); assertTrue(personTypes.contains("crazy")); assertTrue(personTypes.contains("crazier")); final Map<String, JSONSchemaProps> addressProperties = properties.get("addresses").getItems() .getSchema().getProperties(); assertEquals(5, addressProperties.size()); final List<String> addressTypes = addressProperties.get("type").getEnum().stream() .map(JsonNode::asText) .collect(Collectors.toList()); assertEquals(2, addressTypes.size()); assertTrue(addressTypes.contains("home")); assertTrue(addressTypes.contains("work")); final TypeDef def = Types.typeDefFrom(Basic.class); schema = JsonSchema.from(def); assertNotNull(schema); properties = schema.getProperties(); assertNotNull(properties); assertEquals(2, properties.size()); Map<String, JSONSchemaProps> spec = properties.get("spec").getProperties(); assertEquals("integer", spec.get("myInt").getType()); assertEquals("integer", spec.get("myLong").getType()); Map<String, JSONSchemaProps> status = properties.get("status").getProperties(); assertEquals("string", status.get("message").getType()); } @Test void shouldAugmentPropertiesSchemaFromAnnotations() { TypeDef annotated = Types.typeDefFrom(Annotated.class); JSONSchemaProps schema = JsonSchema.from(annotated); assertNotNull(schema); Map<String, JSONSchemaProps> properties = schema.getProperties(); assertEquals(2, properties.size()); final JSONSchemaProps specSchema = properties.get("spec"); Map<String, JSONSchemaProps> spec = specSchema.getProperties(); assertEquals(6, spec.size()); // check descriptions are present assertTrue(spec.containsKey("from-field")); JSONSchemaProps prop = spec.get("from-field"); assertEquals("from-field-description", prop.getDescription()); assertTrue(spec.containsKey("from-getter")); prop = spec.get("from-getter"); assertEquals("from-getter-description", prop.getDescription()); // fields without description annotation shouldn't have them assertTrue(spec.containsKey("unnamed")); assertNull(spec.get("unnamed").getDescription()); assertTrue(spec.containsKey("emptySetter")); assertNull(spec.get("emptySetter").getDescription()); assertTrue(spec.containsKey("anEnum")); // check required list, should register properties with their modified name if needed final List<String> required = specSchema.getRequired(); assertEquals(2, required.size()); assertTrue(required.contains("emptySetter")); assertTrue(required.contains("from-getter")); // check the enum values final JSONSchemaProps anEnum = spec.get("anEnum"); final List<JsonNode> enumValues = anEnum.getEnum(); assertEquals(2, enumValues.size()); enumValues.stream().map(JsonNode::textValue).forEach(s -> assertTrue("oui".equals(s) || "non".equals(s))); // check ignored fields assertFalse(spec.containsKey("ignoredFoo")); assertFalse(spec.containsKey("ignoredBar")); } @Test void shouldProduceKubernetesPreserveFields() { TypeDef containingJson = Types.typeDefFrom(ContainingJson.class); JSONSchemaProps schema = JsonSchema.from(containingJson); assertNotNull(schema); Map<String, JSONSchemaProps> properties = schema.getProperties(); assertEquals(2, properties.size()); final JSONSchemaProps specSchema = properties.get("spec"); Map<String, JSONSchemaProps> spec = specSchema.getProperties(); assertEquals(3, spec.size()); // check preserve unknown fields is present assertTrue(spec.containsKey("free")); JSONSchemaProps freeField = spec.get("free"); assertTrue(freeField.getXKubernetesPreserveUnknownFields()); assertTrue(spec.containsKey("field")); JSONSchemaProps field = spec.get("field"); assertNull(field.getXKubernetesPreserveUnknownFields()); assertTrue(spec.containsKey("foo")); JSONSchemaProps fooField = spec.get("foo"); assertTrue(fooField.getXKubernetesPreserveUnknownFields()); } @Test void shouldExtractPropertiesSchemaFromExtractValueAnnotation() { TypeDef extraction = Types.typeDefFrom(Extraction.class); JSONSchemaProps schema = JsonSchema.from(extraction); assertNotNull(schema); Map<String, JSONSchemaProps> properties = schema.getProperties(); assertEquals(2, properties.size()); final JSONSchemaProps specSchema = properties.get("spec"); Map<String, JSONSchemaProps> spec = specSchema.getProperties(); assertEquals(2, spec.size()); // check typed SchemaFrom JSONSchemaProps foo = spec.get("foo"); Map<String, JSONSchemaProps> fooProps = foo.getProperties(); assertNotNull(fooProps); // you can change everything assertEquals("integer", fooProps.get("BAZ").getType()); assertTrue(foo.getRequired().contains("BAZ")); // you can exclude fields assertNull(fooProps.get("baz")); // check typed SchemaSwap JSONSchemaProps bar = spec.get("bar"); Map<String, JSONSchemaProps> barProps = bar.getProperties(); assertNotNull(barProps); // you can change everything assertEquals("integer", barProps.get("BAZ").getType()); assertTrue(bar.getRequired().contains("BAZ")); // you can exclude fields assertNull(barProps.get("baz")); } @Test void shouldThrowIfSchemaSwapHasUnmatchedField() { TypeDef incorrectExtraction = Types.typeDefFrom(IncorrectExtraction.class); assertThrows(IllegalArgumentException.class, () -> JsonSchema.from(incorrectExtraction)); } @Test void shouldThrowIfSchemaSwapHasUnmatchedClass() { TypeDef incorrectExtraction2 = Types.typeDefFrom(IncorrectExtraction2.class); assertThrows(IllegalArgumentException.class, () -> JsonSchema.from(incorrectExtraction2)); } }
fabric8io/kubernetes-client
crd-generator/api/src/test/java/io/fabric8/crd/generator/v1/JsonSchemaTest.java
Java
apache-2.0
7,648
/* * Copyright 2017 Young Digital Planet S.A. * * 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 eu.ydp.empiria.player.client.module.identification; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.json.client.JSONArray; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.xml.client.Element; import com.google.gwt.xml.client.Node; import com.google.inject.Inject; import eu.ydp.empiria.player.client.controller.body.InlineBodyGeneratorSocket; import eu.ydp.empiria.player.client.controller.variables.objects.response.CorrectAnswers; import eu.ydp.empiria.player.client.gin.factory.IdentificationModuleFactory; import eu.ydp.empiria.player.client.module.core.base.InteractionModuleBase; import eu.ydp.empiria.player.client.module.ModuleJsSocketFactory; import eu.ydp.empiria.player.client.module.identification.presenter.SelectableChoicePresenter; import eu.ydp.gwtutil.client.event.factory.Command; import eu.ydp.gwtutil.client.event.factory.EventHandlerProxy; import eu.ydp.gwtutil.client.event.factory.UserInteractionHandlerFactory; import eu.ydp.gwtutil.client.xml.XMLUtils; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class IdentificationModule extends InteractionModuleBase { private int maxSelections; private boolean locked = false; private boolean showingCorrectAnswers = false; @Inject private UserInteractionHandlerFactory interactionHandlerFactory; @Inject private IdentificationModuleFactory identificationModuleFactory; @Inject private IdentificationChoicesManager choicesManager; private final List<Element> multiViewElements = new ArrayList<>(); @Override public void addElement(Element element) { multiViewElements.add(element); } @Override public void installViews(List<HasWidgets> placeholders) { setResponseFromElement(multiViewElements.get(0)); maxSelections = XMLUtils.getAttributeAsInt(multiViewElements.get(0), "maxSelections"); for (int i = 0; i < multiViewElements.size(); i++) { Element element = multiViewElements.get(i); SelectableChoicePresenter selectableChoice = createSelectableChoiceFromElement(element); addClickHandler(selectableChoice); HasWidgets currPlaceholder = placeholders.get(i); currPlaceholder.add(selectableChoice.getView()); choicesManager.addChoice(selectableChoice); } } private SelectableChoicePresenter createSelectableChoiceFromElement(Element element) { Node simpleChoice = element.getElementsByTagName("simpleChoice").item(0); SelectableChoicePresenter selectableChoice = createSelectableChoice((Element) simpleChoice); return selectableChoice; } private SelectableChoicePresenter createSelectableChoice(Element item) { String identifier = XMLUtils.getAttributeAsString(item, "identifier"); InlineBodyGeneratorSocket inlineBodyGeneratorSocket = getModuleSocket().getInlineBodyGeneratorSocket(); Widget contentWidget = inlineBodyGeneratorSocket.generateInlineBody(item); SelectableChoicePresenter selectableChoice = identificationModuleFactory.createSelectableChoice(contentWidget, identifier); return selectableChoice; } private void addClickHandler(final SelectableChoicePresenter selectableChoice) { Command clickCommand = createClickCommand(selectableChoice); EventHandlerProxy userClickHandler = interactionHandlerFactory.createUserClickHandler(clickCommand); userClickHandler.apply(selectableChoice.getView()); } private Command createClickCommand(final SelectableChoicePresenter selectableChoice) { return new Command() { @Override public void execute(NativeEvent event) { onChoiceClick(selectableChoice); } }; } @Override public void lock(boolean locked) { this.locked = locked; if (locked) { choicesManager.lockAll(); } else { choicesManager.unlockAll(); } } @Override public void markAnswers(boolean mark) { CorrectAnswers correctAnswers = getResponse().correctAnswers; choicesManager.markAnswers(mark, correctAnswers); } @Override public void reset() { super.reset(); markAnswers(false); lock(false); choicesManager.clearSelections(); updateResponse(false, true); } @Override public void showCorrectAnswers(boolean show) { if (show) { CorrectAnswers correctAnswers = getResponse().correctAnswers; choicesManager.selectCorrectAnswers(correctAnswers); } else { List<String> values = getResponse().values; choicesManager.restoreView(values); } showingCorrectAnswers = show; } @Override public JavaScriptObject getJsSocket() { return ModuleJsSocketFactory.createSocketObject(this); } @Override public JSONArray getState() { return choicesManager.getState(); } @Override public void setState(JSONArray newState) { choicesManager.setState(newState); updateResponse(false); } private void onChoiceClick(SelectableChoicePresenter selectableChoice) { if (!locked) { selectableChoice.setSelected(!selectableChoice.isSelected()); Collection<SelectableChoicePresenter> selectedOptions = choicesManager.getSelectedChoices(); int currSelectionsCount = selectedOptions.size(); if (currSelectionsCount > maxSelections) { for (SelectableChoicePresenter choice : selectedOptions) { if (selectableChoice != choice) { choice.setSelected(false); break; } } } updateResponse(true); } } private void updateResponse(boolean userInteract) { updateResponse(userInteract, false); } private void updateResponse(boolean userInteract, boolean isReset) { if (!showingCorrectAnswers) { List<String> currResponseValues = choicesManager.getIdentifiersSelectedChoices(); if (!getResponse().compare(currResponseValues) || !getResponse().isInitialized()) { getResponse().set(currResponseValues); fireStateChanged(userInteract, isReset); } } } @Override public void onBodyLoad() { } @Override public void onBodyUnload() { } @Override public void onSetUp() { updateResponse(false); } @Override public void onStart() { } @Override public void onClose() { } }
YoungDigitalPlanet/empiria.player
src/main/java/eu/ydp/empiria/player/client/module/identification/IdentificationModule.java
Java
apache-2.0
7,707
/* * Copyright 2021 Apollo Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.ctrip.framework.apollo.openapi.v1.controller; import com.ctrip.framework.apollo.common.dto.ItemDTO; import com.ctrip.framework.apollo.common.exception.BadRequestException; import com.ctrip.framework.apollo.common.utils.RequestPrecondition; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO; import com.ctrip.framework.apollo.openapi.util.OpenApiBeanUtils; import com.ctrip.framework.apollo.portal.service.ItemService; import com.ctrip.framework.apollo.portal.spi.UserService; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpStatusCodeException; import javax.servlet.http.HttpServletRequest; @RestController("openapiItemController") @RequestMapping("/openapi/v1/envs/{env}") public class ItemController { private final ItemService itemService; private final UserService userService; public ItemController(final ItemService itemService, final UserService userService) { this.itemService = itemService; this.userService = userService; } @GetMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key:.+}") public OpenItemDTO getItem(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @PathVariable String key) { ItemDTO itemDTO = itemService.loadItem(Env.valueOf(env), appId, clusterName, namespaceName, key); return itemDTO == null ? null : OpenApiBeanUtils.transformFromItemDTO(itemDTO); } @PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)") @PostMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items") public OpenItemDTO createItem(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @RequestBody OpenItemDTO item, HttpServletRequest request) { RequestPrecondition.checkArguments( !StringUtils.isContainEmpty(item.getKey(), item.getDataChangeCreatedBy()), "key and dataChangeCreatedBy should not be null or empty"); if (userService.findByUserId(item.getDataChangeCreatedBy()) == null) { throw new BadRequestException("User " + item.getDataChangeCreatedBy() + " doesn't exist!"); } if(!StringUtils.isEmpty(item.getComment()) && item.getComment().length() > 256){ throw new BadRequestException("Comment length should not exceed 256 characters"); } ItemDTO toCreate = OpenApiBeanUtils.transformToItemDTO(item); //protect toCreate.setLineNum(0); toCreate.setId(0); toCreate.setDataChangeLastModifiedBy(toCreate.getDataChangeCreatedBy()); toCreate.setDataChangeLastModifiedTime(null); toCreate.setDataChangeCreatedTime(null); ItemDTO createdItem = itemService.createItem(appId, Env.valueOf(env), clusterName, namespaceName, toCreate); return OpenApiBeanUtils.transformFromItemDTO(createdItem); } @PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)") @PutMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key:.+}") public void updateItem(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @PathVariable String key, @RequestBody OpenItemDTO item, @RequestParam(defaultValue = "false") boolean createIfNotExists, HttpServletRequest request) { RequestPrecondition.checkArguments(item != null, "item payload can not be empty"); RequestPrecondition.checkArguments( !StringUtils.isContainEmpty(item.getKey(), item.getDataChangeLastModifiedBy()), "key and dataChangeLastModifiedBy can not be empty"); RequestPrecondition.checkArguments(item.getKey().equals(key), "Key in path and payload is not consistent"); if (userService.findByUserId(item.getDataChangeLastModifiedBy()) == null) { throw new BadRequestException("user(dataChangeLastModifiedBy) not exists"); } if(!StringUtils.isEmpty(item.getComment()) && item.getComment().length() > 256){ throw new BadRequestException("Comment length should not exceed 256 characters"); } try { ItemDTO toUpdateItem = itemService .loadItem(Env.valueOf(env), appId, clusterName, namespaceName, item.getKey()); //protect. only value,comment,lastModifiedBy can be modified toUpdateItem.setComment(item.getComment()); toUpdateItem.setValue(item.getValue()); toUpdateItem.setDataChangeLastModifiedBy(item.getDataChangeLastModifiedBy()); itemService.updateItem(appId, Env.valueOf(env), clusterName, namespaceName, toUpdateItem); } catch (Throwable ex) { if (ex instanceof HttpStatusCodeException) { // check createIfNotExists if (((HttpStatusCodeException) ex).getStatusCode().equals(HttpStatus.NOT_FOUND) && createIfNotExists) { createItem(appId, env, clusterName, namespaceName, item, request); return; } } throw ex; } } @PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)") @DeleteMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key:.+}") public void deleteItem(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @PathVariable String key, @RequestParam String operator, HttpServletRequest request) { if (userService.findByUserId(operator) == null) { throw new BadRequestException("user(operator) not exists"); } ItemDTO toDeleteItem = itemService.loadItem(Env.valueOf(env), appId, clusterName, namespaceName, key); if (toDeleteItem == null){ throw new BadRequestException("item not exists"); } itemService.deleteItem(Env.valueOf(env), toDeleteItem.getId(), operator); } }
ctripcorp/apollo
apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/ItemController.java
Java
apache-2.0
7,531
package com.felix.unbiz.json.rpc.util; import java.util.Collection; /** * ClassName: CollectionUtils <br> * Function: 集合工具类 * * @author wangxujin */ public final class CollectionUtils { private CollectionUtils() { } /** * 判断集合是否为空 * * @param coll 集合对象 * * @return */ public static boolean isEmpty(Collection coll) { return coll == null || coll.isEmpty(); } /** * 判断集合对象不为空 * * @param coll 集合对象 * * @return */ public static boolean isNotEmpty(Collection coll) { return !isEmpty(coll); } }
wangxujin/json-rpc
src/main/java/com/felix/unbiz/json/rpc/util/CollectionUtils.java
Java
apache-2.0
666
// this sets the background color of the master UIView (when there are no windows/tab groups on it) Titanium.UI.setBackgroundColor('#000'); Ti.API.info( "Platform: " + Titanium.Platform.name ); ///////////////////////////////////////////// // Global Variables ///////////////////////////////////////////// var site_url = 'http://www.wedvite.us/'; var idKey = ''; // This is the event_id_seq // Arbitrary Windows var arbitraryWinID = ''; var textAboutUs = ''; var textWeddingParty = ''; ///////////////////////////////////////////// // Creating All Windows ///////////////////////////////////////////// var windowLogin = Titanium.UI.createWindow({ title:'User Authentication', url:'main_windows/login.js', exitOnClose: true }); var windowHome = Titanium.UI.createWindow({ title:'Home Page', url:'main_windows/home.js' }); var windowEventInfo = Titanium.UI.createWindow({ title:'Event Info', url:'main_windows/eventInfo.js' }); var windowMap = Titanium.UI.createWindow({ title:'Map', url:'main_windows/map.js' }); var windowRsvp = Titanium.UI.createWindow({ title:'RSVP', url:'main_windows/rsvp.js' }); var windowArbitrary = Titanium.UI.createWindow({ title:'Arbitrary', url:'main_windows/arbitrary.js' }); // This window just displays a picture var windowFullPhoto = Titanium.UI.createWindow({ title:'Full PHoto', url:'main_windows/photoFullScreen.js' }); var windowPhotos = Titanium.UI.createWindow({ title:'Guests Photos', url:'main_windows/photos.js' }); var windowGiftRegistry = Titanium.UI.createWindow({ title:'Gift Registry', url:'main_windows/giftRegistry.js' }); var windowLBS = Titanium.UI.createWindow({ title:'Location Based Search', url:'main_windows/lbs.js' }); var windowLocationList = Titanium.UI.createWindow({ title:'LBS Location List', url:'main_windows/lbsLocationList.js' }); var windowLocationDetail = Titanium.UI.createWindow({ title:'LBS Location Details', url:'main_windows/lbsLocationDetails.js' }); var windowWeddingComments = Titanium.UI.createWindow({ title:'Wedding Comments', url:'main_windows/weddingComments.js' }); var windowComments = Titanium.UI.createWindow({ title:'Comment Anything Page', url:'main_windows/comments.js' }); var windowAnonymousLogin = Titanium.UI.createWindow({ title:'Anonymous Login', url:'main_windows/anonymousLogin.js' }); ///////////////////////////////////////////// // Creating App Objects ///////////////////////////////////////////// // Can only have one map view. Creating it here and passing it around var mapview = Titanium.Map.createView({ top:40, mapType: Titanium.Map.STANDARD_TYPE, animate:true, regionFit:true, userLocation:false }); // Having problems with webviews. Trying to create one and pass it around var webview = Titanium.UI.createWebView({ top:40, scalesPageToFit:false }); // Create our HTTP Client and name it "loader" //var loader = Titanium.Network.createHTTPClient(); ///////////////////////////////////////////// // Passing Variables to Each Window ///////////////////////////////////////////// // Login Window windowLogin.windowHome = windowHome; windowLogin.windowAnonymousLogin = windowAnonymousLogin; windowLogin.idkey = idKey; windowLogin.site_url = site_url; //windowLogin.loader = loader; // Home Screen Window windowHome.windowLogin = windowLogin; windowHome.windowEventInfo = windowEventInfo; windowHome.windowMap = windowMap; windowHome.mapview = mapview; windowHome.windowRsvp = windowRsvp; windowHome.idKey = idKey; windowHome.site_url = site_url; windowHome.windowArbitrary = windowArbitrary; windowHome.windowFullPhoto = windowFullPhoto; windowHome.windowPhotos = windowPhotos; windowHome.windowGiftRegistry = windowGiftRegistry; windowHome.windowLBS = windowLBS; windowHome.windowWeddingComments = windowWeddingComments; //windowHome.loader = loader; // Event Info Window windowEventInfo.windowHome = windowHome; windowEventInfo.idKey = idKey; windowEventInfo.site_url = site_url; //windowEventInfo.loader = loader; // Map Window windowMap.windowHome = windowHome; windowMap.mapview = mapview; windowMap.idKey = idKey; windowMap.site_url = site_url; //windowMap.loader = loader; // RSVP Window windowRsvp.windowHome = windowHome; windowRsvp.site_url = site_url; //windowRsvp.loader = loader; // Arbitrary Window windowArbitrary.windowHome = windowHome; windowArbitrary.site_url = site_url; //windowArbitrary.loader = loader; // Full Photo Window windowFullPhoto.windowHome = windowHome; windowFullPhoto.windowPhotos = windowPhotos; //windowFullPhoto.webview = webview; windowFullPhoto.windowComments = windowComments; // Photos windowPhotos.windowHome = windowHome; windowPhotos.windowFullPhoto = windowFullPhoto; windowPhotos.site_url = site_url; windowPhotos.idKey = idKey; //windowPhotos.loader = loader; // Gift Registry windowGiftRegistry.site_url = site_url; windowGiftRegistry.windowHome = windowHome; windowGiftRegistry.idKey = idKey; // LBS windowLBS.windowHome = windowHome; windowLBS.windowLocationList = windowLocationList; windowLBS.mapview = mapview; // LBS -> Category List windowLocationList.windowLocationDetail = windowLocationDetail; // LBS -> Category List -> Detail Page with map windowLocationDetail.windowLBS = windowLBS; // Wedding Comments windowWeddingComments.windowHome = windowHome; windowWeddingComments.idKey = idKey; windowWeddingComments.webview = webview; windowWeddingComments.site_url = site_url; // Comment Anything Page windowComments.webview = webview; windowComments.site_url = site_url; // Anonymous Login Screen windowAnonymousLogin.windowLogin = windowLogin; ///////////////////////////////////////////// // Open First Window ///////////////////////////////////////////// windowLogin.open();
sekka1/Events-App
Resources/app.js
JavaScript
apache-2.0
5,846
package com.google.api.ads.dfp.jaxws.v201405; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * An error having to do with {@link BaseRate}. * * * <p>Java class for BaseRateError complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="BaseRateError"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201405}ApiError"> * &lt;sequence> * &lt;element name="reason" type="{https://www.google.com/apis/ads/publisher/v201405}BaseRateError.Reason" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BaseRateError", propOrder = { "reason" }) public class BaseRateError extends ApiError { protected BaseRateErrorReason reason; /** * Gets the value of the reason property. * * @return * possible object is * {@link BaseRateErrorReason } * */ public BaseRateErrorReason getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link BaseRateErrorReason } * */ public void setReason(BaseRateErrorReason value) { this.reason = value; } }
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201405/BaseRateError.java
Java
apache-2.0
1,565
/******************************************************************************* * Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith * * 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.github.christophersmith.summer.mqtt.core.util; import org.springframework.context.ApplicationEventPublisher; import org.springframework.messaging.MessagingException; import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectedEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectionFailureEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectionLostEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttClientDisconnectedEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttMessageDeliveredEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttMessagePublishFailureEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttMessagePublishedEvent; /** * This is a convenience class that facilitates the publishing of Events to an * {@link ApplicationEventPublisher} instance. * <p> * This class in only used internally. */ public final class MqttClientEventPublisher { /** * Publishes a {@link MqttClientConnectedEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param serverUri the Server URI the MQTT Client is connected to * @param subscribedTopics the Topic Filters the MQTT Client is subscribed to * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } /** * Publishes a {@link MqttClientConnectionFailureEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param autoReconnect whether the MQTT Client will automatically reconnect * @param throwable the originating {@link Throwable} * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } /** * Publishes a {@link MqttClientConnectionLostEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param autoReconnect whether the MQTT Client will automatically reconnect * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } /** * Publishes a {@link MqttClientDisconnectedEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } /** * Publishes a {@link MqttMessageDeliveredEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param messageIdentifier the Message Identifier * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } /** * Publishes a {@link MqttMessagePublishedEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param messageIdentifier the Message Identifier * @param correlationId the Correlation ID * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } /** * Publishes a {@link MqttMessagePublishFailureEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param exception the {@link MessagingException} for this event * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessagePublishFailureEvent(clientId, exception, source)); } } }
christophersmith/summer-mqtt
summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/util/MqttClientEventPublisher.java
Java
apache-2.0
8,095
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require jquery.Jcrop.min //= require bootstrap //= require bootstrap-datepicker //= require jquery-fileupload/basic //= require attendances //= require courses //= require jcrop_mugshot //= require people //= require rolls //= require users //= require hogan-2.0.0 //= require typeahead //= require people_typeahead //= require underscore //= require jquery.tokeninput //= require token-input-wireup //= require_tree . function initializeDatePicker() { $('input.date_picker').datepicker({ autoclose: true, todayHighlight: true, dateFormat: 'mm/dd/yyyy' }); } $(document).ready(initializeDatePicker); $(document).on('page:change', initializeDatePicker); // whenever the bootstrap modal closes, reset it's contents $(function() { $('#myModal').on('hidden', function () { $('#myModal div.modal-body').html("<p>Loading... <i class=\"icon-refresh\"></i></p>"); $('#myModalLabel').text(''); }); }); // handle link_to remote and replace contents into data-replace id element $(function() { $(document) .data('type', 'html') .delegate('[data-remote][data-replace]', 'ajax:success', function(event, data) { var $this = $(this); $($this.data('replace')).html(data); $this.trigger('ajax:replaced'); }); });
mfrederickson/ssat
app/assets/javascripts/application.js
JavaScript
apache-2.0
1,885
package org.incode.module.document.dom.impl.docs.minio; import javax.inject.Inject; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.Mixin; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.value.Blob; import org.incode.module.document.DocumentModule; import org.incode.module.document.dom.impl.docs.Document; import org.incode.module.document.dom.impl.docs.DocumentSort; import org.incode.module.document.spi.minio.ExternalUrlDownloadService; @Mixin(method="act") public class Document_downloadExternalUrlAsBlob { private final Document document; public Document_downloadExternalUrlAsBlob(final Document document) { this.document = document; } public static class ActionDomainEvent extends DocumentModule.ActionDomainEvent<Document_downloadExternalUrlAsBlob> { } @Action( semantics = SemanticsOf.SAFE, domainEvent = ActionDomainEvent.class ) @ActionLayout(named = "Download") public Blob act() { return externalUrlDownloadService.downloadAsBlob(document); } public boolean hideAct() { return document.getSort() != DocumentSort.EXTERNAL_BLOB; } @Inject ExternalUrlDownloadService externalUrlDownloadService; }
estatio/estatio
estatioapp/app/src/main/java/org/incode/module/document/dom/impl/docs/minio/Document_downloadExternalUrlAsBlob.java
Java
apache-2.0
1,351
var searchData= [ ['scroll',['scroll',['../select2_8js.html#a6e3896ca7181e81b7757bfcca39055ec',1,'select2.js']]], ['scrollbardimensions',['scrollBarDimensions',['../select2_8js.html#a30eb565a7710bd54761b6bfbcfd9d3fd',1,'select2.js']]], ['select',['select',['../select2_8js.html#ac07257b5178416a2fbbba7365d2703a6',1,'select2.js']]], ['select2',['Select2',['../select2_8js.html#affb4af66e7784ac044be37289c148953',1,'Select2():&#160;select2.js'],['../select2_8js.html#a30a3359bfdd9ad6a698d6fd69a38a76a',1,'select2():&#160;select2.js']]], ['self',['self',['../select2_8js.html#ab3e74e211b41d329801623ae131d2585',1,'select2.js']]], ['singleselect2',['SingleSelect2',['../select2_8js.html#ab661105ae7b811b84224646465ea5c63',1,'select2.js']]], ['sizer',['sizer',['../select2_8js.html#a9db90058e07b269a04a8990251dab3c4',1,'select2.js']]], ['sn',['sn',['../j_query_8js.html#a70ece1b3f74db2cb3cb7e4b72d59b226',1,'jQuery.js']]] ];
zwmcfarland/MSEF
doxygen documentation/search/variables_15.js
JavaScript
apache-2.0
936
package imageapis import ( "fmt" "time" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kutilerrors "k8s.io/apimachinery/pkg/util/errors" kapi "k8s.io/kubernetes/pkg/apis/core" g "github.com/onsi/ginkgo" o "github.com/onsi/gomega" imageapi "github.com/openshift/origin/pkg/image/apis/image" imagesutil "github.com/openshift/origin/test/extended/images" exutil "github.com/openshift/origin/test/extended/util" testutil "github.com/openshift/origin/test/util" ) const ( imageSize = 100 quotaName = "isquota" waitTimeout = time.Second * 600 ) var _ = g.Describe("[Feature:ImageQuota][registry][Serial][Suite:openshift/registry/serial][local] Image resource quota", func() { defer g.GinkgoRecover() var oc = exutil.NewCLI("resourcequota-admission", exutil.KubeConfigPath()) g.JustBeforeEach(func() { g.By("Waiting for builder service account") err := exutil.WaitForBuilderAccount(oc.KubeClient().Core().ServiceAccounts(oc.Namespace())) o.Expect(err).NotTo(o.HaveOccurred()) }) // needs to be run at the of of each It; cannot be run in AfterEach which is run after the project // is destroyed tearDown := func(oc *exutil.CLI) { g.By(fmt.Sprintf("Deleting quota %s", quotaName)) oc.AdminKubeClient().Core().ResourceQuotas(oc.Namespace()).Delete(quotaName, nil) deleteTestImagesAndStreams(oc) } g.It(fmt.Sprintf("should deny a push of built image exceeding %s quota", imageapi.ResourceImageStreams), func() { defer tearDown(oc) dClient, err := testutil.NewDockerClient() o.Expect(err).NotTo(o.HaveOccurred()) outSink := g.GinkgoWriter quota := kapi.ResourceList{ imageapi.ResourceImageStreams: resource.MustParse("0"), } _, err = createResourceQuota(oc, quota) o.Expect(err).NotTo(o.HaveOccurred()) g.By(fmt.Sprintf("trying to push image exceeding quota %v", quota)) _, _, err = imagesutil.BuildAndPushImageOfSizeWithDocker(oc, dClient, "first", "refused", imageSize, 1, outSink, false, true) o.Expect(err).NotTo(o.HaveOccurred()) quota, err = bumpQuota(oc, imageapi.ResourceImageStreams, 1) o.Expect(err).NotTo(o.HaveOccurred()) g.By(fmt.Sprintf("trying to push image below quota %v", quota)) _, _, err = imagesutil.BuildAndPushImageOfSizeWithDocker(oc, dClient, "first", "tag1", imageSize, 1, outSink, true, true) o.Expect(err).NotTo(o.HaveOccurred()) used, err := waitForResourceQuotaSync(oc, quotaName, quota) o.Expect(err).NotTo(o.HaveOccurred()) o.Expect(assertQuotasEqual(used, quota)).NotTo(o.HaveOccurred()) g.By(fmt.Sprintf("trying to push image to existing image stream %v", quota)) _, _, err = imagesutil.BuildAndPushImageOfSizeWithDocker(oc, dClient, "first", "tag2", imageSize, 1, outSink, true, true) o.Expect(err).NotTo(o.HaveOccurred()) g.By(fmt.Sprintf("trying to push image exceeding quota %v", quota)) _, _, err = imagesutil.BuildAndPushImageOfSizeWithDocker(oc, dClient, "second", "refused", imageSize, 1, outSink, false, true) quota, err = bumpQuota(oc, imageapi.ResourceImageStreams, 2) o.Expect(err).NotTo(o.HaveOccurred()) used, err = waitForResourceQuotaSync(oc, quotaName, used) o.Expect(err).NotTo(o.HaveOccurred()) g.By(fmt.Sprintf("trying to push image below quota %v", quota)) _, _, err = imagesutil.BuildAndPushImageOfSizeWithDocker(oc, dClient, "second", "tag1", imageSize, 1, outSink, true, true) o.Expect(err).NotTo(o.HaveOccurred()) used, err = waitForResourceQuotaSync(oc, quotaName, quota) o.Expect(err).NotTo(o.HaveOccurred()) o.Expect(assertQuotasEqual(used, quota)).NotTo(o.HaveOccurred()) g.By(fmt.Sprintf("trying to push image exceeding quota %v", quota)) _, _, err = imagesutil.BuildAndPushImageOfSizeWithDocker(oc, dClient, "third", "refused", imageSize, 1, outSink, false, true) o.Expect(err).NotTo(o.HaveOccurred()) g.By("deleting first image stream") err = oc.ImageClient().Image().ImageStreams(oc.Namespace()).Delete("first", nil) o.Expect(err).NotTo(o.HaveOccurred()) used, err = exutil.WaitForResourceQuotaSync( oc.InternalKubeClient().Core().ResourceQuotas(oc.Namespace()), quotaName, kapi.ResourceList{imageapi.ResourceImageStreams: resource.MustParse("1")}, true, waitTimeout, ) o.Expect(err).NotTo(o.HaveOccurred()) o.Expect(assertQuotasEqual(used, kapi.ResourceList{imageapi.ResourceImageStreams: resource.MustParse("1")})).NotTo(o.HaveOccurred()) g.By(fmt.Sprintf("trying to push image below quota %v", quota)) _, _, err = imagesutil.BuildAndPushImageOfSizeWithDocker(oc, dClient, "third", "tag", imageSize, 1, outSink, true, true) o.Expect(err).NotTo(o.HaveOccurred()) used, err = waitForResourceQuotaSync(oc, quotaName, quota) o.Expect(err).NotTo(o.HaveOccurred()) o.Expect(assertQuotasEqual(used, quota)).NotTo(o.HaveOccurred()) }) }) // createResourceQuota creates a resource quota with given hard limits in a current namespace and waits until // a first usage refresh func createResourceQuota(oc *exutil.CLI, hard kapi.ResourceList) (*kapi.ResourceQuota, error) { rq := &kapi.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{ Name: quotaName, }, Spec: kapi.ResourceQuotaSpec{ Hard: hard, }, } g.By(fmt.Sprintf("creating resource quota with a limit %v", hard)) rq, err := oc.InternalAdminKubeClient().Core().ResourceQuotas(oc.Namespace()).Create(rq) if err != nil { return nil, err } err = waitForLimitSync(oc, hard) return rq, err } // assertQuotasEqual compares two quota sets and returns an error with proper description when they don't match func assertQuotasEqual(a, b kapi.ResourceList) error { errs := []error{} if len(a) != len(b) { errs = append(errs, fmt.Errorf("number of items does not match (%d != %d)", len(a), len(b))) } for k, av := range a { if bv, exists := b[k]; exists { if av.Cmp(bv) != 0 { errs = append(errs, fmt.Errorf("a[%s] != b[%s] (%s != %s)", k, k, av.String(), bv.String())) } } else { errs = append(errs, fmt.Errorf("resource %q not present in b", k)) } } for k := range b { if _, exists := a[k]; !exists { errs = append(errs, fmt.Errorf("resource %q not present in a", k)) } } return kutilerrors.NewAggregate(errs) } // bumpQuota modifies hard spec of quota object with the given value. It returns modified hard spec. func bumpQuota(oc *exutil.CLI, resourceName kapi.ResourceName, value int64) (kapi.ResourceList, error) { g.By(fmt.Sprintf("bump the quota to %s=%d", resourceName, value)) rq, err := oc.InternalAdminKubeClient().Core().ResourceQuotas(oc.Namespace()).Get(quotaName, metav1.GetOptions{}) if err != nil { return nil, err } rq.Spec.Hard[resourceName] = *resource.NewQuantity(value, resource.DecimalSI) _, err = oc.InternalAdminKubeClient().Core().ResourceQuotas(oc.Namespace()).Update(rq) if err != nil { return nil, err } err = waitForLimitSync(oc, rq.Spec.Hard) if err != nil { return nil, err } return rq.Spec.Hard, nil } // waitForResourceQuotaSync waits until a usage of a quota reaches given limit with a short timeout func waitForResourceQuotaSync(oc *exutil.CLI, name string, expectedResources kapi.ResourceList) (kapi.ResourceList, error) { g.By(fmt.Sprintf("waiting for resource quota %s to get updated", name)) used, err := exutil.WaitForResourceQuotaSync( oc.InternalKubeClient().Core().ResourceQuotas(oc.Namespace()), quotaName, expectedResources, false, waitTimeout, ) if err != nil { return nil, err } return used, nil } // waitForLimitSync waits until a usage of a quota reaches given limit with a short timeout func waitForLimitSync(oc *exutil.CLI, hardLimit kapi.ResourceList) error { g.By(fmt.Sprintf("waiting for resource quota %s to get updated", quotaName)) return testutil.WaitForResourceQuotaLimitSync( oc.InternalKubeClient().Core().ResourceQuotas(oc.Namespace()), quotaName, hardLimit, waitTimeout) } // deleteTestImagesAndStreams deletes test images built in current and shared // namespaces. It also deletes shared projects. func deleteTestImagesAndStreams(oc *exutil.CLI) { for _, projectName := range []string{ oc.Namespace() + "-s2", oc.Namespace() + "-s1", oc.Namespace() + "-shared", oc.Namespace(), } { g.By(fmt.Sprintf("Deleting images and image streams in project %q", projectName)) iss, err := oc.AdminImageClient().Image().ImageStreams(projectName).List(metav1.ListOptions{}) if err != nil { continue } for _, is := range iss.Items { for _, history := range is.Status.Tags { for i := range history.Items { oc.AdminImageClient().Image().Images().Delete(history.Items[i].Image, nil) } } for _, tagRef := range is.Spec.Tags { switch tagRef.From.Kind { case "ImageStreamImage": _, id, err := imageapi.ParseImageStreamImageName(tagRef.From.Name) if err != nil { continue } oc.AdminImageClient().Image().Images().Delete(id, nil) } } } // let the extended framework take care of the current namespace if projectName != oc.Namespace() { g.By(fmt.Sprintf("Deleting project %q", projectName)) oc.AdminProjectClient().Project().Projects().Delete(projectName, nil) } } }
php-coder/origin
test/extended/imageapis/quota_admission.go
GO
apache-2.0
9,127
package dataparser; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class TestReadDate { public static void main(String[] args) { String file = "D:\\工作积累\\CSDN-中文IT社区-600万\\www.csdn.net.sql"; int cache = 10000; int dbcache = 1000; try { List<DataBean> list = new ArrayList<DataBean>(); DataBean bean = null; String[] data = null; String temp = null; BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); while ((temp = br.readLine()) != null) { data = temp.split("#"); bean = new DataBean(); bean.setName(null); bean.setPassword(null); bean.setEmail(data[2].trim()); if (list.size() < cache) { list.add(bean); } else { DBHelper.insertData(list, dbcache); list.clear(); } } if (list.size() > 0) { DBHelper.insertData(list, dbcache); list.clear(); } } catch (Exception e) { e.printStackTrace(); } } }
toulezu/play
sendEmail/test/dataparser/TestReadDate.java
Java
artistic-2.0
1,071
#ifndef YOBAPERL_PERL_STACK_HPP #define YOBAPERL_PERL_STACK_HPP #include "yobaperl/common.hpp" namespace yoba { class Perl; class Scalar; class Array; class Code; } namespace yoba { namespace priv { class PerlStack { public: PerlStack(Perl & perl); ~PerlStack(); void extend(SSize_t size); void pushSV(SV * sv, bool extend); SV * popSV(); void pushScalar(Scalar arg); void pushArray(Array args); Scalar popScalar(); Array popArray(); void call(Code code, I32 flags); void callMethod(Code code, I32 flags); void eval(const std::string & code, I32 flags); private: Perl & _perl; PerlInterpreter * _interpreter = nullptr; SV ** sp = nullptr; I32 _returns_count = -1; }; }} // namespace yoba::priv #endif // YOBAPERL_PERL_STACK_HPP
theanonym/libyoba-perl
include/yobaperl/perl_stack.hpp
C++
artistic-2.0
794
using UnityEngine; using System.Collections; using System.Collections.Generic; [AddComponentMenu("Ferr SuperCube/SuperMesh Combiner")] public class SuperMeshCombiner : MonoBehaviour { public const int MaxVerts = 65534; class Subset { public List<Vector3> mPoints = new List<Vector3>(); public List<Vector3> mNormals = new List<Vector3>(); public List<Vector2> mUVs = new List<Vector2>(); public List<Vector2> mLightUVs = new List<Vector2>(); public List<Vector4> mTangents = new List<Vector4>(); public List<Color> mColors = new List<Color>(); public List<int > mIndices = new List<int>(); public Material mMaterial = null; public int mLightmapID = -1; public int mMeshGroup = -1; public int Count { get {return mPoints.Count;} } public void Add (Subset aOther) { CheckArrays(aOther); mPoints .AddRange(aOther.mPoints); mNormals .AddRange(aOther.mNormals); mUVs .AddRange(aOther.mUVs); mLightUVs.AddRange(aOther.mLightUVs); mTangents.AddRange(aOther.mTangents); mColors .AddRange(aOther.mColors); } public void CheckArrays(Subset aSubset = null) { if (aSubset == null) aSubset = this; if (aSubset.mNormals .Count > 0) CheckFilled<Vector3>(ref mNormals, Vector3.zero, mPoints.Count); if (aSubset.mUVs .Count > 0) CheckFilled<Vector2>(ref mUVs, Vector2.zero, mPoints.Count); if (aSubset.mLightUVs.Count > 0) CheckFilled<Vector2>(ref mLightUVs, Vector2.zero, mPoints.Count); if (aSubset.mTangents.Count > 0) CheckFilled<Vector4>(ref mTangents, Vector4.zero, mPoints.Count); if (aSubset.mColors .Count > 0) CheckFilled<Color >(ref mColors, Color.white, mPoints.Count); } static void CheckFilled<T>(ref List<T> aList, T aValue, int aCount) { for (int i = aList.Count; i < aCount; i++) { aList.Add(aValue); } } } [SerializeField] bool mOnlyCombineChildren = false; #if UNITY_5 [SerializeField, HideInInspector] #else [SerializeField] #endif bool mOnlyStaticObjects = false; [SerializeField] bool mOnlySuperObjects = false; [SerializeField] bool mLogTimeCost = false; public void Start() { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); bool isPro = Application.HasProLicense(); #if UNITY_5 isPro = true; #endif // Find all the meshes in our domain MeshFilter[] meshes = null; if (mOnlyCombineChildren) { meshes = GetComponentsInChildren <MeshFilter>(); } else { meshes = GameObject.FindObjectsOfType<MeshFilter>(); } List<Subset> subsets = new List<Subset>(); Dictionary<int, int> layers = new Dictionary<int, int>(); int validCount = 0; for (int i = 0; i < meshes.Length; i+=1) { // determine if the mesh is valid, and check it with our settings if (meshes[i] == null || meshes[i].sharedMesh == null) continue; if (meshes[i].GetComponent<SuperMeshCombiner>() != null) continue; if (mOnlySuperObjects && meshes[i].GetComponent(typeof(Ferr.IProceduralMesh)) == null) continue; if (isPro && meshes[i].gameObject.isStatic) continue; // Unity pro is already handling this object, we'll only crash the program if we try this. if (mOnlyStaticObjects && !meshes[i].gameObject.isStatic) continue; // just tracking count =D validCount += 1; // add the material subsets of the valid mesh Renderer r = meshes[i].GetComponent<Renderer>(); Matrix4x4 mat = meshes[i].transform.localToWorldMatrix; for (int s = 0; s < meshes[i].sharedMesh.subMeshCount; s+=1) { #if UNITY_5 AddSubset(ref subsets, meshes[i].sharedMesh, r.lightmapIndex, s, r.sharedMaterials[s], mat, r.realtimeLightmapScaleOffset); #else AddSubset(ref subsets, meshes[i].sharedMesh, r.lightmapIndex, s, r.sharedMaterials[s], mat, r.lightmapTilingOffset); #endif } r.enabled = false; // keep track what layer this is on, and how many are on it if (!layers.ContainsKey(meshes[i].gameObject.layer)) layers.Add(meshes[i].gameObject.layer, 0); layers[meshes[i].gameObject.layer] += 1; } // figure out the most common layer type, and use that for our layer overall if (gameObject.layer == 0) { int commonLayer = gameObject.layer; int max = 0; foreach (KeyValuePair<int, int> pair in layers) { if (pair.Value > max) { commonLayer = pair.Key; max = pair.Value; } } gameObject.layer = commonLayer; } // create meshes based on the info we've collected int lightmapCount = LightmapCount(subsets); for (int i=0; i<lightmapCount; i+=1) { CreateSizedMeshes(gameObject, subsets, LightmapID(subsets, i)); } sw.Stop(); if (mLogTimeCost) Debug.Log(string.Format("Merging geometry [{1} objects scanned: {2} valid, {3} subsets]: {0}ms", System.Math.Round((float)sw.Elapsed.TotalMilliseconds, 2), meshes.Length, validCount, subsets.Count)); } static void CreateSizedMeshes(GameObject aParent, List<Subset> aSubsets, int aLightmapID) { List<List<Subset>> sizedMeshes = new List<List<Subset>>(); List<int> meshVertCount = new List<int>(); // this should reduce extra draw calls that might happen when mesh subsets get split too small aSubsets.Sort((a,b)=> {return a.mMaterial==null?0:a.mMaterial.GetInstanceID().CompareTo(b.mMaterial==null?0:b.mMaterial.GetInstanceID());}); sizedMeshes .Add(new List<Subset>()); meshVertCount.Add(0); for (int i = 0; i < aSubsets.Count; i++) { if (aSubsets[i].mLightmapID != aLightmapID) continue; // see if we can find room in one of the meshes we're about to create bool found = false; for (int m = 0; m < sizedMeshes.Count; m++) { if (meshVertCount[m] + aSubsets[i].Count < SuperMeshCombiner.MaxVerts) { found = true; meshVertCount[m] += aSubsets[i].Count; sizedMeshes [m].Add(aSubsets[i]); } } // if there's no room, add a new mesh to the end! if (!found) { List<Subset> newMesh = new List<Subset>(); newMesh.Add(aSubsets[i]); meshVertCount.Add(aSubsets[i].Count); sizedMeshes .Add(newMesh); } } // create a mesh object for each collection of subsets for (int i = 0; i < sizedMeshes.Count; i++) { GameObject go = new GameObject("Lightmap_" + aLightmapID + "_mesh_" + i); MeshFilter mesh = go.AddComponent<MeshFilter >(); MeshRenderer r = go.AddComponent<MeshRenderer>(); mesh.sharedMesh = MergeSubsets(sizedMeshes[i], aLightmapID); r.sharedMaterials = GetMaterials(sizedMeshes[i], aLightmapID); r.lightmapIndex = aLightmapID; go.layer = aParent.layer; go.transform.parent = aParent.transform; go.transform.position = Vector3.zero; go.transform.localScale = Vector3.one; go.transform.rotation = Quaternion.identity; } } static void AddSubset(ref List<Subset> aSubsets, Mesh aMesh, int aLightmapID, int aMeshSubsetID, Material aMaterial, Matrix4x4 aTransform, Vector4 aLightmapOffset) { Vector3[] meshVerts = aMesh.vertices; Vector3[] meshNorms = aMesh.normals; Vector4[] meshTans = aMesh.tangents; Vector2[] meshUVs = aMesh.uv; Color [] meshColors = aMesh.colors; int [] inds = aMesh.GetIndices( aMeshSubsetID ); #if UNITY_5 Vector2[] meshLightUVs = aMesh.uv2; #else Vector2[] meshLightUVs = aMesh.uv1; #endif SortedList remapIndices = new SortedList(); List<Vector3> verts = new List<Vector3>(); List<Vector3> norms = new List<Vector3>(); List<Vector2> uvs = new List<Vector2>(); List<Vector2> lights = new List<Vector2>(); List<Vector4> tans = new List<Vector4>(); List<Color> cols = new List<Color> (); List<int> setInds= new List<int> (); // gather all mesh data in this subset, and remap the indices to match the new index of each vert. for (int i = 0; i < inds.Length; ++i) { int id = inds[i]; int remap = remapIndices.IndexOfKey(id); if (remap == -1) { remapIndices.Add(id, verts.Count); setInds .Add( verts.Count); verts .Add(aTransform.MultiplyPoint3x4(meshVerts[id])); norms .Add(aTransform.MultiplyVector (meshNorms[id])); uvs .Add(meshUVs [id]); if (meshColors.Length > 0) { cols.Add(meshColors [id]); } else { cols.Add(Color.white); } if (meshLightUVs.Length >= meshUVs.Length) { lights.Add(new Vector2(aLightmapOffset.z, aLightmapOffset.w) + Vector2.Scale(new Vector2(aLightmapOffset.x, aLightmapOffset.y), meshLightUVs[id])); } tans.Add(meshTans[id]); } else { setInds.Add((int)remapIndices.GetByIndex(remap)); } } // find a subset that matches material, lightmap, and has room for this mesh! int subsetID = -1; for (int i = 0; i < aSubsets.Count; i+=1) { if (aSubsets[i].mMaterial == aMaterial && aSubsets[i].mLightmapID == aLightmapID && aSubsets[i].Count+verts.Count < SuperMeshCombiner.MaxVerts) { subsetID = i; } } // if none was found, add one if (subsetID == -1) { Subset s = new Subset(); s.mMaterial = aMaterial; s.mLightmapID = aLightmapID; aSubsets.Add(s); subsetID = aSubsets.Count-1; } // fill the subset with the data we just gathered Subset set = aSubsets[subsetID]; int startID = set.mPoints.Count; set.mPoints .AddRange(verts ); set.mNormals .AddRange(norms ); set.mColors .AddRange(cols ); set.mUVs .AddRange(uvs ); set.mLightUVs.AddRange(lights); set.mTangents.AddRange(tans ); for (int i=0; i<setInds.Count; i++) set.mIndices.Add(setInds[i] + startID); } static Mesh MergeSubsets(List<Subset> aSubsets, int aLightmapID) { Mesh result = new Mesh(); Subset resultSubset = new Subset(); List<List<int>> indices = new List<List<int>>(); for (int i = 0; i < aSubsets.Count; ++i) { if (aSubsets[i].mLightmapID != aLightmapID) continue; int startID = resultSubset.Count; resultSubset.Add(aSubsets[i]); List<int> subIndices = new List<int>(); for (int t = 0; t < aSubsets[i].mIndices.Count; t+=1) { subIndices.Add(startID + aSubsets[i].mIndices[t]); } indices.Add(subIndices); } // cap it off if we used that category of data at all! resultSubset.CheckArrays(); result.vertices = resultSubset.mPoints .ToArray(); result.normals = resultSubset.mNormals .ToArray(); result.uv = resultSubset.mUVs .ToArray(); result.tangents = resultSubset.mTangents.ToArray(); result.colors = resultSubset.mColors .ToArray(); #if UNITY_5 result.uv2 = resultSubset.mLightUVs.ToArray(); #else result.uv1 = resultSubset.mLightUVs.ToArray(); #endif result.subMeshCount = aSubsets.Count; for (int i = 0; i < indices.Count; ++i) { result.SetIndices(indices[i].ToArray(), MeshTopology.Triangles, i); } result.RecalculateBounds(); return result; } static Material[] GetMaterials(List<Subset> aSubsets ,int aLightmapID) { List<Material> result = new List<Material>(aSubsets.Count); for (int i=0; i<aSubsets.Count; i+=1) { if (aSubsets[i].mLightmapID == aLightmapID) { result.Add(aSubsets[i].mMaterial); } } return result.ToArray(); } static int LightmapCount(List<Subset> aSubsets) { List<int> lightmaps = new List<int>(); for (int i = 0; i < aSubsets.Count; i+=1) { if (!lightmaps.Contains(aSubsets[i].mLightmapID)) lightmaps.Add(aSubsets[i].mLightmapID); } return lightmaps.Count; } static int LightmapID(List<Subset> aSubsets, int aIndex) { List<int> lightmaps = new List<int>(); for (int i = 0; i < aSubsets.Count; i+=1) { if (!lightmaps.Contains(aSubsets[i].mLightmapID)) { if (lightmaps.Count == aIndex) { return aSubsets[i].mLightmapID; } lightmaps.Add(aSubsets[i].mLightmapID); } } return -1; } }
Rckdrigo/Emma
Assets/Ferr/SuperCube/Scripts/SuperMeshCombiner.cs
C#
artistic-2.0
11,802
<?php use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; // Enable APC for autoloading to improve performance. // You should change the ApcClassLoader first argument to a unique prefix // in order to prevent cache key conflicts with other applications // also using APC. $apcLoader = new ApcClassLoader(sha1(__FILE__), $loader); $loader->unregister(); $apcLoader->register(true); require_once __DIR__.'/../app/AppKernel.php'; require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', true); $kernel->loadClassCache(); $kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
sasedev/alluco
web/app.php
PHP
artistic-2.0
1,001
package com.sloop.adapter.utils; import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import java.util.ArrayList; import java.util.List; /** * ListView 的通用适配器 * Author: Sloop * Version: v1.1 * Date: 2015/11/17 * <ul type="disc"> * <li><a href="http://www.sloop.icoc.cc" target="_blank">作者网站</a> </li> * <li><a href="http://weibo.com/5459430586" target="_blank">作者微博</a> </li> * <li><a href="https://github.com/GcsSloop" target="_blank">作者GitHub</a> </li> * </ul> */ public abstract class CommonAdapter<T> extends BaseAdapter { private LayoutInflater mInflater; private Context mContext; private List<T> mDatas = new ArrayList<>(); private int mLayoutId; /** * @param context 上下文 * @param datas 数据集 * @param layoutId 布局ID */ public CommonAdapter(@NonNull Context context, List<T> datas, @NonNull int layoutId) { mInflater = LayoutInflater.from(context); this.mContext = context; this.mLayoutId = layoutId; if(datas!=null){ this.mDatas = datas; } } public void addDatas(List<T> datas){ this.mDatas.addAll(datas); notifyDataSetChanged(); } public void clearDatas(){ this.mDatas.clear(); notifyDataSetChanged(); } public T getDataById(int position){ return mDatas.get(position); } @Override public int getCount() { return mDatas.size(); } @Override public T getItem(int position) { return mDatas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { //实例化一个ViewHolder ViewHolder holder = ViewHolder.getInstance(mContext, convertView, parent, mLayoutId, position); //需要自定义的部分 convert(position, holder, getItem(position)); return holder.getConvertView(); } /** * 需要处理的部分,在这里给View设置值 * * @param holder ViewHolder * @param bean 数据集 */ public abstract void convert(int position, ViewHolder holder, T bean); }
GcsSloop/SUtils
library/src/main/java/com/sloop/adapter/utils/CommonAdapter.java
Java
artistic-2.0
2,424
from __future__ import absolute_import, unicode_literals import os from django import VERSION as DJANGO_VERSION from django.utils.translation import ugettext_lazy as _ ###################### # MEZZANINE SETTINGS # ###################### # The following settings are already defined with default values in # the ``defaults.py`` module within each of Mezzanine's apps, but are # common enough to be put here, commented out, for conveniently # overriding. Please consult the settings documentation for a full list # of settings Mezzanine implements: # http://mezzanine.jupo.org/docs/configuration.html#default-settings # Controls the ordering and grouping of the admin menu. # # ADMIN_MENU_ORDER = ( # ("Content", ("pages.Page", "blog.BlogPost", # "generic.ThreadedComment", (_("Media Library"), "media-library"),)), # ("Site", ("sites.Site", "redirects.Redirect", "conf.Setting")), # ("Users", ("auth.User", "auth.Group",)), # ) # A three item sequence, each containing a sequence of template tags # used to render the admin dashboard. # # DASHBOARD_TAGS = ( # ("blog_tags.quick_blog", "mezzanine_tags.app_list"), # ("comment_tags.recent_comments",), # ("mezzanine_tags.recent_actions",), # ) # A sequence of templates used by the ``page_menu`` template tag. Each # item in the sequence is a three item sequence, containing a unique ID # for the template, a label for the template, and the template path. # These templates are then available for selection when editing which # menus a page should appear in. Note that if a menu template is used # that doesn't appear in this setting, all pages will appear in it. # PAGE_MENU_TEMPLATES = ( # (1, _("Top navigation bar"), "pages/menus/dropdown.html"), # (2, _("Left-hand tree"), "pages/menus/tree.html"), # (3, _("Footer"), "pages/menus/footer.html"), # ) # A sequence of fields that will be injected into Mezzanine's (or any # library's) models. Each item in the sequence is a four item sequence. # The first two items are the dotted path to the model and its field # name to be added, and the dotted path to the field class to use for # the field. The third and fourth items are a sequence of positional # args and a dictionary of keyword args, to use when creating the # field instance. When specifying the field class, the path # ``django.models.db.`` can be omitted for regular Django model fields. # # EXTRA_MODEL_FIELDS = ( # ( # # Dotted path to field. # "mezzanine.blog.models.BlogPost.image", # # Dotted path to field class. # "somelib.fields.ImageField", # # Positional args for field class. # (_("Image"),), # # Keyword args for field class. # {"blank": True, "upload_to": "blog"}, # ), # # Example of adding a field to *all* of Mezzanine's content types: # ( # "mezzanine.pages.models.Page.another_field", # "IntegerField", # 'django.db.models.' is implied if path is omitted. # (_("Another name"),), # {"blank": True, "default": 1}, # ), # ) # Setting to turn on featured images for blog posts. Defaults to False. # # BLOG_USE_FEATURED_IMAGE = True # If True, the django-modeltranslation will be added to the # INSTALLED_APPS setting. USE_MODELTRANSLATION = False ######################## # MAIN DJANGO SETTINGS # ######################## # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['localhost', '127.0.0.1', '111.222.333.444'] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'UTC' # If you set this to True, Django will use timezone-aware datetimes. USE_TZ = True # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = "en" # Supported languages LANGUAGES = ( ('en', _('English')), ) # A boolean that turns on/off debug mode. When set to ``True``, stack traces # are displayed for error pages. Should always be set to ``False`` in # production. Best set to ``True`` in local_settings.py DEBUG = False # Whether a user's session cookie expires when the Web browser is closed. SESSION_EXPIRE_AT_BROWSER_CLOSE = True SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = False AUTHENTICATION_BACKENDS = ("mezzanine.core.auth_backends.MezzanineBackend",) # The numeric mode to set newly-uploaded files to. The value should be # a mode you'd pass directly to os.chmod. FILE_UPLOAD_PERMISSIONS = 0o644 ############# # DATABASES # ############# DATABASES = { "default": { # Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.", # DB name or path to database file if using sqlite3. "NAME": "cloudSolarDB", # Not used with sqlite3. "USER": "valia", # Not used with sqlite3. "PASSWORD": "scenetwork", # Set to empty string for localhost. Not used with sqlite3. "HOST": "localhost", # Set to empty string for default. Not used with sqlite3. "PORT": "5432", } } ######### # PATHS # ######### # Full filesystem path to the project. PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__)) PROJECT_APP = os.path.basename(PROJECT_APP_PATH) PROJECT_ROOT = BASE_DIR = os.path.dirname(PROJECT_APP_PATH) # Every cache key will get prefixed with this value - here we set it to # the name of the directory the project is in to try and use something # project specific. CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_APP # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = "/static/" # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/")) # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = STATIC_URL + "media/" # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/")) # Package/module name to import the root urlpatterns from for the project. ROOT_URLCONF = "%s.urls" % PROJECT_APP TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join(PROJECT_ROOT, "templates") ], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.template.context_processors.debug", "django.template.context_processors.i18n", "django.template.context_processors.static", "django.template.context_processors.media", "django.template.context_processors.request", "django.template.context_processors.tz", "mezzanine.conf.context_processors.settings", "mezzanine.pages.context_processors.page", ], "builtins": [ "mezzanine.template.loader_tags", ], }, }, ] if DJANGO_VERSION < (1, 9): del TEMPLATES[0]["OPTIONS"]["builtins"] ################ # APPLICATIONS # ################ INSTALLED_APPS = ( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.redirects", "django.contrib.sessions", "django.contrib.sites", "django.contrib.sitemaps", "django.contrib.staticfiles", "mezzanine.boot", "mezzanine.conf", "mezzanine.core", "mezzanine.generic", "mezzanine.pages", "mezzanine.blog", "mezzanine.forms", "mezzanine.galleries", "mezzanine.twitter", # "mezzanine.accounts", # "mezzanine.mobile", ) # List of middleware classes to use. Order is important; in the request phase, # these middleware classes will be applied in the order given, and in the # response phase the middleware will be applied in reverse order. MIDDLEWARE_CLASSES = ( "mezzanine.core.middleware.UpdateCacheMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', # Uncomment if using internationalisation or localisation # 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "mezzanine.core.request.CurrentRequestMiddleware", "mezzanine.core.middleware.RedirectFallbackMiddleware", "mezzanine.core.middleware.TemplateForDeviceMiddleware", "mezzanine.core.middleware.TemplateForHostMiddleware", "mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware", "mezzanine.core.middleware.SitePermissionMiddleware", # Uncomment the following if using any of the SSL settings: # "mezzanine.core.middleware.SSLRedirectMiddleware", "mezzanine.pages.middleware.PageMiddleware", "mezzanine.core.middleware.FetchFromCacheMiddleware", ) # Store these package names here as they may change in the future since # at the moment we are using custom forks of them. PACKAGE_NAME_FILEBROWSER = "filebrowser_safe" PACKAGE_NAME_GRAPPELLI = "grappelli_safe" ######################### # OPTIONAL APPLICATIONS # ######################### # These will be added to ``INSTALLED_APPS``, only if available. OPTIONAL_APPS = ( "debug_toolbar", "django_extensions", "compressor", PACKAGE_NAME_FILEBROWSER, PACKAGE_NAME_GRAPPELLI, ) ################## # LOCAL SETTINGS # ################## # Allow any settings to be defined in local_settings.py which should be # ignored in your version control system allowing for settings to be # defined per machine. # Instead of doing "from .local_settings import *", we use exec so that # local_settings has full access to everything defined in this module. # Also force into sys.modules so it's visible to Django's autoreload. f = os.path.join(PROJECT_APP_PATH, "local_settings.py") if os.path.exists(f): import sys import imp module_name = "%s.local_settings" % PROJECT_APP module = imp.new_module(module_name) module.__file__ = f sys.modules[module_name] = module exec(open(f, "rb").read()) #################### # DYNAMIC SETTINGS # #################### # set_dynamic_settings() will rewrite globals based on what has been # defined so far, in order to provide some better defaults where # applicable. We also allow this settings module to be imported # without Mezzanine installed, as the case may be when using the # fabfile, where setting the dynamic settings below isn't strictly # required. try: from mezzanine.utils.conf import set_dynamic_settings except ImportError: pass else: set_dynamic_settings(globals())
nikdval/cloudSolar
solarApp/solar/settings.py
Python
artistic-2.0
11,845
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Web; using System.Web.Mvc; using KompetansetorgetServer.Models; namespace KompetansetorgetServer.Controllers { public class StudentsController : Controller { private KompetansetorgetServerContext db = new KompetansetorgetServerContext(); // GET: students public async Task<ActionResult> Index() { return View(await db.students.ToListAsync()); } // GET: students/Details/5 public async Task<ActionResult> Details(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Student student = await db.students.FindAsync(id); if (student == null) { return HttpNotFound(); } return View(student); } // GET: students/Create public ActionResult Create() { return View(); } // POST: students/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "username,name,email")] Student student) { if (ModelState.IsValid) { db.students.Add(student); await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(student); } // GET: students/Edit/5 public async Task<ActionResult> Edit(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Student student = await db.students.FindAsync(id); if (student == null) { return HttpNotFound(); } return View(student); } // POST: students/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "username,name,email")] Student student) { if (ModelState.IsValid) { db.Entry(student).State = EntityState.Modified; await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(student); } // GET: students/Delete/5 public async Task<ActionResult> Delete(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Student student = await db.students.FindAsync(id); if (student == null) { return HttpNotFound(); } return View(student); } // POST: students/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<ActionResult> DeleteConfirmed(string id) { Student student = await db.students.FindAsync(id); db.students.Remove(student); await db.SaveChangesAsync(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
patsy02/KompetansetorgetServer
KompetansetorgetServer/Controllers/StudentsController.cs
C#
artistic-2.0
3,911
using System.Collections.Generic; namespace AGS.API { /// <summary> /// Custom properties that you can attach to entities and can be used to get/set values during the game. /// </summary> public interface ICustomPropertiesPerType<TValue> { /// <summary> /// Gets the stored value for the custom property with the specified name. /// If no value is stored for this property, returns the specified default value instead /// (and stored that default value as the property's new value). /// </summary> /// <returns>The value.</returns> /// <param name="name">Name.</param> /// <param name="defaultValue">Default value.</param> TValue GetValue(string name, TValue defaultValue = default); /// <summary> /// Stores a new value for the custom property with the specified name. /// If an old value is stored it will be overridden by the new value. /// </summary> /// <param name="name">Name.</param> /// <param name="value">Value.</param> void SetValue(string name, TValue value); /// <summary> /// Returns a dictionary with all existing custom properties for this type. /// </summary> /// <returns>The properties.</returns> IDictionary<string, TValue> AllProperties(); /// <summary> /// Copies the custom properties from a different object (this will override /// values in the current object, but will not delete properties which don't /// have an equivalent in the given object). /// </summary> /// <param name="properties">Properties.</param> void CopyFrom(ICustomPropertiesPerType<TValue> properties); } }
tzachshabtay/MonoAGS
Source/AGS.API/Misc/CustomProperties/ICustomPropertiesPerType.cs
C#
artistic-2.0
1,758
// Copyright (C) 2019 - 2021 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2012 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "CQPlotSubwidget.h" #include "CQPlotEditWidget.h" #include "curve2dwidget.h" #include "HistoWidget.h" #ifdef COPASI_BANDED_GRAPH #include "BandedGraphWidget.h" #endif // COPASI_BANDED_GRAPH #include <copasi/plotUI/CQSpectogramWidget.h> #include "plotwindow.h" #include "copasi/plot/CPlotSpecification.h" #include "copasi/plot/COutputDefinitionVector.h" #include "copasi/report/CKeyFactory.h" #include "copasi/core/CDataArray.h" #include "copasi/UI/CCopasiPlotSelectionDialog.h" #include "copasi/UI/CCopasiPlot2YSelectionDialog.h" #include "copasi/model/CMetabNameInterface.h" #include "copasi/CopasiDataModel/CDataModel.h" #include "copasi/UI/DataModelGUI.h" #include "copasi/UI/qtUtilities.h" #include "copasi/core/CRootContainer.h" #include "copasi/UI/CCopasiSelectionDialog.h" #include "copasi/UI/CQMultipleSelectionDialog.h" #include <QListWidgetItem> #include <QtCore/QList> #include <QtCore/QMap> #include <QMessageBox> //----------------------------------------------------------------------------- /* * Constructs a PlotWidget1 as a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQPlotSubwidget::CQPlotSubwidget(QWidget* parent, const char* name, Qt::WindowFlags fl) : CopasiWidget(parent, name, fl) , mpCurveWidget(NULL) , mpHistoWidget(NULL) #ifdef COPASI_BANDED_GRAPH , mpBandedGraphWidget(NULL) #endif , mpSpectogramWidget(NULL) , mLastItem(NULL) { setupUi(this); mpCurveWidget = new Curve2DWidget(this); mpStack->addWidget(mpCurveWidget); mpHistoWidget = new HistoWidget(this); mpStack->addWidget(mpHistoWidget); #ifdef COPASI_BANDED_GRAPH QPushButton *buttonBandedGraph = new QPushButton(this); buttonBandedGraph->setText("New &Banded Graph"); layoutCurves->insertWidget(5, buttonBandedGraph); connect(buttonBandedGraph, SIGNAL(clicked()), this, SLOT(addBandedGraphSlot())); mpBandedGraphWidget = new BandedGraphWidget(this); mpStack->addWidget(mpBandedGraphWidget); #endif // COPASI_BANDED_GRAPH mpSpectogramWidget = new CQSpectogramWidget(this); mpStack->addWidget(mpSpectogramWidget); auto it = CTaskEnum::TaskName.begin(); for (; it != CTaskEnum::TaskName.end(); ++it) { mTaskNames << FROM_UTF8(*it); } } CPlotItem *CQPlotSubwidget::updateItem(CPlotItem *item) { if (item == NULL || !mpStack->isEnabled()) return NULL; QWidget *widget = mpStack->currentWidget(); CQPlotEditWidget *current = dynamic_cast<CQPlotEditWidget *>(widget); if (current != NULL) { if (!current->SaveToCurveSpec(item, mLastItem)) { return NULL; } } return item; } void CQPlotSubwidget::storeChanges() { if (mLastSelection.size() == 0) return; if (mLastSelection.size() == 1) { QString oldName = mLastSelection[0]->text(); CPlotItem *item = mList[oldName]; updateItem(item); if (item == NULL) return; QString newName = FROM_UTF8(item->getTitle()); if (oldName != newName) { mList.remove(oldName); mLastSelection[0]->setText(newName); mList.insert(newName, item); } } else { QList<QListWidgetItem *>::const_iterator it; for (it = mLastSelection.begin(); it != mLastSelection.end(); ++it) { // This suffices since editing the name/title is blocked. updateItem(mList[(*it)->text()]); } } } //----------------------------------------------------------------------------- /* * Destroys the object and frees any allocated resources */ CQPlotSubwidget::~CQPlotSubwidget() {} //----------------------------------------------------------------------------- //the slot... void CQPlotSubwidget::addCurveSlot() { if (mType == CPlotItem::plot2d) addCurve2D(); } #ifdef COPASI_BANDED_GRAPH void CQPlotSubwidget::addBandedGraphSlot() { if (mType == CPlotItem::plot2d) addBandedGraph(); } #endif // COPASI_BANDED_GRAPH void CQPlotSubwidget::addSpectrumSlot() { if (mType == CPlotItem::plot2d) addSpectrum(); } void CQPlotSubwidget::addHistoSlot() { if (mType == CPlotItem::plot2d) addHisto1D(); } int CQPlotSubwidget::getCurrentIndex() { return mpListPlotItems->currentRow(); } void CQPlotSubwidget::deleteCurves() { mLastSelection.clear(); for (int i = mpListPlotItems->count(); i >= 0; --i) { deleteCurve(i); } mList.clear(); mpListPlotItems->clear(); mLastSelection.clear(); } int CQPlotSubwidget::getRow(QListWidgetItem *item) { for (int i = 0; i < mpListPlotItems->count(); ++i) { if (mpListPlotItems->item(i)->text() == item->text()) return i; } return -1; } void CQPlotSubwidget::deleteCurve(QListWidgetItem *item) { if (item == NULL) return; delete mList[item->text()]; mList.remove(item->text()); mLastSelection.removeOne(item); delete mpListPlotItems->takeItem(getRow(item)); } void CQPlotSubwidget::deleteCurve(int index) { QListWidgetItem *item = mpListPlotItems->item(index); deleteCurve(item); } void CQPlotSubwidget::setCurrentIndex(int index) { if (index < 0) { mpListPlotItems->clearSelection(); return; } if (mpListPlotItems->count() == 0) return; if (index < 0 && mpListPlotItems->count() > 0) index = 0; if (index >= mpListPlotItems->count()) index = mpListPlotItems->count() - 1; mpListPlotItems->setCurrentRow(index, QItemSelectionModel::Select); } void CQPlotSubwidget::addPlotItem(CPlotItem *item) { QString title = FROM_UTF8(item->getTitle()); int count = 0; mpListPlotItems->clearSelection(); while (mList.contains(title)) { title = (FROM_UTF8(item->getTitle()) + " %1").arg(++count); } item->setTitle(TO_UTF8(title)); QListWidgetItem *listItem = new QListWidgetItem(FROM_UTF8(item->getTitle())); mpListPlotItems->addItem(listItem); mList.insert(FROM_UTF8(item->getTitle()), new CPlotItem(*item, NO_PARENT)); mpListPlotItems->setCurrentRow(mpListPlotItems->count() - 1); } CQPlotEditWidget *CQPlotSubwidget::selectControl(CPlotItem::Type type) { switch (type) { #ifdef COPASI_BANDED_GRAPH case CPlotItem::bandedGraph: { mpStack->setCurrentIndex(2); return mpBandedGraphWidget; } #endif case CPlotItem::histoItem1d: { mpStack->setCurrentIndex(1); return mpHistoWidget; } case CPlotItem::curve2d: { mpStack->setCurrentIndex(0); return mpCurveWidget; } case CPlotItem::spectogram: { #ifdef COPASI_BANDED_GRAPH mpStack->setCurrentIndex(3); #else mpStack->setCurrentIndex(2); #endif return mpSpectogramWidget; } default: return NULL; } } void CQPlotSubwidget::selectPlotItem(CPlotItem *item) { CQPlotEditWidget *current = static_cast< CQPlotEditWidget * >(mpStack->currentWidget()); if (current == NULL) return; if (item != NULL) { current = selectControl(item->getType()); } if (item == NULL) { mpStack->setEnabled(false); } current->setModel(mpDataModel->getModel()); current->LoadFromCurveSpec(item); pdelete(mLastItem); if (item != NULL) mLastItem = new CPlotItem(*item, NO_PARENT); } void CQPlotSubwidget::addCurveTab(const std::string &title, const CPlotDataChannelSpec &x, const CPlotDataChannelSpec &y) { CPlotItem *item = new CPlotItem(title, NULL, CPlotItem::curve2d); item->addChannel(x); item->addChannel(y); addPlotItem(item); } void chooseAxisFromSelection( std::vector<const CDataObject *> &vector1, std::vector<const CDataObject *> &vector2, std::vector< const CDataObject * > & vector3, std::vector<CCommonName> &objects1, std::vector<CCommonName> &objects2, std::vector< CCommonName > & objects3, std::map< std::string, std::string > & mapCNToDisplayName) { size_t i; std::vector<CCommonName>::const_iterator sit; const CDataArray *pArray; // 1. enable user to choose either a cell, an entire row/column, or even the objects themselves, if they are arrays. // 2. translate to CNs and remove duplicates // x-axis is set for single cell selection std::string cn; for (i = 0; i < vector1.size(); i++) { if (vector1[i]) // the object is not empty { // is it an array annotation? if ((pArray = dynamic_cast<const CDataArray *>(vector1[i]))) { // second argument is true as only single cell here is allowed. In this case we //can assume that the size of the return vector is 1. const CDataObject *pObject = CCopasiSelectionDialog::chooseCellMatrix(pArray, true, true, "X axis: ")[0]; if (!pObject) continue; cn = pObject->getCN(); mapCNToDisplayName[cn] = pObject->getObjectDisplayName(); } else { cn = vector1[i]->getCN(); mapCNToDisplayName[cn] = vector1[i]->getObjectDisplayName(); } // check whether cn is already on objects1 for (sit = objects1.begin(); sit != objects1.end(); ++sit) { if (*sit == cn) break; } // if not exist, input cn into objects1 if (sit == objects1.end()) { objects1.push_back(cn); } } } for (i = 0; i < vector2.size(); i++) { if (vector2[i]) { // is it an array annotation? if ((pArray = dynamic_cast<const CDataArray *>(vector2[i]))) { // second argument is set false for multi selection std::vector<const CDataObject *> vvv = CCopasiSelectionDialog::chooseCellMatrix(pArray, false, true, "Y axis: "); std::vector<const CDataObject *>::const_iterator it; for (it = vvv.begin(); it != vvv.end(); ++it) { if (!*it) continue; cn = (*it)->getCN(); //check if the CN already is in the list, if not add it. for (sit = objects2.begin(); sit != objects2.end(); ++sit) if (*sit == cn) break; mapCNToDisplayName[cn] = (*it)->getObjectDisplayName(); if (sit == objects2.end()) objects2.push_back(cn); } } else { cn = vector2[i]->getCN(); mapCNToDisplayName[cn] = vector2[i]->getObjectDisplayName(); //check if the CN already is in the list, if not add it. for (sit = objects2.begin(); sit != objects2.end(); ++sit) if (*sit == cn) break; if (sit == objects2.end()) objects2.push_back(cn); } } } for (i = 0; i < vector3.size(); i++) { if (vector3[i]) { // is it an array annotation? if ((pArray = dynamic_cast< const CDataArray * >(vector3[i]))) { // second argument is set false for multi selection std::vector< const CDataObject * > vvv = CCopasiSelectionDialog::chooseCellMatrix(pArray, false, true, "Y axis 2: "); std::vector< const CDataObject * >::const_iterator it; for (it = vvv.begin(); it != vvv.end(); ++it) { if (!*it) continue; cn = (*it)->getCN(); //check if the CN already is in the list, if not add it. for (sit = objects3.begin(); sit != objects3.end(); ++sit) if (*sit == cn) break; mapCNToDisplayName[cn] = (*it)->getObjectDisplayName(); if (sit == objects3.end()) objects3.push_back(cn); } } else { cn = vector3[i]->getCN(); mapCNToDisplayName[cn] = vector3[i]->getObjectDisplayName(); //check if the CN already is in the list, if not add it. for (sit = objects3.begin(); sit != objects3.end(); ++sit) if (*sit == cn) break; if (sit == objects3.end()) objects3.push_back(cn); } } } } void chooseAxisFromSelection( std::vector< const CDataObject * > & vector1, std::vector< const CDataObject * > & vector2, std::vector< CCommonName > & objects1, std::vector< CCommonName > & objects2, std::map< std::string, std::string > & mapCNToDisplayName) { std::vector< const CDataObject * > vector3; std::vector< CCommonName > objects3; chooseAxisFromSelection(vector1, vector2, vector3, objects1, objects2, objects3, mapCNToDisplayName); } void CQPlotSubwidget::addCurve2D() { CCopasiPlotSelectionDialog *pBrowser = new CCopasiPlotSelectionDialog(); pBrowser->setWindowTitle("New Curve"); std::vector< const CDataObject * > vector1; std::vector< const CDataObject * > vector2; pBrowser->setOutputVectors(&vector1, &vector2); assert(mpDataModel != NULL); pBrowser->setModel(mpDataModel->getModel(), CQSimpleSelectionTree::NumericValues); if (pBrowser->exec() == QDialog::Rejected) { return; } //this assumes that the vector is empty if nothing was chosen if (vector1.size() == 0 || vector2.size() == 0) { return; } std::vector< CCommonName > objects1, objects2; std::map<std::string, std::string> mapCNToDisplayName; size_t i; chooseAxisFromSelection(vector1, vector2, objects1, objects2, mapCNToDisplayName); if (objects1.size() == 1) { for (i = 0; i < objects2.size(); ++i) { addCurveTab(mapCNToDisplayName[objects2[i]] + "|" + mapCNToDisplayName[objects1[0]], objects1[0], objects2[i]); } } else if (objects2.size() == 1) { for (i = 0; i < objects1.size(); ++i) { addCurveTab(mapCNToDisplayName[objects2[0]] + "|" + mapCNToDisplayName[objects1[i]], objects1[i], objects2[0]); } } else { size_t imax; if (objects1.size() > objects2.size()) imax = objects2.size(); else imax = objects1.size(); for (i = 0; i < imax; ++i) { addCurveTab(mapCNToDisplayName[objects2[i]] + "|" + mapCNToDisplayName[objects1[i]], objects1[i], objects2[i]); } } } void CQPlotSubwidget::addSpectrum() { CCopasiPlot2YSelectionDialog * pBrowser = new CCopasiPlot2YSelectionDialog(); pBrowser->setWindowTitle("New Contour"); pBrowser->setY2Label("Z-Axis"); pBrowser->setSingleSelectionY(true); pBrowser->setSingleSelectionY2(true); std::vector< const CDataObject * > vector1; std::vector< const CDataObject * > vector2; std::vector< const CDataObject * > vector3; pBrowser->setOutputVectors(&vector1, &vector2, &vector3); assert(mpDataModel != NULL); pBrowser->setModel(mpDataModel->getModel(), CQSimpleSelectionTree::NumericValues); if (pBrowser->exec() == QDialog::Rejected) { return; } //this assumes that the vector is empty if nothing was chosen if (vector1.size() == 0 || vector2.size() == 0 || vector3.size() == 0) { return; } std::vector< CCommonName > objects1, objects2, objects3; std::map<std::string, std::string> mapCNToDisplayName; size_t i; chooseAxisFromSelection(vector1, vector2, vector3, objects1, objects2, objects3, mapCNToDisplayName); if (objects1.size() == 1) { size_t imax; if (objects3.size() > objects2.size()) imax = objects2.size(); else imax = objects3.size(); for (i = 0; i < objects2.size(); ++i) { addSpectrumTab(mapCNToDisplayName[objects2[i]] + "|" + mapCNToDisplayName[objects1[0]], objects1[0], objects2[i], objects3[i]); } } else if (objects2.size() == 1) { size_t imax; if (objects3.size() > objects1.size()) imax = objects1.size(); else imax = objects3.size(); for (i = 0; i < imax; ++i) { addSpectrumTab(mapCNToDisplayName[objects2[0]] + "|" + mapCNToDisplayName[objects1[i]], objects1[i], objects2[0], objects3[i]); } } else { size_t imax; if (objects1.size() > objects2.size()) imax = objects2.size(); else imax = objects1.size(); if (imax > objects3.size()) imax = objects3.size(); for (i = 0; i < imax; ++i) { addSpectrumTab(mapCNToDisplayName[objects2[i]] + "|" + mapCNToDisplayName[objects1[i]], objects1[i], objects2[i], objects3[i]); } } } #ifdef COPASI_BANDED_GRAPH void CQPlotSubwidget::addBandedGraphTab(const std::string &title, const CPlotDataChannelSpec &x, const CPlotDataChannelSpec &yone, const CPlotDataChannelSpec &ytwo) { CPlotItem *item = new CPlotItem(title, NULL, CPlotItem::bandedGraph); item->addChannel(x); item->addChannel(yone); item->addChannel(ytwo); addPlotItem(item); } void CQPlotSubwidget::addBandedGraph() { CCopasiPlot2YSelectionDialog * pBrowser = new CCopasiPlot2YSelectionDialog(); pBrowser->setWindowTitle("New Banded Graph"); pBrowser->setSingleSelectionY(true); pBrowser->setSingleSelectionY2(true); std::vector< const CDataObject * > vector1; std::vector< const CDataObject * > vector2; std::vector< const CDataObject * > vector3; pBrowser->setOutputVectors(&vector1, &vector2, &vector3); assert(mpDataModel != NULL); pBrowser->setModel(mpDataModel->getModel(), CQSimpleSelectionTree::NumericValues); if (pBrowser->exec() == QDialog::Rejected) { return; } //this assumes that the vector is empty if nothing was chosen if (vector1.size() == 0 || vector2.size() == 0 || vector3.size() == 0) { return; } std::vector<CCommonName> objects1, objects2, objects3; std::map<std::string, std::string> mapCNToDisplayName; size_t i; chooseAxisFromSelection(vector1, vector2, vector3, objects1, objects2, objects3, mapCNToDisplayName); if (objects1.size() == 1) { size_t imax; if (objects3.size() > objects2.size()) imax = objects2.size(); else imax = objects3.size(); for (i = 0; i < imax; ++i) { addBandedGraphTab(mapCNToDisplayName[objects2[i]] + "|" + mapCNToDisplayName[objects1[0]], objects1[0], objects2[i], objects3[i]); } } else if (objects2.size() == 1) { size_t imax; if (objects3.size() > objects1.size()) imax = objects1.size(); else imax = objects3.size(); for (i = 0; i < imax; ++i) { addBandedGraphTab(mapCNToDisplayName[objects2[0]] + "|" + mapCNToDisplayName[objects1[i]], objects1[i], objects2[0], objects3[i]); } } else { size_t imax; if (objects1.size() > objects2.size()) imax = objects2.size(); else imax = objects1.size(); if (imax > objects3.size()) imax = objects3.size(); for (i = 0; i < imax; ++i) { addBandedGraphTab(mapCNToDisplayName[objects2[i]] + "|" + mapCNToDisplayName[objects1[i]], objects1[i], objects2[i], objects3[i]); } } } #endif // COPASI_BANDED_GRAPH void CQPlotSubwidget::addSpectrumTab(const std::string &title, const CPlotDataChannelSpec &x, const CPlotDataChannelSpec &yone, const CPlotDataChannelSpec &ytwo) { CPlotItem *item = new CPlotItem(title, NULL, CPlotItem::spectogram); item->addChannel(x); item->addChannel(yone); item->addChannel(ytwo); addPlotItem(item); } void CQPlotSubwidget::addHisto1DTab(const std::string &title, const CPlotDataChannelSpec &x, const C_FLOAT64 &incr) { CPlotItem *item = new CPlotItem(title, NULL, CPlotItem::histoItem1d); item->addChannel(x); item->setValue("increment", incr); addPlotItem(item); } void CQPlotSubwidget::addHisto1D() { addHisto1DTab("Histogram", CPlotDataChannelSpec(CCommonName("")), 1.0); } void CQPlotSubwidget::createHistograms(std::vector<const CDataObject * >objects, const C_FLOAT64 &incr) { C_INT32 storeTab = getCurrentIndex(); size_t i; for (i = 1; i < objects.size(); ++i) { if (objects[i]) addHisto1DTab("Histogram: " + objects[i]->getObjectDisplayName(), CPlotDataChannelSpec(objects[i]->getCN()), incr); // lineEditTitle->setText("Histogram: " + FROM_UTF8(mpObjectX->getObjectDisplayName())); } setCurrentIndex(storeTab); } //----------------------------------------------------------------------------- void CQPlotSubwidget::removeCurve() { QList<QListWidgetItem *> selection = mpListPlotItems->selectedItems(); if (selection.size() == 0) return; if (QMessageBox::question(this, "Delete Curves", QString("Do you really want to delete the %1 selected curve(s)?").arg(selection.size()), QMessageBox::Yes, QMessageBox::No | QMessageBox::Default) == QMessageBox::Yes) { for (int index = selection.size() - 1; index >= 0; --index) { deleteCurve(selection.at(index)); } mLastSelection.clear(); } } //----------------------------------------------------------------------------- void CQPlotSubwidget::commitPlot() { saveToPlotSpec(); loadFromPlotSpec(dynamic_cast<CPlotSpecification *>(mpObject)); } //----------------------------------------------------------------------------- void CQPlotSubwidget::deletePlot() { size_t Index, Size; assert(mpDataModel != NULL); if (!mpDataModel->getModel()) return; CPlotSpecification *pspec = dynamic_cast< CPlotSpecification * >(mpObject); if (!pspec) return; Index = mpDataModel->getPlotDefinitionList()->CDataVector<CPlotSpecification>::getIndex(pspec); mpDataModel->getPlotDefinitionList()->CDataVector<CPlotSpecification>::remove(Index); std::string deletedObjectCN = mObjectCN; Size = mpDataModel->getPlotDefinitionList()->size(); if (Size > 0) enter(mpDataModel->getPlotDefinitionList()->operator[](std::min(Index, Size - 1)).getCN()); else enter(std::string()); //ListViews:: protectedNotify(ListViews::ObjectType::PLOT, ListViews::DELETE, deletedObjectCN); } //----------------------------------------------------------------------------- void CQPlotSubwidget::copyPlot() { leaveProtected(); CDataModel *pDataModel = mpObject->getObjectDataModel(); if (pDataModel == NULL) return; CPlotSpecification *pPl = new CPlotSpecification(*dynamic_cast<CPlotSpecification *>(mpObject), NO_PARENT); std::string baseName = pPl->getObjectName() + "_copy"; std::string name = baseName; int i = 1; while (pDataModel->getPlotDefinitionList()->getIndex(name) != C_INVALID_INDEX) { i++; name = baseName + TO_UTF8(QString::number(i)); } pPl->setObjectName(name); pDataModel->getPlotDefinitionList()->add(pPl, true); std::string cn = pPl->CCopasiParameter::getCN(); protectedNotify(ListViews::ObjectType::PLOT, ListViews::ADD, cn); enter(cn); mpListView->switchToOtherWidget(ListViews::WidgetType::PlotDetail, cn); } //----------------------------------------------------------------------------- void CQPlotSubwidget::addPlot() { leaveProtected(); CDataModel *pDataModel = mpObject->getObjectDataModel(); if (pDataModel == NULL) return; std::string name = "plot_"; int i = 0; CPlotSpecification *pPl = NULL; name += TO_UTF8(QString::number(i)); while (!(pPl = pDataModel->getPlotDefinitionList()->createPlotSpec(name, CPlotItem::plot2d))) { i++; name = "plot_"; name += TO_UTF8(QString::number(i)); } std::string cn = pPl->CCopasiParameter::getCN(); protectedNotify(ListViews::ObjectType::PLOT, ListViews::ADD, cn); enter(cn); mpListView->switchToOtherWidget(ListViews::WidgetType::PlotDetail, cn); } //----------------------------------------------------------------------------- void CQPlotSubwidget::resetPlot() { loadFromPlotSpec(dynamic_cast<CPlotSpecification *>(mpObject)); } #include <QInputDialog> void CQPlotSubwidget::selectTaskTypes() { CQMultipleSelectionDialog* dlg = new CQMultipleSelectionDialog(this); dlg->setWindowTitle("Select Tasks"); dlg->setMinimumHeight(400); dlg->setSelectionList(mTaskNames); QStringList currentSelection; if (!mTaskTypes.empty()) { std::istringstream ss(mTaskTypes); std::string token; while (std::getline(ss, token, ',')) { while (token[0] == ' ') // remove leading spaces token.erase(0, 1); currentSelection << FROM_UTF8(token); } } dlg->setCurrentSelection(currentSelection); if (dlg->exec() != QDialog::Accepted) return; const QStringList& selection = dlg->getSelection(); std::stringstream str; if (!selection.empty()) { auto it = selection.begin(); str << TO_UTF8(*it++); for (; it != selection.end(); ++it) { str << ", "; str << TO_UTF8(*it); } } mTaskTypes = str.str(); chkTaskTypes->setChecked(mTaskTypes.empty()); txtTaskTypes->setText(FROM_UTF8(mTaskTypes)); } void CQPlotSubwidget::allTaskTypesClicked() { if (!mTaskTypes.empty()) { mTaskTypes.clear(); txtTaskTypes->clear(); } else { selectTaskTypes(); } } //----------------------------------------------------------------------------- bool CQPlotSubwidget::loadFromPlotSpec(const CPlotSpecification *pspec) { if (!pspec) return false; mLastSelection.clear(); //title titleLineEdit->setText(pspec->getTitle().c_str()); //active? activeCheckBox->setChecked(pspec->isActive()); //type mType = pspec->getType(); mTaskTypes = pspec->getTaskTypes(); txtTaskTypes->setText(FROM_UTF8(mTaskTypes)); chkTaskTypes->setChecked(mTaskTypes.empty()); switch (mType) { #ifdef COPASI_BANDED_GRAPH case CPlotItem::bandedGraph: #endif // COPASI_BANDED_GRAPH case CPlotItem::spectogram: case CPlotItem::plot2d: checkLogX->setChecked(pspec->isLogX()); checkLogY->setChecked(pspec->isLogY()); break; default: return false; } //clear tabWidget deleteCurves(); mpListPlotItems->clearSelection(); //reconstruct tabWidget from curve specs CDataVector<CPlotItem>::const_iterator it = pspec->getItems().begin(); CDataVector<CPlotItem>::const_iterator end = pspec->getItems().end(); QStringList PlotItems; for (; it != end; ++it) { QString title = FROM_UTF8(it->getTitle()); PlotItems.append(title); CPlotItem *pItem = new CPlotItem(*it, NO_PARENT); // The copy has the same parent as the original, i.e., it has been added to the plot specification. const_cast< CPlotSpecification * >(pspec)->getItems().remove(pItem); mList.insert(title, pItem); } mpListPlotItems->addItems(PlotItems); if (pspec->getItems().size() > 0) { mpListPlotItems->setCurrentRow(0, QItemSelectionModel::Select); } else { // We need to clear the current items display selectPlotItem(NULL); } return true; //TODO really check } bool CQPlotSubwidget::saveToPlotSpec() { CPlotSpecification *pspec = dynamic_cast< CPlotSpecification * >(mpObject); if (!pspec) return true; pspec->cleanup(); //title if (pspec->getTitle() != TO_UTF8(titleLineEdit->text())) { pspec->setTitle(TO_UTF8(titleLineEdit->text())); protectedNotify(ListViews::ObjectType::PLOT, ListViews::RENAME, mObjectCN); } //active? pspec->setActive(activeCheckBox->isChecked()); //scales pspec->setLogX(checkLogX->isChecked()); pspec->setLogY(checkLogY->isChecked()); // task types pspec->setTaskTypes(mTaskTypes); //curves CPlotItem *item; storeChanges(); for (int i = 0, imax = mpListPlotItems->count(); i < imax; ++i) { CPlotItem *currentItem = mList[mpListPlotItems->item(i)->text()]; if (currentItem == NULL) continue; item = new CPlotItem(*currentItem, NO_PARENT); pspec->getItems().add(item, true); } // :TODO Bug 322: This should only be called when actual changes have been saved. // However we do not check whether the scan item are changed we delete all // and create them new. if (true) { if (mpDataModel != NULL) { mpDataModel->changed(); } // mChanged = false; } return true; } //----------------------------------------------------------------------------- //TODO: save a copy! bool CQPlotSubwidget::enterProtected() { CPlotSpecification *pspec = dynamic_cast< CPlotSpecification * >(mpObject); if (!pspec) { mpListView->switchToOtherWidget(ListViews::WidgetType::Plots, std::string()); return false; } return loadFromPlotSpec(pspec); } bool CQPlotSubwidget::areOfSameType(QList<QListWidgetItem *> &items) { if (items.size() <= 1) return true; QList<CPlotItem::Type> listOfUniqueTypes; QList<QListWidgetItem *>::const_iterator it = items.begin(); while (it != items.end()) { QString currentText = (*it)->text(); CPlotItem *item = mList[currentText]; if (!listOfUniqueTypes.contains(item->getType())) listOfUniqueTypes.append(item->getType()); ++it; } return listOfUniqueTypes.size() == 1; } void CQPlotSubwidget::itemSelectionChanged() { storeChanges(); QList<QListWidgetItem *> current = mpListPlotItems->selectedItems(); if (current.size() == 0) { mpStack->setEnabled(false); } else if (current.size() == 1) { mpStack->setEnabled(true); selectPlotItem(mList[current[0]->text()]); (static_cast<CQPlotEditWidget *>(mpStack->currentWidget()))->setMultipleEditMode(false); } else { if (!areOfSameType(current)) { mpStack->setEnabled(false); } else { mpStack->setEnabled(true); selectPlotItem(mList[current[0]->text()]); (static_cast<CQPlotEditWidget *>(mpStack->currentWidget()))->setMultipleEditMode(true); } } mLastSelection = current; } //----------------------------------------------------------------------------- bool CQPlotSubwidget::updateProtected(ListViews::ObjectType objectType, ListViews::Action action, const CCommonName & cn) { if (mIgnoreUpdates || isHidden()) return true; switch (objectType) { //TODO: check list: case ListViews::ObjectType::MODEL: switch (action) { case ListViews::DELETE: case ListViews::ADD: mpObject = NULL; mObjectCN.clear(); return enterProtected(); break; default: break; } break; case ListViews::ObjectType::PLOT: if (cn == mObjectCN) { switch (action) { case ListViews::DELETE: mpObject = NULL; mObjectCN.clear(); return enterProtected(); break; case ListViews::CHANGE: return enterProtected(); break; default: break; } } break; default: break; } return true; } //----------------------------------------------------------------------------- bool CQPlotSubwidget::leaveProtected() { return saveToPlotSpec(); }
copasi/COPASI
copasi/plotUI/CQPlotSubwidget.cpp
C++
artistic-2.0
33,073
import pyautogui, win32api, win32con, ctypes, autoit from PIL import ImageOps, Image, ImageGrab from numpy import * import os import time import cv2 import random from Bot import * def main(): bot = Bot() autoit.win_wait(bot.title, 5) counter = 0 poitonUse = 0 cycle = True fullCounter = 0 while cycle: hpstatus = bot.checkOwnHp() print 'hp ' + str(hpstatus) if hpstatus == 0: autoit.control_send(bot.title, '', '{F9}', 0) bot.sleep(0.3,0.6) print 'Dead' cv2.imwrite('Dead' + str(int(time.time())) + '.png',bot.getScreen(leftCornerx,leftCornery,x2,fullY2)) cycle = False if hpstatus == 1: if poitonUse == 0: autoit.control_send(bot.title, '', '{F10}', 0) poitonUse += 1 if poitonUse > 5: poitonUse = 0 else: poitonUse = 0 res = bot.findHP(); print 'tgs ' + str(res) if res == 3: fullCounter += 1 print 'fc ' + str(fullCounter) autoit.control_send(bot.title, '', '{F1}', 0) else: fullCounter = 0 if fullCounter > 4: autoit.control_send(bot.title, '', '{ESC}', 0) bot.sleep(0.3,0.6) autoit.control_send(bot.title, '', '{F3}', 0) bot.sleep(0.1,0.3) autoit.control_send(bot.title, '', '{F1}', 0) # bot.mouseRotate() fullCounter = 0 if res > 0: autoit.control_send(bot.title, '', '{F1}', 0) counter = 0 if res == 1 or res == 3: bot.sleep(0.3,0.6) if res > 1 and res < 3: bot.sleep(1,3) if res == 1: autoit.control_send(bot.title, '', '{F3}', 0) bot.sleep(0.3,0.6) autoit.control_send(bot.title, '', '{F2}', 0) bot.sleep(0.3,0.6) autoit.control_send(bot.title, '', '{F1}', 0) else: fullCounter = 0 if counter < 3: autoit.control_send(bot.title, '', '{F3}', 0) bot.sleep(0.5,0.8) autoit.control_send(bot.title, '', '{F1}', 0) print 'F3' if counter > 2: # bot.findTarget() autoit.control_send(bot.title, '', '{F7}', 0) # if counter > 3: # autoit.control_send(bot.title, '', '{F8}', 0) # counter = 0 counter += 1 print 'cnt ' + str(counter) pass if __name__ == '__main__': main()
oyajiro/l2bot
hf/wl.py
Python
artistic-2.0
2,661
cask 'torbrowser-cn' do version '5.5.5' sha256 '86e14037abd36faa98bb47fe321a40a368b1cc8945677f5bfc646745b47e421b' url "https://dist.torproject.org/torbrowser/#{version}/TorBrowser-#{version}-osx64_zh-CN.dmg" name 'Tor Browser' homepage 'https://www.torproject.org/projects/torbrowser.html' license :oss gpg "#{url}.asc", key_id: 'ef6e286dda85ea2a4ba7de684e2c6e8793298290' app 'TorBrowser.app' end
mauricerkelly/homebrew-versions
Casks/torbrowser-cn.rb
Ruby
bsd-2-clause
421
package com.dozenx.game.engine.item.parser; import cola.machine.game.myblocks.engine.Constants; import cola.machine.game.myblocks.engine.modes.GamingState; import cola.machine.game.myblocks.manager.TextureManager; import cola.machine.game.myblocks.model.base.BaseBlock; import com.dozenx.game.engine.command.EquipPartType; import com.dozenx.game.engine.command.ItemMainType; import com.dozenx.game.engine.element.model.BoxModel; import com.dozenx.game.engine.element.model.CakeModel; import com.dozenx.game.engine.element.model.IconModel; import com.dozenx.game.engine.item.bean.ItemDefinition; import com.dozenx.game.engine.item.bean.ItemWearProperties; import core.log.LogUtil; import java.util.Map; /** * Created by dozen.zhang on 2017/5/9. */ public class ItemEquipParser { public static void parse(ItemDefinition item,Map map){ //item.setType(Constants.ICON_TYPE_WEAR); ItemWearProperties properties = new ItemWearProperties(); item.itemTypeProperties = properties; if (map.get("spirit") != null) { int spirit = (int) map.get("spirit"); item.setSpirit(spirit); properties.spirit = spirit; } if (map.get("agile") != null) { int agile = (int) map.get("agile"); item.setAgile(agile); properties.agile = agile; } if (map.get("intelli") != null) { int intelli = (int) map.get("intelli"); item.setIntelli(intelli); properties.intel = intelli; } if (map.get("strenth") != null) { int strenth = (int) map.get("strenth"); item.setStrenth(strenth); properties.strength = strenth; } String position = (String) map.get("position"); if (position != null) { if (position.equals("head")) { item.setPosition(Constants.WEAR_POSI_HEAD); properties.part = EquipPartType.HEAD; } else if (position.equals("body")) { item.setPosition(Constants.WEAR_POSI_BODY); properties.part = EquipPartType.BODY; } else if (position.equals("leg")) { item.setPosition(Constants.WEAR_POSI_LEG); properties.part = EquipPartType.LEG; } else if (position.equals("foot")) { item.setPosition(Constants.WEAR_POSI_FOOT); properties.part = EquipPartType.FOOT; } else if (position.equals("hand")) { item.setPosition(Constants.WEAR_POSI_HAND); properties.part = EquipPartType.HAND; } } item.setType(ItemMainType.WEAR); if (GamingState.player != null) {//区分服务器版本和客户端版本 // String shapeName = (String) map.get("shape"); /*if(icon.equals("fur_helmet")){ LogUtil.println("123"); }*/ item.getItemModel().setIcon(item.itemModel.getIcon()); BaseBlock shape = TextureManager.getShape(item.getName()); if (shape == null) {//如果没有shape 说明还没有用到该物体 还没有定义shape LogUtil.println("hello"); item.getItemModel().init(); } else { item.setShape(shape); item.itemModel.wearModel = new BoxModel(shape); item.itemModel.handModel = new CakeModel(item.itemModel.getIcon()); item.itemModel.outdoorModel = new IconModel(item.itemModel.getIcon()); item.itemModel.placeModel = null; } } // return null; } public void renderHand(){ } public void renderBody(){ } public void renderTerrain(){ } public void renderDrop(){ } }
ColaMachine/MyBlock
src/main/java/com/dozenx/game/engine/item/parser/ItemEquipParser.java
Java
bsd-2-clause
3,844
class Groovysdk < Formula desc "SDK for Groovy: a Java-based scripting language" homepage "http://www.groovy-lang.org" url "https://dl.bintray.com/groovy/maven/apache-groovy-sdk-2.5.0.zip" sha256 "866e9c7217f1fce76f202f8e64cdb3f910910e4ad8533724246a0b1310b3d5aa" bottle :unneeded depends_on :java => "1.6+" conflicts_with "groovy", :because => "both install the same binaries" def install ENV["GROOVY_HOME"] = libexec # We don't need Windows' files. rm_f Dir["bin/*.bat"] prefix.install_metafiles bin.install Dir["bin/*"] libexec.install "conf", "lib", "src", "doc" bin.env_script_all_files(libexec+"bin", :GROOVY_HOME => ENV["GROOVY_HOME"]) end test do system "#{bin}/grape", "install", "org.activiti", "activiti-engine", "5.16.4" end end
battlemidget/homebrew-core
Formula/groovysdk.rb
Ruby
bsd-2-clause
801
# Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. def fibs(): previous, current = 0, 1 while True: previous, current = current, previous + current yield current def problem2(bound): sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: sum += n return sum print problem2(4000000)
nabilhassein/project-euler
p2.py
Python
bsd-2-clause
638
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Media; namespace CoderOffice.Windows.Document { /// <summary> /// The text style class. /// All of the styles are represented by this class /// </summary> public class TextStyle { public TextStyle() { } public TextStyle(Brush foreground, Brush background, FontWeight weight, FontStyle style, double size) { this.Foreground = foreground; this.Background = background; this.Weight = weight; this.Style = style; this.Size = size; } /// <summary> /// /// </summary> public Brush Foreground { get; set; } /// <summary> /// /// </summary> public Brush Background { get; set; } /// <summary> /// /// </summary> public FontWeight Weight { get; set; } /// <summary> /// /// </summary> public FontStyle Style { get; set; } /// <summary> /// /// </summary> public double Size { get; set; } /// <summary> /// Text alignment /// </summary> public TextAlignment TextAlignment { get; set; } /// <summary> /// The flow direction /// </summary> public FlowDirection FlowDirection { get; set; } } }
snowdreamist/CoderOffice
CoderOffice/CoderOffice.Core/Windows/Document/TextStyle.cs
C#
bsd-2-clause
1,464
// Copyright (C) 2010, Kyle Lemons <kyle@kylelemons.net>. All rights reserved. package log4go import ( "fmt" "io/ioutil" "os" "path/filepath" "sort" "strings" "time" ) // This log writer sends output to a file type FileLogWriter struct { rec chan *LogRecord rot chan bool // The opened file filename string file *os.File // The logging format format string // File header/trailer header, trailer string // Rotate at linecount maxlines int maxlines_curlines int // Rotate at size maxsize int maxsize_cursize int maxtotalsize int64 // Rotate daily daily bool daily_opendate int // Keep old logfiles (.001, .002, etc) rotate bool } // This is the FileLogWriter's output method func (w *FileLogWriter) LogWrite(rec *LogRecord) { w.rec <- rec } func (w *FileLogWriter) Close() { close(w.rec) } // NewFileLogWriter creates a new LogWriter which writes to the given file and // has rotation enabled if rotate is true. // // If rotate is true, any time a new log file is opened, the old one is renamed // with a .### extension to preserve it. The various Set* methods can be used // to configure log rotation based on lines, size, and daily. // // The standard log-line format is: // [%D %T] [%L] (%S) %M func NewFileLogWriter(fname string, rotate bool) *FileLogWriter { w := &FileLogWriter{ rec: make(chan *LogRecord, LogBufferLength), rot: make(chan bool), filename: fname, format: "[%D %T] [%L] (%S) %M", rotate: rotate, } // open the file for the first time if err := w.intRotate(); err != nil { fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) return nil } go func() { defer func() { if w.file != nil { fmt.Fprint(w.file, FormatLogRecord(w.trailer, &LogRecord{Created: time.Now()})) w.file.Close() } w.Close() }() for { select { case <-w.rot: if err := w.intRotate(); err != nil { fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) return } case rec, ok := <-w.rec: if !ok { return } now := time.Now() if (w.maxlines > 0 && w.maxlines_curlines >= w.maxlines) || (w.maxsize > 0 && w.maxsize_cursize >= w.maxsize) || (w.daily && now.Day() != w.daily_opendate) { if err := w.intRotate(); err != nil { fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) return } } // Perform the write n, err := fmt.Fprint(w.file, FormatLogRecord(w.format, rec)) if err != nil { fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) return } // Update the counts w.maxlines_curlines++ w.maxsize_cursize += n } } }() return w } // Request that the logs rotate func (w *FileLogWriter) Rotate() { w.rot <- true } // If this is called in a threaded context, it MUST be synchronized func (w *FileLogWriter) intRotate() error { // Close any log file that may be open if w.file != nil { fmt.Fprint(w.file, FormatLogRecord(w.trailer, &LogRecord{Created: time.Now()})) w.file.Close() } canReset := true // If we are keeping log files, rename it if w.rotate { info, err := os.Lstat(w.filename) if err == nil { // file exists // new name ext := filepath.Ext(w.filename) fname := w.filename + fmt.Sprintf(".%04d%02d%02d.%02d%02d%02d.%03d%s", info.ModTime().Year(), info.ModTime().Month(), info.ModTime().Day(), info.ModTime().Hour(), info.ModTime().Minute(), info.ModTime().Second(), info.ModTime().Nanosecond()/1000000, ext) // Rename the file to its newfound home err = os.Rename(w.filename, fname) if err != nil { fmt.Printf("Rotation failed: %s\n", err) canReset = false // will retry again next time... } } } w.checkTotalSize() // Open the log file fd, err := os.OpenFile(w.filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) if err != nil { return err } w.file = fd now := time.Now() fmt.Fprint(w.file, FormatLogRecord(w.header, &LogRecord{Created: now})) if canReset { // Set the daily open date to the current date w.daily_opendate = now.Day() // initialize rotation values w.maxlines_curlines = 0 w.maxsize_cursize = 0 } return nil } type ByDateASC []os.FileInfo func (a ByDateASC) Len() int { return len(a) } func (a ByDateASC) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByDateASC) Less(i, j int) bool { return a[i].ModTime().Before(a[j].ModTime()) } func (w *FileLogWriter) checkTotalSize() { if w.maxtotalsize == 0 { // no file cleanup return } dir := filepath.Dir(w.filename) base := filepath.Base(w.filename) infos, err := ioutil.ReadDir(dir) if err != nil { return } var totalsize int64 matchedFiles := make([]os.FileInfo, 0) for _, info := range infos { if !info.IsDir() && strings.HasPrefix(info.Name(), base) { // one of our file matchedFiles = append(matchedFiles, info) totalsize += info.Size() } } sort.Sort(ByDateASC(matchedFiles)) for _, info := range matchedFiles { if w.maxtotalsize > totalsize { break } totalsize -= info.Size() os.Remove(filepath.Join(dir, info.Name())) } } // Set the logging format (chainable). Must be called before the first log // message is written. func (w *FileLogWriter) SetFormat(format string) *FileLogWriter { w.format = format return w } // Set the logfile header and footer (chainable). Must be called before the first log // message is written. These are formatted similar to the FormatLogRecord (e.g. // you can use %D and %T in your header/footer for date and time). func (w *FileLogWriter) SetHeadFoot(head, foot string) *FileLogWriter { w.header, w.trailer = head, foot if w.maxlines_curlines == 0 { fmt.Fprint(w.file, FormatLogRecord(w.header, &LogRecord{Created: time.Now()})) } return w } // Set rotate at linecount (chainable). Must be called before the first log // message is written. func (w *FileLogWriter) SetRotateLines(maxlines int) *FileLogWriter { //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotateLines: %v\n", maxlines) w.maxlines = maxlines return w } // Set rotate at size (chainable). Must be called before the first log message // is written. func (w *FileLogWriter) SetRotateSize(maxsize int) *FileLogWriter { //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotateSize: %v\n", maxsize) w.maxsize = maxsize return w } func (w *FileLogWriter) SetMaxTotalSize(max int64) *FileLogWriter { w.maxtotalsize = max return w } // Set rotate daily (chainable). Must be called before the first log message is // written. func (w *FileLogWriter) SetRotateDaily(daily bool) *FileLogWriter { //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotateDaily: %v\n", daily) w.daily = daily return w } // SetRotate changes whether or not the old logs are kept. (chainable) Must be // called before the first log message is written. If rotate is false, the // files are overwritten; otherwise, they are rotated to another file before the // new log is opened. func (w *FileLogWriter) SetRotate(rotate bool) *FileLogWriter { //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotate: %v\n", rotate) w.rotate = rotate return w } // NewXMLLogWriter is a utility method for creating a FileLogWriter set up to // output XML record log messages instead of line-based ones. func NewXMLLogWriter(fname string, rotate bool) *FileLogWriter { return NewFileLogWriter(fname, rotate).SetFormat( ` <record level="%L"> <timestamp>%D %T</timestamp> <source>%S</source> <message>%M</message> </record>`).SetHeadFoot("<log created=\"%D %T\">", "</log>") }
dhx71/log4go
filelog.go
GO
bsd-2-clause
7,587
/** * anothergltry - Another GL try * Copyright (c) 2015, Matej Kormuth <http://www.github.com/dobrakmato> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package eu.matejkormuth.jge.exceptions.gl; import org.lwjgl.opengl.OpenGLException; /** * Thrown when there was error while linking a program. */ public class ProgramLinkException extends OpenGLException { public ProgramLinkException() { } public ProgramLinkException(String msg) { super(msg); } }
dobrakmato/jge
src/main/java/eu/matejkormuth/jge/exceptions/gl/ProgramLinkException.java
Java
bsd-2-clause
1,761
/* globals define */ define(function(require, exports, module) { "use strict"; // Import famo.us dependencies var Engine = require("famous/core/Engine"); var FastClick = require("famous/inputs/FastClick"); // Create main application view var AppView = require("views/AppView"); var context = Engine.createContext(); context.setPerspective(2000); var view = new AppView(); context.add(view); });
trigger-corp/generator-famous-triggerio
app/templates/src/js/main.js
JavaScript
bsd-2-clause
437
/* global define */ define([ 'jquery', 'marionette' ], function($, Marionette) { var CountItem = Marionette.ItemView.extend({ tagName: 'tr', template: 'stats/count-item' }); var CountList = Marionette.CompositeView.extend({ template: 'stats/count-list', itemView: CountItem, itemViewContainer: 'tbody', ui: { 'statsTable': 'table', 'loader': '.loading-message' }, events: { 'click thead th': 'handleSort' }, collectionEvents: { 'sort': '_renderChildren', 'request': 'showLoader', 'reset': 'hideLoader' }, hideLoader: function() { this.ui.loader.hide(); this.ui.statsTable.show(); }, showLoader: function() { this.ui.loader.show(); this.ui.statsTable.hide(); }, handleSort: function(event) { if (!this.collection.length) return; this.applySort($(event.target).data('sort')); }, applySort: function(attr) { var dir = 'asc'; // Already sorted by the attribute, cycle direction. if (this.collection._sortAttr === attr) { dir = this.collection._sortDir === 'asc' ? 'desc' : 'asc'; } this.$('[data-sort=' + this.collection._sortAttr + ']') .removeClass(this.collection._sortDir); this.$('[data-sort=' + attr + ']').addClass(dir); // Reference for cycling. this.collection._sortAttr = attr; this.collection._sortDir = dir; // Parse function for handling the sort attributes. var parse = function(v) { return v; }; this.collection.comparator = function(m1, m2) { var v1 = parse(m1.get(attr)), v2 = parse(m2.get(attr)); if (v1 < v2) return (dir === 'asc' ? -1 : 1); if (v1 > v2) return (dir === 'asc' ? 1 : -1); return 0; }; this.collection.sort(); } }); return { CountList: CountList }; });
chop-dbhi/varify
varify/static/cilantro/js/cilantro/ui/stats.js.src.js
JavaScript
bsd-2-clause
2,255
package setting import ( "github.com/insionng/makross" "github.com/insionng/makross/cache" "runtime" "time" "github.com/insionng/yougam/helper" "github.com/insionng/yougam/models" ) func BaseMiddler() makross.Handler { return func(self *makross.Context) error { tm := time.Now().UTC() self.Set("PageStartTime", tm.UnixNano()) self.Set("Version", helper.Version) self.Set("SiteName", helper.SiteName) self.Set("SiteTitle", helper.SiteTitle) self.Set("requesturi", self.RequestURI()) self.Set("gorotines", runtime.NumGoroutine()) self.Set("golangver", runtime.Version()) self.Set("UsersOnline", self.Session.Count()) if user, okay := self.Session.Get("SignedUser").(*models.User); okay { self.Set("IsSigned", true) self.Set("IsRoot", user.Role == -1000) self.Set("SignedUser", user) self.Set("friends", models.GetFriendsByUidJoinUser(user.Id, 0, 0, "", "id")) messages, e := models.GetMessagesViaReceiver(0, 0, user.Username, "created") if !(e != nil) { self.Set("messages", *messages) } } if cats, err := models.GetCategoriesByNodeCount(0, 0, 0, "id"); cats != nil && err == nil { self.Set("categories", *cats) } if pages, err := models.GetPages(0, 0, "id"); pages != nil && err == nil { self.Set("pages", pages) } if links, err := models.GetLinks(0, 0, "id"); links != nil && err == nil { self.Set("links", links) } var categoriesc, nodesc, topicsc, usersc, ReplysCount, pageviews int cc := cache.Store(self) if !cc.IsExist("nodescount") { categoriesc, nodesc, topicsc, usersc, ReplysCount = models.Counts() /* cc.Set("categoriescount", categoriesc) cc.Set("nodescount", nodesc) cc.Set("topicscount", topicsc) cc.Set("userscount", usersc) cc.Set("ReplysCount", ReplysCount) */ self.Set("categoriescount", categoriesc) self.Set("nodescount", nodesc) self.Set("topicscount", topicsc) self.Set("userscount", usersc) self.Set("ReplysCount", ReplysCount) } else { cc.Get("categoriescount", &categoriesc) self.Set("categoriescount", categoriesc) cc.Get("nodescount", &nodesc) self.Set("nodescount", nodesc) cc.Get("topicscount", &topicsc) self.Set("topicscount", topicsc) cc.Get("userscount", &usersc) self.Set("userscount", usersc) cc.Get("ReplysCount", &ReplysCount) self.Set("ReplysCount", ReplysCount) } if cc.Get("pageviews", &pageviews); pageviews == 0 { pageviews := int64(1) cc.Set("pageviews", pageviews, 60*60) self.Set("pageviews", pageviews) } else { pageviews = pageviews + 1 cc.Set("pageviews", pageviews, 60*60) self.Set("pageviews", pageviews) } //模板函数 self.Set("TimeSince", helper.TimeSince) self.Set("Split", helper.Split) self.Set("Metric", helper.Metric) self.Set("Htm2Str", helper.Htm2Str) self.Set("Markdown", helper.Markdown) self.Set("Markdown2Text", helper.Markdown2Text) self.Set("ConvertToBase64", helper.ConvertToBase64) self.Set("Unix2Time", helper.Unix2Time) self.Set("Compare", helper.Compare) self.Set("TimeConsuming", func(start int64) float64 { // 0.001 s return float64(time.Now().UnixNano()-start) / 1000000 * 0.001 }) self.Set("Text", func(content string, start, length int) string { return helper.Substr(helper.HTML2str(content), start, length, "...") }) //self.Set("Split", helper.SplitByPongo2) self.Set("Cropword", helper.Substr) self.Set("File", helper.File) self.Set("GetNodesByCid", func(cid int64, offset int, limit int, field string) *[]*models.Node { x, _ := models.GetNodesByCid(cid, offset, limit, field) return x }) return self.Next() } }
insionng/yougam
modules/setting/base.go
GO
bsd-2-clause
3,649
# frozen_string_literal: true require "test_helper" unless ENV["LIBEDIT"] module Byebug # # Tests Byebug's command line history. # class HistoryTest < TestCase def program strip_line_numbers <<-RUBY 1: module Byebug 2: byebug 3: 4: a = 2 5: a + 3 6: end RUBY end def test_history_displays_latest_records_from_readline_history enter "show", "history" debug_code(program) check_output_includes(/\d+ show$/, /\d+ history$/) end def test_history_n_displays_whole_history_if_n_is_bigger_than_history_size enter "show", "history 3" debug_code(program) check_output_includes(/\d+ show$/, /\d+ history 3$/) end def test_history_n_displays_lastest_n_records_from_readline_history enter "show width", "show autolist", "history 2" debug_code(program) check_output_includes(/\d+ show autolist$/, /\d+ history 2$/) end def test_history_does_not_save_empty_commands enter "show", "show width", "", "history 3" debug_code(program) check_output_includes( /\d+ show$/, /\d+ show width$/, /\d+ history 3$/ ) end def test_history_does_not_save_duplicated_consecutive_commands enter "show", "show width", "show width", "history 3" debug_code(program) check_output_includes( /\d+ show$/, /\d+ show width$/, /\d+ history 3$/ ) end def test_cmds_from_previous_repls_are_remembered_if_autosave_enabled with_setting :autosave, true do enter "next", "history 2" debug_code(program) check_output_includes(/\d+ next$/, /\d+ history 2$/) end end def test_cmds_from_previous_repls_are_not_remembered_if_autosave_disabled with_setting :autosave, false do enter "next", "history" debug_code(program) check_output_includes(/\d+ history$/) check_output_doesnt_include(/\d+ next$/) end end end end end
yui-knk/byebug
test/commands/history_test.rb
Ruby
bsd-2-clause
2,164
var proj4 = require('proj4'); var transformCoordinates = function transformCoordinates(fromProjection, toProjection, coordinates) { proj4.defs([ [ 'EPSG:3006', '+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3007', '+proj=tmerc +lat_0=0 +lon_0=12 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3008', '+proj=tmerc +lat_0=0 +lon_0=13.5 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3009', '+proj=tmerc +lat_0=0 +lon_0=15 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3010', '+proj=tmerc +lat_0=0 +lon_0=16.5 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3011', '+proj=tmerc +lat_0=0 +lon_0=18 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3012', '+proj=tmerc +lat_0=0 +lon_0=14.25 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3013', '+proj=tmerc +lat_0=0 +lon_0=15.75 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3014', '+proj=tmerc +lat_0=0 +lon_0=17.25 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3015', '+proj=tmerc +lat_0=0 +lon_0=18.75 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3016', '+proj=tmerc +lat_0=0 +lon_0=20.25 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3017', '+proj=tmerc +lat_0=0 +lon_0=21.75 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3018', '+proj=tmerc +lat_0=0 +lon_0=23.25 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ] ]); // If the projections is the same do nothing otherwise try transform if (fromProjection === toProjection) { return coordinates; } else { try { return proj4('EPSG:' + fromProjection, 'EPSG:' + toProjection, coordinates); } catch (e) { console.error('Error: ' + e); return coordinates; } } } module.exports = transformCoordinates;
origo-map/origo-server
lib/utils/transformcoordinates.js
JavaScript
bsd-2-clause
2,452
 namespace WpfGlyphics { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { } }
katascope/Glyphics
Glyphics/Apps/WpfGlyphics/App.xaml.cs
C#
bsd-2-clause
147
<?php $queries = []; $queries[] = 'ALTER TABLE `permission` CHANGE `user_id` `user_id` INT(11) UNSIGNED NOT NULL;'; $queries[] = 'ALTER TABLE `permission` ADD FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;';
wouteradem/octo
Octo/System/Migration/20140304-1532.php
PHP
bsd-2-clause
251
using UnityEngine; /// <summary> /// Base class for decorations /// </summary> public abstract class Decoration : IDecoration { private readonly WorldData m_WorldData; public Decoration(WorldData worldData) { m_WorldData = worldData; } public WorldData WorldData { get { return m_WorldData; } } public abstract bool Decorate(Chunk chunk, Vector3i localBlockPosition, IRandom random); /// <summary> /// Creates the tree canopy...a ball of leaves. /// </summary> /// <param name="blockX"></param> /// <param name="blockY"></param> /// <param name="blockZ"></param> /// <param name="radius"></param> protected void CreateSphereAt(int blockX, int blockY, int blockZ, int radius) { for (int x = blockX - radius; x <= blockX + radius; x++) { for (int y = blockY - radius; y <= blockY + radius; y++) { for (int z = blockZ - radius; z <= blockZ + radius; z++) { if (Vector3.Distance(new Vector3(blockX, blockY, blockZ), new Vector3(x, y, z)) <= radius) { WorldData.SetBlockType(x, y, z, BlockType.Leaves); } } } } } public void CreateColumnAt(int blockX, int blockY, int blockZ, int columnLength, BlockType blockType) { // Trunk for (int z = blockZ + 1; z <= blockZ + columnLength; z++) { CreateColumnAt(blockX, blockY, z, blockType); } } private void CreateColumnAt(int blockX, int blockY, int z, BlockType blockType) { WorldData.SetBlockType(blockX, blockY, z, blockType); } protected bool TheSpaceHereIsEmpty(int blockX, int blockY, int blockZ) { Vector3i blockSize = BlockSize; for (int z = blockZ + 1; z <= blockZ + blockSize.Z; z++) { for (int x = blockX - blockSize.X / 2; x <= blockX + blockSize.X / 2; x++) { for (int y = blockY - blockSize.Y / 2; y < blockY + blockSize.Y / 2; y++) { if (WorldData.GetBlock(x, y, z).Type != BlockType.Air) { return false; } } } } return true; } protected bool IsLocationLowEnough(int blockZ) { return blockZ < m_WorldData.DepthInBlocks - BlockSize.Z; } public abstract Vector3i BlockSize { get; } protected void CreateDiskAt(int blockX, int blockY, int blockZ, int radius, BlockType blockType) { for (int x = blockX - radius; x <= blockX + radius; x++) { for (int y = blockY - radius; y <= blockY + radius; y++) { if (Vector3.Distance(new Vector3(blockX, blockY, blockZ), new Vector3(x, y, blockZ)) <= radius) { m_WorldData.SetBlockType(x, y, blockZ, blockType); } } } } protected bool IsASolidDiskAreaAt(int blockX, int blockY, int blockZ, int radius) { for (int x = blockX - radius; x <= blockX + radius; x++) { for (int y = blockY - radius; y <= blockY + radius; y++) { if (Vector3.Distance(new Vector3(blockX, blockY, blockZ), new Vector3(x, y, blockZ)) <= radius) { if (m_WorldData.GetBlock(x, y, blockZ).Type == BlockType.Air) { return false; } } } } return true; } public void AddGameObjectDecorationToWorld(string name, Chunk chunk, Vector3 localMapPosition, Vector3 rotation) { chunk.AddGameObjectCreationData(new GameObjectCreationData(name, new Vector3(localMapPosition.x, localMapPosition.y, localMapPosition.z), rotation, m_WorldData)); } public void AddGameObjectDecorationToWorld(Chunk chunk, Vector3 position, Vector3 rotation) { AddGameObjectDecorationToWorld(ToString(), chunk, position, rotation); } }
kldavis4/MinePackage
Assets/Scripts/WorldDecorations/Decoration.cs
C#
bsd-2-clause
4,428
#ifndef _SDD_DD_TOP_HH_ #define _SDD_DD_TOP_HH_ #include <exception> #include <memory> // make_shared, shared_ptr #include <sstream> #include <string> #include <vector> #include "sdd/dd/definition_fwd.hh" namespace sdd { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief A base class to wrap operations of different type. struct operation_wrapper_base { virtual ~operation_wrapper_base() {} virtual std::string print() const noexcept = 0; }; /// @internal /// @brief A new type for each different operation, but which inherits from /// operation_wrapper_base. /// /// It it thus possible to have a list containing different operations by having a pointer /// to the base class operation_wrapper_base. template <typename Operation> struct operation_wrapper : public operation_wrapper_base { const Operation operation_; /// @brief Constructor. /// /// Operations are non-copyable, but movable. operation_wrapper(Operation&& op) : operation_(std::move(op)) {} /// @brief Return a textual description of the contained operation. std::string print() const noexcept { std::stringstream ss; ss << operation_; return ss.str(); } }; /*------------------------------------------------------------------------------------------------*/ /// @exception top /// @brief The top terminal. /// /// The top terminal is represented with an exception thrown when encoutering incompatible SDD. template <typename C> class top final : public std::exception { private: /// @brief The left incompatible operand. const SDD<C> lhs_; /// @brief The right incompatible operand. const SDD<C> rhs_; /// @brief The sequence, in reverse order, of operations that led to the error. std::vector<std::shared_ptr<operation_wrapper_base>> steps_; /// @brief Textual description of the error. mutable std::string description_; public: /// @internal top(const SDD<C>& lhs, const SDD<C>& rhs) : lhs_(lhs), rhs_(rhs), steps_(), description_() {} ~top() noexcept {} /// @brief Return the textual description of the error. /// /// All operations that led to the error are printed. const char* what() const noexcept { return description().c_str(); } /// @brief Get the left incompatible operand. /// /// Note that 'left' and 'right' are arbitrary. SDD<C> lhs() const noexcept { return lhs_; } /// @brief Get the right incompatible operand. /// /// Note that 'left' and 'right' are arbitrary. SDD<C> rhs() const noexcept { return rhs_; } /// @internal /// @brief Add an operation to the sequence of operations that lead to incompatible SDD. /// /// Called by mem::cache. template <typename Operation> void add_step(Operation&& op) { steps_.emplace_back(std::make_shared<operation_wrapper<Operation>>(std::move(op))); } /// @internal /// @brief Return a textual description. std::string& description() const noexcept { if (description_.empty()) { std::stringstream ss; ss << "Incompatible SDD: " << lhs_ << " and " << rhs_ << "." << std::endl << "The following operations led to this error (first to last): " << std::endl; std::size_t i = 1; for (auto rcit = steps_.crbegin(); rcit != steps_.crend(); ++rcit, ++i) { ss << i << " : " << (*rcit)->print() << std::endl; } description_ = ss.str(); } return description_; } }; /*------------------------------------------------------------------------------------------------*/ } // namespace sdd #endif // _SDD_DD_TOP_HH_
ahamez/proto-dd
sdd/dd/top.hh
C++
bsd-2-clause
3,697
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. export import Client = require('./lib/client'); export import ConnectionString = require('./lib/connection_string'); export import Registry = require('./lib/registry'); export import SharedAccessSignature = require('./lib/shared_access_signature'); export import Amqp = require('./lib/amqp'); export import AmqpWs = require('./lib/amqp_ws'); export import DeviceMethodParams = require('./lib/device_method_params'); export import JobClient = require('./lib/job_client'); export import Device = require('./lib/device');
vunvulear/IoTHomeProject
nodejs-grovepi-azureiot/node_modules/azure-iothub/iothub.d.ts
TypeScript
bsd-2-clause
671
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-id-get-value-err.case // - src/dstr-binding/error/gen-func-decl-dflt.template /*--- description: Error thrown when accessing the corresponding property of the value object (generator function declaration (default parameter)) esid: sec-generator-function-definitions-runtime-semantics-instantiatefunctionobject es6id: 14.4.12 features: [generators, destructuring-binding, default-parameters] flags: [generated] info: | GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody } [...] 2. Let F be GeneratorFunctionCreate(Normal, FormalParameters, GeneratorBody, scope, strict). [...] 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 4. Let v be GetV(value, propertyName). 5. ReturnIfAbrupt(v). ---*/ var poisonedProperty = Object.defineProperty({}, 'poisoned', { get: function() { throw new Test262Error(); } }); function* f({ poisoned } = poisonedProperty) {} assert.throws(Test262Error, function() { f(); });
sebastienros/jint
Jint.Tests.Test262/test/language/statements/generators/dstr-dflt-obj-ptrn-id-get-value-err.js
JavaScript
bsd-2-clause
1,835
# -*- coding: utf-8 -*- #!/usr/bin/env python from setuptools import setup, find_packages setup( name = 'wechat-python-sdk', version = '0.5.7', keywords = ('wechat', 'sdk', 'wechat sdk'), description = u'微信公众平台Python开发包', long_description = open("README.rst").read(), license = 'BSD License', url = 'https://github.com/doraemonext/wechat-python-sdk', author = 'doraemonext', author_email = 'doraemonext@gmail.com', packages = find_packages(), include_package_data = True, platforms = 'any', install_requires=open("requirements.txt").readlines(), )
Beeblio/wechat-python-sdk
setup.py
Python
bsd-2-clause
622
#include <CtrlLib/CtrlLib.h> using namespace Upp; GUI_APP_MAIN { ConvertOpeningHours cv; DDUMP(cv.Format(cv.Scan("11:00-22:00 12:00-18:00 23:00-23:30"))); EditField ef; ef.SetConvert(cv); TopWindow win; win.Add(ef.TopPos(0, Ctrl::STDSIZE).HSizePos()); win.Run(); }
dreamsxin/ultimatepp
uppdev/OpeningPeriod/main.cpp
C++
bsd-2-clause
288
import sys import itertools from functools import reduce from operator import iadd import numpy from PyQt4.QtGui import ( QFormLayout, QGraphicsRectItem, QGraphicsGridLayout, QFontMetrics, QPen, QIcon, QPixmap, QLinearGradient, QPainter, QColor, QBrush, QTransform, QGraphicsWidget, QApplication ) from PyQt4.QtCore import Qt, QRect, QRectF, QSize, QPointF from PyQt4.QtCore import pyqtSignal as Signal import pyqtgraph as pg import Orange.data import Orange.misc from Orange.clustering import hierarchical from Orange.widgets import widget, gui, settings from Orange.widgets.utils import itemmodels, colorbrewer from .owhierarchicalclustering import DendrogramWidget, GraphicsSimpleTextList from Orange.widgets.io import FileFormat def _remove_item(item): item.setParentItem(None) scene = item.scene() if scene is not None: scene.removeItem(item) class DistanceMapItem(pg.ImageItem): """A distance matrix image with user selectable regions. """ class SelectionRect(QGraphicsRectItem): def boundingRect(self): return super().boundingRect().adjusted(-1, -1, 1, 1) def paint(self, painter, option, widget=None): t = painter.transform() rect = t.mapRect(self.rect()) painter.save() painter.setTransform(QTransform()) pwidth = self.pen().widthF() painter.setPen(self.pen()) painter.drawRect(rect.adjusted(pwidth, -pwidth, -pwidth, pwidth)) painter.restore() selectionChanged = Signal() Clear, Select, Commit = 1, 2, 4 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setAcceptedMouseButtons(Qt.LeftButton | Qt.RightButton) self.setAcceptHoverEvents(True) self.__selections = [] #: (QGraphicsRectItem, QRectF) | None self.__dragging = None def __select(self, area, command): if command & self.Clear: self.__clearSelections() if command & self.Select: area = area.normalized() intersects = [rect.intersects(area) for item, rect in self.__selections] def partition(predicate, iterable): t1, t2 = itertools.tee(iterable) return (itertools.filterfalse(predicate, t1), filter(predicate, t2)) def intersects(selection): _, selarea = selection return selarea.intersects(area) disjoint, intersection = partition(intersects, self.__selections) disjoint = list(disjoint) intersection = list(intersection) # merge intersecting selections into a single area area = reduce(QRect.united, (area for _, area in intersection), area) visualarea = self.__visualRectForSelection(area) item = DistanceMapItem.SelectionRect(visualarea, self) item.setPen(QPen(Qt.red, 0)) selection = disjoint + [(item, area)] for item, _ in intersection: _remove_item(item) self.__selections = selection self.selectionChanged.emit() def __elastic_band_select(self, area, command): if command & self.Clear and self.__dragging: item, area = self.__dragging _remove_item(item) self.__dragging = None if command & self.Select: if self.__dragging: item, _ = self.__dragging else: item = DistanceMapItem.SelectionRect(self) item.setPen(QPen(Qt.red, 0)) # intersection with existing regions intersection = [(item, selarea) for item, selarea in self.__selections if area.intersects(selarea)] fullarea = reduce( QRect.united, (selarea for _, selarea in intersection), area ) visualarea = self.__visualRectForSelection(fullarea) item.setRect(visualarea) self.__dragging = item, area if command & self.Commit and self.__dragging: item, area = self.__dragging self.__select(area, self.Select) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: r, c = self._cellAt(event.pos()) if r != -1 and c != -1: # Clear existing selection # TODO: Fix extended selection. self.__select(QRect(), self.Clear) selrange = QRect(c, r, 1, 1) self.__elastic_band_select(selrange, self.Select | self.Clear) elif event.button() == Qt.RightButton: self.__select(QRect(), self.Clear) super().mousePressEvent(event) event.accept() def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton and self.__dragging: r1, c1 = self._cellAt(event.buttonDownPos(Qt.LeftButton)) r2, c2 = self._cellCloseTo(event.pos()) selrange = QRect(c1, r1, 1, 1).united(QRect(c2, r2, 1, 1)) self.__elastic_band_select(selrange, self.Select) super().mouseMoveEvent(event) event.accept() def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton and self.__dragging: r1, c1 = self._cellAt(event.buttonDownPos(Qt.LeftButton)) r2, c2 = self._cellCloseTo(event.pos()) selrange = QRect(c1, r1, 1, 1).united(QRect(c2, r2, 1, 1)) self.__elastic_band_select(selrange, self.Select | self.Commit) self.__elastic_band_select(QRect(), self.Clear) super().mouseReleaseEvent(event) event.accept() def _cellAt(self, pos): """Return the i, j cell index at `pos` in local coordinates.""" if self.image is None: return -1, -1 else: h, w = self.image.shape i, j = numpy.floor([pos.y(), pos.x()]) if 0 <= i < h and 0 <= j < w: return int(i), int(j) else: return -1, -1 def _cellCloseTo(self, pos): """Return the i, j cell index closest to `pos` in local coordinates.""" if self.image is None: return -1, -1 else: h, w = self.image.shape i, j = numpy.floor([pos.y(), pos.x()]) i = numpy.clip(i, 0, h - 1) j = numpy.clip(j, 0, w - 1) return int(i), int(j) def __clearSelections(self): for item, _ in self.__selections: _remove_item(item) self.__selections = [] def __visualRectForSelection(self, rect): h, w = self.image.shape rect = rect.normalized() rect = rect.intersected(QRect(0, 0, w, h)) r1, r2 = rect.top(), rect.bottom() + 1 c1, c2 = rect.left(), rect.right() + 1 return QRectF(QPointF(c1, r1), QPointF(c2, r2)) def __selectionForArea(self, area): r1, c1 = self._cellAt(area.topLeft()) r2, c2 = self._cellAt(area.bottomRight()) selarea = QRect(c1, r1, c2 - c1 + 1, r2 - r1 + 1) return selarea.normalized() def selections(self): selections = [self.__selectionForArea(area) for _, area in self.__selections] return [(range(r.top(), r.bottom() + 1), range(r.left(), r.right() + 1)) for r in selections] def hoverMoveEvent(self, event): super().hoverMoveEvent(event) i, j = self._cellAt(event.pos()) if i != -1 and j != -1: d = self.image[i, j] self.setToolTip("{}, {}: {:.3f}".format(i, j, d)) else: self.setToolTip("") _color_palettes = sorted(colorbrewer.colorSchemes["sequential"].items()) + \ [("Blue-Yellow", {2: [(0, 0, 255), (255, 255, 0)]})] _default_colormap_index = len(_color_palettes) - 1 class OWDistanceMap(widget.OWWidget): name = "Distance Map" description = "Visualize a distance matrix." icon = "icons/DistanceMap.svg" priority = 1200 inputs = [("Distances", Orange.misc.DistMatrix, "set_distances")] outputs = [("Data", Orange.data.Table), ("Features", widget.AttributeList)] settingsHandler = settings.PerfectDomainContextHandler() #: type of ordering to apply to matrix rows/columns NoOrdering, Clustering, OrderedClustering = 0, 1, 2 sorting = settings.Setting(NoOrdering) colormap = settings.Setting(_default_colormap_index) color_gamma = settings.Setting(0.0) color_low = settings.Setting(0.0) color_high = settings.Setting(1.0) annotation_idx = settings.ContextSetting(0, exclude_metas=False) autocommit = settings.Setting(True) graph_name = "grid_widget" # Disable clustering for inputs bigger than this _MaxClustering = 3000 # Disable cluster leaf ordering for inputs bigger than this _MaxOrderedClustering = 1000 def __init__(self): super().__init__() self.matrix = None self._tree = None self._ordered_tree = None self._sorted_matrix = None self._sort_indices = None self._selection = None box = gui.widgetBox(self.controlArea, "Element sorting", margin=0) self.sorting_cb = gui.comboBox( box, self, "sorting", items=["None", "Clustering", "Clustering with ordered leaves"], callback=self._invalidate_ordering) box = gui.widgetBox(self.controlArea, "Colors") self.colormap_cb = gui.comboBox( box, self, "colormap", callback=self._update_color ) self.colormap_cb.setIconSize(QSize(64, 16)) self.palettes = list(_color_palettes) init_color_combo(self.colormap_cb, self.palettes, QSize(64, 16)) self.colormap_cb.setCurrentIndex(self.colormap) form = QFormLayout( formAlignment=Qt.AlignLeft, labelAlignment=Qt.AlignLeft, fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow ) # form.addRow( # "Gamma", # gui.hSlider(box, self, "color_gamma", minValue=0.0, maxValue=1.0, # step=0.05, ticks=True, intOnly=False, # createLabel=False, callback=self._update_color) # ) form.addRow( "Low", gui.hSlider(box, self, "color_low", minValue=0.0, maxValue=1.0, step=0.05, ticks=True, intOnly=False, createLabel=False, callback=self._update_color) ) form.addRow( "High", gui.hSlider(box, self, "color_high", minValue=0.0, maxValue=1.0, step=0.05, ticks=True, intOnly=False, createLabel=False, callback=self._update_color) ) box.layout().addLayout(form) box = gui.widgetBox(self.controlArea, "Annotations") self.annot_combo = gui.comboBox(box, self, "annotation_idx", callback=self._invalidate_annotations, contentsLength=12) self.annot_combo.setModel(itemmodels.VariableListModel()) self.annot_combo.model()[:] = ["None", "Enumeration"] self.controlArea.layout().addStretch() gui.auto_commit(self.controlArea, self, "autocommit", "Send data", "Auto send is on") self.inline_graph_report() self.view = pg.GraphicsView(background="w") self.mainArea.layout().addWidget(self.view) self.grid_widget = pg.GraphicsWidget() self.grid = QGraphicsGridLayout() self.grid_widget.setLayout(self.grid) self.viewbox = pg.ViewBox(enableMouse=False, enableMenu=False) self.viewbox.setAcceptedMouseButtons(Qt.NoButton) self.viewbox.setAcceptHoverEvents(False) self.grid.addItem(self.viewbox, 1, 1) self.left_dendrogram = DendrogramWidget( self.grid_widget, orientation=DendrogramWidget.Left, selectionMode=DendrogramWidget.NoSelection, hoverHighlightEnabled=False ) self.left_dendrogram.setAcceptedMouseButtons(Qt.NoButton) self.left_dendrogram.setAcceptHoverEvents(False) self.top_dendrogram = DendrogramWidget( self.grid_widget, orientation=DendrogramWidget.Top, selectionMode=DendrogramWidget.NoSelection, hoverHighlightEnabled=False ) self.top_dendrogram.setAcceptedMouseButtons(Qt.NoButton) self.top_dendrogram.setAcceptHoverEvents(False) self.grid.addItem(self.left_dendrogram, 1, 0) self.grid.addItem(self.top_dendrogram, 0, 1) self.right_labels = TextList( alignment=Qt.AlignLeft) self.bottom_labels = TextList( orientation=Qt.Horizontal, alignment=Qt.AlignRight) self.grid.addItem(self.right_labels, 1, 2) self.grid.addItem(self.bottom_labels, 2, 1) self.view.setCentralItem(self.grid_widget) self.left_dendrogram.hide() self.top_dendrogram.hide() self.right_labels.hide() self.bottom_labels.hide() self.matrix_item = None self.dendrogram = None self.grid_widget.scene().installEventFilter(self) def set_distances(self, matrix): self.closeContext() self.clear() self.error(0) if matrix is not None: N, _ = matrix.shape if N < 2: self.error(0, "Empty distance matrix.") matrix = None self.matrix = matrix if matrix is not None: self.set_items(matrix.row_items, matrix.axis) else: self.set_items(None) if matrix is not None: N, _ = matrix.shape else: N = 0 model = self.sorting_cb.model() item = model.item(2) msg = None if N > OWDistanceMap._MaxOrderedClustering: item.setFlags(item.flags() & ~Qt.ItemIsEnabled) if self.sorting == OWDistanceMap.OrderedClustering: self.sorting = OWDistanceMap.Clustering msg = "Cluster ordering was disabled due to the input " \ "matrix being to big" else: item.setFlags(item.flags() | Qt.ItemIsEnabled) item = model.item(1) if N > OWDistanceMap._MaxClustering: item.setFlags(item.flags() & ~Qt.ItemIsEnabled) if self.sorting == OWDistanceMap.Clustering: self.sorting = OWDistanceMap.NoOrdering msg = "Clustering was disabled due to the input " \ "matrix being to big" else: item.setFlags(item.flags() | Qt.ItemIsEnabled) self.information(1, msg) def set_items(self, items, axis=1): self.items = items model = self.annot_combo.model() if items is None: model[:] = ["None", "Enumeration"] elif not axis: model[:] = ["None", "Enumeration", "Attribute names"] elif isinstance(items, Orange.data.Table): annot_vars = list(items.domain) + list(items.domain.metas) model[:] = ["None", "Enumeration"] + annot_vars self.annotation_idx = 0 self.openContext(items.domain) elif isinstance(items, list) and \ all(isinstance(item, Orange.data.Variable) for item in items): model[:] = ["None", "Enumeration", "Name"] else: model[:] = ["None", "Enumeration"] self.annotation_idx = min(self.annotation_idx, len(model) - 1) def clear(self): self.matrix = None self.cluster = None self._tree = None self._ordered_tree = None self._sorted_matrix = None self._selection = [] self._clear_plot() def handleNewSignals(self): if self.matrix is not None: self._update_ordering() self._setup_scene() self._update_labels() self.unconditional_commit() def _clear_plot(self): def remove(item): item.setParentItem(None) item.scene().removeItem(item) if self.matrix_item is not None: self.matrix_item.selectionChanged.disconnect( self._invalidate_selection) remove(self.matrix_item) self.matrix_item = None self._set_displayed_dendrogram(None) self._set_labels(None) def _cluster_tree(self): if self._tree is None: self._tree = hierarchical.dist_matrix_clustering(self.matrix) return self._tree def _ordered_cluster_tree(self): if self._ordered_tree is None: tree = self._cluster_tree() self._ordered_tree = \ hierarchical.optimal_leaf_ordering(tree, self.matrix) return self._ordered_tree def _setup_scene(self): self._clear_plot() self.matrix_item = DistanceMapItem(self._sorted_matrix) # Scale the y axis to compensate for pg.ViewBox's y axis invert self.matrix_item.scale(1, -1) self.viewbox.addItem(self.matrix_item) # Set fixed view box range. h, w = self._sorted_matrix.shape self.viewbox.setRange(QRectF(0, -h, w, h), padding=0) self.matrix_item.selectionChanged.connect(self._invalidate_selection) if self.sorting == OWDistanceMap.NoOrdering: tree = None elif self.sorting == OWDistanceMap.Clustering: tree = self._cluster_tree() elif self.sorting == OWDistanceMap.OrderedClustering: tree = self._ordered_cluster_tree() self._set_displayed_dendrogram(tree) self._update_color() def _set_displayed_dendrogram(self, root): self.left_dendrogram.set_root(root) self.top_dendrogram.set_root(root) self.left_dendrogram.setVisible(root is not None) self.top_dendrogram.setVisible(root is not None) constraint = 0 if root is None else -1 # 150 self.left_dendrogram.setMaximumWidth(constraint) self.top_dendrogram.setMaximumHeight(constraint) def _invalidate_ordering(self): self._sorted_matrix = None if self.matrix is not None: self._update_ordering() self._setup_scene() def _update_ordering(self): if self.sorting == OWDistanceMap.NoOrdering: self._sorted_matrix = self.matrix self._sort_indices = None else: if self.sorting == OWDistanceMap.Clustering: tree = self._cluster_tree() elif self.sorting == OWDistanceMap.OrderedClustering: tree = self._ordered_cluster_tree() leaves = hierarchical.leaves(tree) indices = numpy.array([leaf.value.index for leaf in leaves]) X = self.matrix self._sorted_matrix = X[indices[:, numpy.newaxis], indices[numpy.newaxis, :]] self._sort_indices = indices def _invalidate_annotations(self): if self.matrix is not None: self._update_labels() def _update_labels(self, ): if self.annotation_idx == 0: labels = None elif self.annotation_idx == 1: labels = [str(i + 1) for i in range(self.matrix.shape[0])] elif self.annot_combo.model()[self.annotation_idx] == "Attribute names": attr = self.matrix.row_items.domain.attributes labels = [str(attr[i]) for i in range(self.matrix.shape[0])] elif self.annotation_idx == 2 and \ isinstance(self.items, widget.AttributeList): labels = [v.name for v in self.items] elif isinstance(self.items, Orange.data.Table): var = self.annot_combo.model()[self.annotation_idx] column, _ = self.items.get_column_view(var) labels = [var.repr_val(value) for value in column] self._set_labels(labels) def _set_labels(self, labels): self._labels = labels if labels and self.sorting != OWDistanceMap.NoOrdering: sortind = self._sort_indices labels = [labels[i] for i in sortind] for textlist in [self.right_labels, self.bottom_labels]: textlist.set_labels(labels or []) textlist.setVisible(bool(labels)) constraint = -1 if labels else 0 self.right_labels.setMaximumWidth(constraint) self.bottom_labels.setMaximumHeight(constraint) def _update_color(self): if self.matrix_item: name, colors = self.palettes[self.colormap] n, colors = max(colors.items()) colors = numpy.array(colors, dtype=numpy.ubyte) low, high = self.color_low * 255, self.color_high * 255 points = numpy.linspace(low, high, n) space = numpy.linspace(0, 255, 255) r = numpy.interp(space, points, colors[:, 0], left=255, right=0) g = numpy.interp(space, points, colors[:, 1], left=255, right=0) b = numpy.interp(space, points, colors[:, 2], left=255, right=0) colortable = numpy.c_[r, g, b] self.matrix_item.setLookupTable(colortable) def _invalidate_selection(self): ranges = self.matrix_item.selections() ranges = reduce(iadd, ranges, []) indices = reduce(iadd, ranges, []) if self.sorting != OWDistanceMap.NoOrdering: sortind = self._sort_indices indices = [sortind[i] for i in indices] self._selection = list(sorted(set(indices))) self.commit() def commit(self): datasubset = None featuresubset = None if not self._selection: pass elif isinstance(self.items, Orange.data.Table): indices = self._selection if self.matrix.axis == 1: datasubset = self.items.from_table_rows(self.items, indices) elif self.matrix.axis == 0: domain = Orange.data.Domain( [self.items.domain[i] for i in indices], self.items.domain.class_vars, self.items.domain.metas) datasubset = Orange.data.Table.from_table(domain, self.items) elif isinstance(self.items, widget.AttributeList): subset = [self.items[i] for i in self._selection] featuresubset = widget.AttributeList(subset) self.send("Data", datasubset) self.send("Features", featuresubset) def onDeleteWidget(self): super().onDeleteWidget() self.clear() def send_report(self): annot = self.annot_combo.currentText() if self.annotation_idx <= 1: annot = annot.lower() self.report_items(( ("Sorting", self.sorting_cb.currentText().lower()), ("Annotations", annot) )) if self.matrix is not None: self.report_plot() class TextList(GraphicsSimpleTextList): def resizeEvent(self, event): super().resizeEvent(event) self._updateFontSize() def _updateFontSize(self): crect = self.contentsRect() if self.orientation == Qt.Vertical: h = crect.height() else: h = crect.width() n = len(getattr(self, "label_items", [])) if n == 0: return if self.scene() is not None: maxfontsize = self.scene().font().pointSize() else: maxfontsize = QApplication.instance().font().pointSize() lineheight = max(1, h / n) fontsize = min(self._point_size(lineheight), maxfontsize) font = self.font() font.setPointSize(fontsize) self.setFont(font) self.layout().invalidate() self.layout().activate() def _point_size(self, height): font = self.font() font.setPointSize(height) fix = 0 while QFontMetrics(font).lineSpacing() > height and height - fix > 1: fix += 1 font.setPointSize(height - fix) return height - fix ########################## # Color palette management ########################## def palette_gradient(colors, discrete=False): n = len(colors) stops = numpy.linspace(0.0, 1.0, n, endpoint=True) gradstops = [(float(stop), color) for stop, color in zip(stops, colors)] grad = QLinearGradient(QPointF(0, 0), QPointF(1, 0)) grad.setStops(gradstops) return grad def palette_pixmap(colors, size): img = QPixmap(size) img.fill(Qt.transparent) painter = QPainter(img) grad = palette_gradient(colors) grad.setCoordinateMode(QLinearGradient.ObjectBoundingMode) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(grad)) painter.drawRect(0, 0, size.width(), size.height()) painter.end() return img def init_color_combo(cb, palettes, iconsize): cb.clear() iconsize = cb.iconSize() for name, palette in palettes: n, colors = max(palette.items()) colors = [QColor(*c) for c in colors] cb.addItem(QIcon(palette_pixmap(colors, iconsize)), name, palette) def test(argv=sys.argv): app = QApplication(list(argv)) argv = app.arguments() if len(argv) > 1: filename = argv[1] else: filename = "iris" import sip import Orange.distance w = OWDistanceMap() w.show() w.raise_() data = Orange.data.Table(filename) dist = Orange.distance.Euclidean(data) w.set_distances(dist) w.handleNewSignals() rval = app.exec_() w.set_distances(None) w.saveSettings() w.onDeleteWidget() sip.delete(w) del w return rval if __name__ == "__main__": sys.exit(test())
kwikadi/orange3
Orange/widgets/unsupervised/owdistancemap.py
Python
bsd-2-clause
26,035
import React from "react" import ServerError from "./ServerError" import NotFoundError from "./NotFoundError" import OtherError from "./OtherError" import { ApolloError } from "@apollo/client" type Props = { /** GraphQL error object */ error: ApolloError } /** * Displays any errors found when issuing a GraphQL query or mutation. * Returns one of the other error components based on the error code. */ const GraphQLErrorPage = ({ error }: Props) => { if (!error || !error.message) return null if (error.networkError) { console.error(error.networkError) return <ServerError /> } let errorCode, errorMsg if (error.graphQLErrors && error.graphQLErrors[0].extensions) { errorCode = error.graphQLErrors[0].extensions.code errorMsg = error.graphQLErrors[0].message } if (errorCode === "Unavailable") { return <ServerError /> } if (errorCode === "NotFound" && errorMsg) { return ( <NotFoundError error={errorMsg.charAt(0).toUpperCase() + errorMsg.slice(1)} /> ) } return <OtherError /> } GraphQLErrorPage.defaultProps = { error: {}, } export default GraphQLErrorPage
dictyBase/genomepage
components/errors/GraphQLErrorPage.tsx
TypeScript
bsd-2-clause
1,151
package com.myking520.github.client; import org.apache.mina.core.session.IoSession; /** * 客户端管理 */ public interface IClientManager { public IClient create(IoSession session); public void remove(IoSession session); }
myking520/gamefm
gamefm-net/src/main/java/com/myking520/github/client/IClientManager.java
Java
bsd-2-clause
232
/* * Copyright (c) 2002-2017, Manorrock.com. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.manorrock.json.convert; import com.manorrock.convert.Converter; import com.manorrock.convert.ConverterContext; import com.manorrock.json.JsonString; /** * A JSON string to String converter. * * @author Manfred Riem (mriem@manorrock.com) */ public class JsonStringStringConverter implements Converter<JsonString, String> { /** * Convert a JSON string to a string. * * @param context the context. * @param string the JSON string. * @return the string. */ @Override public String convert(ConverterContext context, JsonString string) { return string != null ? string.getString() : null; } }
manorrock/json
convert/src/main/java/com/manorrock/json/convert/JsonStringStringConverter.java
Java
bsd-2-clause
2,078
// RUN: %clang_cc1 -verify=expected,omp45 -fopenmp-version=45 -fopenmp %s -Wuninitialized // RUN: %clang_cc1 -verify=expected,omp50 -fopenmp-version=50 -fopenmp %s -Wuninitialized // RUN: %clang_cc1 -verify=expected,omp45 -fopenmp-version=45 -fopenmp-simd %s -Wuninitialized // RUN: %clang_cc1 -verify=expected,omp50 -fopenmp-version=50 -fopenmp-simd %s -Wuninitialized typedef void **omp_allocator_handle_t; extern const omp_allocator_handle_t omp_default_mem_alloc; extern const omp_allocator_handle_t omp_large_cap_mem_alloc; extern const omp_allocator_handle_t omp_const_mem_alloc; extern const omp_allocator_handle_t omp_high_bw_mem_alloc; extern const omp_allocator_handle_t omp_low_lat_mem_alloc; extern const omp_allocator_handle_t omp_cgroup_mem_alloc; extern const omp_allocator_handle_t omp_pteam_mem_alloc; extern const omp_allocator_handle_t omp_thread_mem_alloc; void foo() { } bool foobool(int argc) { return argc; } struct S1; // expected-note 2 {{declared here}} expected-note 2 {{forward declaration of 'S1'}} extern S1 a; class S2 { mutable int a; public: S2() : a(0) {} S2(S2 &s2) : a(s2.a) {} const S2 &operator =(const S2&) const; S2 &operator =(const S2&); static float S2s; // expected-note {{static data member is predetermined as shared}} static const float S2sc; // expected-note {{'S2sc' declared here}} }; const float S2::S2sc = 0; const S2 b; const S2 ba[5]; class S3 { int a; S3 &operator=(const S3 &s3); // expected-note 2 {{implicitly declared private here}} public: S3() : a(0) {} S3(S3 &s3) : a(s3.a) {} }; const S3 c; // expected-note {{'c' defined here}} const S3 ca[5]; // expected-note {{'ca' defined here}} extern const int f; // expected-note {{'f' declared here}} class S4 { int a; S4(); // expected-note 3 {{implicitly declared private here}} S4(const S4 &s4); public: S4(int v) : a(v) {} }; class S5 { int a; S5() : a(0) {} // expected-note {{implicitly declared private here}} public: S5(const S5 &s5) : a(s5.a) {} S5(int v) : a(v) {} }; class S6 { int a; S6() : a(0) {} public: S6(const S6 &s6) : a(s6.a) {} S6(int v) : a(v) {} }; S3 h; #pragma omp threadprivate(h) // expected-note 2 {{defined as threadprivate or thread local}} template <class I, class C> int foomain(int argc, char **argv) { I e(4); I g(5); int i, z; int &j = i; #pragma omp parallel #pragma omp master taskloop simd lastprivate // expected-error {{expected '(' after 'lastprivate'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate() // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(argc) allocate , allocate(, allocate(omp_default , allocate(omp_default_mem_alloc, allocate(omp_default_mem_alloc:, allocate(omp_default_mem_alloc: argc, allocate(omp_default_mem_alloc: argv), allocate(argv) // expected-error {{expected '(' after 'allocate'}} expected-error 2 {{expected expression}} expected-error 2 {{expected ')'}} expected-error {{use of undeclared identifier 'omp_default'}} expected-note 2 {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(conditional: argc) lastprivate(conditional: // expected-error 2 {{use of undeclared identifier 'conditional'}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(z, a, b) // expected-error {{lastprivate variable with incomplete type 'S1'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(e, g) // expected-error 2 {{calling a private constructor of class 'S4'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(h) // expected-error {{threadprivate or thread local variable cannot be lastprivate}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel { int v = 0; int i; #pragma omp master taskloop simd lastprivate(i) allocate(omp_thread_mem_alloc: i) // expected-warning {{allocator with the 'thread' trait access has unspecified behavior on 'master taskloop simd' directive}} for (int k = 0; k < argc; ++k) { i = k; v += i; } } #pragma omp parallel shared(i) #pragma omp parallel private(i) #pragma omp master taskloop simd lastprivate(j) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel #pragma omp master taskloop simd lastprivate(i) for (int k = 0; k < argc; ++k) ++k; return 0; } void bar(S4 a[2]) { #pragma omp parallel #pragma omp master taskloop simd lastprivate(a) for (int i = 0; i < 2; ++i) foo(); } namespace A { double x; #pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}} } namespace B { using A::x; } int main(int argc, char **argv) { const int d = 5; // expected-note {{'d' defined here}} const int da[5] = {0}; // expected-note {{'da' defined here}} S4 e(4); S5 g(5); S3 m; S6 n(2); int i, z; int &j = i; #pragma omp parallel #pragma omp master taskloop simd lastprivate // expected-error {{expected '(' after 'lastprivate'}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate() // expected-error {{expected expression}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(argc, z) for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(S1) // expected-error {{'S1' does not refer to a value}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(a, b, c, d, f) // expected-error {{lastprivate variable with incomplete type 'S1'}} expected-error 1 {{const-qualified variable without mutable fields cannot be lastprivate}} expected-error 2 {{const-qualified variable cannot be lastprivate}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(argv[1]) // expected-error {{expected variable name}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(2 * 2) // expected-error {{expected variable name}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(ba) for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(ca) // expected-error {{const-qualified variable without mutable fields cannot be lastprivate}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(da) // expected-error {{const-qualified variable cannot be lastprivate}} for (i = 0; i < argc; ++i) foo(); int xa; #pragma omp parallel #pragma omp master taskloop simd lastprivate(xa) // OK for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(S2::S2s) // expected-error {{shared variable cannot be lastprivate}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(S2::S2sc) // expected-error {{const-qualified variable cannot be lastprivate}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd safelen(5) for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(e, g) // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(m) // expected-error {{'operator=' is a private member of 'S3'}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(h) // expected-error {{threadprivate or thread local variable cannot be lastprivate}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(B::x) // expected-error {{threadprivate or thread local variable cannot be lastprivate}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd private(xa), lastprivate(xa) // expected-error {{private variable cannot be lastprivate}} expected-note {{defined as private}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(i) // omp45-note {{defined as lastprivate}} for (i = 0; i < argc; ++i) // omp45-error {{loop iteration variable in the associated loop of 'omp master taskloop simd' directive may not be lastprivate, predetermined as linear}} foo(); #pragma omp parallel private(xa) #pragma omp master taskloop simd lastprivate(xa) for (i = 0; i < argc; ++i) foo(); #pragma omp parallel reduction(+ : xa) #pragma omp master taskloop simd lastprivate(xa) for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(j) for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd firstprivate(m) lastprivate(m) // expected-error {{'operator=' is a private member of 'S3'}} for (i = 0; i < argc; ++i) foo(); #pragma omp parallel #pragma omp master taskloop simd lastprivate(n) firstprivate(n) // OK for (i = 0; i < argc; ++i) foo(); static int si; #pragma omp master taskloop simd lastprivate(si) // OK for (i = 0; i < argc; ++i) si = i + 1; return foomain<S4, S5>(argc, argv); // expected-note {{in instantiation of function template specialization 'foomain<S4, S5>' requested here}} }
epiqc/ScaffCC
clang/test/OpenMP/master_taskloop_simd_lastprivate_messages.cpp
C++
bsd-2-clause
11,739
// // paCriticalSection.cpp // #include "PhyaPluginPrivatePCH.h"
PopCap/GameIdea
Engine/Plugins/Experimental/Phya/Source/Phya/Private/PhyaLib/src/System/paCriticalSection.cpp
C++
bsd-2-clause
66
# frozen_string_literal: true require 'json' require 'faraday' require 'addressable' require_relative 'response' require_relative '../defs/version' require_relative '../support/mixins' require_relative '../stdlib/time' module Wavefront # # Constructs and makes API calls to Wavefront. # class ApiCaller include Wavefront::Mixins attr_reader :opts, :noop, :debug, :verbose, :net, :logger, :calling_class # @param calling_class [ # @param creds [Hash] Wavefront credentials # @param opts [Hash] # @return [Nil] # def initialize(calling_class, creds = {}, opts = {}) @calling_class = calling_class @opts = opts setup_class_vars(opts) setup_endpoint(creds) end def setup_class_vars(opts) @logger = Wavefront::Logger.new(opts) @noop = opts[:noop] || false @verbose = opts[:verbose] || false @debug = opts[:debug] || false end # Create a Faraday connection object. The server comes from the # endpoint passed to the initializer in the 'creds' hash; the # root of the URI is dynamically derived by the #setup_endpoint # method. # # @param path [String] uri path # @param headers [Hash] additional headers # @param request_opts [Hash] Faraday request parameters # @return [URI::HTTPS] # def mk_conn(path, headers = {}, opts = {}) url = format('%<scheme>s://%<endpoint>s%<path>s', scheme: net[:scheme], endpoint: net[:endpoint], path: [net[:api_base], path].uri_concat) set_opts = { url: Addressable::URI.encode(url), headers: net[:headers].merge(headers) } Faraday.new(set_opts.merge(opts)) end # Make a GET call to the Wavefront API and return the result as # a Ruby hash. # # @param path [String] path to be appended to the # #net[:api_base] path. # @param query [Hash] optional key-value pairs with will be made # into a query string # @param request_opts [Hash] parameters to pass through to # Faraday # @return [Hash] API response # def get(path, query = {}) make_call(mk_conn(path, {}), :get, nil, query) end # Had to introduce this for the Wavefront::Dashboard#acls # method, which uses a query string of multiple id=s. By default # Faraday only uses the last one. You must set the # `params_encoder`. Rather than convolute the existing logic, it # was cleaner to add this method. Parameters are same as #get. # def get_flat_params(path, query = {}) make_call(flat_param_conn(path, query), :get) end # This is used by the Wavefront::Unstable::Spy methods to stream data. # It prints to standard out. # @param path [String] path to be appended to the net[:api_base] path. # @param query [Hash] optional key-value pairs with will be made into a # query string # @param opts [Hash] keys: # timestamp_chunks -- prints a timestamp before each chunk of streamed # data # timeout -- after approximately this many seconds, return. It will be # the first chunk *after* the given time # @return # def get_stream(path, query = {}, opts = {}) conn = flat_param_conn(path, query) verbosity(conn, :get, query) stream_connection(conn, query, opts) rescue Faraday::TimeoutError raise Wavefront::Exception::NetworkTimeout rescue StopIteration nil end def stream_connection(conn, query, opts) t_end = end_time(opts) conn.get do |req| req.params = query req.options.on_data = proc do |chunk, _size| raise StopIteration if t_end && Time.right_now >= t_end puts Time.now if opts[:timestamp_chunks] puts chunk end end end def end_time(opts) Time.right_now + opts[:timeout] if opts[:timeout]&.positive? end # Make a POST call to the Wavefront API and return the result as # a Ruby hash. # # @param path [String] path to be appended to the # #net[:api_base] path. # @param body [String,Object] optional body text to post. # Objects will be converted to JSON # @param ctype [String] the content type to use when posting # @return [Hash] API response # def post(path, body = nil, ctype = 'text/plain') body = body.to_json unless body.is_a?(String) make_call(mk_conn(path, 'Content-Type': ctype, Accept: 'application/json'), :post, nil, body) end # Make a PUT call to the Wavefront API and return the result as # a Ruby hash. # # @param path [String] path to be appended to the # #net[:api_base] path. # @param body [String] optional body text to post # @param ctype [String] the content type to use when putting # @return [Hash] API response # def put(path, body = nil, ctype = 'application/json') make_call(mk_conn(path, 'Content-Type': ctype, Accept: 'application/json'), :put, nil, body.to_json) end # Make a DELETE call to the Wavefront API and return the result # as a Ruby hash. # # @param path [String] path to be appended to the # #net[:api_base] path. # @return [Hash] API response # def delete(path) make_call(mk_conn(path), :delete) end # If we need to massage a raw response to fit what the # Wavefront::Response class expects (I'm looking at you, # 'User'), a class can provide a {#response_shim} method. # @param resp [Faraday::Response] # @return [String] body of response (JSON) # def respond(resp) body = if calling_class.respond_to?(:response_shim) calling_class.response_shim(resp.body, resp.status) else resp.body end return body if opts[:raw_response] Wavefront::Response.new(body, resp.status, opts) end # Try to describe the actual HTTP calls we make. There's a bit # of clumsy guesswork here # def verbosity(conn, method, *args) return unless noop || verbose log format('uri: %<method>s %<path>s', method: method.upcase, path: conn.url_prefix) return unless args.last && !args.last.empty? log method == :get ? "params: #{args.last}" : "body: #{args.last}" end private def paginator_class(method) require_relative File.join('..', 'paginator', method.to_s) Object.const_get(format('Wavefront::Paginator::%<method>s', method: method.to_s.capitalize)) end # A dispatcher for making API calls. We now have three methods # that do the real call, two of which live inside the requisite # Wavefront::Paginator class # @raise [Faraday::ConnectionFailed] if cannot connect to # endpoint # def make_call(conn, method, *args) paginator = paginator_class(method).new(self, conn, method, *args) case paginator.initial_limit when :all, 'all' paginator.make_recursive_call when :lazy, 'lazy' paginator.make_lazy_call else make_single_call(conn, method, *args) end end def make_single_call(conn, method, *args) verbosity(conn, method, *args) return if noop pp args if debug resp = conn.public_send(method, *args) if debug require 'pp' pp resp end respond(resp) end def setup_endpoint(creds) validate_credentials(creds) unless creds.key?(:agent) && creds[:agent] creds[:agent] = "wavefront-sdk #{WF_SDK_VERSION}" end @net = { headers: headers(creds), scheme: opts[:scheme] || 'https', endpoint: creds[:endpoint], api_base: calling_class.api_path } end def headers(creds) ret = { 'user-agent': creds[:agent] } ret[:Authorization] = "Bearer #{creds[:token]}" if creds[:token] ret end def validate_credentials(creds) if calling_class.respond_to?(:validate_credentials) calling_class.validate_credentials(creds) else _validate_credentials(creds) end end def _validate_credentials(creds) %w[endpoint token].each do |k| unless creds.key?(k.to_sym) raise(Wavefront::Exception::CredentialError, format('credentials must contain %<key>s', key: k)) end end end def flat_param_conn(path, query) mk_conn(path, {}, request: { params_encoder: Faraday::FlatParamsEncoder }, params: query) end end end
snltd/wavefront-sdk
lib/wavefront-sdk/core/api_caller.rb
Ruby
bsd-2-clause
8,830
#!/usr/bin/env python from rdflib import Graph, BNode, Literal, URIRef from rdflib.namespace import FOAF from flask import Flask import flask_rdf import random app = Flask(__name__) # set up a custom formatter to return turtle in text/plain to browsers custom_formatter = flask_rdf.FormatSelector() custom_formatter.wildcard_mimetype = 'text/plain' custom_formatter.add_format('text/plain', 'turtle') custom_decorator = flask_rdf.flask.Decorator(custom_formatter) @app.route('/') @app.route('/<path:path>') @custom_decorator def random_age(path=''): graph = Graph('IOMemory', BNode()) graph.add((URIRef(path), FOAF.age, Literal(random.randint(20, 50)))) return graph if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
hufman/flask_rdf
examples/browser_default.py
Python
bsd-2-clause
751
<?php require_once __DIR__ . '/vendor/autoload.php'; use Goutte\Client; $BASE_URL = 'https://vertretungsplan.leiningergymnasium.de'; $INDEX_URL = $BASE_URL . '/index'; $TOMORROW_URL = $BASE_URL . '/morgen'; date_default_timezone_set('Europe/Berlin'); $URL = $INDEX_URL; if (isset($_GET['type'])) { if ($_GET['type'] == 'tomorrow') { $URL = $TOMORROW_URL; } } $client = new Client(); $crawler = $client->request('POST', $URL, array( 'username' => '', 'password' => '' )); function loadMetadata($crawler) { $nameElement = $crawler->filter('#right')->first(); if ($nameElement == NULL) { return NULL; } $name = $nameElement->text(); $dateElement = $crawler->filter('#date')->first(); if ($dateElement == NULL) { return NULL; } $dateString = $dateElement->text(); $components = explode(' ', $dateString); $dateComponents = explode('.', end($components)); $date = $dateComponents[2] . '-' . $dateComponents[1] . '-' . $dateComponents[0]; $lastUpdateElement = $crawler->filter('#stand')->first(); if ($lastUpdateElement == NULL) { return NULL; } $lastUpdateString = $lastUpdateElement->text(); $components = explode(' ', $lastUpdateString); $dateComponents = explode('.', $components[2]); $timeComponents = explode(':', $components[3]); $day = intval($dateComponents[0]); $month = intval($dateComponents[1]); $year = intval($dateComponents[2]); $hour = intval($timeComponents[0]); $minute = intval($timeComponents[1]); $second = intval($timeComponents[2]); $lastUpdate = new DateTime(); $lastUpdate->setDate($year, $month, $day); $lastUpdate->setTime($hour, $minute, $second); return array( 'name' => $name, 'date' => $date, 'lastUpdate' => $lastUpdate->format(DateTime::ATOM) ); } function loadEntry($element) { $columns = $element->filter('td')->each(function($node) { return preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u', '', str_replace('---', '', $node->text())); }); if (count($columns) < 9) { return NULL; } return array( 'classes' => $columns[0], 'hours' => $columns[1], 'subject' => $columns[2], 'substituteTeacher' => $columns[3], 'substituteSubject' => $columns[4], 'room' => $columns[5], 'type' => $columns[6], 'text' => $columns[7], 'replaces' => $columns[8] ); } function loadEntries($crawler) { return $crawler->filter('#vertretungsplan tr')->each(function($node) { return loadEntry($node); }); } function loadPlan($crawler) { $data = loadMetadata($crawler); $data['entries'] = loadEntries($crawler); return $data; } header('Content-Type: application/json'); echo json_encode(loadPlan($crawler));
vertretungen/api
index.php
PHP
bsd-2-clause
2,700