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
<?php namespace OpenConext\Value\Saml\Metadata; use OpenConext\Value\Assert\Assertion; use OpenConext\Value\RegularExpression; use OpenConext\Value\Serializable; final class ShibbolethMetadataScope implements Serializable { /** * @var string */ private $scope; /** * @var bool */ private $isRegexp; /** * @param string $literal * @return ShibbolethMetadataScope */ public static function literal($literal) { Assertion::nonEmptyString($literal, 'literal'); return new self($literal); } /** * @param string $regexp * @return ShibbolethMetadataScope */ public static function regexp($regexp) { Assertion::nonEmptyString($regexp, 'regexp'); return new self($regexp, true); } /** * @param string $scope the scope as defined * @param bool $isRegexp whether or not the scope is a regular expression as identified by the regexp attribute */ public function __construct($scope, $isRegexp = false) { Assertion::nonEmptyString($scope, 'scope'); Assertion::boolean($isRegexp); if ($isRegexp) { Assertion::validRegularExpression('#' . $scope . '#i', 'scope'); } $this->scope = $scope; $this->isRegexp = $isRegexp; } /** * @param string $string * @return bool */ public function allows($string) { Assertion::string($string, 'Scope to check should be a string, "%s" given'); if (!$this->isRegexp) { return strcasecmp($this->scope, $string) === 0; } $regexp = new RegularExpression('#' . $this->scope . '#i'); return $regexp->matches($string); } /** * @param ShibbolethMetadataScope $other * @return bool */ public function equals(ShibbolethMetadataScope $other) { return (strcasecmp($this->scope, $other->scope) === 0 && $this->isRegexp === $other->isRegexp); } public static function deserialize($data) { Assertion::isArray($data); Assertion::keysExist($data, array('is_regexp', 'scope')); return new self($data['scope'], $data['is_regexp']); } public function serialize() { return array( 'scope' => $this->scope, 'is_regexp' => $this->isRegexp ); } public function __toString() { return sprintf( 'ShibbolethMetadataScope(scope=%s, regexp=%s)', $this->scope, $this->isRegexp ? 'true' : 'false' ); } }
OpenConext/SamlValueObject
src/OpenConext/Value/Saml/Metadata/ShibbolethMetadataScope.php
PHP
apache-2.0
2,613
/*jshint camelcase: false */ var common = require('../../lib/common'); var msRestRequest = require('../../lib/common/msRestRequest'); var chai = require('chai'); var should = chai.should(); var util = require('util'); exports.clean = function(provisioningParameters, done) { var resourceGroupName = provisioningParameters.resourceGroup; if (!resourceGroupName) { return done(); } var environmentName = process.env['ENVIRONMENT']; var subscriptionId = process.env['SUBSCRIPTION_ID']; var API_VERSIONS = common.API_VERSION[environmentName]; var environment = common.getEnvironment(environmentName); var resourceManagerEndpointUrl = environment.resourceManagerEndpointUrl; var resourceGroupUrl = util.format('%s/subscriptions/%s/resourcegroups/%s', resourceManagerEndpointUrl, subscriptionId, resourceGroupName); var headers = common.mergeCommonHeaders('Delete resource group for integration test', {}); msRestRequest.DELETE(resourceGroupUrl, headers, API_VERSIONS.RESOURCE_GROUP, function (err, res, body) { should.not.exist(err); res.statusCode.should.equal(202); done(); }); };
zhongyi-zhang/meta-azure-service-broker
test/integration/cleaner.js
JavaScript
apache-2.0
1,244
/* * Copyright 2014 Christophe Pollet * * 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.cpollet.sportracker.dozer; import net.cpollet.sportracker.service.api.HashingService; import org.dozer.MappingException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import static org.fest.assertions.Assertions.assertThat; /** * @author Christophe Pollet */ @RunWith(MockitoJUnitRunner.class) public class TestHashingDozerConverter { private HashingDozerConverter hashingDozerConverter; @Mock private HashingService hashingService; @Rule public ExpectedException expectedException = ExpectedException.none(); @Before public void setUp() { Mockito.when(hashingService.hash("plain")).thenReturn("hash"); hashingDozerConverter = new HashingDozerConverter(); hashingDozerConverter.setHashingService(hashingService); } @Test public void convertReturnsNullWhenNullPassed() { // GIVEN String plain = null; // WHEN String hash = (String) hashingDozerConverter.convert(null, plain, null, null); // THEN assertThat(hash).isNull(); } @Test public void convertThrowsExceptionWhenNoStringPassed() { // GIVEN Object plain = new Object(); // THEN expectedException.expect(MappingException.class); expectedException.expectMessage("Converter HashingDozerConverter used incorrectly. Arguments passed were " // + "null and " + plain.toString()); // WHEN hashingDozerConverter.convert(null, plain, null, null); } @Test public void convertHashesTheInputStringAndReturnsTheHash() { // GIVEN String plain = "plain"; // WHEN String hash = (String) hashingDozerConverter.convert(null, plain, null, null); // THEN assertThat(hash).isEqualTo("hash"); } }
cpollet/sportracker
webapp/src/test/java/net/cpollet/sportracker/dozer/TestHashingDozerConverter.java
Java
apache-2.0
2,427
/* * Copyright 2014 FIZ Karlsruhe * * 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 ROLE_ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.escidocng; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; /** * @author mih */ public class WebInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(EscidocngServerConfiguration.class, EscidocngServerSecurityConfiguration.class, OAuth2ServerConfiguration.class); } }
escidoc-ng/escidoc-ng
escidocng-backend/src/main/java/de/escidocng/WebInitializer.java
Java
apache-2.0
1,132
using System; namespace DotKafka.Prototype.Common.Errors { public class UnknownServerException : ApiException { public UnknownServerException() { } public UnknownServerException(string message) : base(message) { } public UnknownServerException(string message, Exception inner) : base(message, inner) { } } }
rudygt/dot-kafka
DotKafka.Prototype/Common/Errors/UnknownServerException.cs
C#
apache-2.0
346
#!/usr/bin/python import sys # try to import from the default place Munki installs it try: from munkilib import FoundationPlist, munkicommon except: sys.path.append('/usr/local/munki') from munkilib import FoundationPlist, munkicommon import os from datetime import datetime FILE_LOCATION = "/Users/Shared/.msc-dnd.plist" # Does the file exist? if not os.path.isfile(FILE_LOCATION): # File isn't here, set the Munki pref to False munkicommon.set_pref('SuppressUserNotification', False) sys.exit(0) # If it does, get the current date? else: plist = FoundationPlist.readPlist(FILE_LOCATION) if 'DNDEndDate' not in plist: # The key we need isn't in there, remove the file, set pref and exit os.remove(FILE_LOCATION) munkicommon.set_pref('SuppressUserNotification', False) sys.exit(0) else: # Is the current date greater than the DND date? saved_time = datetime.strptime(str(plist['DNDEndDate']), "%Y-%m-%d %H:%M:%S +0000") current_time = datetime.now() if saved_time < current_time: # print "Current time is greater" # If yes, remove the file and set the Munki pref for suppress notifications to False os.remove(FILE_LOCATION) munkicommon.set_pref('SuppressUserNotification', False) sys.exit(0) else: # print "Saved Time is greater" munkicommon.set_pref('SuppressUserNotification', True) sys.exit(0) # If no, make sure suppress notifications is True
grahamgilbert/munki-dnd
munki-dnd.py
Python
apache-2.0
1,572
package com.nitorcreations.willow.metrics; import javax.inject.Named; @Named("/types") public class MessageTypesMetric extends TagListMetric { public MessageTypesMetric() { super("category"); } }
NitorCreations/willow
willow-servers/src/main/java/com/nitorcreations/willow/metrics/MessageTypesMetric.java
Java
apache-2.0
206
package model // Pool . type Pool struct { Id int64 `json:"id"` CoinId int64 `json:"coin_id"` Title string `json:"title"` Description string `json:"description"` StartTime int64 `json:"start_time"` EndTime int64 `json:"end_time"` Status int64 `json:"status"` IsBottom int64 `json:"is_bottom"` } // Coin . type Coin struct { Id int64 `json:"id"` Title string `json:"title"` GiftType int64 `json:"gift_type"` ChangeNum int64 `json:"change_num"` StartTime int64 `json:"start_time"` EndTime int64 `json:"end_time"` Status int64 `json:"status"` } // UserInfo . type UserInfo struct { Uid int64 `json:"uid"` NormalScore int64 `json:"normal_score"` ColorfulScore int64 `json:"colorful_score"` } // GiftMsg . type GiftMsg struct { // by notify MsgContent string `form:"msg_content"` } // CoinConfig . type CoinConfig struct { CoinId int64 `json:"coin_id"` Type int64 `json:"type"` AreaV2ParentId int64 `json:"area_v2_parent_id"` AreaV2Id int64 `json:"area_v2_id"` GiftId int64 `json:"gift_id"` IsAll int64 `json:"is_all"` } // PoolPrize . type PoolPrize struct { Id int64 `json:"id"` PoolId int64 `json:"pool_id"` Type int64 `json:"type"` Num int64 `json:"num"` ObjectId int64 `json:"object_id"` Expire int64 `json:"expire"` WebUrl string `json:"web_url"` MobileUrl string `json:"mobile_url"` Description string `json:"description"` JumpUrl string `json:"jump_url"` ProType int64 `json:"pro_type"` Chance int64 `json:"chance"` LoopNum int64 `json:"loop_num"` LimitNum int64 `json:"limit_num"` Weight int64 `json:"weight"` } // AddCapsule AddCapsule type AddCapsule struct { Uid int64 `json:"uid"` Type string `json:"type"` CoinId int64 `json:"coin_id"` Num int64 `json:"num"` Source string `json:"source"` MsgId string `json:"msg_id"` } // ExtraData . type ExtraData struct { Id int64 `json:"id"` Uid int64 `json:"uid"` Type string `json:"type"` ItemValue int64 `json:"item_value"` ItemExtra string `json:"item_extra"` }
LQJJ/demo
126-go-common-master/app/job/live/xlottery/internal/model/model.go
GO
apache-2.0
2,202
/* * Copyright to 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.rioproject.resolver.aether.util; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.sonatype.aether.transfer.AbstractTransferListener; import org.sonatype.aether.transfer.TransferEvent; import org.sonatype.aether.transfer.TransferResource; /** * A simplistic transfer listener that logs uploads/downloads to the console. */ public class ConsoleTransferListener extends AbstractTransferListener { private PrintStream out; private Map<TransferResource, Long> downloads = new ConcurrentHashMap<TransferResource, Long>(); private int lastLength; public ConsoleTransferListener() { this(null); } public ConsoleTransferListener(PrintStream out) { this.out = (out != null) ? out : System.out; } @Override public void transferProgressed(TransferEvent event) { TransferResource resource = event.getResource(); downloads.put(resource, event.getTransferredBytes()); StringBuilder buffer = new StringBuilder(64); for (Map.Entry<TransferResource, Long> entry : downloads.entrySet()) { long total = entry.getKey().getContentLength(); long complete = entry.getValue(); buffer.append(getStatus(complete, total)).append(" "); } int pad = lastLength - buffer.length(); lastLength = buffer.length(); pad(buffer, pad); buffer.append('\r'); out.print(buffer); } private String getStatus(long complete, long total) { if (total >= 1024) { return toKB(complete) + "/" + toKB(total) + " KB "; } else if (total >= 0) { return complete + "/" + total + " B "; } else if (complete >= 1024) { return toKB(complete) + " KB "; } else { return complete + " B "; } } private void pad(StringBuilder buffer, final int spaces) { int spaceCountDown = spaces; String block = " "; while (spaceCountDown > 0) { int n = Math.min(spaces, block.length()); buffer.append(block, 0, n); spaceCountDown -= n; } } @Override public void transferSucceeded(TransferEvent event) { transferCompleted(event); TransferResource resource = event.getResource(); long contentLength = event.getTransferredBytes(); if (contentLength >= 0) { String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded"); String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B"; String throughput = ""; long duration = System.currentTimeMillis() - resource.getTransferStartTime(); if (duration > 0) { DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH)); double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0); throughput = " at " + format.format(kbPerSec) + " KB/sec"; } out.println(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len + throughput + ")"); } } @Override public void transferFailed(TransferEvent event) { transferCompleted(event); //out.println("[WARNING] "+event.getException().getLocalizedMessage()); } private void transferCompleted(TransferEvent event) { downloads.remove(event.getResource()); if (event.getDataLength() > 0) { StringBuilder buffer = new StringBuilder(64); pad(buffer, lastLength); buffer.append('\r'); out.print(buffer); } } public void transferCorrupted(TransferEvent event) { TransferResource resource = event.getResource(); out.println("[WARNING] " + event.getException().getMessage() + " for " + resource.getRepositoryUrl() + resource.getResourceName()); } protected long toKB(long bytes) { return (bytes + 1023) / 1024; } }
khartig/assimilator
rio-resolver/resolver-aether/src/main/java/org/rioproject/resolver/aether/util/ConsoleTransferListener.java
Java
apache-2.0
4,898
var Canvas = require('canvas'); var Image = Canvas.Image; // Constants var canvasWidth = 350; var canvasHeight = 150; var cellSize = 30; var colorMap = { 0: 'rgba(0, 0, 0, 0)', 1: '#F7F6EA', 2: '#E6E6E1', 3: '#EBC000' }; module.exports = generate; function generate(title, accuracy) { var canvas = new Canvas(canvasWidth, canvasHeight); var ctx = canvas.getContext('2d'); drawTitle(ctx, title); drawAccuracy(ctx, accuracy); drawAccuracySub(ctx); drawHeatMap(ctx); return canvas.toBuffer(); }; function drawHeatMap(ctx) { var grid = [ [ 1, 3, 3, 2 ], [ 0, 1, 2, 1 ], [ 0, 2, 3, 1 ] ]; var y = 60; grid.forEach(function(r) { var x = canvasWidth - cellSize; r.reverse().forEach(function(c, j) { drawCell(ctx, x - (j * 2), y, colorMap[c]); x -= cellSize; }); y += cellSize; }); } function drawCell(ctx, x, y, fillColor) { ctx.fillStyle = fillColor; ctx.fillRect(x, y, cellSize, cellSize); } function drawTitle(ctx, title) { //var title = 'Profit and Discount drives sales with a'; ctx.font = '14px Kozuka Gothic Pro'; ctx.fillText(title, 20, 30); } function drawAccuracy(ctx, accuracy) { accuracy += '%'; ctx.font = '60px Kozuka Gothic Pro'; ctx.fillText(accuracy, 20, 100); } function drawAccuracySub(ctx) { var sub = 'driver strength'; ctx.font = '14px Kozuka Gothic Pro'; ctx.fillText(sub, 20, 125); }
gw1018/imageservice
images/heatmap.js
JavaScript
apache-2.0
1,415
package com.cyou.cpush.apns.notification; import java.util.concurrent.atomic.AtomicInteger; public class DefaultNotification implements Notification { private static AtomicInteger IDENTIFIER_GENERATOR = new AtomicInteger(Integer.MAX_VALUE-1); private int identifier; private Device device; private Payload payload; public DefaultNotification(Device device, Payload payload) { this(IDENTIFIER_GENERATOR.incrementAndGet(), device, payload); } public DefaultNotification(int identifier, Device device, Payload payload) { this.identifier = identifier; this.device = device; this.payload = payload; } /* * (non-Javadoc) * * @see com.cyou.cpush.apns.Notification#getDevice() */ @Override public Device getDevice() { return device; } /* * (non-Javadoc) * * @see com.cyou.cpush.apns.Notification#getPayload() */ @Override public Payload getPayload() { return payload; } public void setDevice(Device device) { this.device = device; } public void setPayload(Payload payload) { this.payload = payload; } public void setIdentifier(int identifier) { this.identifier = identifier; } @Override public int getIdentifier() { return identifier; } }
beforeeight/cpush-apns
src/main/java/com/cyou/cpush/apns/notification/DefaultNotification.java
Java
apache-2.0
1,207
package com.craftmend.openaudiomc.spigot.modules.proxy.service; import com.craftmend.openaudiomc.generic.networking.DefaultNetworkingService; import com.craftmend.openaudiomc.generic.networking.abstracts.AbstractPacket; import com.craftmend.openaudiomc.generic.networking.client.objects.player.ClientConnection; import com.craftmend.openaudiomc.generic.networking.interfaces.Authenticatable; import com.craftmend.openaudiomc.generic.networking.interfaces.INetworkingEvents; import com.craftmend.openaudiomc.generic.networking.interfaces.NetworkingService; import com.craftmend.openaudiomc.generic.node.packets.ForwardSocketPacket; import com.craftmend.openaudiomc.generic.player.SpigotPlayerAdapter; import com.craftmend.openaudiomc.spigot.OpenAudioMcSpigot; import com.craftmend.openaudiomc.spigot.modules.proxy.listeners.BungeePacketListener; import com.craftmend.openaudiomc.api.velocitypluginmessageframework.PacketPlayer; import com.craftmend.openaudiomc.api.velocitypluginmessageframework.implementations.BukkitPacketManager; import lombok.Getter; import net.md_5.bungee.api.connection.ProxiedPlayer; import org.bukkit.entity.Player; import java.util.*; public class ProxyNetworkingService extends NetworkingService { @Getter private final Set<INetworkingEvents> eventHandlers = new HashSet<>(); private final DefaultNetworkingService realService = new DefaultNetworkingService(); private final BukkitPacketManager packetManager; public ProxyNetworkingService() { packetManager = new BukkitPacketManager(OpenAudioMcSpigot.getInstance(), "openaudiomc:node"); packetManager.registerListener(new BungeePacketListener()); } @Override public void connectIfDown() { // unused in fake system } @Override public void send(Authenticatable client, AbstractPacket packet) { // handle packet if it should be passed to bungee // forward every packet starting with PacketClient if (!(client instanceof ClientConnection)) throw new UnsupportedOperationException("The bungee adapter for the networking service only supports client connections"); if (packet.getClass().getSimpleName().startsWith("PacketClient")) { packet.setClient(client.getOwnerUUID()); Player player = ((SpigotPlayerAdapter) ((ClientConnection) client).getPlayer()).getPlayer(); packetManager.sendPacket(new PacketPlayer(player), new ForwardSocketPacket(packet)); } } @Override public void triggerPacket(AbstractPacket abstractPacket) { // unused in fake system } @Override public ClientConnection getClient(UUID uuid) { return realService.getClient(uuid); } @Override public Collection<ClientConnection> getClients() { return realService.getClients(); } @Override public void remove(UUID player) { realService.remove(player); } @Override public ClientConnection register(Player player) { return realService.register(player); } @Override public ClientConnection register(ProxiedPlayer player) { return realService.register(player); } public ClientConnection register(com.velocitypowered.api.proxy.Player player) { return realService.register(player); } @Override public void stop() { // unused in fake system } @Override public Set<INetworkingEvents> getEvents() { return eventHandlers; } @Override public void addEventHandler(INetworkingEvents events) { eventHandlers.add(events); } }
ApocalypsjeNL/OpenAudioMc
plugin/src/main/java/com/craftmend/openaudiomc/spigot/modules/proxy/service/ProxyNetworkingService.java
Java
apache-2.0
3,602
package fr.excilys.computerdatabase.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import fr.excilys.computerdatabase.model.Description; import fr.excilys.computerdatabase.model.Role; import fr.excilys.computerdatabase.model.User; import fr.excilys.computerdatabase.persistence.UserDao; import fr.excilys.computerdatabase.validator.DescriptionDTO; import fr.excilys.computerdatabase.validator.UserDTO; @Service public class UserServices implements UserDetailsService { @Autowired UserDao userDao; @Autowired CompanyServices companyServices; public User findUserByUsername(String username) { return userDao.findUserByUsername(username); } public List<Description> findAllUsers() { return userDao.findAllDescriptions(); } public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException { User user = userDao.findUserByUsername(username); if (user == null) { throw new UsernameNotFoundException(" Username not found ! "); } List<Role> roles = userDao.findRolesForUser(username); List<GrantedAuthority> grantList = new ArrayList<>(); if (roles != null) { for (Role role : roles) { GrantedAuthority authority = new SimpleGrantedAuthority(role.getRole()); grantList.add(authority); } } UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(), grantList); return userDetails; } public boolean createUser(UserDTO user) { User userToInsert = new User(user.getUsername(), user.getPassword()); userDao.createUser(userToInsert); return true; } public boolean userNotExist(String username) { return userDao.usernameNotExist(username); } public boolean modifyDescription(DescriptionDTO descriptionDTO) { Description description = new Description.Builder() .id(descriptionDTO.getId()) .email(descriptionDTO.getEmail()) .firstname(descriptionDTO.getFirstname()) .lastname(descriptionDTO.getLastname()) .information(descriptionDTO.getInformation()) .user(userDao.findUserById(descriptionDTO.getUser_id())) .company(descriptionDTO.getCompany()!= null && !descriptionDTO.getCompany().isEmpty() ? companyServices.getOrCreateCompany(descriptionDTO.getCompany()) : null) .build(); userDao.modifyDescription(description); return true; } public DescriptionDTO getDescription(String username) { Description description = userDao.findDescription(username); if (description == null) { return null; } DescriptionDTO dDto = new DescriptionDTO.Builder() .id(description.getId()) .email(description.getEmail()) .firstname(description.getFirstname()) .lastname(description.getLastname()) .information(description.getInformation()) .user_id(description.getUser().getId()) .company_id(description.getCompany() != null ? description.getCompany().getId() : -1) .company(description.getCompany()!= null ? description.getCompany().getName() : "") .build(); return dDto; } }
krmmlsh/Java_Training
service/src/main/java/fr/excilys/computerdatabase/service/UserServices.java
Java
apache-2.0
3,492
package com.wecan.xhin.studio; import android.app.Application; import android.content.Context; import com.avos.avoscloud.AVOSCloud; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Response; import com.wecan.xhin.baselib.net.LoggingInterceptor; import com.wecan.xhin.studio.api.Api; import java.io.IOException; import java.util.HashMap; import retrofit.GsonConverterFactory; import retrofit.Retrofit; import retrofit.RxJavaCallAdapterFactory; public class App extends Application { public static final String VALUE_AVOS_APPID = "AkVsXJ4RoWq1juPauOHe1OW5"; public static final String VALUE_AVOS_APPKEY = "gFICBkjJSxlI5fHnvNyB7Lfj"; public static final String KEY_PREFERENCE_USER = "user"; public static final String KEY_PREFERENCE_PHONE = "phone"; public static final String KEY_BUILD_VERSION = "build_version"; public static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; private final HashMap<Class, Object> apis = new HashMap<>(); private Retrofit retrofit; //返回当前单例的静态方法,判断是否是当前的App调用 public static App from(Context context) { Context application = context.getApplicationContext(); if (application instanceof App) return (App) application; throw new IllegalArgumentException("Context must be from Studio"); } @Override public void onCreate() { super.onCreate(); AVOSCloud.initialize(this, VALUE_AVOS_APPID, VALUE_AVOS_APPKEY); OkHttpClient okHttpClient = new OkHttpClient(); //OKHttp的使用 okHttpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .header(KEY_BUILD_VERSION, BuildConfig.VERSION_NAME) .build()); } }); if (BuildConfig.DEBUG) { okHttpClient.networkInterceptors().add(new LoggingInterceptor()); } //初始化Gson Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setDateFormat(DATE_FORMAT_PATTERN) .create(); //初始化Retrofit retrofit = new Retrofit.Builder() .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(Api.BASE_URL) .build(); } //返回Retrofit的API public <T> T createApi(Class<T> service) { if (!apis.containsKey(service)) { T instance = retrofit.create(service); apis.put(service, instance); } //noinspection unchecked return (T) apis.get(service); } public OkHttpClient getHttpClient() { return retrofit.client(); } }
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/App.java
Java
apache-2.0
3,181
package com.cantinho.spoonacularexample.retrofit_models; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by samirtf on 14/02/17. */ public class Recipe { @SerializedName("id") private Integer id; @SerializedName("image") private String image; @SerializedName("usedIngredientCount") private Integer usedIngredientCount; @SerializedName("missedIngredientCount") private Integer missedIngredientCount; @SerializedName("likes") private Integer likes; @Override public String toString() { return "Recipe{" + "id=" + id + ", image='" + image + '\'' + ", usedIngredientCount=" + usedIngredientCount + ", missedIngredientCount=" + missedIngredientCount + ", likes=" + likes + '}'; } }
Cantinho/spoonaculator-android-example
SpoonacularExample/app/src/main/java/com/cantinho/spoonacularexample/retrofit_models/Recipe.java
Java
apache-2.0
923
#pragma once #include <map> #include "..\..\Defines.hpp" namespace te { class DynamicLibrary; class TE_EXPORT DynamicLibraryManager { protected: std::map<string, DynamicLibrary*> m_loadedLibraries; public: DynamicLibraryManager(); ~DynamicLibraryManager(); /* Loads the library with the specified name. The file extension can be omitted. Returns a pointer to the loaded library. */ DynamicLibrary* load(const string& name); /* Unloads the specified DynLib. */ void unload(DynamicLibrary* dynLib); }; }
unpause/TeazelEngine
TeazelEngine/TeazelEngine/core/dynlib/DynamicLibraryManager.hpp
C++
apache-2.0
543
/* * The University of Wales, Cardiff Triana Project Software License (Based * on the Apache Software License Version 1.1) * * Copyright (c) 2007 University of Wales, Cardiff. All rights reserved. * * Redistribution and use of the software 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. * * 3. The end-user documentation included with the redistribution, if any, * must include the following acknowledgment: "This product includes * software developed by the University of Wales, Cardiff for the Triana * Project (http://www.trianacode.org)." Alternately, this * acknowledgment may appear in the software itself, if and wherever * such third-party acknowledgments normally appear. * * 4. The names "Triana" and "University of Wales, Cardiff" must not be * used to endorse or promote products derived from this software * without prior written permission. For written permission, please * contact triana@trianacode.org. * * 5. Products derived from this software may not be called "Triana," nor * may Triana appear in their name, without prior written permission of * the University of Wales, Cardiff. * * 6. This software may not be sold, used or incorporated into any product * for sale to third parties. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 UNIVERSITY OF WALES, CARDIFF OR ITS 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. * * ------------------------------------------------------------------------ * * This software consists of voluntary contributions made by many * individuals on behalf of the Triana Project. For more information on the * Triana Project, please see. http://www.trianacode.org. * * This license is based on the BSD license as adopted by the Apache * Foundation and is governed by the laws of England and Wales. * */ package org.trianacode.gui.main.imp; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.AbstractButton; import org.trianacode.gui.main.TrianaLayoutConstants; /** * A class that displays a little plus minus icon * * @author Ian Wang * @version $Revision: 4048 $ */ public class PlusMinusIcon extends AbstractButton implements MouseListener { /** * Variable representing the PlusMinusIcon default preferred size */ private Dimension DEFAULT_SIZE = TrianaLayoutConstants.DEFAULT_PLUS_MINUS_SIZE; private boolean input = true; private boolean plus = true; public PlusMinusIcon(boolean plus) { this.plus = plus; addMouseListener(this); setPreferredSize(DEFAULT_SIZE); } public PlusMinusIcon(boolean plus, boolean input) { this.input = input; this.plus = plus; addMouseListener(this); setPreferredSize(DEFAULT_SIZE); } protected void paintComponent(Graphics graphs) { super.paintComponent(graphs); Dimension size = getSize(); Color col = graphs.getColor(); int left = 0; int top = 0; int width = size.width; int height = size.height; if (size.width % 2 == 0) { width = size.width - 1; if (!input) { left = 1; } } if (size.height % 2 == 0) { height = size.height - 1; if (plus) { top = 1; } } graphs.setColor(getForeground()); graphs.drawLine(left, top + (height / 2), left + width, top + (height / 2)); if (plus) { graphs.drawLine(left + (width / 2), top, left + (width / 2), top + height); } graphs.setColor(col); } /** * Invoked when the mouse button has been clicked (pressed and released) on a component. */ public void mouseClicked(MouseEvent event) { String command; if (plus) { command = "+"; } else { command = "-"; } fireActionPerformed(new ActionEvent(this, event.getID(), command)); } /** * Invoked when the mouse enters a component. */ public void mouseEntered(MouseEvent e) { } /** * Invoked when the mouse exits a component. */ public void mouseExited(MouseEvent e) { } /** * Invoked when a mouse button has been pressed on a component. */ public void mousePressed(MouseEvent e) { } /** * Invoked when a mouse button has been released on a component. */ public void mouseReleased(MouseEvent e) { } }
CSCSI/Triana
triana-gui/src/main/java/org/trianacode/gui/main/imp/PlusMinusIcon.java
Java
apache-2.0
5,724
package ru.job4j.profession; /** * This class describes student with no parameters and operations. * * @author Kucykh Vasily (mailto:basil135@mail.ru) * @version $Id$ * @since 12.04.2017 */ public class Student extends Human { /** * constructor of Student class. * * @param name is name of a student */ public Student(String name) { super(name); } }
Basil135/vkucyh
chapter_002/src/main/java/ru/job4j/profession/Student.java
Java
apache-2.0
399
package io.datakernel.di.impl; import java.util.concurrent.atomic.AtomicReferenceArray; @SuppressWarnings("rawtypes") public abstract class AbstractUnsyncCompiledBinding<R> implements CompiledBinding<R> { protected final int scope; protected final int index; protected AbstractUnsyncCompiledBinding(int scope, int index) { this.scope = scope; this.index = index; } @SuppressWarnings("unchecked") @Override public final R getInstance(AtomicReferenceArray[] scopedInstances, int synchronizedScope) { AtomicReferenceArray array = scopedInstances[scope]; R instance = (R) array.get(index); if (instance != null) return instance; instance = doCreateInstance(scopedInstances, synchronizedScope); array.lazySet(index, instance); return instance; } protected abstract R doCreateInstance(AtomicReferenceArray[] scopedInstances, int synchronizedScope); }
softindex/datakernel
core-di/src/main/java/io/datakernel/di/impl/AbstractUnsyncCompiledBinding.java
Java
apache-2.0
875
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.api.java.io.jdbc; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.flink.api.java.tuple.Tuple5; import org.apache.flink.types.Row; import org.junit.After; import org.junit.Assert; import org.junit.Test; public class JDBCOutputFormatTest extends JDBCTestBase { private JDBCOutputFormat jdbcOutputFormat; private Tuple5<Integer, String, String, Double, String> tuple5 = new Tuple5<>(); @After public void tearDown() throws IOException { if (jdbcOutputFormat != null) { jdbcOutputFormat.close(); } jdbcOutputFormat = null; } @Test(expected = IllegalArgumentException.class) public void testInvalidDriver() throws IOException { jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat() .setDrivername("org.apache.derby.jdbc.idontexist") .setDBUrl(DB_URL) .setQuery(String.format(INSERT_TEMPLATE, INPUT_TABLE)) .finish(); jdbcOutputFormat.open(0, 1); } @Test(expected = IllegalArgumentException.class) public void testInvalidURL() throws IOException { jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat() .setDrivername(DRIVER_CLASS) .setDBUrl("jdbc:der:iamanerror:mory:ebookshop") .setQuery(String.format(INSERT_TEMPLATE, INPUT_TABLE)) .finish(); jdbcOutputFormat.open(0, 1); } @Test(expected = IllegalArgumentException.class) public void testInvalidQuery() throws IOException { jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat() .setDrivername(DRIVER_CLASS) .setDBUrl(DB_URL) .setQuery("iamnotsql") .finish(); jdbcOutputFormat.open(0, 1); } @Test(expected = IllegalArgumentException.class) public void testIncompleteConfiguration() throws IOException { jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat() .setDrivername(DRIVER_CLASS) .setQuery(String.format(INSERT_TEMPLATE, INPUT_TABLE)) .finish(); } @Test(expected = IllegalArgumentException.class) public void testIncompatibleTypes() throws IOException { jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat() .setDrivername(DRIVER_CLASS) .setDBUrl(DB_URL) .setQuery(String.format(INSERT_TEMPLATE, INPUT_TABLE)) .finish(); jdbcOutputFormat.open(0, 1); tuple5.setField(4, 0); tuple5.setField("hello", 1); tuple5.setField("world", 2); tuple5.setField(0.99, 3); tuple5.setField("imthewrongtype", 4); Row row = new Row(tuple5.getArity()); for (int i = 0; i < tuple5.getArity(); i++) { row.setField(i, tuple5.getField(i)); } jdbcOutputFormat.writeRecord(row); jdbcOutputFormat.close(); } @Test public void testJDBCOutputFormat() throws IOException, InstantiationException, IllegalAccessException { jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat() .setDrivername(DRIVER_CLASS) .setDBUrl(DB_URL) .setQuery(String.format(INSERT_TEMPLATE, OUTPUT_TABLE)) .finish(); jdbcOutputFormat.open(0, 1); for (int i = 0; i < testData.length; i++) { Row row = new Row(testData[i].length); for (int j = 0; j < testData[i].length; j++) { row.setField(j, testData[i][j]); } jdbcOutputFormat.writeRecord(row); } jdbcOutputFormat.close(); try ( Connection dbConn = DriverManager.getConnection(JDBCTestBase.DB_URL); PreparedStatement statement = dbConn.prepareStatement(JDBCTestBase.SELECT_ALL_NEWBOOKS); ResultSet resultSet = statement.executeQuery() ) { int recordCount = 0; while (resultSet.next()) { Row row = new Row(tuple5.getArity()); for (int i = 0; i < tuple5.getArity(); i++) { row.setField(i, resultSet.getObject(i + 1)); } if (row.getField(0) != null) { Assert.assertEquals("Field 0 should be int", Integer.class, row.getField(0).getClass()); } if (row.getField(1) != null) { Assert.assertEquals("Field 1 should be String", String.class, row.getField(1).getClass()); } if (row.getField(2) != null) { Assert.assertEquals("Field 2 should be String", String.class, row.getField(2).getClass()); } if (row.getField(3) != null) { Assert.assertEquals("Field 3 should be float", Double.class, row.getField(3).getClass()); } if (row.getField(4) != null) { Assert.assertEquals("Field 4 should be int", Integer.class, row.getField(4).getClass()); } for (int x = 0; x < tuple5.getArity(); x++) { if (JDBCTestBase.testData[recordCount][x] != null) { Assert.assertEquals(JDBCTestBase.testData[recordCount][x], row.getField(x)); } } recordCount++; } Assert.assertEquals(JDBCTestBase.testData.length, recordCount); } catch (SQLException e) { Assert.fail("JDBC OutputFormat test failed. " + e.getMessage()); } } }
DieBauer/flink
flink-connectors/flink-jdbc/src/test/java/org/apache/flink/api/java/io/jdbc/JDBCOutputFormatTest.java
Java
apache-2.0
5,607
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by 俊帆 on 2016/10/13. */ public class Test { public void init() throws InterruptedException { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); } public static void main(String[] args) throws InterruptedException { new Test().init(); } }
tctxl/gulosity
test/src/main/java/Test.java
Java
apache-2.0
474
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants; import java.util.List; public class AndroidSenseManagerService implements DeviceManagementService { private DeviceManager deviceManager; @Override public String getType() { return AndroidSenseConstants.DEVICE_TYPE; } @Override public String getProviderTenantDomain() { return AndroidSenseConstants.DEVICE_TYPE_PROVIDER_DOMAIN; } @Override public boolean isSharedWithAllTenants() { return true; } @Override public void init() throws DeviceManagementException { this.deviceManager=new AndroidSenseManager(); } @Override public DeviceManager getDeviceManager() { return deviceManager; } @Override public ApplicationManager getApplicationManager() { return null; } @Override public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> list) throws DeviceManagementException { } @Override public Application[] getApplications(String domain, int pageNumber, int size) throws ApplicationManagementException { return new Application[0]; } @Override public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, String status) throws ApplicationManagementException { } @Override public String getApplicationStatus(DeviceIdentifier deviceId, Application application) throws ApplicationManagementException { return null; } @Override public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> list) throws ApplicationManagementException { } @Override public void installApplicationForUsers(Operation operation, List<String> list) throws ApplicationManagementException { } @Override public void installApplicationForUserRoles(Operation operation, List<String> list) throws ApplicationManagementException { } }
NuwanSameera/carbon-device-mgt-plugins
components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.plugin/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/plugin/impl/AndroidSenseManagerService.java
Java
apache-2.0
3,097
package com.bestxty.designpattern.decorator; /** * @author jiangtaiyang * Created by jiangtaiyang on 2017/6/29. */ public class ConcreteComponent implements Component { @Override public void operation() { System.out.println("real operation."); } }
swjjxyxty/Study
studyjavase/studyjavasedesignpattern/src/main/java/com/bestxty/designpattern/decorator/ConcreteComponent.java
Java
apache-2.0
281
/* * Copyright 2015 - 2021 TU Dortmund * * 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 de.learnlib.alex.data.entities.actions.misc; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import com.fasterxml.jackson.databind.ObjectMapper; import de.learnlib.alex.data.entities.ExecuteResult; import de.learnlib.alex.data.entities.Project; import de.learnlib.alex.data.entities.Symbol; import de.learnlib.alex.data.entities.SymbolAction; import de.learnlib.alex.learning.services.connectors.ConnectorManager; import de.learnlib.alex.learning.services.connectors.VariableStoreConnector; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class AssertVariableActionTest { private static final String TEST_VALUE = "foobar"; private static final String TEST_NAME = "variable"; private AssertVariableAction assertAction; @BeforeEach public void setUp() { final Symbol symbol = new Symbol(); symbol.setProject(new Project(1L)); assertAction = new AssertVariableAction(); assertAction.setName(TEST_NAME); assertAction.setValue(TEST_VALUE); assertAction.setRegexp(false); assertAction.setSymbol(symbol); } @Test public void testJSON() throws IOException { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(assertAction); AssertVariableAction assertAction2 = (AssertVariableAction) mapper.readValue(json, SymbolAction.class); assertEquals(assertAction.getName(), assertAction2.getName()); assertEquals(assertAction.getValue(), assertAction2.getValue()); assertEquals(assertAction.isRegexp(), assertAction2.isRegexp()); } @Test public void testJSONFile() throws IOException, URISyntaxException { ObjectMapper mapper = new ObjectMapper(); File file = new File(getClass().getResource("/actions/StoreSymbolActions/AssertVariableTestData.json").toURI()); SymbolAction obj = mapper.readValue(file, SymbolAction.class); assertTrue(obj instanceof AssertVariableAction); AssertVariableAction objAsAction = (AssertVariableAction) obj; assertEquals(TEST_NAME, objAsAction.getName()); assertEquals(TEST_VALUE, objAsAction.getValue()); assertTrue(objAsAction.isRegexp()); } @Test public void ensureThatAssertingWithoutRegexWorks() { VariableStoreConnector variables = mock(VariableStoreConnector.class); ConnectorManager connector = mock(ConnectorManager.class); given(connector.getConnector(VariableStoreConnector.class)).willReturn(variables); // OK given(variables.get(TEST_NAME)).willReturn(TEST_VALUE); ExecuteResult result = assertAction.executeAction(connector); assertTrue(result.isSuccess()); // not OK given(variables.get(TEST_NAME)).willReturn(TEST_VALUE + " - invalid"); result = assertAction.executeAction(connector); assertFalse(result.isSuccess()); } @Test public void ensureThatAssertingWithRegexWorks() { VariableStoreConnector variables = mock(VariableStoreConnector.class); ConnectorManager connector = mock(ConnectorManager.class); given(connector.getConnector(VariableStoreConnector.class)).willReturn(variables); assertAction.setRegexp(true); assertAction.setValue("f[o]+bar"); // OK given(variables.get(TEST_NAME)).willReturn(TEST_VALUE); ExecuteResult result = assertAction.executeAction(connector); assertTrue(result.isSuccess()); // not OK given(variables.get(TEST_NAME)).willReturn(TEST_VALUE + " - invalid"); result = assertAction.executeAction(connector); assertFalse(result.isSuccess()); } }
LearnLib/alex
backend/src/test/java/de/learnlib/alex/data/entities/actions/misc/AssertVariableActionTest.java
Java
apache-2.0
4,771
package com.nollec.datebasetest; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
songyang2088/A-week-to-develop-android-app-plan
001_FeatureGuide/databasetest/src/androidTest/java/com/nollec/datebasetest/ApplicationTest.java
Java
apache-2.0
354
/* * Copyright 2003 - 2014 The eFaps 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ /** * The dojo package. includes all js from dojo 1.7.2. */ package org.efaps.ui.wicket.behaviors.dojo;
eFaps/eFaps-WebApp
src/main/java/org/efaps/ui/wicket/behaviors/dojo/package-info.java
Java
apache-2.0
797
/******************************************************************************* * Copyright 2007-2013 See AUTHORS file. * * 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 xworker.swt.xworker; import org.eclipse.swt.widgets.Control; import org.xmeta.ActionContext; import org.xmeta.Bindings; import org.xmeta.Thing; import org.xmeta.World; import xworker.swt.design.Designer; public class ExtendWidgetCreator { public static Object create(ActionContext actionContext){ //World world = World.getInstance(); Thing self = (Thing) actionContext.get("self"); Thing widgetThing = self.doAction("getExtendWidget", actionContext); if(widgetThing != null){ Object acObj = self.doAction("getActionContext", actionContext); ActionContext ac = null; if(acObj instanceof String){ acObj = actionContext.get(acObj.toString()); } if(acObj == null || !(acObj instanceof ActionContext)){ ac = null; }else{ ac = (ActionContext) acObj; } if(ac == null){ String actionContextName = self.getStringBlankAsNull("actionContext"); if(actionContextName != null){ Boolean createActionContextIfNotExists = self.doAction("isCreateActionContextIfNotExists", actionContext); if(createActionContextIfNotExists != null && createActionContextIfNotExists){ ac = new ActionContext(); ac.put("parentContext", actionContext); ac.put("parent", actionContext.get("parent")); ac.put("parentThing", self); actionContext.getScope(0).put(actionContextName, ac); } }else{ //旧的已过时的属性 if(self.getBoolean("newActionContext")){ ac = new ActionContext(); ac.put("parentContext", actionContext); ac.put("parentThing", self); ac.put("parent", actionContext.get("parent")); String newActionContextName = self.getStringBlankAsNull("newActionContextName"); if(newActionContextName != null){ actionContext.getScope(0).put(newActionContextName, ac); } }else{ ac = actionContext; } } } ac.peek().put("parent", actionContext.getObject("parent")); Object control = null; Designer.pushCreator(self); try{ control = widgetThing.doAction("create", ac); }finally{ Designer.popCreator(); } Bindings bindings = actionContext.push(); bindings.put("parent", control); try{ for(Thing child : self.getChilds()){ child.doAction("create", actionContext); } }finally{ actionContext.pop(); } if(control instanceof Control) { Designer.attachCreator((Control) control, self.getMetadata().getPath(), actionContext); } actionContext.getScope(0).put(self.getMetadata().getName(), control); return control; } else { return null; } } }
x-meta/xworker
xworker_swt/src/main/java/xworker/swt/xworker/ExtendWidgetCreator.java
Java
apache-2.0
3,602
package com.psc.vote.vote.domain; import java.math.BigDecimal; import java.util.Date; import java.util.List; public class Anchor { String anchorName; BigDecimal anchorPrice; Date creationDate; String status; String clientId; String clientName; String clientWebsiteAddress; String clientInfo; List<Campaign> campaigns; public String getAnchorName() { return anchorName; } public void setAnchorName(String anchorName) { this.anchorName = anchorName; } public BigDecimal getAnchorPrice() { return anchorPrice; } public void setAnchorPrice(BigDecimal anchorPrice) { this.anchorPrice = anchorPrice; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getClientName() { return clientName; } public void setClientName(String clientName) { this.clientName = clientName; } public String getClientWebsiteAddress() { return clientWebsiteAddress; } public void setClientWebsiteAddress(String clientWebsiteAddress) { this.clientWebsiteAddress = clientWebsiteAddress; } public String getClientInfo() { return clientInfo; } public void setClientInfo(String clientInfo) { this.clientInfo = clientInfo; } public List<Campaign> getCampaigns() { return campaigns; } public void setCampaigns(List<Campaign> campaigns) { this.campaigns = campaigns; } @Override public String toString() { return "Anchor{" + "anchorName='" + anchorName + '\'' + ", anchorPrice=" + anchorPrice + ", creationDate=" + creationDate + ", status='" + status + '\'' + ", clientId='" + clientId + '\'' + ", clientName='" + clientName + '\'' + ", clientWebsiteAddress='" + clientWebsiteAddress + '\'' + ", clientInfo='" + clientInfo + '\'' + ", campaigns=" + campaigns + '}'; } }
sgudupat/psc-vote-server
src/main/java/com/psc/vote/vote/domain/Anchor.java
Java
apache-2.0
2,490
package ar.com.larreta.stepper.controllers; import javax.servlet.ServletContext; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import ar.com.larreta.annotations.PerformanceMonitor; import ar.com.larreta.stepper.Step; import ar.com.larreta.stepper.StepElement; import ar.com.larreta.stepper.messages.Body; import ar.com.larreta.stepper.messages.JSONable; import ar.com.larreta.stepper.messages.LoadBody; import ar.com.larreta.stepper.messages.Request; import ar.com.larreta.stepper.messages.Response; import ar.com.larreta.stepper.messages.TargetedBody; public abstract class ParentController<UpdateBodyRequest extends Body, LoadBodyRequest extends Body> extends StepElement { public static final String LOAD = "/load"; public static final String DELETE = "/delete"; public static final String UPDATE = "/update"; public static final String CREATE = "/create"; @Autowired protected ServletContext servletContext; protected Step createBusiness; protected Step updateBusiness; protected Step deleteBusiness; protected Step loadBusiness; public abstract void setCreateBusiness(Step createBusiness); public abstract void setUpdateBusiness(Step updateBusiness); public abstract void setDeleteBusiness(Step deleteBusiness); public abstract void setLoadBusiness(Step loadBusiness); @PerformanceMonitor @RequestMapping(value = CREATE, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public Response<TargetedBody> createPost(@Valid @RequestBody Request<UpdateBodyRequest> request, Errors errors) throws Exception{ return executeBusiness(request, createBusiness); } @PerformanceMonitor @RequestMapping(value = UPDATE, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public Response<TargetedBody> updatePost(@Valid @RequestBody Request<UpdateBodyRequest> request, Errors errors) throws Exception{ return executeBusiness(request, updateBusiness); } private Response<TargetedBody> executeBusiness(Request<UpdateBodyRequest> request, Step business) throws Exception{ Response<TargetedBody> response = applicationContext.getBean(Response.class); Long target = (Long) business.execute(request.getBody(), null, null); TargetedBody responseBody = new TargetedBody(); responseBody.setTarget(target); response.setBody(responseBody); return response; } @PerformanceMonitor @RequestMapping(value = DELETE, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public Response<TargetedBody> deletePost(@Valid @RequestBody Request<TargetedBody> request, Errors errors) throws Exception{ Response<TargetedBody> response = applicationContext.getBean(Response.class); TargetedBody responseBody = new TargetedBody(); responseBody.setTarget(request.getBody().getTarget()); response.setBody(responseBody); deleteBusiness.execute(request.getBody().getTarget(), null, null); return response; } @PerformanceMonitor @RequestMapping(value = LOAD, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public Response<LoadBody<JSONable>> loadPost(@Valid @RequestBody Request<LoadBodyRequest> request, Errors errors) throws Exception{ Response<LoadBody<JSONable>> response = applicationContext.getBean(Response.class);; LoadBody body = (LoadBody) loadBusiness.execute(request.getBody(), null, null); response.setBody(body); return response; } }
llarreta/larretasources
Stepper/src/main/java/ar/com/larreta/stepper/controllers/ParentController.java
Java
apache-2.0
3,717
import {moduleFor, test} from 'ember-qunit'; moduleFor('controller:login', 'Unit | Controller | login', { needs: ['service:metrics', 'service:session'] }); test('it exists', function (assert) { let controller = this.subject(); assert.ok(controller); });
piotrb5e3/0bit
tests/unit/controllers/login-test.js
JavaScript
apache-2.0
262
namespace SoukeyNetget { partial class frmAddPlanTask { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmAddPlanTask)); this.raSoukeyTask = new System.Windows.Forms.RadioButton(); this.raOtherTask = new System.Windows.Forms.RadioButton(); this.panel1 = new System.Windows.Forms.Panel(); this.listTask = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.columnHeader3 = new System.Windows.Forms.ColumnHeader(); this.columnHeader4 = new System.Windows.Forms.ColumnHeader(); this.label1 = new System.Windows.Forms.Label(); this.comTaskClass = new System.Windows.Forms.ComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.panel3 = new System.Windows.Forms.Panel(); this.comTableName = new System.Windows.Forms.ComboBox(); this.button12 = new System.Windows.Forms.Button(); this.txtDataSource = new System.Windows.Forms.TextBox(); this.raMySqlTask = new System.Windows.Forms.RadioButton(); this.raMSSQLTask = new System.Windows.Forms.RadioButton(); this.raAccessTask = new System.Windows.Forms.RadioButton(); this.label8 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.panel2 = new System.Windows.Forms.Panel(); this.txtPara = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.txtFileName = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.raDataTask = new System.Windows.Forms.RadioButton(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdOK = new System.Windows.Forms.Button(); this.panel1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.panel3.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // raSoukeyTask // this.raSoukeyTask.AccessibleDescription = null; this.raSoukeyTask.AccessibleName = null; resources.ApplyResources(this.raSoukeyTask, "raSoukeyTask"); this.raSoukeyTask.BackgroundImage = null; this.raSoukeyTask.Checked = true; this.raSoukeyTask.Font = null; this.raSoukeyTask.Name = "raSoukeyTask"; this.raSoukeyTask.TabStop = true; this.raSoukeyTask.UseVisualStyleBackColor = true; this.raSoukeyTask.CheckedChanged += new System.EventHandler(this.raSoukeyTask_CheckedChanged); // // raOtherTask // this.raOtherTask.AccessibleDescription = null; this.raOtherTask.AccessibleName = null; resources.ApplyResources(this.raOtherTask, "raOtherTask"); this.raOtherTask.BackgroundImage = null; this.raOtherTask.Font = null; this.raOtherTask.Name = "raOtherTask"; this.raOtherTask.UseVisualStyleBackColor = true; this.raOtherTask.CheckedChanged += new System.EventHandler(this.raOtherTask_CheckedChanged); // // panel1 // this.panel1.AccessibleDescription = null; this.panel1.AccessibleName = null; resources.ApplyResources(this.panel1, "panel1"); this.panel1.BackgroundImage = null; this.panel1.Controls.Add(this.listTask); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.comTaskClass); this.panel1.Font = null; this.panel1.Name = "panel1"; // // listTask // this.listTask.AccessibleDescription = null; this.listTask.AccessibleName = null; resources.ApplyResources(this.listTask, "listTask"); this.listTask.BackgroundImage = null; this.listTask.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3, this.columnHeader4}); this.listTask.Font = null; this.listTask.FullRowSelect = true; this.listTask.MultiSelect = false; this.listTask.Name = "listTask"; this.listTask.UseCompatibleStateImageBehavior = false; this.listTask.View = System.Windows.Forms.View.Details; this.listTask.DoubleClick += new System.EventHandler(this.listTask_DoubleClick); // // columnHeader1 // resources.ApplyResources(this.columnHeader1, "columnHeader1"); // // columnHeader2 // resources.ApplyResources(this.columnHeader2, "columnHeader2"); // // columnHeader3 // resources.ApplyResources(this.columnHeader3, "columnHeader3"); // // columnHeader4 // resources.ApplyResources(this.columnHeader4, "columnHeader4"); // // label1 // this.label1.AccessibleDescription = null; this.label1.AccessibleName = null; resources.ApplyResources(this.label1, "label1"); this.label1.Font = null; this.label1.Name = "label1"; // // comTaskClass // this.comTaskClass.AccessibleDescription = null; this.comTaskClass.AccessibleName = null; resources.ApplyResources(this.comTaskClass, "comTaskClass"); this.comTaskClass.BackgroundImage = null; this.comTaskClass.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comTaskClass.Font = null; this.comTaskClass.FormattingEnabled = true; this.comTaskClass.Name = "comTaskClass"; this.comTaskClass.SelectedIndexChanged += new System.EventHandler(this.comTaskClass_SelectedIndexChanged); // // groupBox1 // this.groupBox1.AccessibleDescription = null; this.groupBox1.AccessibleName = null; resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.BackgroundImage = null; this.groupBox1.Controls.Add(this.panel2); this.groupBox1.Controls.Add(this.panel1); this.groupBox1.Controls.Add(this.panel3); this.groupBox1.Font = null; this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // panel3 // this.panel3.AccessibleDescription = null; this.panel3.AccessibleName = null; resources.ApplyResources(this.panel3, "panel3"); this.panel3.BackgroundImage = null; this.panel3.Controls.Add(this.comTableName); this.panel3.Controls.Add(this.button12); this.panel3.Controls.Add(this.txtDataSource); this.panel3.Controls.Add(this.raMySqlTask); this.panel3.Controls.Add(this.raMSSQLTask); this.panel3.Controls.Add(this.raAccessTask); this.panel3.Controls.Add(this.label8); this.panel3.Controls.Add(this.label6); this.panel3.Font = null; this.panel3.Name = "panel3"; // // comTableName // this.comTableName.AccessibleDescription = null; this.comTableName.AccessibleName = null; resources.ApplyResources(this.comTableName, "comTableName"); this.comTableName.BackgroundImage = null; this.comTableName.Font = null; this.comTableName.FormattingEnabled = true; this.comTableName.Name = "comTableName"; this.comTableName.DropDown += new System.EventHandler(this.comTableName_DropDown); // // button12 // this.button12.AccessibleDescription = null; this.button12.AccessibleName = null; resources.ApplyResources(this.button12, "button12"); this.button12.BackgroundImage = null; this.button12.Font = null; this.button12.Name = "button12"; this.button12.UseVisualStyleBackColor = true; this.button12.Click += new System.EventHandler(this.button12_Click); // // txtDataSource // this.txtDataSource.AccessibleDescription = null; this.txtDataSource.AccessibleName = null; resources.ApplyResources(this.txtDataSource, "txtDataSource"); this.txtDataSource.BackgroundImage = null; this.txtDataSource.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtDataSource.Font = null; this.txtDataSource.Name = "txtDataSource"; // // raMySqlTask // this.raMySqlTask.AccessibleDescription = null; this.raMySqlTask.AccessibleName = null; resources.ApplyResources(this.raMySqlTask, "raMySqlTask"); this.raMySqlTask.BackgroundImage = null; this.raMySqlTask.Font = null; this.raMySqlTask.Name = "raMySqlTask"; this.raMySqlTask.UseVisualStyleBackColor = true; // // raMSSQLTask // this.raMSSQLTask.AccessibleDescription = null; this.raMSSQLTask.AccessibleName = null; resources.ApplyResources(this.raMSSQLTask, "raMSSQLTask"); this.raMSSQLTask.BackgroundImage = null; this.raMSSQLTask.Font = null; this.raMSSQLTask.Name = "raMSSQLTask"; this.raMSSQLTask.UseVisualStyleBackColor = true; // // raAccessTask // this.raAccessTask.AccessibleDescription = null; this.raAccessTask.AccessibleName = null; resources.ApplyResources(this.raAccessTask, "raAccessTask"); this.raAccessTask.BackgroundImage = null; this.raAccessTask.Checked = true; this.raAccessTask.Font = null; this.raAccessTask.Name = "raAccessTask"; this.raAccessTask.TabStop = true; this.raAccessTask.UseVisualStyleBackColor = true; // // label8 // this.label8.AccessibleDescription = null; this.label8.AccessibleName = null; resources.ApplyResources(this.label8, "label8"); this.label8.Font = null; this.label8.Name = "label8"; // // label6 // this.label6.AccessibleDescription = null; this.label6.AccessibleName = null; resources.ApplyResources(this.label6, "label6"); this.label6.Font = null; this.label6.Name = "label6"; // // panel2 // this.panel2.AccessibleDescription = null; this.panel2.AccessibleName = null; resources.ApplyResources(this.panel2, "panel2"); this.panel2.BackgroundImage = null; this.panel2.Controls.Add(this.txtPara); this.panel2.Controls.Add(this.label3); this.panel2.Controls.Add(this.button1); this.panel2.Controls.Add(this.txtFileName); this.panel2.Controls.Add(this.label2); this.panel2.Font = null; this.panel2.Name = "panel2"; // // txtPara // this.txtPara.AccessibleDescription = null; this.txtPara.AccessibleName = null; resources.ApplyResources(this.txtPara, "txtPara"); this.txtPara.BackgroundImage = null; this.txtPara.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtPara.Font = null; this.txtPara.Name = "txtPara"; // // label3 // this.label3.AccessibleDescription = null; this.label3.AccessibleName = null; resources.ApplyResources(this.label3, "label3"); this.label3.Font = null; this.label3.Name = "label3"; // // button1 // this.button1.AccessibleDescription = null; this.button1.AccessibleName = null; resources.ApplyResources(this.button1, "button1"); this.button1.BackgroundImage = null; this.button1.Font = null; this.button1.Name = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // txtFileName // this.txtFileName.AccessibleDescription = null; this.txtFileName.AccessibleName = null; resources.ApplyResources(this.txtFileName, "txtFileName"); this.txtFileName.BackgroundImage = null; this.txtFileName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtFileName.Font = null; this.txtFileName.Name = "txtFileName"; // // label2 // this.label2.AccessibleDescription = null; this.label2.AccessibleName = null; resources.ApplyResources(this.label2, "label2"); this.label2.Font = null; this.label2.Name = "label2"; // // groupBox2 // this.groupBox2.AccessibleDescription = null; this.groupBox2.AccessibleName = null; resources.ApplyResources(this.groupBox2, "groupBox2"); this.groupBox2.BackgroundImage = null; this.groupBox2.Font = null; this.groupBox2.Name = "groupBox2"; this.groupBox2.TabStop = false; // // openFileDialog1 // resources.ApplyResources(this.openFileDialog1, "openFileDialog1"); // // raDataTask // this.raDataTask.AccessibleDescription = null; this.raDataTask.AccessibleName = null; resources.ApplyResources(this.raDataTask, "raDataTask"); this.raDataTask.BackgroundImage = null; this.raDataTask.Font = null; this.raDataTask.Name = "raDataTask"; this.raDataTask.TabStop = true; this.raDataTask.UseVisualStyleBackColor = true; this.raDataTask.CheckedChanged += new System.EventHandler(this.raDataTask_CheckedChanged); // // cmdCancel // this.cmdCancel.AccessibleDescription = null; this.cmdCancel.AccessibleName = null; resources.ApplyResources(this.cmdCancel, "cmdCancel"); this.cmdCancel.BackgroundImage = null; this.cmdCancel.Font = null; this.cmdCancel.Name = "cmdCancel"; this.cmdCancel.UseVisualStyleBackColor = true; this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click); // // cmdOK // this.cmdOK.AccessibleDescription = null; this.cmdOK.AccessibleName = null; resources.ApplyResources(this.cmdOK, "cmdOK"); this.cmdOK.BackgroundImage = null; this.cmdOK.Font = null; this.cmdOK.Name = "cmdOK"; this.cmdOK.UseVisualStyleBackColor = true; this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click); // // frmAddPlanTask // this.AccessibleDescription = null; this.AccessibleName = null; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = null; this.Controls.Add(this.raDataTask); this.Controls.Add(this.cmdCancel); this.Controls.Add(this.cmdOK); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.raOtherTask); this.Controls.Add(this.raSoukeyTask); this.Font = null; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmAddPlanTask"; this.Load += new System.EventHandler(this.frmAddPlanTask_Load); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.frmAddPlanTask_FormClosed); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.groupBox1.ResumeLayout(false); this.panel3.ResumeLayout(false); this.panel3.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.RadioButton raSoukeyTask; private System.Windows.Forms.RadioButton raOtherTask; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ListView listTask; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox comTaskClass; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button cmdCancel; private System.Windows.Forms.Button cmdOK; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtPara; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox txtFileName; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.RadioButton raDataTask; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.ComboBox comTableName; private System.Windows.Forms.Button button12; private System.Windows.Forms.TextBox txtDataSource; private System.Windows.Forms.RadioButton raMySqlTask; private System.Windows.Forms.RadioButton raMSSQLTask; private System.Windows.Forms.RadioButton raAccessTask; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label6; } }
zhouweiaccp/code
SoukeyNetget/frmAddPlanTask.Designer.cs
C#
apache-2.0
20,352
import os from ..libs import xlrd_tools HERE = os.path.dirname(os.path.abspath(__file__)) def test_xlsx_xlrd(): with open(os.path.join(HERE, 'fixtures', 'test.xlsx')) as fp: headers, data = xlrd_tools.xlsx_xlrd(fp) assert headers[0] == {'field': 'one', 'id': 'one', 'name': 'one'} assert data[0] == {'one': 'a', 'two': 'b', 'three': 'c'}
chrisseto/modular-file-renderer
mfr/ext/tabular/tests/test_xlsx_tools.py
Python
apache-2.0
362
/* * Copyright 2015 David A. Boyuka II * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * test-zo-iter.cpp * * Created on: Jan 16, 2014 * Author: David A. Boyuka II */ #include <cassert> #include <cstdint> //#include <zo-iter.hpp> #include "pique/util/zo-iter2.hpp" //void do_iter_test(ZOIter &it, uint64_t *expected, uint64_t expected_len) { // for (uint64_t i = 0; i < expected_len; i++) { // it.next(); // assert(it.has_top()); // assert(it.get_top_zid() == i); // assert(it.get_top_rmoid() == *expected++); // } // // it.next(); // assert(!it.has_top()); //} static const uint64_t expected_zids1[] = {0, 1, 2, 3, 4, 6, 8, 9, 12}; static const uint64_t expected_rmoids1[] = {0, 1, 5, 6, 2, 7, 10, 11, 12}; static const uint64_t expected_x1[] = {0, 0, 1, 1, 0, 1, 2, 2, 2}; static const uint64_t expected_y1[] = {0, 1, 0, 1, 2, 2, 0, 1, 2}; static const uint64_t expected_zids2[] = {0, 1, 2, 3, 8, 9, 10, 11}; static const uint64_t expected_rmoids2[] = {0, 1, 4, 5, 8, 9, 12, 13}; static const uint64_t expected_x2[] = {0, 0, 1, 1, 2, 2, 3, 3}; static const uint64_t expected_y2[] = {0, 1, 0, 1, 0, 1, 0, 1}; struct Iter2Test { Iter2Test(const uint64_t expected_zids[], const uint64_t expected_rmoids[], const uint64_t expected_x[], const uint64_t expected_y[]) : i(0), expected_zids(expected_zids), expected_rmoids(expected_rmoids), expected_x(expected_x), expected_y(expected_y) {} void operator()(uint64_t zid, uint64_t rmoid, uint64_t dims[2]) { assert(zid == expected_zids[i]); assert(rmoid == expected_rmoids[i]); assert(dims[0] == expected_y[i]); assert(dims[1] == expected_x[i]); #ifdef VERBOSE_TESTS printf("ZOIter2: zid(%llu), rmoid(%llu)\n", zid, rmoid); #endif i++; } int i; const uint64_t *expected_zids; const uint64_t *expected_rmoids; const uint64_t *expected_x; const uint64_t *expected_y; }; int main(int argc, char **argv) { uint64_t dims[] = { 5, 5 }; uint64_t subdims[] = { 3, 3 }; // grid_t *grid = lin_new_grid(2, dims, true); // grid_t *subgrid = lin_new_grid(2, subdims, true); // ZOIter it(grid, subgrid); // uint64_t exp[] = {0, 1, 5, 6, 2, ~0ULL, 7, ~0ULL, 10, 11, ~0ULL, ~0ULL, 12, ~0ULL, ~0ULL, ~0ULL}; // do_iter_test(it, exp, 16); ZOIterLoop<2/*ndim*/, 3/*exp_level*/> loop; loop.iterate(dims, subdims, true, Iter2Test(expected_zids1, expected_rmoids1, expected_x1, expected_y1)); uint64_t dims2[] = { 4, 4 }; uint64_t subdims2[] = { 4, 2 }; ZOIterLoop<2/*ndim*/, 2/*exp_level*/> loop2; loop2.iterate(dims2, subdims2, true, Iter2Test(expected_zids2, expected_rmoids2, expected_x2, expected_y2)); }
daboyuka/PIQUE
tests/util/test-zo-iter.cpp
C++
apache-2.0
3,200
package com.ecas.base; import com.ecas.domain.User; import java.util.Date; import javax.persistence.Column; import javax.persistence.MappedSuperclass; @MappedSuperclass public abstract class BaseDomain extends AbstractDomain { private User updateUser; @Column(name = "update_time") private Date updateTime; public User getUpdateUser() { return updateUser; } public void setUpdateUser(User updateUser) { this.updateUser = updateUser; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
mrhailua/ecas
domain/src/main/java/com/ecas/base/BaseDomain.java
Java
apache-2.0
682
package ru.nivanov; import org.json.simple.JSONObject; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; /** * Created by Nikolay Ivanov on 27.03.2018. */ public class UserFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(false); String role = (String) session.getAttribute("rolename"); if (role.equals("admin")) { filterChain.doFilter(request, response); } else { JSONObject object = new JSONObject(); object.put("result", "cannot perform operation, you are not admin"); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.println(object); out.flush(); } } @Override public void destroy() { } }
Piterski72/Java-a-to-z
chapter_009/Task08/src/main/java/ru/nivanov/UserFilter.java
Java
apache-2.0
1,401
package org.apereo.cas.configuration.model.support.cookie; import org.apereo.cas.configuration.support.RequiresModule; import com.fasterxml.jackson.annotation.JsonFilter; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; /** * Common properties for all cookie configs. * * @author Dmitriy Kopylenko * @since 5.0.0 */ @RequiresModule(name = "cas-server-core-cookie", automated = true) @Getter @Setter @Accessors(chain = true) @JsonFilter("CookieProperties") public class CookieProperties implements Serializable { private static final long serialVersionUID = 6804770601645126835L; /** * Cookie name. Constructs a cookie with a specified name and value. * The name must conform to RFC 2965. That means it can contain only ASCII alphanumeric characters and * cannot contain commas, semicolons, or white space or begin with a $ character. * The cookie's name cannot be changed after creation. * By default, cookies are created according to the RFC 2965 cookie specification. */ private String name; /** * Cookie path. * Specifies a path for the cookie to which the client should return the cookie. * The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's * subdirectories. A cookie's path must include the servlet that set the cookie, for example, /catalog, * which makes the cookie visible to all directories on the server under /catalog. * Consult RFC 2965 (available on the Internet) for more information on setting path names for cookies. */ private String path = StringUtils.EMPTY; /** * Cookie domain. Specifies the domain within which this cookie should be presented. * The form of the domain name is specified by RFC 2965. A domain name begins with a dot (.foo.com) * and means that the cookie is visible to servers in a * specified Domain Name System (DNS) zone (for example, www.foo.com, but not a.b.foo.com). * By default, cookies are only returned to the server that sent them. */ private String domain = StringUtils.EMPTY; /** * CAS Cookie comment, describes the cookie's usage and purpose. */ private String comment = "CAS Cookie"; /** * True if sending this cookie should be restricted to a secure protocol, or * false if the it can be sent using any protocol. */ private boolean secure = true; /** * true if this cookie contains the HttpOnly attribute. This means that the cookie should * not be accessible to scripting engines, like javascript. */ private boolean httpOnly = true; /** * The maximum age of the cookie, specified in seconds. By default, -1 indicating the cookie will persist until browser shutdown. * A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is * the maximum age when the cookie will expire, not the cookie's current age. * A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. * A zero value causes the cookie to be deleted. */ private int maxAge = -1; /** * When generating cookie values, determine whether the value * should be compounded and signed with the properties of * the current session, such as IP address, user-agent, etc. */ private boolean pinToSession = true; /** * If a cookie is only intended to be accessed in a first party context, the * developer has the option to apply one of settings * {@code SameSite=Lax or SameSite=Strict or SameSite=None} to prevent external access. * <p> * To safeguard more websites and their users, the new secure-by-default model * assumes all cookies should be protected from external access unless otherwise * specified. Developers must use a new cookie setting, {@code SameSite=None}, to designate * cookies for cross-site access. When the {@code SameSite=None} attribute is present, an additional * {@code Secure} attribute is used so cross-site cookies can only be accessed over HTTPS * connections. * </p> * <p>Accepted values are: {@code Lax}, {@code Strict}, {@code None}.</p> */ private String sameSitePolicy = StringUtils.EMPTY; }
pdrados/cas
api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/cookie/CookieProperties.java
Java
apache-2.0
4,453
#include "OI.h" #include "WPILib.h" #include "RobotMap.h" #include "Commands/Elevator/Lift.h" #include "Commands/Elevator/Lower.h" #include "Commands/Grabber/OpenArms.h" #include "Commands/Grabber/CloseArms.h" #include "Commands/Chassis/Drive.h" #include "Commands/PutToSmartDashboard.h" OI::OI() { this->stick = new Joystick(JOYSTICK_CHANNEL); for (int i = 0; i < 10; i++) { this->buttons[i] = new JoystickButton(this->stick, i + 1); } this->autoSwitch1 = new DigitalInput(AUTONOMOUS_SWITCH1); this->autoSwitch2 = new DigitalInput(AUTONOMOUS_SWITCH2); this->buttons[0]->WhenPressed(new OpenArms()); // 'A' Button this->buttons[1]->WhenPressed(new CloseArms()); // 'B' Button this->buttons[3]->WhileHeld(new Drive(0.3, 0)); // 'Y' Button this->buttons[4]->WhileHeld(new Lower()); // 'LB' Button this->buttons[5]->WhileHeld(new Lift()); // 'RB' Button Scheduler::GetInstance()->AddCommand(new PutToSmartDashboard()); } Joystick* OI::getJoystick() { return this->stick; } JoystickButton** OI::GetButtons() { return this->buttons; } DigitalInput* OI::GetAutonomousSwitch1() { return this->autoSwitch1; } DigitalInput* OI::GetAutonomousSwitch2() { return this->autoSwitch2; }
NeatTeam1943/Slifer
src/OI.cpp
C++
apache-2.0
1,198
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import functools import json from oslo_config import cfg from oslo_log import log as logging from conveyor.clone.drivers import driver from conveyor.clone.resources import common from conveyor.conveyoragentclient.v1 import client as birdiegatewayclient from conveyor.i18n import _LE from conveyor.i18n import _LW from conveyor import exception from conveyor import utils CONF = cfg.CONF LOG = logging.getLogger(__name__) class OpenstackDriver(driver.BaseDriver): def __init__(self): super(OpenstackDriver, self).__init__() def handle_resources(self, context, plan_id, resource_map, sys_clone, copy_data): LOG.debug('Begin handle resources') undo_mgr = utils.UndoManager() try: self._add_extra_properties(context, resource_map, sys_clone, copy_data, undo_mgr) # self._set_resources_state(context, resource_map) return undo_mgr except Exception as e: LOG.error(_LE('Generate template of plan failed, err:%s'), str(e)) undo_mgr._rollback() raise exception.ExportTemplateFailed(id=plan_id, msg=str(e)) def _set_resources_state(self, context, resource_map): for key, value in resource_map.items(): resource_type = value.type resource_id = value.id if resource_type == 'OS::Nova::Server': self.compute_api.reset_state(context, resource_id, 'cloning') elif resource_type == 'OS::Cinder::Volume': self.volume_api.reset_state(context, resource_id, 'cloning') elif resource_type == 'OS::Heat::Stack': self._set_resources_state_for_stack(context, value) def _set_resources_state_for_stack(self, context, resource): template_str = resource.properties.get('template') template = json.loads(template_str) def _set_state(template): temp_res = template.get('resources') for key, value in temp_res.items(): res_type = value.get('type') if res_type == 'OS::Cinder::Volume': vid = value.get('extra_properties', {}).get('id') if vid: self.volume_api.reset_state(context, vid, 'cloning') elif res_type == 'OS::Nova::Server': sid = value.get('extra_properties', {}).get('id') if sid: self.compute_api.reset_state(context, sid, 'cloning') elif res_type and res_type.startswith('file://'): son_template = value.get('content') son_template = json.loads(son_template) _set_state(son_template) _set_state(template) def add_extra_properties_for_server(self, context, resource, resource_map, sys_clone, copy_data, undo_mgr): migrate_net_map = CONF.migrate_net_map server_properties = resource.properties server_id = resource.id server_extra_properties = resource.extra_properties server_az = server_properties.get('availability_zone') vm_state = server_extra_properties.get('vm_state') gw_url = server_extra_properties.get('gw_url') if not gw_url: if vm_state == 'stopped': gw_id, gw_ip = utils.get_next_vgw(server_az) if not gw_id or not gw_ip: raise exception.V2vException(message='no vgw host found') gw_url = gw_ip + ':' + str(CONF.v2vgateway_api_listen_port) resource.extra_properties.update({"gw_url": gw_url, "gw_id": gw_id}) resource.extra_properties['sys_clone'] = sys_clone resource.extra_properties['is_deacidized'] = True block_device_mapping = server_properties.get( 'block_device_mapping_v2') if block_device_mapping: for block_device in block_device_mapping: volume_name = block_device.get('volume_id').get( 'get_resource') volume_resource = resource_map.get(volume_name) volume_resource.extra_properties['gw_url'] = gw_url volume_resource.extra_properties['is_deacidized'] = \ True boot_index = block_device.get('boot_index') dev_name = block_device.get('device_name') if boot_index == 0 or boot_index == '0': volume_resource.extra_properties['sys_clone'] = \ sys_clone if sys_clone: self._handle_dv_for_svm(context, volume_resource, server_id, dev_name, gw_id, gw_ip, undo_mgr) else: d_copy = copy_data and volume_resource. \ extra_properties['copy_data'] volume_resource.extra_properties['copy_data'] = \ d_copy if not d_copy: continue self._handle_dv_for_svm(context, volume_resource, server_id, dev_name, gw_id, gw_ip, undo_mgr) else: if migrate_net_map: # get the availability_zone of server server_az = server_properties.get('availability_zone') if not server_az: LOG.error(_LE('Not get the availability_zone' 'of server %s') % resource.id) raise exception.AvailabilityZoneNotFound( server_uuid=resource.id) migrate_net_id = migrate_net_map.get(server_az) if not migrate_net_id: LOG.error(_LE('Not get the migrate net of server %s') % resource.id) raise exception.NoMigrateNetProvided( server_uuid=resource.id) # attach interface LOG.debug('Attach a port of net %s to server %s', migrate_net_id, server_id) obj = self.compute_api.interface_attach(context, server_id, migrate_net_id, None, None) interface_attachment = obj._info if interface_attachment: LOG.debug('The interface attachment info is %s ' % str(interface_attachment)) migrate_fix_ip = interface_attachment.get('fixed_ips')[0] \ .get('ip_address') migrate_port_id = interface_attachment.get('port_id') undo_mgr.undo_with(functools.partial (self.compute_api.interface_detach, context, server_id, migrate_port_id)) gw_url = migrate_fix_ip + ':' + str( CONF.v2vgateway_api_listen_port) extra_properties = {} extra_properties['gw_url'] = gw_url extra_properties['is_deacidized'] = True extra_properties['migrate_port_id'] = migrate_port_id extra_properties['sys_clone'] = sys_clone resource.extra_properties.update(extra_properties) # waiting port attach finished, and can ping this vm self._await_port_status(context, migrate_port_id, migrate_fix_ip) # else: # interfaces = self.neutron_api.port_list( # context, device_id=server_id) # host_ip = None # for infa in interfaces: # if host_ip: # break # binding_profile = infa.get("binding:profile", []) # if binding_profile: # host_ip = binding_profile.get('host_ip') # if not host_ip: # LOG.error(_LE('Not find the clone data # ip for server')) # raise exception.NoMigrateNetProvided( # server_uuid=resource.id # ) # gw_url = host_ip + ':' + str( # CONF.v2vgateway_api_listen_port) # extra_properties = {} # extra_properties['gw_url'] = gw_url # extra_properties['sys_clone'] = sys_clone # resource.extra_properties.update(extra_properties) block_device_mapping = server_properties.get( 'block_device_mapping_v2') if block_device_mapping: client = None if gw_url: gw_urls = gw_url.split(':') client = birdiegatewayclient.get_birdiegateway_client( gw_urls[0], gw_urls[1]) for block_device in block_device_mapping: device_name = block_device.get('device_name') volume_name = block_device.get('volume_id').get( 'get_resource') volume_resource = resource_map.get(volume_name) boot_index = block_device.get('boot_index') if boot_index == 0 or boot_index == '0': volume_resource.extra_properties['sys_clone'] = \ sys_clone if not sys_clone: continue else: d_copy = copy_data and volume_resource. \ extra_properties['copy_data'] volume_resource.extra_properties['copy_data'] = \ d_copy if not d_copy: continue # need to check the vm disk name if not client: continue src_dev_format = client.vservices. \ get_disk_format(device_name).get('disk_format') src_mount_point = client. \ vservices.get_disk_mount_point(device_name). \ get('mount_point') volume_resource.extra_properties['guest_format'] = \ src_dev_format volume_resource.extra_properties['mount_point'] = \ src_mount_point volume_resource.extra_properties['gw_url'] = gw_url volume_resource.extra_properties['is_deacidized'] = \ True sys_dev_name = client. \ vservices.get_disk_name(volume_resource.id). \ get('dev_name') if not sys_dev_name: sys_dev_name = device_name volume_resource.extra_properties['sys_dev_name'] = \ sys_dev_name def _handle_sv_for_svm(self, context, vol_res, gw_id, gw_ip, undo_mgr): volume_id = vol_res.id LOG.debug('Set the volume %s shareable', volume_id) self.volume_api.set_volume_shareable(context, volume_id, True) undo_mgr.undo_with(functools.partial(self._set_volume_shareable, context, volume_id, False)) client = birdiegatewayclient.get_birdiegateway_client( gw_ip, str(CONF.v2vgateway_api_listen_port) ) disks = set(client.vservices.get_disk_name().get('dev_name')) self.compute_api.attach_volume(context, gw_id, volume_id, None) LOG.debug('Attach the volume %s to gw host %s ', volume_id, gw_id) undo_mgr.undo_with(functools.partial(self._detach_volume, context, gw_id, volume_id)) self._wait_for_volume_status(context, volume_id, gw_id, 'in-use') n_disks = set(client.vservices.get_disk_name().get('dev_name')) diff_disk = n_disks - disks LOG.debug('Begin get info for volume,the vgw ip %s' % gw_ip) client = birdiegatewayclient.get_birdiegateway_client( gw_ip, str(CONF.v2vgateway_api_listen_port)) # sys_dev_name = client.vservices.get_disk_name(volume_id).get( # 'dev_name') # sys_dev_name = device_name # sys_dev_name = attach_resp._info.get('device') sys_dev_name = list(diff_disk)[0] if len(diff_disk) >= 1 else None LOG.debug("dev_name = %s", sys_dev_name) vol_res.extra_properties['sys_dev_name'] = sys_dev_name guest_format = client.vservices.get_disk_format(sys_dev_name) \ .get('disk_format') if guest_format: vol_res.extra_properties['guest_format'] = guest_format mount_point = client.vservices.force_mount_disk( sys_dev_name, "/opt/" + volume_id) vol_res.extra_properties['mount_point'] = mount_point.get( 'mount_disk') def add_extra_properties_for_stack(self, context, resource, sys_clone, copy_data, undo_mgr): res_prop = resource.properties stack_id = resource.id template = json.loads(res_prop.get('template')) def _add_extra_prop(template, stack_id): temp_res = template.get('resources') for key, value in temp_res.items(): res_type = value.get('type') if res_type == 'OS::Cinder::Volume': # v_prop = value.get('properties') v_exra_prop = value.get('extra_properties', {}) d_copy = copy_data and v_exra_prop['copy_data'] v_exra_prop['copy_data'] = d_copy if not d_copy: continue if not v_exra_prop or not v_exra_prop.get('gw_url'): phy_id = v_exra_prop.get('id') res_info = self.volume_api.get(context, phy_id) az = res_info.get('availability_zone') gw_id, gw_ip = utils.get_next_vgw(az) if not gw_id or not gw_ip: raise exception.V2vException( message='no vgw host found') gw_url = gw_ip + ':' + str( CONF.v2vgateway_api_listen_port) v_exra_prop.update({"gw_url": gw_url, "gw_id": gw_id}) volume_status = res_info['status'] v_exra_prop['status'] = volume_status value['extra_properties'] = v_exra_prop value['id'] = phy_id self._handle_volume_for_stack(context, value, gw_id, gw_ip, undo_mgr) elif res_type == 'OS::Nova::Server': v_exra_prop = value.get('extra_properties', {}) phy_id = v_exra_prop.get('id') server_info = self.compute_api.get_server(context, phy_id) vm_state = server_info.get('OS-EXT-STS:vm_state', None) v_exra_prop['vm_state'] = vm_state value['extra_properties'] = v_exra_prop _add_extra_prop(template, stack_id) res_prop['template'] = json.dumps(template) def _handle_volume_for_stack(self, context, vol_res, gw_id, gw_ip, undo_mgr): volume_id = vol_res.get('id') volume_info = self.volume_api.get(context, volume_id) volume_status = volume_info['status'] v_shareable = volume_info['shareable'] if not v_shareable and volume_status == 'in-use': volume_attachments = volume_info.get('attachments', []) vol_res.get('extra_properties')['attachments'] = volume_attachments for attachment in volume_attachments: server_id = attachment.get('server_id') server_info = self.compute_api.get_server(context, server_id) vm_state = server_info.get('OS-EXT-STS:vm_state', None) if vm_state != 'stopped': _msg = 'the server %s not stopped' % server_id raise exception.V2vException(message=_msg) device = attachment.get('device') self.compute_api.detach_volume(context, server_id, volume_id) self._wait_for_volume_status(context, volume_id, server_id, 'available') undo_mgr.undo_with(functools.partial(self._attach_volume, context, server_id, volume_id, device)) client = birdiegatewayclient.get_birdiegateway_client( gw_ip, str(CONF.v2vgateway_api_listen_port) ) disks = set(client.vservices.get_disk_name().get('dev_name')) LOG.debug('Attach volume %s to gw host %s', volume_id, gw_id) attach_resp = self.compute_api.attach_volume(context, gw_id, volume_id, None) LOG.debug('The volume attachment info is %s ' % str(attach_resp)) undo_mgr.undo_with(functools.partial(self._detach_volume, context, gw_id, volume_id)) self._wait_for_volume_status(context, volume_id, gw_id, 'in-use') n_disks = set(client.vservices.get_disk_name().get('dev_name')) diff_disk = n_disks - disks vol_res.get('extra_properties')['status'] = 'in-use' LOG.debug('Begin get info for volume,the vgw ip %s' % gw_ip) sys_dev_name = list(diff_disk)[0] if len(diff_disk) >= 1 else None LOG.debug("dev_name = %s", sys_dev_name) # device_name = attach_resp._info.get('device') # sys_dev_name = client.vservices.get_disk_name(volume_id).get( # 'dev_name') # sys_dev_name = device_name vol_res.get('extra_properties')['sys_dev_name'] = sys_dev_name guest_format = client.vservices.get_disk_format(sys_dev_name) \ .get('disk_format') if guest_format: vol_res.get('extra_properties')['guest_format'] = guest_format mount_point = client.vservices.force_mount_disk( sys_dev_name, "/opt/" + volume_id) vol_res.get('extra_properties')['mount_point'] = mount_point.get( 'mount_disk') def reset_resources(self, context, resources): # self._reset_resources_state(context, resources) self._handle_resources_after_clone(context, resources) def _reset_resources_state(self, context, resources): for key, value in resources.items(): try: resource_type = value.get('type') resource_id = value.get('extra_properties', {}).get('id') if resource_type == 'OS::Nova::Server': vm_state = value.get('extra_properties', {}) \ .get('vm_state') self.compute_api.reset_state(context, resource_id, vm_state) elif resource_type == 'OS::Cinder::Volume': volume_state = value.get('extra_properties', {}) \ .get('status') self.volume_api.reset_state(context, resource_id, volume_state) elif resource_type == 'OS::Heat::Stack': self._reset_resources_state_for_stack(context, value) except Exception as e: LOG.warn(_LW('Reset resource state error, Error=%(e)s'), {'e': e}) def _reset_resources_state_for_stack(self, context, stack_res): template_str = stack_res.get('properties', {}).get('template') template = json.loads(template_str) def _reset_state(template): temp_res = template.get('resources') for key, value in temp_res.items(): res_type = value.get('type') if res_type == 'OS::Cinder::Volume': vid = value.get('extra_properties', {}).get('id') v_state = value.get('extra_properties', {}).get('status') if vid: self.volume_api.reset_state(context, vid, v_state) elif res_type == 'OS::Nova::Server': sid = value.get('extra_properties', {}).get('id') s_state = value.get('extra_properties', {}).get('vm_state') if sid: self.compute_api.reset_state(context, sid, s_state) elif res_type and res_type.startswith('file://'): son_template = value.get('content') son_template = json.loads(son_template) _reset_state(son_template) _reset_state(template) def handle_server_after_clone(self, context, resource, resources): self._detach_server_temporary_port(context, resource) extra_properties = resource.get('extra_properties', {}) vm_state = extra_properties.get('vm_state') if vm_state == 'stopped': self._handle_volume_for_svm_after_clone(context, resource, resources) def handle_stack_after_clone(self, context, resource, resources): template_str = resource.get('properties', {}).get('template') template = json.loads(template_str) self._handle_volume_for_stack_after_clone(context, template) def _handle_volume_for_stack_after_clone(self, context, template): try: resources = template.get('resources') for key, res in resources.items(): res_type = res.get('type') if res_type == 'OS::Cinder::Volume': try: copy_data = res.get('extra_properties', {}). \ get('copy_data') if not copy_data: continue attachments = res.get('extra_properties', {}) \ .get('attachments') volume_id = res.get('extra_properties', {}) \ .get('id') vgw_id = res.get('extra_properties').get('gw_id') self._detach_volume(context, vgw_id, volume_id) if attachments: for attachment in attachments: server_id = attachment.get('server_id') device = attachment.get('device') self.compute_api.attach_volume(context, server_id, volume_id, device) except Exception as e: LOG.error(_LE('Error from handle volume of stack after' ' clone.' 'Error=%(e)s'), {'e': e}) except Exception as e: LOG.warn('detach the volume %s from vgw %s error,' 'the volume not attached to vgw', volume_id, vgw_id) def _handle_volume_for_svm_after_clone(self, context, server_resource, resources): bdms = server_resource['properties'].get('block_device_mapping_v2', []) vgw_id = server_resource.get('extra_properties', {}).get('gw_id') for bdm in bdms: volume_key = bdm.get('volume_id', {}).get('get_resource') boot_index = bdm.get('boot_index') device_name = bdm.get('device_name') volume_res = resources.get(volume_key) try: if volume_res.get('extra_properties', {}).get('is_deacidized'): volume_id = volume_res.get('extra_properties', {}) \ .get('id') vgw_url = volume_res.get('extra_properties', {}) \ .get('gw_url') sys_clone = volume_res.get('extra_properties', {}) \ .get('sys_clone') copy_data = volume_res.get('extra_properties', {}). \ get('copy_data') if (boot_index in ['0', 0] and not sys_clone) or \ not copy_data: continue vgw_ip = vgw_url.split(':')[0] client = birdiegatewayclient.get_birdiegateway_client( vgw_ip, str(CONF.v2vgateway_api_listen_port)) if boot_index not in ['0', 0] or sys_clone: client.vservices._force_umount_disk( "/opt/" + volume_id) # if provider cloud can not detcah volume in active status if not CONF.is_active_detach_volume: resouce_common = common.ResourceCommon() self.compute_api.stop_server(context, vgw_id) resouce_common._await_instance_status(context, vgw_id, 'SHUTOFF') self.compute_api.detach_volume(context, vgw_id, volume_id) self._wait_for_volume_status(context, volume_id, vgw_id, 'available') server_id = server_resource.get('extra_properties', {}) \ .get('id') self.compute_api.attach_volume(context, server_id, volume_id, device_name) self._wait_for_volume_status(context, volume_id, server_id, 'in-use') if not CONF.is_active_detach_volume: self.compute_api.start_server(context, vgw_id) resouce_common._await_instance_status(context, vgw_id, 'ACTIVE') except Exception as e: LOG.error(_LE('Error from handle volume of vm after' ' clone.' 'Error=%(e)s'), {'e': e}) def _detach_server_temporary_port(self, context, server_res): # Read template file of this plan server_id = server_res.get('extra_properties', {}).get('id') migrate_port = server_res.get('extra_properties', {}) \ .get('migrate_port_id') if server_res.get('extra_properties', {}).get('is_deacidized'): if not server_id or not migrate_port: return try: self.compute_api.migrate_interface_detach(context, server_id, migrate_port) LOG.debug("Detach migrate port of server <%s> succeed.", server_id) except Exception as e: LOG.error("Fail to detach migrate port of server <%s>. %s", server_id, unicode(e))
Hybrid-Cloud/conveyor
conveyor/clone/drivers/openstack/driver.py
Python
apache-2.0
31,506
/* * Copyright 2015 Ayuget * * 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.ayuget.redface.ui; import com.ayuget.redface.RedfaceApp; import com.ayuget.redface.account.AccountModule; import com.ayuget.redface.account.UserManager; import com.ayuget.redface.image.ImageModule; import com.ayuget.redface.settings.RedfaceSettings; import com.ayuget.redface.ui.activity.AccountActivity; import com.ayuget.redface.ui.activity.EditPostActivity; import com.ayuget.redface.ui.activity.ExifDetailsActivity; import com.ayuget.redface.ui.activity.ImageSharingActivity; import com.ayuget.redface.ui.activity.PrivateMessagesActivity; import com.ayuget.redface.ui.activity.ReplyActivity; import com.ayuget.redface.ui.activity.SettingsActivity; import com.ayuget.redface.ui.activity.TopicsActivity; import com.ayuget.redface.ui.activity.WritePrivateMessageActivity; import com.ayuget.redface.ui.fragment.DefaultFragment; import com.ayuget.redface.ui.fragment.DetailsDefaultFragment; import com.ayuget.redface.ui.fragment.HomePreferenceFragment; import com.ayuget.redface.ui.fragment.MetaPageFragment; import com.ayuget.redface.ui.fragment.NestedPreferenceFragment; import com.ayuget.redface.ui.fragment.PostsFragment; import com.ayuget.redface.ui.fragment.PrivateMessageListFragment; import com.ayuget.redface.ui.fragment.TopicFragment; import com.ayuget.redface.ui.fragment.TopicListFragment; import com.ayuget.redface.ui.misc.ImageMenuHandler; import com.ayuget.redface.ui.misc.ThemeManager; import com.ayuget.redface.ui.template.AvatarTemplate; import com.ayuget.redface.ui.template.PostActionsTemplate; import com.ayuget.redface.ui.template.PostExtraDetailsTemplate; import com.ayuget.redface.ui.template.PostTemplate; import com.ayuget.redface.ui.template.PostsTemplate; import com.ayuget.redface.ui.template.QuickActionsTemplate; import com.ayuget.redface.ui.template.SmileyTemplate; import com.ayuget.redface.ui.template.SmileysTemplate; import com.ayuget.redface.ui.view.SmileySelectorView; import com.ayuget.redface.ui.view.TopicPageView; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; @Module( includes = { AccountModule.class, ImageModule.class }, injects = { TopicsActivity.class, TopicListFragment.class, TopicPageView.class, PostsFragment.class, TopicFragment.class, DefaultFragment.class, DetailsDefaultFragment.class, AccountActivity.class, ReplyActivity.class, SmileySelectorView.class, NestedPreferenceFragment.class, HomePreferenceFragment.class, SettingsActivity.class, EditPostActivity.class, MetaPageFragment.class, PrivateMessagesActivity.class, PrivateMessageListFragment.class, WritePrivateMessageActivity.class, ExifDetailsActivity.class, ImageSharingActivity.class }, library = true, complete = false ) public class UIModule { @Provides @Singleton AvatarTemplate provideAvatarTemplate(RedfaceApp app) { return new AvatarTemplate(app.getApplicationContext()); } @Provides @Singleton SmileyTemplate provideSmileyTemplate(RedfaceApp app) { return new SmileyTemplate(app.getApplicationContext()); } @Provides @Singleton QuickActionsTemplate provideQuickActions(RedfaceApp app, UserManager userManager) { return new QuickActionsTemplate(app.getApplicationContext(), userManager); } @Provides @Singleton PostTemplate providePostTemplate(RedfaceApp app, UserManager userManager, AvatarTemplate avatarTemplate, PostExtraDetailsTemplate extraDetailsTemplate, PostActionsTemplate postActionsTemplate, QuickActionsTemplate quickActionsTemplate, RedfaceSettings appSettings) { return new PostTemplate(app.getApplicationContext(), userManager, avatarTemplate, extraDetailsTemplate, postActionsTemplate, quickActionsTemplate, appSettings); } @Provides @Singleton PostsTemplate providePostsTemplate(RedfaceApp app, PostTemplate postTemplate, ThemeManager themeManager) { return new PostsTemplate(app.getApplicationContext(), postTemplate, themeManager); } @Provides @Singleton SmileysTemplate provideSmileysTemplate(RedfaceApp app, SmileyTemplate smileyTemplate, ThemeManager themeManager) { return new SmileysTemplate(app.getApplicationContext(), smileyTemplate, themeManager); } @Provides @Singleton PostActionsTemplate providePostActionsTemplate(RedfaceApp app, UserManager userManager) { return new PostActionsTemplate(app.getApplicationContext(), userManager); } @Provides @Singleton PostExtraDetailsTemplate providePostExtraDetailsTemplate(RedfaceApp app) { return new PostExtraDetailsTemplate(app.getApplicationContext()); } @Provides @Singleton ThemeManager provideThemeManager(RedfaceSettings settings) { return new ThemeManager(settings); } }
nbonnec/Redface
app/src/main/java/com/ayuget/redface/ui/UIModule.java
Java
apache-2.0
5,666
using System; namespace NuGet { public interface IPackageManager { IFileSystem FileSystem { get; set; } IPackageRepository LocalRepository { get; } ILogger Logger { get; set; } IPackageRepository SourceRepository { get; } event EventHandler<PackageOperationEventArgs> PackageInstalled; event EventHandler<PackageOperationEventArgs> PackageInstalling; event EventHandler<PackageOperationEventArgs> PackageUninstalled; event EventHandler<PackageOperationEventArgs> PackageUninstalling; void InstallPackage(IPackage package, bool ignoreDependencies); void InstallPackage(string packageId, Version version, bool ignoreDependencies); void UpdatePackage(IPackage oldPackage, IPackage newPackage, bool updateDependencies); void UpdatePackage(string packageId, Version version, bool updateDependencies); void UninstallPackage(IPackage package, bool forceRemove, bool removeDependencies); void UninstallPackage(string packageId, Version version, bool forceRemove, bool removeDependencies); } }
grendello/nuget
src/Core/IPackageManager.cs
C#
apache-2.0
1,128
package de.tomjanke.lost.game.action; import de.tomjanke.lost.game.world.WorldObject; /** * Created by Tom on 28.05.2016. */ public class WorldObjectAction extends Action { public WorldObject Object; public WorldObjectAction(WorldObject o, float d, Runnable r) { super(d, r); Object = o; } public WorldObjectAction(WorldObject o, float d) { super(d); Object = o; } }
Tom7353/Lost
core/src/de/tomjanke/lost/game/action/WorldObjectAction.java
Java
apache-2.0
427
package org.peace.savingtracker.ui.home; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import butterknife.OnClick; import org.peace.savingtracker.MyApp; import org.peace.savingtracker.R; import org.peace.savingtracker.ui.AddExpenseActivity; import org.peace.savingtracker.ui.accountbook.AddAccountBookActivity; import org.peace.savingtracker.ui.accountbook.SelectAccountBookActivity; import org.peace.savingtracker.ui.user.FriendListActivity; import org.peace.savingtracker.ui.user.MessageCenterActivity; import org.peace.savingtracker.ui.user.SearchUserActivity; import org.peace.savingtracker.ui.user.UserActivity; import org.peace.savingtracker.utils.ResUtil; /** * Created by peacepassion on 15/12/19. */ public class HomeUserCenterFragment extends BaseHomeFragment { public static HomeUserCenterFragment newInstance() { return new HomeUserCenterFragment(); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @OnClick({ R.id.user_center, R.id.add_account_book, R.id.select_account_book, R.id.search_user, R.id.message_center, R.id.friend_list }) public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.user_center: startActivity(new Intent(activity, UserActivity.class)); break; case R.id.add_account_book: startActivity(new Intent(activity, AddAccountBookActivity.class)); break; case R.id.select_account_book: startActivity(new Intent(activity, SelectAccountBookActivity.class)); break; case R.id.search_user: startActivity(new Intent(activity, SearchUserActivity.class)); break; case R.id.message_center: startActivity(new Intent(activity, MessageCenterActivity.class)); break; case R.id.friend_list: startActivity(new Intent(activity, FriendListActivity.class)); break; default: break; } } @Override protected int getLayoutRes() { return R.layout.fragment_home_user_center; } @Override public String getTitle() { return ResUtil.getString(R.string.user_center); } }
peacepassion/SavingTracker
app/src/main/java/org/peace/savingtracker/ui/home/HomeUserCenterFragment.java
Java
apache-2.0
2,275
/* * Copyright 2015 Open Networking Laboratory * * 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.onosproject.rest; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Lists; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DeviceId; import org.onosproject.net.Link; import org.onosproject.net.PortNumber; import org.onosproject.net.topology.ClusterId; import org.onosproject.net.topology.Topology; import org.onosproject.net.topology.TopologyCluster; import org.onosproject.net.topology.TopologyService; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import static org.onlab.util.Tools.nullIsNotFound; /** * REST resource for interacting with the inventory of clusters. */ @Path("topology") public class TopologyWebResource extends AbstractWebResource { public static final String CLUSTER_NOT_FOUND = "Cluster is not found"; /** * Gets the topology overview for a REST GET operation. * * @return topology overview */ @GET @Produces(MediaType.APPLICATION_JSON) public Response getTopology() { Topology topology = get(TopologyService.class).currentTopology(); ObjectNode root = codec(Topology.class).encode(topology, this); return ok(root).build(); } /** * Gets the topology clusters overview for a REST GET operation. * * @return topology clusters overview */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("clusters") public Response getClusters() { TopologyService service = get(TopologyService.class); Topology topology = service.currentTopology(); Iterable<TopologyCluster> clusters = service.getClusters(topology); ObjectNode root = encodeArray(TopologyCluster.class, "clusters", clusters); return ok(root).build(); } /** * Gets details for a topology cluster for a REST GET operation. * * @param clusterId id of the cluster to query * @return topology cluster details */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("clusters/{id}") public Response getCluster(@PathParam("id") int clusterId) { Topology topology = get(TopologyService.class).currentTopology(); TopologyCluster cluster = getTopologyCluster(clusterId, topology); ObjectNode root = codec(TopologyCluster.class).encode(cluster, this); return ok(root).build(); } private TopologyCluster getTopologyCluster(int clusterId, Topology topology) { return nullIsNotFound( get(TopologyService.class) .getCluster(topology, ClusterId.clusterId(clusterId)), CLUSTER_NOT_FOUND); } /** * Gets devices for a topology cluster for a REST GET operation. * * @param clusterId id of the cluster to query * @return topology cluster devices */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("clusters/{id}/devices") public Response getClusterDevices(@PathParam("id") int clusterId) { TopologyService service = get(TopologyService.class); Topology topology = service.currentTopology(); TopologyCluster cluster = getTopologyCluster(clusterId, topology); List<DeviceId> deviceIds = Lists.newArrayList(service.getClusterDevices(topology, cluster)); ObjectNode root = mapper().createObjectNode(); ArrayNode devicesNode = root.putArray("devices"); deviceIds.forEach(id -> devicesNode.add(id.toString())); return ok(root).build(); } /** * Gets links for a topology cluster for a REST GET operation. * * @param clusterId id of the cluster to query * @return topology cluster links */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("clusters/{id}/links") public Response getClusterLinks(@PathParam("id") int clusterId) { Topology topology = get(TopologyService.class).currentTopology(); TopologyCluster cluster = getTopologyCluster(clusterId, topology); List<Link> links = Lists.newArrayList(get(TopologyService.class) .getClusterLinks(topology, cluster)); return ok(encodeArray(Link.class, "links", links)).build(); } /** * Extracts the port number portion of the ConnectPoint. * * @param deviceString string representing the device/port * @return port number as a string, empty string if the port is not found */ private static String getPortNumber(String deviceString) { int separator = deviceString.lastIndexOf(':'); if (separator <= 0) { return ""; } return deviceString.substring(separator + 1, deviceString.length()); } /** * Extracts the device ID portion of the ConnectPoint. * * @param deviceString string representing the device/port * @return device ID string */ private static String getDeviceId(String deviceString) { int separator = deviceString.lastIndexOf(':'); if (separator <= 0) { return ""; } return deviceString.substring(0, separator); } /** * Gets the broadcast flag of a connect point for a REST GET operation. * * @param connectPointString string representation of the connect point to query. * Format is deviceid:portnumber * @return JSON representation of true if the connect point is broadcast, * false otherwise */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("broadcast/{connectPoint}") public Response getConnectPointBroadcast( @PathParam("connectPoint") String connectPointString) { Topology topology = get(TopologyService.class).currentTopology(); DeviceId deviceId = DeviceId.deviceId(getDeviceId(connectPointString)); PortNumber portNumber = PortNumber.portNumber(getPortNumber(connectPointString)); ConnectPoint connectPoint = new ConnectPoint(deviceId, portNumber); boolean isBroadcast = get(TopologyService.class).isBroadcastPoint(topology, connectPoint); return ok(mapper() .createObjectNode() .put("broadcast", isBroadcast)) .build(); } /** * Gets the infrastructure flag of a connect point for a REST GET operation. * * @param connectPointString string representation of the connect point to query. * Format is deviceid:portnumber * @return JSON representation of true if the connect point is broadcast, * false otherwise */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("infrastructure/{connectPoint}") public Response getConnectPointInfrastructure( @PathParam("connectPoint") String connectPointString) { Topology topology = get(TopologyService.class).currentTopology(); DeviceId deviceId = DeviceId.deviceId(getDeviceId(connectPointString)); PortNumber portNumber = PortNumber.portNumber(getPortNumber(connectPointString)); ConnectPoint connectPoint = new ConnectPoint(deviceId, portNumber); boolean isInfrastructure = get(TopologyService.class).isInfrastructure(topology, connectPoint); return ok(mapper() .createObjectNode() .put("infrastructure", isInfrastructure)) .build(); } }
ravikumaran2015/ravikumaran201504
web/api/src/main/java/org/onosproject/rest/TopologyWebResource.java
Java
apache-2.0
8,214
/** * * No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 1.6.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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.gatebuzz.oxfordapi.model; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Schema for the &#39;sentences&#39; endpoint */ public class SentencesResults { @SerializedName("metadata") private Object metadata = null; @SerializedName("results") private List<SentencesEntry> results = new ArrayList<SentencesEntry>(); public SentencesResults metadata(Object metadata) { this.metadata = metadata; return this; } /** * Additional Information provided by OUP * @return metadata **/ public Object getMetadata() { return metadata; } public void setMetadata(Object metadata) { this.metadata = metadata; } public SentencesResults results(List<SentencesEntry> results) { this.results = results; return this; } public SentencesResults addResultsItem(SentencesEntry resultsItem) { this.results.add(resultsItem); return this; } /** * A list of entries and all the data related to them * @return results **/ public List<SentencesEntry> getResults() { return results; } public void setResults(List<SentencesEntry> results) { this.results = results; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SentencesResults sentencesResults = (SentencesResults) o; return Objects.equals(this.metadata, sentencesResults.metadata) && Objects.equals(this.results, sentencesResults.results); } @Override public int hashCode() { return Objects.hash(metadata, results); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SentencesResults {\n"); sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); sb.append(" results: ").append(toIndentedString(results)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
psh/OxfordDictionarySample
app/src/main/java/com/gatebuzz/oxfordapi/model/SentencesResults.java
Java
apache-2.0
3,199
/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include "JointClientContext.h" #include <osvr/Common/SystemComponent.h> #include <osvr/Common/CreateDevice.h> #include <osvr/Common/PathTreeFull.h> #include <osvr/Common/PathElementTools.h> #include <osvr/Common/PathElementTypes.h> #include <osvr/Common/ClientInterface.h> #include <osvr/Util/Verbosity.h> #include <osvr/Common/DeduplicatingFunctionWrapper.h> #include <osvr/Connection/Connection.h> #include <osvr/Server/Server.h> // Library/third-party includes #include <json/value.h> // Standard includes #include <unordered_set> #include <thread> namespace osvr { namespace client { static const auto HOST = "localhost"; static const std::chrono::milliseconds STARTUP_CONNECT_TIMEOUT(200); static const std::chrono::milliseconds STARTUP_TREE_TIMEOUT(1000); static const std::chrono::milliseconds STARTUP_LOOP_SLEEP(1); JointClientContext::JointClientContext(const char appId[], common::ClientContextDeleter del) : ::OSVR_ClientContextObject(appId, del), m_ifaceMgr(m_pathTreeOwner, m_factory, *static_cast<common::ClientContext *>(this)) { /// Create all the remote handler factories. populateRemoteHandlerFactory(m_factory, m_vrpnConns); /// creates the OSVR connection with its nested VRPN connection auto conn = connection::Connection::createLoopbackConnection(); /// Get the VRPN connection out and use it. m_mainConn = static_cast<vrpn_Connection *>(std::get<0>(conn)); m_vrpnConns.addConnection(m_mainConn, HOST); BOOST_ASSERT(!m_vrpnConns.empty()); /// Get the OSVR connection out and use it to make a server. m_server = server::Server::createNonListening(std::get<1>(conn)); std::string sysDeviceName = std::string(common::SystemComponent::deviceName()) + "@" + HOST; /// Create the system client device. m_systemDevice = common::createClientDevice(sysDeviceName, m_mainConn); m_systemComponent = m_systemDevice->addComponent(common::SystemComponent::create()); typedef common::DeduplicatingFunctionWrapper<Json::Value const &> DedupJsonFunction; using DedupJsonFunction = common::DeduplicatingFunctionWrapper<Json::Value const &>; m_systemComponent->registerReplaceTreeHandler( DedupJsonFunction([&](Json::Value nodes) { OSVR_DEV_VERBOSE("Got updated path tree, processing"); // Tree observers will handle destruction/creation of remote // handlers. m_pathTreeOwner.replaceTree(nodes); })); } JointClientContext::~JointClientContext() {} void JointClientContext::m_update() { /// Run the server m_server->update(); /// Mainloop connections m_vrpnConns.updateAll(); /// Update system device m_systemDevice->update(); /// Update handlers. m_ifaceMgr.updateHandlers(); } void JointClientContext::m_sendRoute(std::string const &route) { m_systemComponent->sendClientRouteUpdate(route); m_update(); } void JointClientContext::m_handleNewInterface( common::ClientInterfacePtr const &iface) { m_ifaceMgr.addInterface(iface); } void JointClientContext::m_handleReleasingInterface( common::ClientInterfacePtr const &iface) { m_ifaceMgr.releaseInterface(iface); } bool JointClientContext::m_getStatus() const { /// Always connected, but don't always have a path tree. return bool(m_pathTreeOwner); } common::PathTree const &JointClientContext::m_getPathTree() const { return m_pathTreeOwner.get(); } } // namespace client } // namespace osvr
leemichaelRazer/OSVR-Core
src/osvr/JointClientKit/JointClientContext.cpp
C++
apache-2.0
4,568
/* * Implementation of scanner for rational number calculator * CSE 374, 17wi, HP */ #include "token.h" #include "scan.h" #include <string> #include <cctype> #include <cstdlib> using namespace std; // Next unprocessed token on current input line. // Undefined if set_input has not been called. token next_tok; // Current input line. // line[pos..line.size()-1] is the unprocessed part of the line string line = ""; string::size_type pos = 0; // Advance next_tok to next token on current input line, if any. // If next_tok.kind == EOL, then return and leave next_tok unaltered. // pre: set_input has been called. void scan() { string::size_type nextpos; // declared here to get rid of a g++ warning if (next_tok.kind ==EOL) { return; } // Skip whitespace. while (pos < line.size() && isspace(line[pos])) { pos++; } // Skipped leading whitespace. Either past end of line, or // next character is not blank. Return if past end of line. if (pos >= line.size()) { next_tok.kind = EOL; return; } // next character is not blank. classify and return next token. switch(line[pos]) { // single-character tokens case '+': next_tok.kind = PLUS; pos++; return; case '-': next_tok.kind = MINUS; pos++; return; case '*': next_tok.kind = TIMES; pos++; return; case '%': next_tok.kind = DIV; pos++; return; case '/': next_tok.kind = SLASH; pos++; return; case '(': next_tok.kind = LPAREN; pos++; return; case ')': next_tok.kind = RPAREN; pos++; return; // integer tokens case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // line[pos] is a digit. // Find last digit in the integer. nextpos = pos+1; while (nextpos < line.size() && isdigit(line[nextpos])) { nextpos++; } // line[pos..nextpos-1] holds the integer characters next_tok.kind = INT; next_tok.ival = atoi(line.substr(pos, nextpos-pos).c_str()); pos = nextpos; return; // unknown character in input default: next_tok.kind = UNKNOWN; pos++; return; } } // Set input line to new_line and advance next_tok to the first token // in that new line (which might be EOL if the line is empty). void set_input(string new_line) { line = new_line; pos = 0; next_tok.kind = UNKNOWN; scan(); }
zachcwillson/uw-cse
cse-374/project-7/scan.cpp
C++
apache-2.0
2,365
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.AspNetCore.SignalR.Internal { internal class HubContext<THub, T> : IHubContext<THub, T> where THub : Hub<T> where T : class { private readonly HubLifetimeManager<THub> _lifetimeManager; private readonly IHubClients<T> _clients; public HubContext(HubLifetimeManager<THub> lifetimeManager) { _lifetimeManager = lifetimeManager; _clients = new HubClients<THub, T>(_lifetimeManager); Groups = new GroupManager<THub>(lifetimeManager); } public IHubClients<T> Clients => _clients; public virtual IGroupManager Groups { get; } } }
aspnet/AspNetCore
src/SignalR/server/Core/src/Internal/HubContext`T.cs
C#
apache-2.0
802
<?php /** * bloodstone community V1.0.0 * @link https://www.facebook.com/Mazn.touati * @author Mazen Touati * @version 1.0.0 */ class Application { protected $controller = 'home', $method = 'index', $params = []; static $prefix = URL; /** * */ public function __construct() { //parse the URL to get the Controller, methods and params $url = $this->parseUrl(); if (isset($url)) { //if the controller exist if (file_exists('../application/controllers/'.$url[0].'.php')) { $this->controller = $url[0]; unset($url[0]); } else { //or show 404 error $this->controller = 'error'; } } //require the Controller require_once '../application/controllers/'.$this->controller.'.php'; //make an instance for controller $this->controller = new $this->controller; //if there's a method in the url if (isset($url[1])) { if (method_exists($this->controller, $url[1])) { //put the method in the holder $this->method = $url[1]; unset($url[1]); } } //if there's params $this->params = $url ? array_values($url) : []; //if the given method is wrong show 404 error if (!method_exists($this->controller, $this->method)) header('Location: ' . URL . 'error'); //call the controller method from the holders and pass the params call_user_func_array([$this->controller, $this->method], $this->params); } /** * @return array */ public function parseUrl() { if (isset($_GET['url'])) return explode('/',filter_var(rtrim($_GET['url'],'/'), FILTER_SANITIZE_URL)); } }
MazenDesigns/bscommunity
application/core/application.php
PHP
apache-2.0
1,928
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; /** * * * <pre> * </pre> * * Protobuf type {@code google.cloud.compute.v1.ManagedInstanceLastAttempt} */ public final class ManagedInstanceLastAttempt extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.ManagedInstanceLastAttempt) ManagedInstanceLastAttemptOrBuilder { private static final long serialVersionUID = 0L; // Use ManagedInstanceLastAttempt.newBuilder() to construct. private ManagedInstanceLastAttempt(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ManagedInstanceLastAttempt() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ManagedInstanceLastAttempt(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ManagedInstanceLastAttempt( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case -1767146662: { com.google.cloud.compute.v1.Errors.Builder subBuilder = null; if (((bitField0_ & 0x00000001) != 0)) { subBuilder = errors_.toBuilder(); } errors_ = input.readMessage(com.google.cloud.compute.v1.Errors.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(errors_); errors_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000001; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ManagedInstanceLastAttempt_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ManagedInstanceLastAttempt_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.ManagedInstanceLastAttempt.class, com.google.cloud.compute.v1.ManagedInstanceLastAttempt.Builder.class); } private int bitField0_; public static final int ERRORS_FIELD_NUMBER = 315977579; private com.google.cloud.compute.v1.Errors errors_; /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> * * @return Whether the errors field is set. */ @java.lang.Override public boolean hasErrors() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> * * @return The errors. */ @java.lang.Override public com.google.cloud.compute.v1.Errors getErrors() { return errors_ == null ? com.google.cloud.compute.v1.Errors.getDefaultInstance() : errors_; } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ @java.lang.Override public com.google.cloud.compute.v1.ErrorsOrBuilder getErrorsOrBuilder() { return errors_ == null ? com.google.cloud.compute.v1.Errors.getDefaultInstance() : errors_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(315977579, getErrors()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(315977579, getErrors()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.ManagedInstanceLastAttempt)) { return super.equals(obj); } com.google.cloud.compute.v1.ManagedInstanceLastAttempt other = (com.google.cloud.compute.v1.ManagedInstanceLastAttempt) obj; if (hasErrors() != other.hasErrors()) return false; if (hasErrors()) { if (!getErrors().equals(other.getErrors())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasErrors()) { hash = (37 * hash) + ERRORS_FIELD_NUMBER; hash = (53 * hash) + getErrors().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.compute.v1.ManagedInstanceLastAttempt prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * </pre> * * Protobuf type {@code google.cloud.compute.v1.ManagedInstanceLastAttempt} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.ManagedInstanceLastAttempt) com.google.cloud.compute.v1.ManagedInstanceLastAttemptOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ManagedInstanceLastAttempt_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ManagedInstanceLastAttempt_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.ManagedInstanceLastAttempt.class, com.google.cloud.compute.v1.ManagedInstanceLastAttempt.Builder.class); } // Construct using com.google.cloud.compute.v1.ManagedInstanceLastAttempt.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getErrorsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (errorsBuilder_ == null) { errors_ = null; } else { errorsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ManagedInstanceLastAttempt_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.ManagedInstanceLastAttempt getDefaultInstanceForType() { return com.google.cloud.compute.v1.ManagedInstanceLastAttempt.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.ManagedInstanceLastAttempt build() { com.google.cloud.compute.v1.ManagedInstanceLastAttempt result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.ManagedInstanceLastAttempt buildPartial() { com.google.cloud.compute.v1.ManagedInstanceLastAttempt result = new com.google.cloud.compute.v1.ManagedInstanceLastAttempt(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { if (errorsBuilder_ == null) { result.errors_ = errors_; } else { result.errors_ = errorsBuilder_.build(); } to_bitField0_ |= 0x00000001; } result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.ManagedInstanceLastAttempt) { return mergeFrom((com.google.cloud.compute.v1.ManagedInstanceLastAttempt) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.ManagedInstanceLastAttempt other) { if (other == com.google.cloud.compute.v1.ManagedInstanceLastAttempt.getDefaultInstance()) return this; if (other.hasErrors()) { mergeErrors(other.getErrors()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.compute.v1.ManagedInstanceLastAttempt parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.compute.v1.ManagedInstanceLastAttempt) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private com.google.cloud.compute.v1.Errors errors_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.Errors, com.google.cloud.compute.v1.Errors.Builder, com.google.cloud.compute.v1.ErrorsOrBuilder> errorsBuilder_; /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> * * @return Whether the errors field is set. */ public boolean hasErrors() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> * * @return The errors. */ public com.google.cloud.compute.v1.Errors getErrors() { if (errorsBuilder_ == null) { return errors_ == null ? com.google.cloud.compute.v1.Errors.getDefaultInstance() : errors_; } else { return errorsBuilder_.getMessage(); } } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public Builder setErrors(com.google.cloud.compute.v1.Errors value) { if (errorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } errors_ = value; onChanged(); } else { errorsBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public Builder setErrors(com.google.cloud.compute.v1.Errors.Builder builderForValue) { if (errorsBuilder_ == null) { errors_ = builderForValue.build(); onChanged(); } else { errorsBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public Builder mergeErrors(com.google.cloud.compute.v1.Errors value) { if (errorsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && errors_ != null && errors_ != com.google.cloud.compute.v1.Errors.getDefaultInstance()) { errors_ = com.google.cloud.compute.v1.Errors.newBuilder(errors_) .mergeFrom(value) .buildPartial(); } else { errors_ = value; } onChanged(); } else { errorsBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public Builder clearErrors() { if (errorsBuilder_ == null) { errors_ = null; onChanged(); } else { errorsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public com.google.cloud.compute.v1.Errors.Builder getErrorsBuilder() { bitField0_ |= 0x00000001; onChanged(); return getErrorsFieldBuilder().getBuilder(); } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public com.google.cloud.compute.v1.ErrorsOrBuilder getErrorsOrBuilder() { if (errorsBuilder_ != null) { return errorsBuilder_.getMessageOrBuilder(); } else { return errors_ == null ? com.google.cloud.compute.v1.Errors.getDefaultInstance() : errors_; } } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.Errors, com.google.cloud.compute.v1.Errors.Builder, com.google.cloud.compute.v1.ErrorsOrBuilder> getErrorsFieldBuilder() { if (errorsBuilder_ == null) { errorsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.Errors, com.google.cloud.compute.v1.Errors.Builder, com.google.cloud.compute.v1.ErrorsOrBuilder>( getErrors(), getParentForChildren(), isClean()); errors_ = null; } return errorsBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.ManagedInstanceLastAttempt) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.ManagedInstanceLastAttempt) private static final com.google.cloud.compute.v1.ManagedInstanceLastAttempt DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.ManagedInstanceLastAttempt(); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ManagedInstanceLastAttempt> PARSER = new com.google.protobuf.AbstractParser<ManagedInstanceLastAttempt>() { @java.lang.Override public ManagedInstanceLastAttempt parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ManagedInstanceLastAttempt(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ManagedInstanceLastAttempt> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ManagedInstanceLastAttempt> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.ManagedInstanceLastAttempt getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/java-compute
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/ManagedInstanceLastAttempt.java
Java
apache-2.0
25,027
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; public interface VpnGatewayStatusTunnelOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.VpnGatewayStatusTunnel) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The VPN gateway interface this VPN tunnel is associated with. * </pre> * * <code>optional uint32 local_gateway_interface = 158764330;</code> * * @return Whether the localGatewayInterface field is set. */ boolean hasLocalGatewayInterface(); /** * * * <pre> * The VPN gateway interface this VPN tunnel is associated with. * </pre> * * <code>optional uint32 local_gateway_interface = 158764330;</code> * * @return The localGatewayInterface. */ int getLocalGatewayInterface(); /** * * * <pre> * The peer gateway interface this VPN tunnel is connected to, the peer gateway could either be an external VPN gateway or GCP VPN gateway. * </pre> * * <code>optional uint32 peer_gateway_interface = 214380385;</code> * * @return Whether the peerGatewayInterface field is set. */ boolean hasPeerGatewayInterface(); /** * * * <pre> * The peer gateway interface this VPN tunnel is connected to, the peer gateway could either be an external VPN gateway or GCP VPN gateway. * </pre> * * <code>optional uint32 peer_gateway_interface = 214380385;</code> * * @return The peerGatewayInterface. */ int getPeerGatewayInterface(); /** * * * <pre> * URL reference to the VPN tunnel. * </pre> * * <code>optional string tunnel_url = 78975256;</code> * * @return Whether the tunnelUrl field is set. */ boolean hasTunnelUrl(); /** * * * <pre> * URL reference to the VPN tunnel. * </pre> * * <code>optional string tunnel_url = 78975256;</code> * * @return The tunnelUrl. */ java.lang.String getTunnelUrl(); /** * * * <pre> * URL reference to the VPN tunnel. * </pre> * * <code>optional string tunnel_url = 78975256;</code> * * @return The bytes for tunnelUrl. */ com.google.protobuf.ByteString getTunnelUrlBytes(); }
googleapis/java-compute
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/VpnGatewayStatusTunnelOrBuilder.java
Java
apache-2.0
2,892
using System; using System.Threading.Tasks; using InsurgenceServerCore.ClientHandler; namespace InsurgenceServerCore.Battles { public class Battle { public Guid Id; public string Username1; public string Username2; public Client Client1; public Client Client2; public string Trainer1; public string Trainer2; public bool Activated { get; private set; } public DateTime StartTime; public DateTime LastMessageTime; public int Seed; public Battle(Client client, string username, string trainer) { Id = Guid.NewGuid(); Username1 = client.Username.ToLowerInvariant(); Username2 = username.ToLowerInvariant(); Client1 = client; Trainer1 = trainer; StartTime = DateTime.UtcNow; LastMessageTime = DateTime.UtcNow; BattleHandler.ActiveBattles.TryAdd(Id, this); Seed = new Random().Next(int.MinValue, int.MaxValue); } public async Task JoinBattle(Client client, string trainer) { Activated = true; Client2 = client; Trainer2 = trainer; LastMessageTime = DateTime.UtcNow; await SendMessage(1, $"<BAT user={Username2} result=4 trainer={Trainer2}>"); await SendMessage(2, $"<BAT user={Username1} result=4 trainer={Trainer1}>"); } public async Task SendMessage(int clientId, string message) { if (clientId == 1) { if (!Client1.IsConnected) { await Client2.SendMessage("<TRA dead>"); return; } await Client1.SendMessage(message); } else { if (!Client2.IsConnected) { await Client1.SendMessage("<TRA dead>"); return; } await Client2.SendMessage(message); } } public async Task GetRandomSeed(Client client, string turnString) { LastMessageTime = DateTime.UtcNow; int turn; if (!int.TryParse(turnString, out turn)) return; var s = (Seed << turn | Seed >> 31); if (client.UserId == Client1.UserId) await SendMessage(1, $"<BAT seed={s}>"); else await SendMessage(2, $"<BAT seed={s}>"); } public async Task SendChoice(string username, string choice, string m, string rseed) { LastMessageTime = DateTime.UtcNow; if (username == Username1) { await SendMessage(2, $"<BAT choices={choice} m={m} rseed={rseed}>"); } else { await SendMessage(1, $"<BAT choices={choice} m={m} rseed={rseed}>"); } } public async Task NewPokemon(string username, string New) { LastMessageTime = DateTime.UtcNow; if (username == Username1) { await SendMessage(2, $"<BAT new={New}>"); } else { await SendMessage(1, $"<BAT new={New}>"); } } public async Task Damage(string username, string damage, string state) { LastMessageTime = DateTime.UtcNow; if (username == Username1) { await SendMessage(2, $"<BAT damage={damage} state={state}>"); } else { await SendMessage(1, $"<BAT damage={damage} state={state}>"); } } public async Task Kill(string reason) { Logger.Logger.Log($"Killing battle between {Username1} and {Username2} because of {reason}"); if (Client1 != null && Client1.Connected) await Client1.SendMessage("<TRA dead>"); if (Client2 != null && Client2.Connected) await Client2.SendMessage("<TRA dead>"); if (Client1 != null) Client1.ActiveBattle = null; if (Client2 != null) Client2.ActiveBattle = null; BattleHandler.DeleteBattle(this); } } }
Deukhoofd/InsurgenceServer
InsurgenceServerCore/Battles/Battle.cs
C#
apache-2.0
4,347
package com.github.randomcodeorg.ppplugin.data.gradle; import java.io.File; import org.gradle.api.tasks.SourceSetContainer; public class JavaSourceSetProvider implements SourceSetProvider { private final SourceSetContainer container; public JavaSourceSetProvider(SourceSetContainer container) { this.container = container; } @Override public SourceSet getByName(String name) { org.gradle.api.tasks.SourceSet set = container.getByName(name); return new SourceSet() { @Override public Iterable<File> getCompileClasspath() { return set.getCompileClasspath(); } }; } @Override public Iterable<String> getNames() { return container.getNames(); } @Override public int size() { return container.size(); } }
RandomCodeOrg/PPPluginGradle
plugin/src/main/java/com/github/randomcodeorg/ppplugin/data/gradle/JavaSourceSetProvider.java
Java
apache-2.0
751
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GDGSPCheckIn")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alefe Souza")] [assembly: AssemblyProduct("GDGSPCheckIn")] [assembly: AssemblyCopyright("Copyright © 2016 Alefe Souza")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
alefesouza/gdg-sp
Desktop/GDGSPCheckIn/Properties/AssemblyInfo.cs
C#
apache-2.0
2,406
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class demonStateSwallow : StateMachineBehaviour { private Image blackscreen; private UnityStandardAssets.Characters.FirstPerson.MouseLook ml; private Transform pcamera; private Transform player; // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { player = GameObject.FindGameObjectWithTag("Player").transform; GameObject stomach = GameObject.FindGameObjectWithTag("Finish"); pcamera = player.GetComponentInChildren<Camera>().transform; player.position = stomach.transform.position; blackscreen = GameObject.FindGameObjectWithTag("blackscreen").GetComponent<Image>(); ml = new UnityStandardAssets.Characters.FirstPerson.MouseLook(); ml.Init(player, pcamera); } // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { blackscreen.color = Color.Lerp(blackscreen.color, Color.black, Time.deltaTime); if(blackscreen.color.a >= .98f) { SceneManager.LoadScene("youlose"); } ml.LookRotation(player, pcamera); } // OnStateExit is called when a transition ends and the state machine finishes evaluating this state //override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} // OnStateMove is called right after Animator.OnAnimatorMove(). Code that processes and affects root motion should be implemented here //override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} // OnStateIK is called right after Animator.OnAnimatorIK(). Code that sets up animation IK (inverse kinematics) should be implemented here. //override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} }
carlsc2/EGDHorrorGame
HeartbeatHorror/Assets/Scripts/Demon/demonStateSwallow.cs
C#
apache-2.0
2,038
package Manager; import Tweet.Tweet; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import java.util.Arrays; import java.util.Properties; public class ServiceManager { public static void main(String[] args) throws Exception { Integer ngram = 5; if (args.length > 0) ngram = Integer.parseInt(args[0]); System.out.println("##RE##N_GRAM: " + ngram); Properties props = new Properties(); props.put("bootstrap.servers", "kafka:9092"); props.put("group.id", "group-1"); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000"); props.put("auto.offset.reset", "earliest"); props.put("session.timeout.ms", "30000"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(props); kafkaConsumer.subscribe(Arrays.asList("tweet")); while (true) { ConsumerRecords<String, String> records = kafkaConsumer.poll(100); for (ConsumerRecord<String, String> record : records) { ObjectMapper jsonParser=new ObjectMapper(); jsonParser.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); jsonParser.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); jsonParser.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); Tweet tweet = jsonParser.readValue(record.value(), Tweet.class); System.out.println("---------------------------------------------------------------------------------"); System.out.println("##RE##TWEETS: " + tweet.getText()); System.out.println("---------------------------------------------------------------------------------"); Runnable proceso1 = new Manager(tweet, 5); proceso1.run(); } } } }
eltitopera/TFM
manager/src/src/main/java/Manager/ServiceManager.java
Java
apache-2.0
2,338
package pl.npe.lpp.preprocessor.line; import java.util.Collections; import java.util.List; /** * Created by IntelliJ IDEA. * User: tomek * Date: 08.06.14 * Time: 15:01 */ public class DirectiveUsage { private String directive; private List<String> params; public DirectiveUsage(String directive, List<String> params) { this.directive = directive; this.params = params; } public String getDirective() { return directive; } public List<String> getParams() { return Collections.unmodifiableList(params); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DirectiveUsage usage = (DirectiveUsage) o; if (directive != null ? !directive.equals(usage.directive) : usage.directive != null) return false; if (params != null ? !params.equals(usage.params) : usage.params != null) return false; return true; } @Override public int hashCode() { int result = directive != null ? directive.hashCode() : 0; result = 31 * result + (params != null ? params.hashCode() : 0); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder("DirectiveUsage{"); sb.append("directive='").append(directive).append('\''); sb.append(", params=").append(params); sb.append('}'); return sb.toString(); } }
traczykowski/lpp
src/main/java/pl/npe/lpp/preprocessor/line/DirectiveUsage.java
Java
apache-2.0
1,523
/* Copyright 2007-2015 QReal Research Group * * 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 "drawRectBlock.h" #include "trikKit/robotModel/parts/trikDisplay.h" using namespace trik::blocks::details; DrawRectBlock::DrawRectBlock(kitBase::robotModel::RobotModelInterface &robotModel) : kitBase::blocksBase::common::DisplayBlock(robotModel) { } void DrawRectBlock::doJob(kitBase::robotModel::robotParts::Display &display) { auto trikDisplay = static_cast<robotModel::parts::TrikDisplay *>(&display); const int x = eval<int>("XCoordinateRect"); const int y = eval<int>("YCoordinateRect"); const int width = eval<int>("WidthRect"); const int height = eval<int>("HeightRect"); if (!errorsOccured()) { trikDisplay->drawRect(x, y, width, height); emit done(mNextBlockId); } }
dvvrd/qreal
plugins/robots/common/trikKit/src/blocks/details/drawRectBlock.cpp
C++
apache-2.0
1,307
/* * Created on 05.des.2005 * * Copyright (c) 2005, Karl Trygve Kalleberg <karltk near strategoxt.org> * * Licensed under the GNU Lesser General Public License, v2.1 */ package org.spoofax.jsglr.tests; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr.client.InvalidParseTableException; import org.spoofax.jsglr.client.ParserException; import org.spoofax.jsglr.client.imploder.TreeBuilder; import org.spoofax.terms.io.binary.TermReader; public class TestAmb extends ParseTestCase { @Override public void gwtSetUp() throws ParserException, InvalidParseTableException { super.gwtSetUp("SmallAmbLang", "txt"); } public void testAmb_1() throws InterruptedException { sglr.setTreeBuilder(new TreeBuilder()); doCompare=false; //c-sglr does not show ambiguity, sglri does??? IStrategoTerm parsed=doParseTest("amb1"); IStrategoTerm wanted=new TermReader(pf).parseFromString("Module(amb([BType,AType(\"xyz\")]))"); if(!parsed.match(wanted)) { fail(); } } }
metaborg/jsglr
org.spoofax.jsglr/test/org/spoofax/jsglr/tests/TestAmb.java
Java
apache-2.0
1,041
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.clustercontroller.core; import com.yahoo.vdslib.state.*; import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo; import com.yahoo.vespa.clustercontroller.core.hostinfo.StorageNodeStatsBridge; import org.junit.Test; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; /** * @author hakonhall */ public class ClusterStateViewTest { private final NodeInfo nodeInfo = mock(NodeInfo.class); private final ClusterStatsAggregator statsAggregator = mock(ClusterStatsAggregator.class); private final ClusterState clusterState = mock(ClusterState.class); private final ClusterStateView clusterStateView = new ClusterStateView(clusterState, statsAggregator); private HostInfo createHostInfo(String version) { return HostInfo.createHostInfo("{ \"cluster-state-version\": " + version + " }"); } @Test public void testWrongNodeType() { when(nodeInfo.isDistributor()).thenReturn(false); clusterStateView.handleUpdatedHostInfo(nodeInfo, createHostInfo("101")); verify(statsAggregator, never()).updateForDistributor(anyInt(), any()); } @Test public void testStateVersionMismatch() { when(nodeInfo.isDistributor()).thenReturn(true); when(clusterState.getVersion()).thenReturn(101); clusterStateView.handleUpdatedHostInfo(nodeInfo, createHostInfo("22")); verify(statsAggregator, never()).updateForDistributor(anyInt(), any()); } @Test public void testFailToGetStats() { when(nodeInfo.isDistributor()).thenReturn(true); when(clusterState.getVersion()).thenReturn(101); clusterStateView.handleUpdatedHostInfo(nodeInfo, createHostInfo("22")); verify(statsAggregator, never()).updateForDistributor(anyInt(), any()); } @Test public void testSuccessCase() { when(nodeInfo.isDistributor()).thenReturn(true); HostInfo hostInfo = HostInfo.createHostInfo( "{" + " \"cluster-state-version\": 101," + " \"distributor\": {\n" + " \"storage-nodes\": [\n" + " {\n" + " \"node-index\": 3\n" + " }\n" + " ]}}"); when(nodeInfo.getNodeIndex()).thenReturn(3); when(clusterState.getVersion()).thenReturn(101); clusterStateView.handleUpdatedHostInfo(nodeInfo, hostInfo); verify(statsAggregator).updateForDistributor(3, StorageNodeStatsBridge.generate(hostInfo.getDistributor())); } @Test public void testIndicesOfUpNodes() { when(clusterState.getNodeCount(NodeType.DISTRIBUTOR)).thenReturn(7); NodeState nodeState = mock(NodeState.class); when(nodeState.getState()). thenReturn(State.MAINTENANCE). // 0 thenReturn(State.RETIRED). // 1 thenReturn(State.INITIALIZING). // 2 thenReturn(State.DOWN). thenReturn(State.STOPPING). thenReturn(State.UNKNOWN). thenReturn(State.UP); // 6 when(clusterState.getNodeState(any())).thenReturn(nodeState); Set<Integer> indices = ClusterStateView.getIndicesOfUpNodes(clusterState, NodeType.DISTRIBUTOR); assertEquals(4, indices.size()); assert(indices.contains(0)); assert(indices.contains(1)); assert(indices.contains(2)); assert(indices.contains(6)); } }
vespa-engine/vespa
clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java
Java
apache-2.0
3,671
using UnityEngine; using System.Collections; public class BasicSword : Weapon { public BasicSword () { damageMultiplier = 1.0; speed = 1.0; } }
jakebacker/UnityGame
Assets/Project/Scripts/BasicSword.cs
C#
apache-2.0
154
package oob import ( "context" "github.com/google/wire" "github.com/skygeario/skygear-server/pkg/auth/dependency/urlprefix" "github.com/skygeario/skygear-server/pkg/core/async" "github.com/skygeario/skygear-server/pkg/core/config" "github.com/skygeario/skygear-server/pkg/core/db" "github.com/skygeario/skygear-server/pkg/core/template" "github.com/skygeario/skygear-server/pkg/core/time" ) func ProvideProvider( ctx context.Context, c *config.TenantConfiguration, sqlb db.SQLBuilder, sqle db.SQLExecutor, t time.Provider, te *template.Engine, upp urlprefix.Provider, tq async.Queue, ) *Provider { return &Provider{ Context: ctx, LocalizationConfiguration: c.AppConfig.Localization, MetadataConfiguration: c.AppConfig.AuthUI.Metadata, Config: c.AppConfig.Authenticator.OOB, SMSMessageConfiguration: c.AppConfig.Messages.SMS, EmailMessageConfiguration: c.AppConfig.Messages.Email, Store: &Store{SQLBuilder: sqlb, SQLExecutor: sqle}, Time: t, TemplateEngine: te, URLPrefixProvider: upp, TaskQueue: tq, } } var DependencySet = wire.NewSet(ProvideProvider)
SkygearIO/skygear-server
pkg/auth/dependency/authenticator/oob/deps.go
GO
apache-2.0
1,217
package com.softwarelma.epe.p3.print; import java.util.ArrayList; import java.util.List; import com.softwarelma.epe.p1.app.EpeAppException; import com.softwarelma.epe.p1.app.EpeAppUtils; import com.softwarelma.epe.p2.exec.EpeExecContent; import com.softwarelma.epe.p2.exec.EpeExecContentInternal; import com.softwarelma.epe.p2.exec.EpeExecParams; import com.softwarelma.epe.p2.exec.EpeExecResult; public final class EpePrintFinalPrint_separator_smart extends EpePrintAbstract { public static final String PROP_COL_SUFFIX = "col_suffix"; @Override public EpeExecResult doFunc(EpeExecParams execParams, List<EpeExecResult> listExecResult) throws EpeAppException { @SuppressWarnings("unused") String postMessage = "print_separator_smart, expected a list with the param, external and internal separators " + "and the contents to print."; String sepParam = "\n";// "\n\n"; String sepExternal = "\n"; String colSuffix = retrievePropValueOrNull("print_separator_smart", listExecResult, PROP_COL_SUFFIX); String str = retrievePrintableStrWithSeparatorsSmart(sepParam, sepExternal, listExecResult, colSuffix); log(execParams, str); return createResult(str); } public static String retrievePrintableStrWithSeparatorsSmart(String sepParam, String sepExternal, List<EpeExecResult> listExecResult, String colSuffix) throws EpeAppException { EpeAppUtils.checkNull("listExecResult", listExecResult); StringBuilder sb = new StringBuilder(); String sepParam2 = ""; for (int i = 0; i < listExecResult.size(); i++) { EpeExecResult result = listExecResult.get(i); EpeAppUtils.checkNull("result", result); EpeExecContent content = result.getExecContent(); EpeAppUtils.checkNull("content", content); if (content.isProp()) { continue; } sb.append(sepParam2); sepParam2 = sepParam; List<Integer> listWidth = retrieveWidths(content); sb.append(content.toString(sepExternal, listWidth, colSuffix)); } return sb.toString(); } private static List<Integer> retrieveWidths(EpeExecContent content) throws EpeAppException { List<Integer> listWidth = new ArrayList<>(); if (content.getContentInternal() == null) { listWidth.add(4); return listWidth; } EpeExecContentInternal contentInternal = content.getContentInternal(); if (contentInternal.isString()) { listWidth.add(contentInternal.getStr().length()); return listWidth; } else if (contentInternal.isListString()) { for (String str : contentInternal.getListStr()) { listWidth.add((str + "").length()); } return listWidth; } else if (contentInternal.isListListString()) { for (List<String> listStr : contentInternal.getListListStr()) { retrieveWidths(listStr, listWidth); } return listWidth; } else { throw new EpeAppException("Unknown internal content type"); } } private static void retrieveWidths(List<String> listStr, List<Integer> listWidth) { if (listStr == null) { return; } int width; for (int i = 0; i < listStr.size(); i++) { String str = listStr.get(i); width = (str + "").length(); if (listWidth.size() < i + 1) { listWidth.add(width); } else { if (width > listWidth.get(i)) { listWidth.set(i, width); } } } } }
softwarelma/utils
src/main/java/com/softwarelma/epe/p3/print/EpePrintFinalPrint_separator_smart.java
Java
apache-2.0
3,797
// Copyright 2018 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. package com.google.api.ads.adwords.jaxws.v201809.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Operations for adding/updating bidding strategies. * * * <p>Java class for BiddingStrategyOperation complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="BiddingStrategyOperation"> * &lt;complexContent> * &lt;extension base="{https://adwords.google.com/api/adwords/cm/v201809}Operation"> * &lt;sequence> * &lt;element name="operand" type="{https://adwords.google.com/api/adwords/cm/v201809}SharedBiddingStrategy" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BiddingStrategyOperation", propOrder = { "operand" }) public class BiddingStrategyOperation extends Operation { protected SharedBiddingStrategy operand; /** * Gets the value of the operand property. * * @return * possible object is * {@link SharedBiddingStrategy } * */ public SharedBiddingStrategy getOperand() { return operand; } /** * Sets the value of the operand property. * * @param value * allowed object is * {@link SharedBiddingStrategy } * */ public void setOperand(SharedBiddingStrategy value) { this.operand = value; } }
googleads/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201809/cm/BiddingStrategyOperation.java
Java
apache-2.0
2,228
package ikube.action; import ikube.AbstractTest; import ikube.IConstants; import ikube.action.index.IndexManager; import ikube.model.IndexContext; import ikube.toolkit.FILE; import ikube.toolkit.THREAD; import org.apache.lucene.index.IndexWriter; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; /** * @author Michael Couck * @version 01.00 * @since 21-11-2010 */ @SuppressWarnings("deprecation") public class ReopenTest extends AbstractTest { private Reopen reopen; private IndexContext indexContext; @Before public void before() { reopen = new Reopen(); indexContext = new IndexContext(); indexContext.setDelta(Boolean.TRUE); indexContext.setName(IConstants.INDEX_CONTEXT); indexContext.setIndexDirectoryPath(indexDirectoryPath); indexContext.setIndexDirectoryPathBackup(indexDirectoryPath); indexContext.setBatchSize(1000); indexContext.setBufferedDocs(1000); indexContext.setBufferSize(128); indexContext.setCompoundFile(Boolean.TRUE); indexContext.setMergeFactor(1000); FILE.deleteFile(new File(indexDirectoryPath)); } @After public void after() throws Exception { FILE.deleteFile(new File(indexContext.getIndexDirectoryPath())); } @Test public void internalExecute() throws Exception { createIndexFileSystem(indexContext, "Hello world"); // First open the index new Open().execute(indexContext); IndexWriter[] indexWriters = IndexManager.openIndexWriterDelta(indexContext); indexContext.setIndexWriters(indexWriters); // Add some documents to the index and reopen addDocuments(indexWriters[0], IConstants.CONTENTS, "Michael Couck"); boolean opened = reopen.execute(indexContext); assertTrue("The index should be open : ", opened); int docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); } private void internalExecute(final IndexContext indexContext, final int numDocsBefore) throws Exception { // Add some more documents to the index and reopen IndexWriter indexWriter = indexContext.getIndexWriters()[0]; addDocuments(indexWriter, IConstants.CONTENTS, "Michael Couck again"); commitIndexWriter(indexWriter); boolean opened = reopen.execute(indexContext); assertTrue("The index should be open : ", opened); int moreDocs = indexContext.getMultiSearcher().getIndexReader().numDocs(); assertNotSame("There should be more documents in the new multi searcher : ", numDocsBefore, moreDocs); } @Test public void memoryValidation() throws Exception { IndexWriter[] indexWriters = IndexManager.openIndexWriterDelta(indexContext); indexContext.setIndexWriters(indexWriters); // Now add documents and reopen again and again System.gc(); int iterations = 1000; long before = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / IConstants.MILLION; for (int i = iterations; i >= 0; i--) { if (i > 0 && i % 100 == 0) { indexWriters[0].commit(); indexWriters[0].forceMerge(10, Boolean.TRUE); new Reopen().execute(indexContext); printMemoryDelta(before); } addDocuments(indexWriters[0], IConstants.CONTENTS, "Michael Couck again"); THREAD.sleep(1); } printMemoryDelta(before); long after = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / IConstants.MILLION; long increase = (after - before); assertTrue(increase < 100); } }
michaelcouck/ikube
code/core/src/test/java/ikube/action/ReopenTest.java
Java
apache-2.0
4,627
/* * Copyright 2000-2017 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.application.options.schemes; import com.intellij.icons.AllIcons; import com.intellij.ide.HelpTooltip; import com.intellij.ide.actions.NonTrivialActionGroup; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.options.Scheme; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.BalloonBuilder; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.util.Disposer; import com.intellij.ui.JBColor; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.ui.JBDimension; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.Collection; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * Base panel for schemes combo box and related actions. When settings change, {@link #updateOnCurrentSettingsChange()} method must be * called to reflect the change in schemes panel. The method should be added to settings model listener. * * @param <T> The actual scheme type. * @see AbstractSchemeActions * @see SchemesModel */ public abstract class AbstractSchemesPanel<T extends Scheme, InfoComponent extends JComponent> extends JPanel { private EditableSchemesCombo<T> mySchemesCombo; private AbstractSchemeActions<T> myActions; private JComponent myToolbar; protected InfoComponent myInfoComponent; // region Colors (probably should be standard for platform UI) protected static final Color HINT_FOREGROUND = JBColor.GRAY; @SuppressWarnings("UseJBColor") protected static final Color ERROR_MESSAGE_FOREGROUND = Color.RED; protected static final int DEFAULT_VGAP = 8; // endregion public AbstractSchemesPanel() { this(DEFAULT_VGAP, null); } public AbstractSchemesPanel(int vGap) { this(vGap, null); } public AbstractSchemesPanel(int vGap, @Nullable JComponent rightCustomComponent) { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); createUIComponents(vGap, rightCustomComponent); } private void createUIComponents(int vGap, @Nullable JComponent rightCustomComponent) { final JPanel verticalContainer = rightCustomComponent != null ? createVerticalContainer() : this; JPanel controlsPanel = createControlsPanel(); verticalContainer.add(controlsPanel); verticalContainer.add(Box.createRigidArea(new JBDimension(0, 12))); if (rightCustomComponent != null) { JPanel horizontalContainer = new JPanel(); horizontalContainer.setLayout(new BoxLayout(horizontalContainer, BoxLayout.X_AXIS)); horizontalContainer.add(verticalContainer); horizontalContainer.add(Box.createHorizontalGlue()); horizontalContainer.add(rightCustomComponent); add(horizontalContainer); } add(new JSeparator()); if (vGap > 0) { add(Box.createVerticalGlue()); add(Box.createRigidArea(new JBDimension(0, vGap))); } } private static JPanel createVerticalContainer() { JPanel container = new JPanel(); container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); return container; } private JPanel createControlsPanel() { JPanel controlsPanel = new JPanel(); controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.LINE_AXIS)); String label = getComboBoxLabel(); if (label != null) { controlsPanel.add(new JLabel(label)); controlsPanel.add(Box.createRigidArea(new JBDimension(10, 0))); } myActions = createSchemeActions(); mySchemesCombo = new EditableSchemesCombo<>(this); controlsPanel.add(mySchemesCombo.getComponent()); myToolbar = createToolbar(); controlsPanel.add(Box.createRigidArea(new JBDimension(4, 0))); controlsPanel.add(myToolbar); controlsPanel.add(Box.createRigidArea(new JBDimension(9, 0))); myInfoComponent = createInfoComponent(); controlsPanel.add(myInfoComponent); controlsPanel.add(Box.createHorizontalGlue()); mySchemesCombo.getComponent().setMaximumSize(mySchemesCombo.getComponent().getPreferredSize()); int height = mySchemesCombo.getComponent().getPreferredSize().height; controlsPanel.setMaximumSize(new Dimension(controlsPanel.getMaximumSize().width, height)); return controlsPanel; } private JComponent createToolbar() { DefaultActionGroup group = new DefaultActionGroup(); group.add(new ShowSchemesActionsListAction(myActions.getActions())); ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.NAVIGATION_BAR_TOOLBAR, group, true); toolbar.setReservePlaceAutoPopupIcon(false); toolbar.setLayoutPolicy(ActionToolbar.NOWRAP_LAYOUT_POLICY); JComponent toolbarComponent = toolbar.getComponent(); toolbarComponent.setBorder(JBUI.Borders.empty(3)); return toolbarComponent; } public final JComponent getToolbar() { return myToolbar; } /** * Creates schemes actions. Used when panel UI components are created. * @return Scheme actions associated with the panel. * @see AbstractSchemeActions */ protected abstract AbstractSchemeActions<T> createSchemeActions(); public final T getSelectedScheme() { return mySchemesCombo.getSelectedScheme(); } public void selectScheme(@Nullable T scheme) { mySchemesCombo.selectScheme(scheme); } public final void resetSchemes(@NotNull Collection<T> schemes) { mySchemesCombo.resetSchemes(schemes); } public void disposeUIResources() { removeAll(); } public final void editCurrentSchemeName(@NotNull BiConsumer<T,String> newSchemeNameConsumer) { T currentScheme = getSelectedScheme(); if (currentScheme != null) { String currentName = currentScheme.getName(); mySchemesCombo.startEdit( currentName, getModel().isProjectScheme(currentScheme), newName -> { if (!newName.equals(currentName)) { newSchemeNameConsumer.accept(currentScheme, newName); } }); } } public final void editNewSchemeName(@NotNull String preferredName, boolean isProjectScheme, @NotNull Consumer<String> nameConsumer) { String name = SchemeNameGenerator.getUniqueName(preferredName, schemeName -> getModel().containsScheme(schemeName, isProjectScheme)); mySchemesCombo.startEdit(name, isProjectScheme, nameConsumer); } public final void cancelEdit() { mySchemesCombo.cancelEdit(); } public final void showInfo(@Nullable String message, @NotNull MessageType messageType) { myToolbar.setVisible(false); showMessage(message, messageType); } protected abstract void showMessage(@Nullable String message, @NotNull MessageType messageType); public final void clearInfo() { myToolbar.setVisible(true); clearMessage(); } protected abstract void clearMessage(); public final AbstractSchemeActions<T> getActions() { return myActions; } @NotNull protected abstract InfoComponent createInfoComponent(); /** * @return a string label to place before the combobox or {@code null} if it is not needed */ @Nullable protected String getComboBoxLabel() { return getSchemeTypeName() + ":"; } protected String getSchemeTypeName() { return ApplicationBundle.message("editbox.scheme.type.name"); } /** * @return Schemes model implementation. * @see SchemesModel */ @NotNull public abstract SchemesModel<T> getModel(); /** * Must be called when any settings are changed. */ public final void updateOnCurrentSettingsChange() { mySchemesCombo.updateSelected(); } /** * Returns an indent to calculate a left margin for the scheme name in the combo box. * By default, all names are aligned to the left. * * @param scheme the scheme to calculate its indent * @return an indent that shows a nesting level for the specified scheme */ protected int getIndent(@NotNull T scheme) { return 0; } /** * @return True if the panel supports project-level schemes along with IDE ones. In this case there will be * additional "Copy to Project" and "Copy to IDE" actions for IDE and project schemes respectively and Project/IDE schemes * separators. */ protected abstract boolean supportsProjectSchemes(); protected abstract boolean highlightNonDefaultSchemes(); protected boolean hideDeleteActionIfUnavailable() { return true; } public abstract boolean useBoldForNonRemovableSchemes(); public void showStatus(final String message, MessageType messageType) { BalloonBuilder balloonBuilder = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(), messageType.getPopupBackground(), null); balloonBuilder.setFadeoutTime(5000); final Balloon balloon = balloonBuilder.createBalloon(); Point pointOnComponent = new Point(myToolbar.getWidth() / 4, myToolbar.getHeight() / 4); balloon.show(new RelativePoint(myToolbar, pointOnComponent), Balloon.Position.above); Disposer.register(ProjectManager.getInstance().getDefaultProject(), balloon); } private static class ShowSchemesActionsListAction extends NonTrivialActionGroup { ShowSchemesActionsListAction(Collection<AnAction> actions) { setPopup(true); getTemplatePresentation().setIcon(AllIcons.General.GearPlain); getTemplatePresentation().setText("Show Scheme Actions"); getTemplatePresentation().setDescription("Show Scheme Actions"); addAll(actions); } @Override public boolean isDumbAware() { return true; } @Override public boolean canBePerformed(DataContext context) { return true; } @Override public void actionPerformed(AnActionEvent e) { ListPopup popup = JBPopupFactory.getInstance(). createActionGroupPopup(null, this, e.getDataContext(), true, null, Integer.MAX_VALUE); HelpTooltip.setMasterPopup(e.getInputEvent().getComponent(), popup); Component component = e.getInputEvent().getComponent(); if (component instanceof ActionButtonComponent) { popup.showUnderneathOf(component); } else { popup.showInCenterOf(component); } } } protected static void showMessage(@Nullable String message, @NotNull MessageType messageType, @NotNull JLabel infoComponent) { infoComponent.setText(message); Color foreground = messageType == MessageType.INFO ? HINT_FOREGROUND : messageType == MessageType.ERROR ? ERROR_MESSAGE_FOREGROUND : messageType.getTitleForeground(); infoComponent.setForeground(foreground); } }
sabi0/intellij-community
platform/platform-impl/src/com/intellij/application/options/schemes/AbstractSchemesPanel.java
Java
apache-2.0
11,570
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dataset utilities.""" import functools import pathlib from typing import Dict, Tuple from absl import logging from graph_nets import graphs as tf_graphs from graph_nets import utils_tf import numpy as np import scipy.sparse as sp import tensorflow as tf import tqdm # pylint: disable=g-bad-import-order import sub_sampler Path = pathlib.Path NUM_PAPERS = 121751666 NUM_AUTHORS = 122383112 NUM_INSTITUTIONS = 25721 EMBEDDING_SIZE = 768 NUM_CLASSES = 153 NUM_NODES = NUM_PAPERS + NUM_AUTHORS + NUM_INSTITUTIONS NUM_EDGES = 1_728_364_232 assert NUM_NODES == 244_160_499 NUM_K_FOLD_SPLITS = 10 OFFSETS = { "paper": 0, "author": NUM_PAPERS, "institution": NUM_PAPERS + NUM_AUTHORS, } SIZES = { "paper": NUM_PAPERS, "author": NUM_AUTHORS, "institution": NUM_INSTITUTIONS } RAW_DIR = Path("raw") PREPROCESSED_DIR = Path("preprocessed") RAW_NODE_FEATURES_FILENAME = RAW_DIR / "node_feat.npy" RAW_NODE_LABELS_FILENAME = RAW_DIR / "node_label.npy" RAW_NODE_YEAR_FILENAME = RAW_DIR / "node_year.npy" TRAIN_INDEX_FILENAME = RAW_DIR / "train_idx.npy" VALID_INDEX_FILENAME = RAW_DIR / "train_idx.npy" TEST_INDEX_FILENAME = RAW_DIR / "train_idx.npy" EDGES_PAPER_PAPER_B = PREPROCESSED_DIR / "paper_paper_b.npz" EDGES_PAPER_PAPER_B_T = PREPROCESSED_DIR / "paper_paper_b_t.npz" EDGES_AUTHOR_INSTITUTION = PREPROCESSED_DIR / "author_institution.npz" EDGES_INSTITUTION_AUTHOR = PREPROCESSED_DIR / "institution_author.npz" EDGES_AUTHOR_PAPER = PREPROCESSED_DIR / "author_paper.npz" EDGES_PAPER_AUTHOR = PREPROCESSED_DIR / "paper_author.npz" PCA_PAPER_FEATURES_FILENAME = PREPROCESSED_DIR / "paper_feat_pca_129.npy" PCA_AUTHOR_FEATURES_FILENAME = ( PREPROCESSED_DIR / "author_feat_from_paper_feat_pca_129.npy") PCA_INSTITUTION_FEATURES_FILENAME = ( PREPROCESSED_DIR / "institution_feat_from_paper_feat_pca_129.npy") PCA_MERGED_FEATURES_FILENAME = ( PREPROCESSED_DIR / "merged_feat_from_paper_feat_pca_129.npy") NEIGHBOR_INDICES_FILENAME = PREPROCESSED_DIR / "neighbor_indices.npy" NEIGHBOR_DISTANCES_FILENAME = PREPROCESSED_DIR / "neighbor_distances.npy" FUSED_NODE_LABELS_FILENAME = PREPROCESSED_DIR / "fused_node_labels.npy" FUSED_PAPER_EDGES_FILENAME = PREPROCESSED_DIR / "fused_paper_edges.npz" FUSED_PAPER_EDGES_T_FILENAME = PREPROCESSED_DIR / "fused_paper_edges_t.npz" K_FOLD_SPLITS_DIR = Path("k_fold_splits") def get_raw_directory(data_root): return Path(data_root) / "raw" def get_preprocessed_directory(data_root): return Path(data_root) / "preprocessed" def _log_path_decorator(fn): def _decorated_fn(path, **kwargs): logging.info("Loading %s", path) output = fn(path, **kwargs) logging.info("Finish loading %s", path) return output return _decorated_fn @_log_path_decorator def load_csr(path, debug=False): if debug: # Dummy matrix for debugging. return sp.csr_matrix(np.zeros([10, 10])) return sp.load_npz(str(path)) @_log_path_decorator def load_npy(path): return np.load(str(path)) @functools.lru_cache() def get_arrays(data_root="/data/", use_fused_node_labels=True, use_fused_node_adjacencies=True, return_pca_embeddings=True, k_fold_split_id=None, return_adjacencies=True, use_dummy_adjacencies=False): """Returns all arrays needed for training.""" logging.info("Starting to get files") data_root = Path(data_root) array_dict = {} array_dict["paper_year"] = load_npy(data_root / RAW_NODE_YEAR_FILENAME) if k_fold_split_id is None: train_indices = load_npy(data_root / TRAIN_INDEX_FILENAME) valid_indices = load_npy(data_root / VALID_INDEX_FILENAME) else: train_indices, valid_indices = get_train_and_valid_idx_for_split( k_fold_split_id, num_splits=NUM_K_FOLD_SPLITS, root_path=data_root / K_FOLD_SPLITS_DIR) array_dict["train_indices"] = train_indices array_dict["valid_indices"] = valid_indices array_dict["test_indices"] = load_npy(data_root / TEST_INDEX_FILENAME) if use_fused_node_labels: array_dict["paper_label"] = load_npy(data_root / FUSED_NODE_LABELS_FILENAME) else: array_dict["paper_label"] = load_npy(data_root / RAW_NODE_LABELS_FILENAME) if return_adjacencies: logging.info("Starting to get adjacencies.") if use_fused_node_adjacencies: paper_paper_index = load_csr( data_root / FUSED_PAPER_EDGES_FILENAME, debug=use_dummy_adjacencies) paper_paper_index_t = load_csr( data_root / FUSED_PAPER_EDGES_T_FILENAME, debug=use_dummy_adjacencies) else: paper_paper_index = load_csr( data_root / EDGES_PAPER_PAPER_B, debug=use_dummy_adjacencies) paper_paper_index_t = load_csr( data_root / EDGES_PAPER_PAPER_B_T, debug=use_dummy_adjacencies) array_dict.update( dict( author_institution_index=load_csr( data_root / EDGES_AUTHOR_INSTITUTION, debug=use_dummy_adjacencies), institution_author_index=load_csr( data_root / EDGES_INSTITUTION_AUTHOR, debug=use_dummy_adjacencies), author_paper_index=load_csr( data_root / EDGES_AUTHOR_PAPER, debug=use_dummy_adjacencies), paper_author_index=load_csr( data_root / EDGES_PAPER_AUTHOR, debug=use_dummy_adjacencies), paper_paper_index=paper_paper_index, paper_paper_index_t=paper_paper_index_t, )) if return_pca_embeddings: array_dict["bert_pca_129"] = np.load( data_root / PCA_MERGED_FEATURES_FILENAME, mmap_mode="r") assert array_dict["bert_pca_129"].shape == (NUM_NODES, 129) logging.info("Finish getting files") # pytype: disable=attribute-error assert array_dict["paper_year"].shape[0] == NUM_PAPERS assert array_dict["paper_label"].shape[0] == NUM_PAPERS if return_adjacencies and not use_dummy_adjacencies: array_dict = _fix_adjacency_shapes(array_dict) assert array_dict["paper_author_index"].shape == (NUM_PAPERS, NUM_AUTHORS) assert array_dict["author_paper_index"].shape == (NUM_AUTHORS, NUM_PAPERS) assert array_dict["paper_paper_index"].shape == (NUM_PAPERS, NUM_PAPERS) assert array_dict["paper_paper_index_t"].shape == (NUM_PAPERS, NUM_PAPERS) assert array_dict["institution_author_index"].shape == ( NUM_INSTITUTIONS, NUM_AUTHORS) assert array_dict["author_institution_index"].shape == ( NUM_AUTHORS, NUM_INSTITUTIONS) # pytype: enable=attribute-error return array_dict def add_nodes_year(graph, paper_year): nodes = graph.nodes.copy() indices = nodes["index"] year = paper_year[np.minimum(indices, paper_year.shape[0] - 1)].copy() year[nodes["type"] != 0] = 1900 nodes["year"] = year return graph._replace(nodes=nodes) def add_nodes_label(graph, paper_label): nodes = graph.nodes.copy() indices = nodes["index"] label = paper_label[np.minimum(indices, paper_label.shape[0] - 1)] label[nodes["type"] != 0] = 0 nodes["label"] = label return graph._replace(nodes=nodes) def add_nodes_embedding_from_array(graph, array): """Adds embeddings from the sstable_service for the indices.""" nodes = graph.nodes.copy() indices = nodes["index"] embedding_indices = indices.copy() embedding_indices[nodes["type"] == 1] += NUM_PAPERS embedding_indices[nodes["type"] == 2] += NUM_PAPERS + NUM_AUTHORS # Gather the embeddings for the indices. nodes["features"] = array[embedding_indices] return graph._replace(nodes=nodes) def get_graph_subsampling_dataset( prefix, arrays, shuffle_indices, ratio_unlabeled_data_to_labeled_data, max_nodes, max_edges, **subsampler_kwargs): """Returns tf_dataset for online sampling.""" def generator(): labeled_indices = arrays[f"{prefix}_indices"] if ratio_unlabeled_data_to_labeled_data > 0: num_unlabeled_data_to_add = int(ratio_unlabeled_data_to_labeled_data * labeled_indices.shape[0]) unlabeled_indices = np.random.choice( NUM_PAPERS, size=num_unlabeled_data_to_add, replace=False) root_node_indices = np.concatenate([labeled_indices, unlabeled_indices]) else: root_node_indices = labeled_indices if shuffle_indices: root_node_indices = root_node_indices.copy() np.random.shuffle(root_node_indices) for index in root_node_indices: graph = sub_sampler.subsample_graph( index, arrays["author_institution_index"], arrays["institution_author_index"], arrays["author_paper_index"], arrays["paper_author_index"], arrays["paper_paper_index"], arrays["paper_paper_index_t"], paper_years=arrays["paper_year"], max_nodes=max_nodes, max_edges=max_edges, **subsampler_kwargs) graph = add_nodes_label(graph, arrays["paper_label"]) graph = add_nodes_year(graph, arrays["paper_year"]) graph = tf_graphs.GraphsTuple(*graph) yield graph sample_graph = next(generator()) return tf.data.Dataset.from_generator( generator, output_signature=utils_tf.specs_from_graphs_tuple(sample_graph)) def paper_features_to_author_features( author_paper_index, paper_features): """Averages paper features to authors.""" assert paper_features.shape[0] == NUM_PAPERS assert author_paper_index.shape[0] == NUM_AUTHORS author_features = np.zeros( [NUM_AUTHORS, paper_features.shape[1]], dtype=paper_features.dtype) for author_i in range(NUM_AUTHORS): paper_indices = author_paper_index[author_i].indices author_features[author_i] = paper_features[paper_indices].mean( axis=0, dtype=np.float32) if author_i % 10000 == 0: logging.info("%d/%d", author_i, NUM_AUTHORS) return author_features def author_features_to_institution_features( institution_author_index, author_features): """Averages author features to institutions.""" assert author_features.shape[0] == NUM_AUTHORS assert institution_author_index.shape[0] == NUM_INSTITUTIONS institution_features = np.zeros( [NUM_INSTITUTIONS, author_features.shape[1]], dtype=author_features.dtype) for institution_i in range(NUM_INSTITUTIONS): author_indices = institution_author_index[institution_i].indices institution_features[institution_i] = author_features[ author_indices].mean(axis=0, dtype=np.float32) if institution_i % 10000 == 0: logging.info("%d/%d", institution_i, NUM_INSTITUTIONS) return institution_features def generate_fused_paper_adjacency_matrix(neighbor_indices, neighbor_distances, paper_paper_csr): """Generates fused adjacency matrix for identical nodes.""" # First construct set of identical node indices. # NOTE: Since we take only top K=26 identical pairs for each node, this is not # actually exhaustive. Also, if A and B are equal, and B and C are equal, # this method would not necessarily detect A and C being equal. # However, this should capture almost all cases. logging.info("Generating fused paper adjacency matrix") eps = 0.0 mask = ((neighbor_indices != np.mgrid[:neighbor_indices.shape[0], :1]) & (neighbor_distances <= eps)) identical_pairs = list(map(tuple, np.nonzero(mask))) del mask # Have a csc version for fast column access. paper_paper_csc = paper_paper_csr.tocsc() # Construct new matrix as coo, starting off with original rows/cols. paper_paper_coo = paper_paper_csr.tocoo() new_rows = [paper_paper_coo.row] new_cols = [paper_paper_coo.col] for pair in tqdm.tqdm(identical_pairs): # STEP ONE: First merge papers being cited by the pair. # Add edges from second paper, to all papers cited by first paper. cited_by_first = paper_paper_csr.getrow(pair[0]).nonzero()[1] if cited_by_first.shape[0] > 0: new_rows.append(pair[1] * np.ones_like(cited_by_first)) new_cols.append(cited_by_first) # Add edges from first paper, to all papers cited by second paper. cited_by_second = paper_paper_csr.getrow(pair[1]).nonzero()[1] if cited_by_second.shape[0] > 0: new_rows.append(pair[0] * np.ones_like(cited_by_second)) new_cols.append(cited_by_second) # STEP TWO: Then merge papers that cite the pair. # Add edges to second paper, from all papers citing the first paper. citing_first = paper_paper_csc.getcol(pair[0]).nonzero()[0] if citing_first.shape[0] > 0: new_rows.append(citing_first) new_cols.append(pair[1] * np.ones_like(citing_first)) # Add edges to first paper, from all papers citing the second paper. citing_second = paper_paper_csc.getcol(pair[1]).nonzero()[0] if citing_second.shape[0] > 0: new_rows.append(citing_second) new_cols.append(pair[0] * np.ones_like(citing_second)) logging.info("Done with adjacency loop") paper_paper_coo_shape = paper_paper_coo.shape del paper_paper_csr del paper_paper_csc del paper_paper_coo # All done; now concatenate everything together and form new matrix. new_rows = np.concatenate(new_rows) new_cols = np.concatenate(new_cols) return sp.coo_matrix( (np.ones_like(new_rows, dtype=np.bool), (new_rows, new_cols)), shape=paper_paper_coo_shape).tocsr() def generate_k_fold_splits( train_idx, valid_idx, output_path, num_splits=NUM_K_FOLD_SPLITS): """Generates splits adding fractions of the validation split to training.""" output_path = Path(output_path) np.random.seed(42) valid_idx = np.random.permutation(valid_idx) # Split into `num_parts` (almost) identically sized arrays. valid_idx_parts = np.array_split(valid_idx, num_splits) for i in range(num_splits): # Add all but the i'th subpart to training set. new_train_idx = np.concatenate( [train_idx, *valid_idx_parts[:i], *valid_idx_parts[i+1:]]) # i'th subpart is validation set. new_valid_idx = valid_idx_parts[i] train_path = output_path / f"train_idx_{i}_{num_splits}.npy" valid_path = output_path / f"valid_idx_{i}_{num_splits}.npy" np.save(train_path, new_train_idx) np.save(valid_path, new_valid_idx) logging.info("Saved: %s", train_path) logging.info("Saved: %s", valid_path) def get_train_and_valid_idx_for_split( split_id: int, num_splits: int, root_path: str, ) -> Tuple[np.ndarray, np.ndarray]: """Returns train and valid indices for given split.""" new_train_idx = load_npy(f"{root_path}/train_idx_{split_id}_{num_splits}.npy") new_valid_idx = load_npy(f"{root_path}/valid_idx_{split_id}_{num_splits}.npy") return new_train_idx, new_valid_idx def generate_fused_node_labels(neighbor_indices, neighbor_distances, node_labels, train_indices, valid_indices, test_indices): """Generates fused adjacency matrix for identical nodes.""" logging.info("Generating fused node labels") valid_indices = set(valid_indices.tolist()) test_indices = set(test_indices.tolist()) valid_or_test_indices = valid_indices | test_indices train_indices = train_indices[train_indices < neighbor_indices.shape[0]] # Go through list of all pairs where one node is in training set, and for i in tqdm.tqdm(train_indices): for j in range(neighbor_indices.shape[1]): other_index = neighbor_indices[i][j] # if the other is not a validation or test node, if other_index in valid_or_test_indices: continue # and they are identical, if neighbor_distances[i][j] == 0: # assign the label of the training node to the other node node_labels[other_index] = node_labels[i] return node_labels def _pad_to_shape( sparse_csr_matrix: sp.csr_matrix, output_shape: Tuple[int, int]) -> sp.csr_matrix: """Pads a csr sparse matrix to the given shape.""" # We should not try to expand anything smaller. assert np.all(sparse_csr_matrix.shape <= output_shape) # Maybe it already has the right shape. if sparse_csr_matrix.shape == output_shape: return sparse_csr_matrix # Append as many indptr elements as we need to match the leading size, # This is achieved by just padding with copies of the last indptr element. required_padding = output_shape[0] - sparse_csr_matrix.shape[0] updated_indptr = np.concatenate( [sparse_csr_matrix.indptr] + [sparse_csr_matrix.indptr[-1:]] * required_padding, axis=0) # The change in trailing size does not have structural implications, it just # determines the highest possible value for the indices, so it is sufficient # to just pass the new output shape, with the correct trailing size. return sp.csr.csr_matrix( (sparse_csr_matrix.data, sparse_csr_matrix.indices, updated_indptr), shape=output_shape) def _fix_adjacency_shapes( arrays: Dict[str, sp.csr.csr_matrix], ) -> Dict[str, sp.csr.csr_matrix]: """Fixes the shapes of the adjacency matrices.""" arrays = arrays.copy() for key in ["author_institution_index", "author_paper_index", "paper_paper_index", "institution_author_index", "paper_author_index", "paper_paper_index_t"]: type_sender = key.split("_")[0] type_receiver = key.split("_")[1] arrays[key] = _pad_to_shape( arrays[key], output_shape=(SIZES[type_sender], SIZES[type_receiver])) return arrays
deepmind/deepmind-research
ogb_lsc/mag/data_utils.py
Python
apache-2.0
18,032
<?php namespace Topxia\Common; use Imagine\Image\Box; use Imagine\Gd\Imagine; use Imagine\Image\Point; use Topxia\Service\Common\ServiceKernel; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\Exception\FileException; class FileToolkit { public static function mungeFilename($fileName, $extensions) { $original = $fileName; // Remove any null bytes. See http://php.net/manual/en/security.filesystem.nullbytes.php $fileName = str_replace(chr(0), '', $fileName); $whitelist = array_unique(explode(' ', trim($extensions))); // Split the filename up by periods. The first part becomes the basename // the last part the final extension. $fileNameParts = explode('.', $fileName); $newFilename = array_shift($fileNameParts); // Remove file basename. $finalExtension = array_pop($fileNameParts); // Remove final extension. // Loop through the middle parts of the name and add an underscore to the // end of each section that could be a file extension but isn't in the list // of allowed extensions. foreach ($fileNameParts as $fileNamePart) { $newFilename .= '.'.$fileNamePart; if (!in_array($fileNamePart, $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $fileNamePart)) { $newFilename .= '_'; } } $fileName = $newFilename.'.'.$finalExtension; return $fileName; } public static function validateFileExtension(File $file, $extensions = array()) { if (empty($extensions)) { $extensions = static::getSecureFileExtensions(); } if ($file instanceof UploadedFile) { $filename = $file->getClientOriginalName(); } else { $filename = $file->getFilename(); } $errors = array(); $regex = '/\.('.preg_replace('/ +/', '|', preg_quote($extensions)).')$/i'; if (!preg_match($regex, $filename)) { $errors[] = "只允许上传以下扩展名的文件:".$extensions; } return $errors; } public static function isImageFile(File $file) { $ext = static::getFileExtension($file); return in_array(strtolower($ext), explode(' ', static::getImageExtensions())); } public static function isIcoFile(File $file) { $ext = strtolower(static::getFileExtension($file)); return $ext == 'ico' ? true : false; } public static function generateFilename($ext = '') { $filename = date('Yndhis').'-'.substr(base_convert(sha1(uniqid(mt_rand(), true)), 16, 36), 0, 6); return $filename.'.'.$ext; } public static function getFileExtension(File $file) { return $file instanceof UploadedFile ? $file->getClientOriginalExtension() : $file->getExtension(); } public static function getSecureFileMimeTypes() { $extensions = self::getSecureFileExtensions(); $extensions = explode(' ', $extensions); $mimeTypes = array(); foreach ($extensions as $key => $extension) { $mimeTypes[] = self::getMimeTypeByExtension($extension); } return $mimeTypes; } public static function getSecureFileExtensions() { return 'jpg jpeg gif png txt doc docx xls xlsx pdf ppt pptx pps ods odp mp4 mp3 avi flv wmv wma mov zip rar gz tar 7z swf ico'; } public static function getImageExtensions() { return 'bmp jpg jpeg gif png ico'; } public static function getMimeTypeByExtension($extension) { $mimes = array( 'ez' => 'application/andrew-inset', 'aw' => 'application/applixware', 'atom' => 'application/atom+xml', 'atomcat' => 'application/atomcat+xml', 'atomsvc' => 'application/atomsvc+xml', 'ccxml' => 'application/ccxml+xml', 'cdmia' => 'application/cdmi-capability', 'cdmic' => 'application/cdmi-container', 'cdmid' => 'application/cdmi-domain', 'cdmio' => 'application/cdmi-object', 'cdmiq' => 'application/cdmi-queue', 'cu' => 'application/cu-seeme', 'davmount' => 'application/davmount+xml', 'dbk' => 'application/docbook+xml', 'dssc' => 'application/dssc+der', 'xdssc' => 'application/dssc+xml', 'ecma' => 'application/ecmascript', 'emma' => 'application/emma+xml', 'epub' => 'application/epub+zip', 'exi' => 'application/exi', 'pfr' => 'application/font-tdpfr', 'gml' => 'application/gml+xml', 'gpx' => 'application/gpx+xml', 'gxf' => 'application/gxf', 'stk' => 'application/hyperstudio', 'ink' => 'application/inkml+xml', 'ipfix' => 'application/ipfix', 'jar' => 'application/java-archive', 'ser' => 'application/java-serialized-object', 'class' => 'application/java-vm', 'js' => 'application/javascript', 'json' => 'application/json', 'jsonml' => 'application/jsonml+json', 'lostxml' => 'application/lost+xml', 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'mads' => 'application/mads+xml', 'mrc' => 'application/marc', 'mrcx' => 'application/marcxml+xml', 'ma' => 'application/mathematica', 'mathml' => 'application/mathml+xml', 'mbox' => 'application/mbox', 'mscml' => 'application/mediaservercontrol+xml', 'metalink' => 'application/metalink+xml', 'meta4' => 'application/metalink4+xml', 'mets' => 'application/mets+xml', 'mods' => 'application/mods+xml', 'm21' => 'application/mp21', 'mp4s' => 'application/mp4', 'doc' => 'application/msword', 'mxf' => 'application/mxf', 'bin' => 'application/octet-stream', 'oda' => 'application/oda', 'opf' => 'application/oebps-package+xml', 'ogx' => 'application/ogg', 'omdoc' => 'application/omdoc+xml', 'onetoc' => 'application/onenote', 'oxps' => 'application/oxps', 'xer' => 'application/patch-ops-error+xml', 'pdf' => 'application/pdf', 'pgp' => 'application/pgp-encrypted', 'asc' => 'application/pgp-signature', 'prf' => 'application/pics-rules', 'p10' => 'application/pkcs10', 'p7m' => 'application/pkcs7-mime', 'p7s' => 'application/pkcs7-signature', 'p8' => 'application/pkcs8', 'ac' => 'application/pkix-attr-cert', 'cer' => 'application/pkix-cert', 'crl' => 'application/pkix-crl', 'pkipath' => 'application/pkix-pkipath', 'pki' => 'application/pkixcmp', 'pls' => 'application/pls+xml', 'ai' => 'application/postscript', 'cww' => 'application/prs.cww', 'pskcxml' => 'application/pskc+xml', 'rdf' => 'application/rdf+xml', 'rif' => 'application/reginfo+xml', 'rnc' => 'application/relax-ng-compact-syntax', 'rl' => 'application/resource-lists+xml', 'rld' => 'application/resource-lists-diff+xml', 'rs' => 'application/rls-services+xml', 'gbr' => 'application/rpki-ghostbusters', 'mft' => 'application/rpki-manifest', 'roa' => 'application/rpki-roa', 'rsd' => 'application/rsd+xml', 'rss' => 'application/rss+xml', 'rtf' => 'application/rtf', 'sbml' => 'application/sbml+xml', 'scq' => 'application/scvp-cv-request', 'scs' => 'application/scvp-cv-response', 'spq' => 'application/scvp-vp-request', 'spp' => 'application/scvp-vp-response', 'sdp' => 'application/sdp', 'setpay' => 'application/set-payment-initiation', 'setreg' => 'application/set-registration-initiation', 'shf' => 'application/shf+xml', 'smi' => 'application/smil+xml', 'rq' => 'application/sparql-query', 'srx' => 'application/sparql-results+xml', 'gram' => 'application/srgs', 'grxml' => 'application/srgs+xml', 'sru' => 'application/sru+xml', 'ssdl' => 'application/ssdl+xml', 'ssml' => 'application/ssml+xml', 'tei' => 'application/tei+xml', 'tfi' => 'application/thraud+xml', 'tsd' => 'application/timestamped-data', 'plb' => 'application/vnd.3gpp.pic-bw-large', 'psb' => 'application/vnd.3gpp.pic-bw-small', 'pvb' => 'application/vnd.3gpp.pic-bw-var', 'tcap' => 'application/vnd.3gpp2.tcap', 'pwn' => 'application/vnd.3m.post-it-notes', 'aso' => 'application/vnd.accpac.simply.aso', 'imp' => 'application/vnd.accpac.simply.imp', 'acu' => 'application/vnd.acucobol', 'atc' => 'application/vnd.acucorp', 'air' => 'application/vnd.adobe.air-application-installer-package+zip', 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', 'fxp' => 'application/vnd.adobe.fxp', 'xdp' => 'application/vnd.adobe.xdp+xml', 'xfdf' => 'application/vnd.adobe.xfdf', 'ahead' => 'application/vnd.ahead.space', 'azf' => 'application/vnd.airzip.filesecure.azf', 'azs' => 'application/vnd.airzip.filesecure.azs', 'azw' => 'application/vnd.amazon.ebook', 'acc' => 'application/vnd.americandynamics.acc', 'ami' => 'application/vnd.amiga.ami', 'apk' => 'application/vnd.android.package-archive', 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', 'atx' => 'application/vnd.antix.game-component', 'mpkg' => 'application/vnd.apple.installer+xml', 'm3u8' => 'application/vnd.apple.mpegurl', 'swi' => 'application/vnd.aristanetworks.swi', 'iota' => 'application/vnd.astraea-software.iota', 'aep' => 'application/vnd.audiograph', 'mpm' => 'application/vnd.blueice.multipass', 'bmi' => 'application/vnd.bmi', 'rep' => 'application/vnd.businessobjects', 'cdxml' => 'application/vnd.chemdraw+xml', 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', 'cdy' => 'application/vnd.cinderella', 'cla' => 'application/vnd.claymore', 'rp9' => 'application/vnd.cloanto.rp9', 'c4g' => 'application/vnd.clonk.c4group', 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', 'csp' => 'application/vnd.commonspace', 'cdbcmsg' => 'application/vnd.contact.cmsg', 'cmc' => 'application/vnd.cosmocaller', 'clkx' => 'application/vnd.crick.clicker', 'clkk' => 'application/vnd.crick.clicker.keyboard', 'clkp' => 'application/vnd.crick.clicker.palette', 'clkt' => 'application/vnd.crick.clicker.template', 'clkw' => 'application/vnd.crick.clicker.wordbank', 'wbs' => 'application/vnd.criticaltools.wbs+xml', 'pml' => 'application/vnd.ctc-posml', 'ppd' => 'application/vnd.cups-ppd', 'car' => 'application/vnd.curl.car', 'pcurl' => 'application/vnd.curl.pcurl', 'dart' => 'application/vnd.dart', 'rdz' => 'application/vnd.data-vision.rdz', 'uvf' => 'application/vnd.dece.data', 'uvt' => 'application/vnd.dece.ttml+xml', 'uvx' => 'application/vnd.dece.unspecified', 'uvz' => 'application/vnd.dece.zip', 'fe_launch' => 'application/vnd.denovo.fcselayout-link', 'dna' => 'application/vnd.dna', 'mlp' => 'application/vnd.dolby.mlp', 'dpg' => 'application/vnd.dpgraph', 'dfac' => 'application/vnd.dreamfactory', 'kpxx' => 'application/vnd.ds-keypoint', 'ait' => 'application/vnd.dvb.ait', 'svc' => 'application/vnd.dvb.service', 'geo' => 'application/vnd.dynageo', 'mag' => 'application/vnd.ecowin.chart', 'nml' => 'application/vnd.enliven', 'esf' => 'application/vnd.epson.esf', 'msf' => 'application/vnd.epson.msf', 'qam' => 'application/vnd.epson.quickanime', 'slt' => 'application/vnd.epson.salt', 'ssf' => 'application/vnd.epson.ssf', 'es3' => 'application/vnd.eszigno3+xml', 'ez2' => 'application/vnd.ezpix-album', 'ez3' => 'application/vnd.ezpix-package', 'fdf' => 'application/vnd.fdf', 'mseed' => 'application/vnd.fdsn.mseed', 'seed' => 'application/vnd.fdsn.seed', 'gph' => 'application/vnd.flographit', 'ftc' => 'application/vnd.fluxtime.clip', 'fm' => 'application/vnd.framemaker', 'fnc' => 'application/vnd.frogans.fnc', 'ltf' => 'application/vnd.frogans.ltf', 'fsc' => 'application/vnd.fsc.weblaunch', 'oas' => 'application/vnd.fujitsu.oasys', 'oa2' => 'application/vnd.fujitsu.oasys2', 'oa3' => 'application/vnd.fujitsu.oasys3', 'fg5' => 'application/vnd.fujitsu.oasysgp', 'bh2' => 'application/vnd.fujitsu.oasysprs', 'ddd' => 'application/vnd.fujixerox.ddd', 'xdw' => 'application/vnd.fujixerox.docuworks', 'xbd' => 'application/vnd.fujixerox.docuworks.binder', 'fzs' => 'application/vnd.fuzzysheet', 'txd' => 'application/vnd.genomatix.tuxedo', 'ggb' => 'application/vnd.geogebra.file', 'ggt' => 'application/vnd.geogebra.tool', 'gex' => 'application/vnd.geometry-explorer', 'gxt' => 'application/vnd.geonext', 'g2w' => 'application/vnd.geoplan', 'g3w' => 'application/vnd.geospace', 'gmx' => 'application/vnd.gmx', 'kml' => 'application/vnd.google-earth.kml+xml', 'kmz' => 'application/vnd.google-earth.kmz', 'gqf' => 'application/vnd.grafeq', 'gac' => 'application/vnd.groove-account', 'ghf' => 'application/vnd.groove-help', 'gim' => 'application/vnd.groove-identity-message', 'grv' => 'application/vnd.groove-injector', 'gtm' => 'application/vnd.groove-tool-message', 'tpl' => 'application/vnd.groove-tool-template', 'vcg' => 'application/vnd.groove-vcard', 'hal' => 'application/vnd.hal+xml', 'zmm' => 'application/vnd.handheld-entertainment+xml', 'hbci' => 'application/vnd.hbci', 'les' => 'application/vnd.hhe.lesson-player', 'hpgl' => 'application/vnd.hp-hpgl', 'hpid' => 'application/vnd.hp-hpid', 'hps' => 'application/vnd.hp-hps', 'jlt' => 'application/vnd.hp-jlyt', 'pcl' => 'application/vnd.hp-pcl', 'pclxl' => 'application/vnd.hp-pclxl', 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', 'mpy' => 'application/vnd.ibm.minipay', 'afp' => 'application/vnd.ibm.modcap', 'irm' => 'application/vnd.ibm.rights-management', 'sc' => 'application/vnd.ibm.secure-container', 'icc' => 'application/vnd.iccprofile', 'igl' => 'application/vnd.igloader', 'ivp' => 'application/vnd.immervision-ivp', 'ivu' => 'application/vnd.immervision-ivu', 'igm' => 'application/vnd.insors.igm', 'xpw' => 'application/vnd.intercon.formnet', 'i2g' => 'application/vnd.intergeo', 'qbo' => 'application/vnd.intu.qbo', 'qfx' => 'application/vnd.intu.qfx', 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', 'irp' => 'application/vnd.irepository.package+xml', 'xpr' => 'application/vnd.is-xpr', 'fcs' => 'application/vnd.isac.fcs', 'jam' => 'application/vnd.jam', 'rms' => 'application/vnd.jcp.javame.midlet-rms', 'jisp' => 'application/vnd.jisp', 'joda' => 'application/vnd.joost.joda-archive', 'ktz' => 'application/vnd.kahootz', 'karbon' => 'application/vnd.kde.karbon', 'chrt' => 'application/vnd.kde.kchart', 'kfo' => 'application/vnd.kde.kformula', 'flw' => 'application/vnd.kde.kivio', 'kon' => 'application/vnd.kde.kontour', 'kpr' => 'application/vnd.kde.kpresenter', 'ksp' => 'application/vnd.kde.kspread', 'kwd' => 'application/vnd.kde.kword', 'htke' => 'application/vnd.kenameaapp', 'kia' => 'application/vnd.kidspiration', 'kne' => 'application/vnd.kinar', 'skp' => 'application/vnd.koan', 'sse' => 'application/vnd.kodak-descriptor', 'lasxml' => 'application/vnd.las.las+xml', 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', '123' => 'application/vnd.lotus-1-2-3', 'apr' => 'application/vnd.lotus-approach', 'pre' => 'application/vnd.lotus-freelance', 'nsf' => 'application/vnd.lotus-notes', 'org' => 'application/vnd.lotus-organizer', 'scm' => 'application/vnd.lotus-screencam', 'lwp' => 'application/vnd.lotus-wordpro', 'portpkg' => 'application/vnd.macports.portpkg', 'mcd' => 'application/vnd.mcd', 'mc1' => 'application/vnd.medcalcdata', 'cdkey' => 'application/vnd.mediastation.cdkey', 'mwf' => 'application/vnd.mfer', 'mfm' => 'application/vnd.mfmp', 'flo' => 'application/vnd.micrografx.flo', 'igx' => 'application/vnd.micrografx.igx', 'mif' => 'application/vnd.mif', 'daf' => 'application/vnd.mobius.daf', 'dis' => 'application/vnd.mobius.dis', 'mbk' => 'application/vnd.mobius.mbk', 'mqy' => 'application/vnd.mobius.mqy', 'msl' => 'application/vnd.mobius.msl', 'plc' => 'application/vnd.mobius.plc', 'txf' => 'application/vnd.mobius.txf', 'mpn' => 'application/vnd.mophun.application', 'mpc' => 'application/vnd.mophun.certificate', 'xul' => 'application/vnd.mozilla.xul+xml', 'cil' => 'application/vnd.ms-artgalry', 'cab' => 'application/vnd.ms-cab-compressed', 'xls' => 'application/vnd.ms-excel', 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', 'eot' => 'application/vnd.ms-fontobject', 'chm' => 'application/vnd.ms-htmlhelp', 'ims' => 'application/vnd.ms-ims', 'lrm' => 'application/vnd.ms-lrm', 'thmx' => 'application/vnd.ms-officetheme', 'cat' => 'application/vnd.ms-pki.seccat', 'stl' => 'application/vnd.ms-pki.stl', 'ppt' => 'application/vnd.ms-powerpoint', 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', 'mpp' => 'application/vnd.ms-project', 'docm' => 'application/vnd.ms-word.document.macroenabled.12', 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', 'wps' => 'application/vnd.ms-works', 'wpl' => 'application/vnd.ms-wpl', 'xps' => 'application/vnd.ms-xpsdocument', 'mseq' => 'application/vnd.mseq', 'mus' => 'application/vnd.musician', 'msty' => 'application/vnd.muvee.style', 'taglet' => 'application/vnd.mynfc', 'nlu' => 'application/vnd.neurolanguage.nlu', 'ntf' => 'application/vnd.nitf', 'nnd' => 'application/vnd.noblenet-directory', 'nns' => 'application/vnd.noblenet-sealer', 'nnw' => 'application/vnd.noblenet-web', 'ngdat' => 'application/vnd.nokia.n-gage.data', 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', 'rpst' => 'application/vnd.nokia.radio-preset', 'rpss' => 'application/vnd.nokia.radio-presets', 'edm' => 'application/vnd.novadigm.edm', 'edx' => 'application/vnd.novadigm.edx', 'ext' => 'application/vnd.novadigm.ext', 'odc' => 'application/vnd.oasis.opendocument.chart', 'otc' => 'application/vnd.oasis.opendocument.chart-template', 'odb' => 'application/vnd.oasis.opendocument.database', 'odf' => 'application/vnd.oasis.opendocument.formula', 'odft' => 'application/vnd.oasis.opendocument.formula-template', 'odg' => 'application/vnd.oasis.opendocument.graphics', 'otg' => 'application/vnd.oasis.opendocument.graphics-template', 'odi' => 'application/vnd.oasis.opendocument.image', 'oti' => 'application/vnd.oasis.opendocument.image-template', 'odp' => 'application/vnd.oasis.opendocument.presentation', 'otp' => 'application/vnd.oasis.opendocument.presentation-template', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', 'odt' => 'application/vnd.oasis.opendocument.text', 'odm' => 'application/vnd.oasis.opendocument.text-master', 'ott' => 'application/vnd.oasis.opendocument.text-template', 'oth' => 'application/vnd.oasis.opendocument.text-web', 'xo' => 'application/vnd.olpc-sugar', 'dd2' => 'application/vnd.oma.dd2+xml', 'oxt' => 'application/vnd.openofficeorg.extension', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'mgp' => 'application/vnd.osgeo.mapguide.package', 'dp' => 'application/vnd.osgi.dp', 'esa' => 'application/vnd.osgi.subsystem', 'pdb' => 'application/vnd.palm', 'paw' => 'application/vnd.pawaafile', 'str' => 'application/vnd.pg.format', 'ei6' => 'application/vnd.pg.osasli', 'efif' => 'application/vnd.picsel', 'wg' => 'application/vnd.pmi.widget', 'plf' => 'application/vnd.pocketlearn', 'pbd' => 'application/vnd.powerbuilder6', 'box' => 'application/vnd.previewsystems.box', 'mgz' => 'application/vnd.proteus.magazine', 'qps' => 'application/vnd.publishare-delta-tree', 'ptid' => 'application/vnd.pvi.ptid1', 'qxd' => 'application/vnd.quark.quarkxpress', 'bed' => 'application/vnd.realvnc.bed', 'mxl' => 'application/vnd.recordare.musicxml', 'musicxml' => 'application/vnd.recordare.musicxml+xml', 'cryptonote' => 'application/vnd.rig.cryptonote', 'cod' => 'application/vnd.rim.cod', 'rm' => 'application/vnd.rn-realmedia', 'rmvb' => 'application/vnd.rn-realmedia-vbr', 'link66' => 'application/vnd.route66.link66+xml', 'st' => 'application/vnd.sailingtracker.track', 'see' => 'application/vnd.seemail', 'sema' => 'application/vnd.sema', 'semd' => 'application/vnd.semd', 'semf' => 'application/vnd.semf', 'ifm' => 'application/vnd.shana.informed.formdata', 'itp' => 'application/vnd.shana.informed.formtemplate', 'iif' => 'application/vnd.shana.informed.interchange', 'ipk' => 'application/vnd.shana.informed.package', 'twd' => 'application/vnd.simtech-mindmapper', 'mmf' => 'application/vnd.smaf', 'teacher' => 'application/vnd.smart.teacher', 'sdkm' => 'application/vnd.solent.sdkm+xml', 'dxp' => 'application/vnd.spotfire.dxp', 'sfs' => 'application/vnd.spotfire.sfs', 'sdc' => 'application/vnd.stardivision.calc', 'sda' => 'application/vnd.stardivision.draw', 'sdd' => 'application/vnd.stardivision.impress', 'smf' => 'application/vnd.stardivision.math', 'sdw' => 'application/vnd.stardivision.writer', 'sgl' => 'application/vnd.stardivision.writer-global', 'smzip' => 'application/vnd.stepmania.package', 'sm' => 'application/vnd.stepmania.stepchart', 'sxc' => 'application/vnd.sun.xml.calc', 'stc' => 'application/vnd.sun.xml.calc.template', 'sxd' => 'application/vnd.sun.xml.draw', 'std' => 'application/vnd.sun.xml.draw.template', 'sxi' => 'application/vnd.sun.xml.impress', 'sti' => 'application/vnd.sun.xml.impress.template', 'sxm' => 'application/vnd.sun.xml.math', 'sxw' => 'application/vnd.sun.xml.writer', 'sxg' => 'application/vnd.sun.xml.writer.global', 'stw' => 'application/vnd.sun.xml.writer.template', 'sus' => 'application/vnd.sus-calendar', 'svd' => 'application/vnd.svd', 'sis' => 'application/vnd.symbian.install', 'xsm' => 'application/vnd.syncml+xml', 'bdm' => 'application/vnd.syncml.dm+wbxml', 'xdm' => 'application/vnd.syncml.dm+xml', 'tao' => 'application/vnd.tao.intent-module-archive', 'pcap' => 'application/vnd.tcpdump.pcap', 'tmo' => 'application/vnd.tmobile-livetv', 'tpt' => 'application/vnd.trid.tpt', 'mxs' => 'application/vnd.triscape.mxs', 'tra' => 'application/vnd.trueapp', 'ufd' => 'application/vnd.ufdl', 'utz' => 'application/vnd.uiq.theme', 'umj' => 'application/vnd.umajin', 'unityweb' => 'application/vnd.unity', 'uoml' => 'application/vnd.uoml+xml', 'vcx' => 'application/vnd.vcx', 'vsd' => 'application/vnd.visio', 'vis' => 'application/vnd.visionary', 'vsf' => 'application/vnd.vsf', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wtb' => 'application/vnd.webturbo', 'nbp' => 'application/vnd.wolfram.player', 'wpd' => 'application/vnd.wordperfect', 'wqd' => 'application/vnd.wqd', 'stf' => 'application/vnd.wt.stf', 'xar' => 'application/vnd.xara', 'xfdl' => 'application/vnd.xfdl', 'hvd' => 'application/vnd.yamaha.hv-dic', 'hvs' => 'application/vnd.yamaha.hv-script', 'hvp' => 'application/vnd.yamaha.hv-voice', 'osf' => 'application/vnd.yamaha.openscoreformat', 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', 'saf' => 'application/vnd.yamaha.smaf-audio', 'spf' => 'application/vnd.yamaha.smaf-phrase', 'cmp' => 'application/vnd.yellowriver-custom-menu', 'zir' => 'application/vnd.zul', 'zaz' => 'application/vnd.zzazz.deck+xml', 'vxml' => 'application/voicexml+xml', 'wgt' => 'application/widget', 'hlp' => 'application/winhlp', 'wsdl' => 'application/wsdl+xml', 'wspolicy' => 'application/wspolicy+xml', '7z' => 'application/x-7z-compressed', 'abw' => 'application/x-abiword', 'ace' => 'application/x-ace-compressed', 'dmg' => 'application/x-apple-diskimage', 'aab' => 'application/x-authorware-bin', 'aam' => 'application/x-authorware-map', 'aas' => 'application/x-authorware-seg', 'bcpio' => 'application/x-bcpio', 'torrent' => 'application/x-bittorrent', 'blb' => 'application/x-blorb', 'bz' => 'application/x-bzip', 'bz2' => 'application/x-bzip2', 'cbr' => 'application/x-cbr', 'vcd' => 'application/x-cdlink', 'cfs' => 'application/x-cfs-compressed', 'chat' => 'application/x-chat', 'pgn' => 'application/x-chess-pgn', 'nsc' => 'application/x-conference', 'cpio' => 'application/x-cpio', 'csh' => 'application/x-csh', 'deb' => 'application/x-debian-package', 'dgc' => 'application/x-dgc-compressed', 'dir' => 'application/x-director', 'wad' => 'application/x-doom', 'ncx' => 'application/x-dtbncx+xml', 'dtb' => 'application/x-dtbook+xml', 'res' => 'application/x-dtbresource+xml', 'dvi' => 'application/x-dvi', 'evy' => 'application/x-envoy', 'eva' => 'application/x-eva', 'bdf' => 'application/x-font-bdf', 'gsf' => 'application/x-font-ghostscript', 'psf' => 'application/x-font-linux-psf', 'otf' => 'application/x-font-otf', 'pcf' => 'application/x-font-pcf', 'snf' => 'application/x-font-snf', 'ttf' => 'application/x-font-ttf', 'pfa' => 'application/x-font-type1', 'woff' => 'application/x-font-woff', 'arc' => 'application/x-freearc', 'spl' => 'application/x-futuresplash', 'gca' => 'application/x-gca-compressed', 'ulx' => 'application/x-glulx', 'gnumeric' => 'application/x-gnumeric', 'gramps' => 'application/x-gramps-xml', 'gtar' => 'application/x-gtar', 'hdf' => 'application/x-hdf', 'install' => 'application/x-install-instructions', 'iso' => 'application/x-iso9660-image', 'jnlp' => 'application/x-java-jnlp-file', 'latex' => 'application/x-latex', 'lzh' => 'application/x-lzh-compressed', 'mie' => 'application/x-mie', 'prc' => 'application/x-mobipocket-ebook', 'application' => 'application/x-ms-application', 'lnk' => 'application/x-ms-shortcut', 'wmd' => 'application/x-ms-wmd', 'wmz' => 'application/x-ms-wmz', 'xbap' => 'application/x-ms-xbap', 'mdb' => 'application/x-msaccess', 'obd' => 'application/x-msbinder', 'crd' => 'application/x-mscardfile', 'clp' => 'application/x-msclip', 'exe' => 'application/x-msdownload', 'mvb' => 'application/x-msmediaview', 'wmf' => 'application/x-msmetafile', 'mny' => 'application/x-msmoney', 'pub' => 'application/x-mspublisher', 'scd' => 'application/x-msschedule', 'trm' => 'application/x-msterminal', 'wri' => 'application/x-mswrite', 'nc' => 'application/x-netcdf', 'nzb' => 'application/x-nzb', 'p12' => 'application/x-pkcs12', 'p7b' => 'application/x-pkcs7-certificates', 'p7r' => 'application/x-pkcs7-certreqresp', 'rar' => 'application/x-rar-compressed', 'rar' => 'application/x-rar', 'ris' => 'application/x-research-info-systems', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'swf' => 'application/x-shockwave-flash', 'xap' => 'application/x-silverlight-app', 'sql' => 'application/x-sql', 'sit' => 'application/x-stuffit', 'sitx' => 'application/x-stuffitx', 'srt' => 'application/x-subrip', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 't3' => 'application/x-t3vm-image', 'gam' => 'application/x-tads', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'tfm' => 'application/x-tex-tfm', 'texinfo' => 'application/x-texinfo', 'obj' => 'application/x-tgif', 'ustar' => 'application/x-ustar', 'src' => 'application/x-wais-source', 'der' => 'application/x-x509-ca-cert', 'fig' => 'application/x-xfig', 'xlf' => 'application/x-xliff+xml', 'xpi' => 'application/x-xpinstall', 'xz' => 'application/x-xz', 'z1' => 'application/x-zmachine', 'xaml' => 'application/xaml+xml', 'xdf' => 'application/xcap-diff+xml', 'xenc' => 'application/xenc+xml', 'xhtml' => 'application/xhtml+xml', 'xml' => 'application/xml', 'dtd' => 'application/xml-dtd', 'xop' => 'application/xop+xml', 'xpl' => 'application/xproc+xml', 'xslt' => 'application/xslt+xml', 'xspf' => 'application/xspf+xml', 'mxml' => 'application/xv+xml', 'yang' => 'application/yang', 'yin' => 'application/yin+xml', 'zip' => 'application/zip', 'adp' => 'audio/adpcm', 'au' => 'audio/basic', 'mid' => 'audio/midi', 'mp4a' => 'audio/mp4', 'mpga' => 'audio/mpeg', 'oga' => 'audio/ogg', 's3m' => 'audio/s3m', 'sil' => 'audio/silk', 'uva' => 'audio/vnd.dece.audio', 'eol' => 'audio/vnd.digital-winds', 'dra' => 'audio/vnd.dra', 'dts' => 'audio/vnd.dts', 'dtshd' => 'audio/vnd.dts.hd', 'lvp' => 'audio/vnd.lucent.voice', 'pya' => 'audio/vnd.ms-playready.media.pya', 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', 'rip' => 'audio/vnd.rip', 'weba' => 'audio/webm', 'aac' => 'audio/x-aac', 'aif' => 'audio/x-aiff', 'caf' => 'audio/x-caf', 'flac' => 'audio/x-flac', 'mka' => 'audio/x-matroska', 'm3u' => 'audio/x-mpegurl', 'wax' => 'audio/x-ms-wax', 'wma' => 'audio/x-ms-wma', 'ram' => 'audio/x-pn-realaudio', 'rmp' => 'audio/x-pn-realaudio-plugin', 'wav' => 'audio/x-wav', 'xm' => 'audio/xm', 'cdx' => 'chemical/x-cdx', 'cif' => 'chemical/x-cif', 'cmdf' => 'chemical/x-cmdf', 'cml' => 'chemical/x-cml', 'csml' => 'chemical/x-csml', 'xyz' => 'chemical/x-xyz', 'bmp' => 'image/bmp', 'cgm' => 'image/cgm', 'g3' => 'image/g3fax', 'gif' => 'image/gif', 'ief' => 'image/ief', 'jpeg' => 'image/jpeg', 'ktx' => 'image/ktx', 'png' => 'image/png', 'btif' => 'image/prs.btif', 'sgi' => 'image/sgi', 'svg' => 'image/svg+xml', 'tiff' => 'image/tiff', 'psd' => 'image/vnd.adobe.photoshop', 'uvi' => 'image/vnd.dece.graphic', 'sub' => 'image/vnd.dvb.subtitle', 'djvu' => 'image/vnd.djvu', 'dwg' => 'image/vnd.dwg', 'dxf' => 'image/vnd.dxf', 'fbs' => 'image/vnd.fastbidsheet', 'fpx' => 'image/vnd.fpx', 'fst' => 'image/vnd.fst', 'mmr' => 'image/vnd.fujixerox.edmics-mmr', 'rlc' => 'image/vnd.fujixerox.edmics-rlc', 'mdi' => 'image/vnd.ms-modi', 'wdp' => 'image/vnd.ms-photo', 'npx' => 'image/vnd.net-fpx', 'wbmp' => 'image/vnd.wap.wbmp', 'xif' => 'image/vnd.xiff', 'webp' => 'image/webp', '3ds' => 'image/x-3ds', 'ras' => 'image/x-cmu-raster', 'cmx' => 'image/x-cmx', 'fh' => 'image/x-freehand', 'ico' => 'image/x-icon', 'sid' => 'image/x-mrsid-image', 'pcx' => 'image/x-pcx', 'pic' => 'image/x-pict', 'pnm' => 'image/x-portable-anymap', 'pbm' => 'image/x-portable-bitmap', 'pgm' => 'image/x-portable-graymap', 'ppm' => 'image/x-portable-pixmap', 'rgb' => 'image/x-rgb', 'tga' => 'image/x-tga', 'xbm' => 'image/x-xbitmap', 'xpm' => 'image/x-xpixmap', 'xwd' => 'image/x-xwindowdump', 'eml' => 'message/rfc822', 'igs' => 'model/iges', 'msh' => 'model/mesh', 'dae' => 'model/vnd.collada+xml', 'dwf' => 'model/vnd.dwf', 'gdl' => 'model/vnd.gdl', 'gtw' => 'model/vnd.gtw', 'mts' => 'model/vnd.mts', 'vtu' => 'model/vnd.vtu', 'wrl' => 'model/vrml', 'x3db' => 'model/x3d+binary', 'x3dv' => 'model/x3d+vrml', 'x3d' => 'model/x3d+xml', 'appcache' => 'text/cache-manifest', 'ics' => 'text/calendar', 'css' => 'text/css', 'csv' => 'text/csv', 'html' => 'text/html', 'n3' => 'text/n3', 'txt' => 'text/plain', 'dsc' => 'text/prs.lines.tag', 'rtx' => 'text/richtext', 'sgml' => 'text/sgml', 'tsv' => 'text/tab-separated-values', 't' => 'text/troff', 'ttl' => 'text/turtle', 'uri' => 'text/uri-list', 'vcard' => 'text/vcard', 'curl' => 'text/vnd.curl', 'dcurl' => 'text/vnd.curl.dcurl', 'scurl' => 'text/vnd.curl.scurl', 'mcurl' => 'text/vnd.curl.mcurl', 'sub' => 'text/vnd.dvb.subtitle', 'fly' => 'text/vnd.fly', 'flx' => 'text/vnd.fmi.flexstor', 'gv' => 'text/vnd.graphviz', '3dml' => 'text/vnd.in3d.3dml', 'spot' => 'text/vnd.in3d.spot', 'jad' => 'text/vnd.sun.j2me.app-descriptor', 'wml' => 'text/vnd.wap.wml', 'wmls' => 'text/vnd.wap.wmlscript', 's' => 'text/x-asm', 'c' => 'text/x-c', 'f' => 'text/x-fortran', 'p' => 'text/x-pascal', 'java' => 'text/x-java-source', 'opml' => 'text/x-opml', 'nfo' => 'text/x-nfo', 'etx' => 'text/x-setext', 'sfv' => 'text/x-sfv', 'uu' => 'text/x-uuencode', 'vcs' => 'text/x-vcalendar', 'vcf' => 'text/x-vcard', '3gp' => 'video/3gpp', '3g2' => 'video/3gpp2', 'h261' => 'video/h261', 'h263' => 'video/h263', 'h264' => 'video/h264', 'jpgv' => 'video/jpeg', 'jpm' => 'video/jpm', 'mj2' => 'video/mj2', 'mp4' => 'video/mp4', 'mpeg' => 'video/mpeg', 'ogv' => 'video/ogg', 'qt' => 'video/quicktime', 'uvh' => 'video/vnd.dece.hd', 'uvm' => 'video/vnd.dece.mobile', 'uvp' => 'video/vnd.dece.pd', 'uvs' => 'video/vnd.dece.sd', 'uvv' => 'video/vnd.dece.video', 'dvb' => 'video/vnd.dvb.file', 'fvt' => 'video/vnd.fvt', 'mxu' => 'video/vnd.mpegurl', 'pyv' => 'video/vnd.ms-playready.media.pyv', 'uvu' => 'video/vnd.uvvu.mp4', 'viv' => 'video/vnd.vivo', 'webm' => 'video/webm', 'f4v' => 'video/x-f4v', 'fli' => 'video/x-fli', 'flv' => 'video/x-flv', 'm4v' => 'video/x-m4v', 'mkv' => 'video/x-matroska', 'mng' => 'video/x-mng', 'asf' => 'video/x-ms-asf', 'vob' => 'video/x-ms-vob', 'wm' => 'video/x-ms-wm', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wvx' => 'video/x-ms-wvx', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie', 'smv' => 'video/x-smv', 'ice' => 'x-conference/x-cooltalk', 'mpg' => 'video/mpeg', 'mp3' => 'audio/mpeg', 'gz' => 'application/x-gzip', 'jpg' => 'image/jpeg', 'pps' => 'application/vnd.ms-powerpoint', 'mov' => 'video/quicktime' ); return empty($mimes[$extension]) ? null : $mimes[$extension]; } public static function getFileTypeByExtension($extension) { $extension = strtolower($extension); if (in_array($extension, array('mp4', 'avi', 'mpg', 'flv', 'f4v', 'wmv', 'mov', 'rmvb', 'mkv', 'm4v'))) { return 'video'; } elseif (in_array($extension, array('mp3', 'wma'))) { return 'audio'; } elseif (in_array($extension, array('jpg', 'jpeg', 'png', 'gif', 'bmp'))) { return 'image'; } elseif (in_array($extension, array('doc', 'docx', 'pdf', 'xls', 'xlsx', 'wps', 'odt'))) { return 'document'; } elseif (in_array($extension, array('ppt', 'pptx'))) { return 'ppt'; } elseif (in_array($extension, array('swf'))) { return 'flash'; } elseif (in_array($extension, array('srt'))) { return 'subtitle'; } else { return 'other'; } } public static function formatFileSize($size) { $currentValue = $currentUnit = null; $unitExps = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3); foreach ($unitExps as $unit => $exp) { $divisor = pow(1024, $exp); $currentUnit = $unit; $currentValue = $size / $divisor; if ($currentValue < 1024) { break; } } return sprintf('%.1f', $currentValue).$currentUnit; } public static function getMaxFilesize() { $max = strtolower(ini_get('upload_max_filesize')); if ('' === $max) { return PHP_INT_MAX; } if (preg_match('#^\+?(0x?)?(.*?)([kmg]?)$#', $max, $match)) { $shifts = array('' => 0, 'k' => 10, 'm' => 20, 'g' => 30); $bases = array('' => 10, '0' => 8, '0x' => 16); return intval($match[2], $bases[$match[1]]) << $shifts[$match[3]]; } return 0; } public static function moveFile($originFile, $targetGroup) { $targetFilenamePrefix = rand(10000, 99999); $hash = substr(md5($targetFilenamePrefix.time()), -8); $ext = $originFile->getClientOriginalExtension(); $filename = $targetFilenamePrefix.$hash.'.'.$ext; $directory = ServiceKernel::instance()->getParameter('topxia.upload.public_directory').'/'.$targetGroup; $file = $originFile->move($directory, $filename); return $file; } public static function remove($filepath) { if (empty($filepath)) { throw new \RuntimeException("filepath to be deleted is empty"); } $isRemoved = false; $prefixArr = array('data/private_files', 'data/udisk', 'web/files'); foreach ($prefixArr as $prefix) { if (strpos($filepath, trim($prefix))) { $fileSystem = new Filesystem(); if ($fileSystem->exists($filepath)) { $fileSystem->remove($filepath); } $isRemoved = true; break; } } if (!$isRemoved) { $prefixString = join(' || ', $prefixArr); throw new \RuntimeException("{$filepath} is not allowed to be deleted without prefix {$prefixString}"); } } public static function crop($rawImage, $targetPath, $x, $y, $width, $height, $resizeWidth = 0, $resizeHeight = 0) { $image = $rawImage->copy(); $image->crop(new Point($x, $y), new Box($width, $height)); if ($resizeWidth > 0 && $resizeHeight > 0) { $image->resize(new Box($resizeWidth, $resizeHeight)); } $image->save($targetPath); return $image; } public static function resize($image, $targetPath, $resizeWidth = 0, $resizeHeight = 0) { $image->resize(new Box($resizeWidth, $resizeHeight)); $image->save($targetPath); return $image; } public static function cropImages($filePath, $options) { $pathinfo = pathinfo($filePath); $imagine = new Imagine(); $rawImage = $imagine->open($filePath); $naturalSize = $rawImage->getSize(); $rate = $naturalSize->getWidth() / $options["width"]; $options["w"] = $rate * $options["w"]; $options["h"] = $rate * $options["h"]; $options["x"] = $rate * $options["x"]; $options["y"] = $rate * $options["y"]; $filePaths = array(); if (!empty($options["imgs"]) && count($options["imgs"]) > 0) { foreach ($options["imgs"] as $key => $value) { $savedFilePath = "{$pathinfo['dirname']}/{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}"; $image = static::crop($rawImage, $savedFilePath, $options['x'], $options['y'], $options['w'], $options['h'], $value[0], $value[1]); $filePaths[$key] = $savedFilePath; } } else { $savedFilePath = "{$pathinfo['dirname']}/{$pathinfo['filename']}.{$pathinfo['extension']}"; $image = static::crop($rawImage, $savedFilePath, $options['x'], $options['y'], $options['w'], $options['h']); $filePaths[] = $savedFilePath; } return $filePaths; } public static function reduceImgQuality($fullPath, $level = 10) { $extension = strtolower(substr(strrchr($fullPath, '.'), 1)); $options = array(); if (in_array($extension, array('jpg', 'jpeg'))) { $options['jpeg_quality'] = $level * 10; } elseif ($extension == 'png') { $options['png_compression_level'] = $level; } else { return $fullPath; } try { $imagine = new Imagine(); $image = $imagine->open($fullPath)->save($fullPath, $options); } catch (\Exception $e) { throw new \Exception("该文件为非图片格式文件,请重新上传。"); } } public static function getImgInfo($fullPath, $width, $height) { try { $imagine = new Imagine(); $image = $imagine->open($fullPath); } catch (\Exception $e) { throw new \Exception("该文件为非图片格式文件,请重新上传。"); } $naturalSize = $image->getSize(); $scaledSize = $naturalSize->widen($width)->heighten($height); return array($naturalSize, $scaledSize); } //将图片旋转正确 public static function imagerotatecorrect($path) { try { //只旋转JPEG的图片 //IMAGETYPE_JPEG = 2 if (extension_loaded('gd') && extension_loaded('exif') && exif_imagetype($path) == 2) { $exif = @exif_read_data($path); if (!empty($exif['Orientation'])) { $image = imagecreatefromstring(file_get_contents($path)); switch ($exif['Orientation']) { case 8: $image = imagerotate($image, 90, 0); break; case 3: $image = imagerotate($image, 180, 0); break; case 6: $image = imagerotate($image, -90, 0); break; } imagejpeg($image, $path); imagedestroy($image); return $path; } } } catch (\Exception $e) { //报错了不旋转,保证不影响上传流程 } return false; } protected function getServiceKernel() { return ServiceKernel::instance(); } public static function downloadImg($url, $savePath) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $imageData = curl_exec($curl); curl_close($curl); $tp = @fopen($savePath, 'w'); fwrite($tp, $imageData); fclose($tp); return $savePath; } }
18826252059/im
src/Topxia/Common/FileToolkit.php
PHP
apache-2.0
56,525
import android.content.Context; import android.graphics.Bitmap; import android.graphics.Rect; import android.graphics.RectF; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.view.WindowManager; public final class lsr { static final lsp<Bitmap> a = new lsq(64); private final RectF A = new RectF(); private final RectF B = new RectF(); private int C; private final Rect[] D; private boolean E; int b; lsv c; int d; int e = 0; final kp<lss> f = new kp(); final Object g = new Object(); final lsu h = new lsu(); final lsu i = new lsu(); final lsu j = new lsu(); int k = -1; int l = -1; public int m; public int n; public float o; public boolean p; final Rect q = new Rect(); lst r; public int s; public int t; View u; private iax v; private int w; private int x; private int y; private boolean z; public lsr(View paramView) { Rect[] arrayOfRect = new Rect[2]; arrayOfRect[0] = new Rect(); arrayOfRect[1] = new Rect(); this.D = arrayOfRect; this.u = paramView; this.r = new lst(this); this.r.setName("TileDecoder"); this.r.start(); } public static int a(Context paramContext) { DisplayMetrics localDisplayMetrics = new DisplayMetrics(); ((WindowManager)paramContext.getSystemService("window")).getDefaultDisplay().getMetrics(localDisplayMetrics); if ((localDisplayMetrics.heightPixels > 2048) || (localDisplayMetrics.widthPixels > 2048)) {} for (int i1 = 1; i1 != 0; i1 = 0) { return 512; } return 256; } private final void a(Rect paramRect, int paramInt1, int paramInt2, int paramInt3, float paramFloat, int paramInt4) { double d1 = Math.toRadians(-paramInt4); double d2 = this.s; double d3 = this.t; double d4 = Math.cos(d1); double d5 = Math.sin(d1); int i1 = (int)Math.ceil(Math.max(Math.abs(d4 * d2 - d5 * d3), Math.abs(d4 * d2 + d5 * d3))); int i2 = (int)Math.ceil(Math.max(Math.abs(d5 * d2 + d4 * d3), Math.abs(d5 * d2 - d4 * d3))); int i3 = (int)Math.floor(paramInt1 - i1 / (2.0F * paramFloat)); int i4 = (int)Math.floor(paramInt2 - i2 / (2.0F * paramFloat)); int i5 = (int)Math.ceil(i3 + i1 / paramFloat); int i6 = (int)Math.ceil(i4 + i2 / paramFloat); int i7 = this.b << paramInt3; paramRect.set(Math.max(0, i7 * (i3 / i7)), Math.max(0, i7 * (i4 / i7)), Math.min(this.k, i5), Math.min(this.l, i6)); } private final void a(lss paramlss) { synchronized (this.g) { if (paramlss.o == 1) { paramlss.o = 2; if (this.j.a(paramlss)) { this.g.notifyAll(); } } return; } } private final boolean a(lss paramlss, iaz paramiaz, RectF paramRectF1, RectF paramRectF2) { if (paramlss.j()) { paramiaz.a(paramlss, paramRectF1, paramRectF2); return true; } if (1 + paramlss.l == paramlss.p.d) {} int i2; int i3; for (lss locallss = null; locallss == null; locallss = paramlss.p.a(i2, i3, 1 + paramlss.l)) { return false; int i1 = paramlss.p.b << 1 + paramlss.l; i2 = i1 * (paramlss.j / i1); i3 = i1 * (paramlss.k / i1); } if (paramlss.j == locallss.j) { paramRectF1.left /= 2.0F; paramRectF1.right /= 2.0F; label139: if (paramlss.k != locallss.k) { break label212; } paramRectF1.top /= 2.0F; } for (paramRectF1.bottom /= 2.0F;; paramRectF1.bottom = ((this.b + paramRectF1.bottom) / 2.0F)) { paramlss = locallss; break; paramRectF1.left = ((this.b + paramRectF1.left) / 2.0F); paramRectF1.right = ((this.b + paramRectF1.right) / 2.0F); break label139; label212: paramRectF1.top = ((this.b + paramRectF1.top) / 2.0F); } } private final lss b(int paramInt1, int paramInt2, int paramInt3) { synchronized (this.g) { lss locallss1 = this.h.a(); if (locallss1 != null) { locallss1.o = 1; locallss1.j = paramInt1; locallss1.k = paramInt2; locallss1.l = paramInt3; if (locallss1.i != null) { locallss1.i(); } locallss1.h = false; locallss1.c = -1; locallss1.d = -1; return locallss1; } lss locallss2 = new lss(this, paramInt1, paramInt2, paramInt3); return locallss2; } } private final void b() { synchronized (this.g) { this.j.a = null; this.i.a = null; kp localkp = this.f; if (localkp.b) { localkp.a(); } int i1 = localkp.e; for (int i2 = 0; i2 < i1; i2++) { b((lss)this.f.b(i2)); } this.f.c(); return; } } private final void b(lss paramlss) { synchronized (this.g) { if (paramlss.o == 4) { paramlss.o = 32; return; } paramlss.o = 64; if (paramlss.n != null) { a.a(paramlss.n); paramlss.n = null; } this.h.a(paramlss); return; } } private static long c(int paramInt1, int paramInt2, int paramInt3) { return (paramInt1 << 16 | paramInt2) << 16 | paramInt3; } private final void c() { this.E = true; kp localkp = this.f; if (localkp.b) { localkp.a(); } int i1 = localkp.e; for (int i2 = 0; i2 < i1; i2++) { lss locallss = (lss)this.f.b(i2); if (!locallss.j()) { a(locallss); } } } final lss a(int paramInt1, int paramInt2, int paramInt3) { return (lss)this.f.a(c(paramInt1, paramInt2, paramInt3)); } public final void a() { this.p = true; this.r.interrupt(); synchronized (this.g) { this.i.a = null; this.j.a = null; for (lss locallss = this.h.a(); locallss != null; locallss = this.h.a()) { locallss.g(); } kp localkp = this.f; if (localkp.b) { localkp.a(); } int i1 = localkp.e; int i2 = 0; if (i2 < i1) { ((lss)this.f.b(i2)).g(); i2++; } } this.f.c(); this.q.set(0, 0, 0, 0); while (a.a() != null) {} } public final void a(lsv paramlsv, int paramInt) { if (this.c != paramlsv) { this.c = paramlsv; b(); if (this.c != null) { break label68; } this.k = 0; this.l = 0; this.d = 0; this.v = null; } for (;;) { this.p = true; if (this.C != paramInt) { this.C = paramInt; this.p = true; } return; label68: this.k = this.c.b(); this.l = this.c.c(); this.v = this.c.d(); this.b = this.c.a(); if (this.v != null) { this.d = Math.max(0, iaw.a(this.k / this.v.b())); } else { int i1 = Math.max(this.k, this.l); int i2 = this.b; for (int i3 = 1; i2 < i1; i3++) { i2 <<= 1; } this.d = i3; } } } public final boolean a(iaz paramiaz) { int i1; lss locallss1; if ((this.s == 0) || (this.t == 0) || (!this.p)) { i1 = 1; locallss1 = null; } int i18; int i19; for (;;) { for (;;) { if (i1 <= 0) { break label837; } synchronized (this.g) { locallss1 = this.i.a(); if (locallss1 == null) { break label837; } if (!locallss1.j()) { if (locallss1.o == 8) { locallss1.b(paramiaz); i1--; continue; this.p = false; this.e = iaw.a(iaw.b(1.0F / this.o), 0, this.d); int i14; if (this.e != this.d) { Rect localRect4 = this.q; a(localRect4, this.m, this.n, this.e, this.o, this.C); this.w = Math.round(this.s / 2.0F + (localRect4.left - this.m) * this.o); this.x = Math.round(this.t / 2.0F + (localRect4.top - this.n) * this.o); if (this.o * (1 << this.e) > 0.75F) { i14 = -1 + this.e; } } int i15; int i16; Rect[] arrayOfRect; for (;;) { i15 = Math.max(0, Math.min(i14, -2 + this.d)); i16 = Math.min(i15 + 2, this.d); arrayOfRect = this.D; for (int i17 = i15; i17 < i16; i17++) { Rect localRect3 = arrayOfRect[(i17 - i15)]; int i32 = this.m; int i33 = this.n; int i34 = this.C; a(localRect3, i32, i33, i17, Math.scalb(1.0F, -(i17 + 1)), i34); } i14 = this.e; continue; i14 = -2 + this.e; this.w = Math.round(this.s / 2.0F - this.m * this.o); this.x = Math.round(this.t / 2.0F - this.n * this.o); } if (this.C % 90 != 0) { break; } for (;;) { int i24; int i25; int i28; int i31; long l1; synchronized (this.g) { this.j.a = null; this.i.a = null; this.E = false; kp localkp1 = this.f; if (localkp1.b) { localkp1.a(); } i18 = localkp1.e; i19 = 0; if (i19 < i18) { lss locallss3 = (lss)this.f.b(i19); int i20 = locallss3.l; if ((i20 >= i15) && (i20 < i16) && (arrayOfRect[(i20 - i15)].contains(locallss3.j, locallss3.k))) { break label1433; } kp localkp2 = this.f; if (localkp2.d[i19] != kp.a) { localkp2.d[i19] = kp.a; localkp2.b = true; } i19--; i18--; b(locallss3); break label1433; } i24 = i15; if (i24 >= i16) { break; } i25 = this.b << i24; Rect localRect2 = arrayOfRect[(i24 - i15)]; int i26 = localRect2.top; int i27 = localRect2.bottom; i28 = i26; if (i28 >= i27) { break label783; } int i29 = localRect2.left; int i30 = localRect2.right; i31 = i29; if (i31 >= i30) { break label773; } l1 = c(i31, i28, i24); lss locallss4 = (lss)this.f.a(l1); if (locallss4 != null) { if (locallss4.o == 2) { locallss4.o = 1; } i31 += i25; } } lss locallss5 = b(i31, i28, i24); this.f.a(l1, locallss5); continue; label773: i28 += i25; continue; label783: i24++; } this.u.postInvalidate(); } } } } int i13 = locallss1.o; new StringBuilder(51).append("Tile in upload queue has invalid state: ").append(i13); } label837: if (locallss1 != null) { this.u.postInvalidate(); } this.y = 1; this.z = true; int i2 = this.e; int i3 = this.C; int i4; if (i3 != 0) { i4 = 2; label878: if (i4 != 0) { paramiaz.a(2); if (i3 != 0) { int i11 = this.s / 2; int i12 = this.t / 2; paramiaz.a(i11, i12); paramiaz.a(i3, 0.0F, 0.0F, 1.0F); paramiaz.a(-i11, -i12); } } } for (;;) { int i5; int i6; int i7; int i8; int i9; lss locallss2; try { if (i2 == this.d) { break label1319; } i5 = this.b << i2; float f1 = i5 * this.o; Rect localRect1 = this.q; i6 = localRect1.top; i7 = 0; if (i6 >= localRect1.bottom) { break label1370; } float f2 = this.x + f1 * i7; i8 = localRect1.left; i9 = 0; if (i8 >= localRect1.right) { break label1471; } float f3 = this.w + f1 * i9; RectF localRectF1 = this.A; RectF localRectF2 = this.B; localRectF2.set(f3, f2, f3 + f1, f2 + f1); localRectF1.set(0.0F, 0.0F, this.b, this.b); locallss2 = a(i8, i6, i2); if (locallss2 != null) { if (!locallss2.j()) { if (locallss2.o != 8) { break label1295; } if (this.y > 0) { this.y = (-1 + this.y); locallss2.b(paramiaz); } } else { if (a(locallss2, paramiaz, localRectF1, localRectF2)) { break label1458; } } } else { if (this.v == null) { break label1458; } int i10 = this.b << i2; float f4 = this.v.b() / this.k; float f5 = this.v.c() / this.l; localRectF1.set(f4 * i8, f5 * i6, f4 * (i8 + i10), f5 * (i10 + i6)); paramiaz.a(this.v, localRectF1, localRectF2); break label1458; } this.z = false; continue; if (locallss2.o == 16) { continue; } } finally { if (i4 != 0) { paramiaz.b(); } } label1295: this.z = false; a(locallss2); continue; label1319: if (this.v != null) { paramiaz.a(this.v, this.w, this.x, Math.round(this.k * this.o), Math.round(this.l * this.o)); } label1370: if (i4 != 0) { paramiaz.b(); } if (this.z) { if (!this.E) { c(); } } while ((this.z) || (this.v != null)) { return true; this.u.postInvalidate(); } return false; i4 = 0; break label878; label1433: int i21 = i19; int i22 = i18; int i23 = i21 + 1; i18 = i22; i19 = i23; break; label1458: i8 += i5; i9++; continue; label1471: i6 += i5; i7++; } } } /* Location: F:\apktool\apktool\com.google.android.apps.plus\classes-dex2jar.jar * Qualified Name: lsr * JD-Core Version: 0.7.0.1 */
ChiangC/FMTech
GooglePlus/app/src/main/java/lsr.java
Java
apache-2.0
15,760
/* * Copyright 2000-2016 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.execution.junit2.configuration; import com.intellij.application.options.ModuleDescriptionsComboBox; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.MethodBrowser; import com.intellij.execution.ShortenCommandLine; import com.intellij.execution.configuration.BrowseModuleValueActionListener; import com.intellij.execution.junit.JUnitConfiguration; import com.intellij.execution.junit.JUnitConfigurationType; import com.intellij.execution.junit.JUnitUtil; import com.intellij.execution.junit.TestClassFilter; import com.intellij.execution.testDiscovery.TestDiscoveryExtension; import com.intellij.execution.testframework.SourceScope; import com.intellij.execution.testframework.TestSearchScope; import com.intellij.execution.ui.*; import com.intellij.ide.util.ClassFilter; import com.intellij.ide.util.PackageChooserDialog; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.fileChooser.FileChooserFactory; import com.intellij.openapi.fileTypes.PlainTextLanguage; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComponentWithBrowseButton; import com.intellij.openapi.ui.LabeledComponent; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.ui.ex.MessagesEx; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.LocalChangeList; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.JavaCodeFragment; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.rt.execution.junit.RepeatCount; import com.intellij.ui.*; import com.intellij.ui.components.JBLabel; import com.intellij.util.IconUtil; import com.intellij.util.ui.UIUtil; import consulo.psi.PsiPackage; import consulo.util.collection.primitive.ints.IntList; import consulo.util.collection.primitive.ints.IntLists; import javax.annotation.Nonnull; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.Document; import javax.swing.text.PlainDocument; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.List; public class JUnitConfigurable<T extends JUnitConfiguration> extends SettingsEditor<T> implements PanelWithAnchor { private static final List<IntList> ourEnabledFields = Arrays.asList(IntLists.newArrayList(new int[]{0}), IntLists.newArrayList(new int[]{1}), IntLists.newArrayList(new int[]{ 1, 2 }), IntLists.newArrayList(new int[]{3}), IntLists.newArrayList(new int[]{4}), IntLists.newArrayList(new int[]{5}), IntLists.newArrayList(new int[]{ 1, 2 }), IntLists.newArrayList(new int[]{6})); private static final String[] FORK_MODE_ALL = { JUnitConfiguration.FORK_NONE, JUnitConfiguration.FORK_METHOD, JUnitConfiguration.FORK_KLASS }; private static final String[] FORK_MODE = { JUnitConfiguration.FORK_NONE, JUnitConfiguration.FORK_METHOD }; private final ConfigurationModuleSelector myModuleSelector; private final LabeledComponent[] myTestLocations = new LabeledComponent[6]; private final JUnitConfigurationModel myModel; private final BrowseModuleValueActionListener[] myBrowsers; private JComponent myPackagePanel; private LabeledComponent<EditorTextFieldWithBrowseButton> myPackage; private LabeledComponent<TextFieldWithBrowseButton> myDir; private LabeledComponent<JPanel> myPattern; private LabeledComponent<EditorTextFieldWithBrowseButton> myClass; private LabeledComponent<EditorTextFieldWithBrowseButton> myMethod; private LabeledComponent<EditorTextFieldWithBrowseButton> myCategory; // Fields private JPanel myWholePanel; private LabeledComponent<ModuleDescriptionsComboBox> myModule; private CommonJavaParametersPanel myCommonJavaParameters; private JRadioButton myWholeProjectScope; private JRadioButton mySingleModuleScope; private JRadioButton myModuleWDScope; private TextFieldWithBrowseButton myPatternTextField; private JrePathEditor myJrePathEditor; private LabeledComponent<ShortenCommandLineModeCombo> myShortenClasspathModeCombo; private JComboBox myForkCb; private JBLabel myTestLabel; private JComboBox myTypeChooser; private JBLabel mySearchForTestsLabel; private JPanel myScopesPanel; private JComboBox myRepeatCb; private JTextField myRepeatCountField; private LabeledComponent<JComboBox<String>> myChangeListLabeledComponent; private LabeledComponent<RawCommandLineEditor> myUniqueIdField; private Project myProject; private JComponent anchor; public JUnitConfigurable(final Project project) { myProject = project; myModel = new JUnitConfigurationModel(project); myModuleSelector = new ConfigurationModuleSelector(project, getModulesComponent()); myJrePathEditor.setDefaultJreSelector(DefaultJreSelector.fromModuleDependencies(getModulesComponent(), false)); myCommonJavaParameters.setModuleContext(myModuleSelector.getModule()); myCommonJavaParameters.setHasModuleMacro(); myModule.getComponent().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myCommonJavaParameters.setModuleContext(myModuleSelector.getModule()); } }); myBrowsers = new BrowseModuleValueActionListener[]{ new PackageChooserActionListener(project), new TestClassBrowser(project), new MethodBrowser(project) { protected Condition<PsiMethod> getFilter(PsiClass testClass) { return new JUnitUtil.TestMethodFilter(testClass); } @Override protected String getClassName() { return JUnitConfigurable.this.getClassName(); } @Override protected ConfigurationModuleSelector getModuleSelector() { return myModuleSelector; } }, new TestsChooserActionListener(project), new BrowseModuleValueActionListener(project) { @Override protected String showDialog() { final VirtualFile virtualFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(), project, null); if(virtualFile != null) { return FileUtil.toSystemDependentName(virtualFile.getPath()); } return null; } }, new CategoryBrowser(project), null }; // Garbage support final DefaultComboBoxModel aModel = new DefaultComboBoxModel(); aModel.addElement(JUnitConfigurationModel.ALL_IN_PACKAGE); aModel.addElement(JUnitConfigurationModel.DIR); aModel.addElement(JUnitConfigurationModel.PATTERN); aModel.addElement(JUnitConfigurationModel.CLASS); aModel.addElement(JUnitConfigurationModel.METHOD); aModel.addElement(JUnitConfigurationModel.CATEGORY); aModel.addElement(JUnitConfigurationModel.UNIQUE_ID); if(TestDiscoveryExtension.TESTDISCOVERY_ENABLED) { aModel.addElement(JUnitConfigurationModel.BY_SOURCE_POSITION); aModel.addElement(JUnitConfigurationModel.BY_SOURCE_CHANGES); } myTypeChooser.setModel(aModel); myTypeChooser.setRenderer(new ListCellRendererWrapper<Integer>() { @Override public void customize(JList list, Integer value, int index, boolean selected, boolean hasFocus) { switch(value) { case JUnitConfigurationModel.ALL_IN_PACKAGE: setText("All in package"); break; case JUnitConfigurationModel.DIR: setText("All in directory"); break; case JUnitConfigurationModel.PATTERN: setText("Pattern"); break; case JUnitConfigurationModel.CLASS: setText("Class"); break; case JUnitConfigurationModel.METHOD: setText("Method"); break; case JUnitConfigurationModel.CATEGORY: setText("Category"); break; case JUnitConfigurationModel.UNIQUE_ID: setText("UniqueId"); break; case JUnitConfigurationModel.BY_SOURCE_POSITION: setText("Through source location"); break; case JUnitConfigurationModel.BY_SOURCE_CHANGES: setText("Over changes in sources"); break; } } }); myTestLocations[JUnitConfigurationModel.ALL_IN_PACKAGE] = myPackage; myTestLocations[JUnitConfigurationModel.CLASS] = myClass; myTestLocations[JUnitConfigurationModel.METHOD] = myMethod; myTestLocations[JUnitConfigurationModel.DIR] = myDir; myTestLocations[JUnitConfigurationModel.CATEGORY] = myCategory; myRepeatCb.setModel(new DefaultComboBoxModel(RepeatCount.REPEAT_TYPES)); myRepeatCb.setSelectedItem(RepeatCount.ONCE); myRepeatCb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myRepeatCountField.setEnabled(RepeatCount.N.equals(myRepeatCb.getSelectedItem())); } }); final JPanel panel = myPattern.getComponent(); panel.setLayout(new BorderLayout()); myPatternTextField = new TextFieldWithBrowseButton(); myPatternTextField.setButtonIcon(IconUtil.getAddIcon()); panel.add(myPatternTextField, BorderLayout.CENTER); myTestLocations[JUnitConfigurationModel.PATTERN] = myPattern; final FileChooserDescriptor dirFileChooser = FileChooserDescriptorFactory.createSingleFolderDescriptor(); dirFileChooser.setHideIgnored(false); final JTextField textField = myDir.getComponent().getTextField(); InsertPathAction.addTo(textField, dirFileChooser); FileChooserFactory.getInstance().installFileCompletion(textField, dirFileChooser, true, null); // Done myModel.setListener(this); myTypeChooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final Object selectedItem = myTypeChooser.getSelectedItem(); myModel.setType((Integer) selectedItem); changePanel(); } }); myRepeatCb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if((Integer) myTypeChooser.getSelectedItem() == JUnitConfigurationModel.CLASS) { myForkCb.setModel(getForkModelBasedOnRepeat()); } } }); myModel.setType(JUnitConfigurationModel.CLASS); installDocuments(); addRadioButtonsListeners(new JRadioButton[]{ myWholeProjectScope, mySingleModuleScope, myModuleWDScope }, null); myWholeProjectScope.addChangeListener(new ChangeListener() { public void stateChanged(final ChangeEvent e) { onScopeChanged(); } }); UIUtil.setEnabled(myCommonJavaParameters.getProgramParametersComponent(), false, true); setAnchor(mySearchForTestsLabel); myJrePathEditor.setAnchor(myModule.getLabel()); myCommonJavaParameters.setAnchor(myModule.getLabel()); myShortenClasspathModeCombo.setAnchor(myModule.getLabel()); final DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(); myChangeListLabeledComponent.getComponent().setModel(model); model.addElement("All"); final List<LocalChangeList> changeLists = ChangeListManager.getInstance(project).getChangeLists(); for(LocalChangeList changeList : changeLists) { model.addElement(changeList.getName()); } myShortenClasspathModeCombo.setComponent(new ShortenCommandLineModeCombo(myProject, myJrePathEditor, myModule.getComponent())); } private static void addRadioButtonsListeners(final JRadioButton[] radioButtons, ChangeListener listener) { final ButtonGroup group = new ButtonGroup(); for(final JRadioButton radioButton : radioButtons) { radioButton.getModel().addChangeListener(listener); group.add(radioButton); } if(group.getSelection() == null) { group.setSelected(radioButtons[0].getModel(), true); } } public void applyEditorTo(@Nonnull final JUnitConfiguration configuration) { configuration.setRepeatMode((String) myRepeatCb.getSelectedItem()); try { configuration.setRepeatCount(Integer.parseInt(myRepeatCountField.getText())); } catch(NumberFormatException e) { configuration.setRepeatCount(1); } myModel.apply(getModuleSelector().getModule(), configuration); configuration.getPersistentData().setUniqueIds(myUniqueIdField.getComponent().getText().split(" ")); configuration.getPersistentData().setChangeList((String) myChangeListLabeledComponent.getComponent().getSelectedItem()); applyHelpersTo(configuration); final JUnitConfiguration.Data data = configuration.getPersistentData(); if(myWholeProjectScope.isSelected()) { data.setScope(TestSearchScope.WHOLE_PROJECT); } else if(mySingleModuleScope.isSelected()) { data.setScope(TestSearchScope.SINGLE_MODULE); } else if(myModuleWDScope.isSelected()) { data.setScope(TestSearchScope.MODULE_WITH_DEPENDENCIES); } configuration.setAlternativeJrePath(myJrePathEditor.getJrePathOrName()); configuration.setAlternativeJrePathEnabled(myJrePathEditor.isAlternativeJreSelected()); myCommonJavaParameters.applyTo(configuration); configuration.setForkMode((String) myForkCb.getSelectedItem()); configuration.setShortenCommandLine((ShortenCommandLine) myShortenClasspathModeCombo.getComponent().getSelectedItem()); } public void resetEditorFrom(@Nonnull final JUnitConfiguration configuration) { final int count = configuration.getRepeatCount(); myRepeatCountField.setText(String.valueOf(count)); myRepeatCountField.setEnabled(count > 1); myRepeatCb.setSelectedItem(configuration.getRepeatMode()); myModel.reset(configuration); myChangeListLabeledComponent.getComponent().setSelectedItem(configuration.getPersistentData().getChangeList()); String[] ids = configuration.getPersistentData().getUniqueIds(); myUniqueIdField.getComponent().setText(ids != null ? StringUtil.join(ids, " ") : null); myCommonJavaParameters.reset(configuration); getModuleSelector().reset(configuration); final TestSearchScope scope = configuration.getPersistentData().getScope(); if(scope == TestSearchScope.SINGLE_MODULE) { mySingleModuleScope.setSelected(true); } else if(scope == TestSearchScope.MODULE_WITH_DEPENDENCIES) { myModuleWDScope.setSelected(true); } else { myWholeProjectScope.setSelected(true); } myJrePathEditor.setPathOrName(configuration.getAlternativeJrePath(), configuration.isAlternativeJrePathEnabled()); myForkCb.setSelectedItem(configuration.getForkMode()); myShortenClasspathModeCombo.getComponent().setSelectedItem(configuration.getShortenCommandLine()); } private void changePanel() { String selectedItem = (String) myForkCb.getSelectedItem(); if(selectedItem == null) { selectedItem = JUnitConfiguration.FORK_NONE; } final Integer selectedType = (Integer) myTypeChooser.getSelectedItem(); if(selectedType == JUnitConfigurationModel.ALL_IN_PACKAGE) { myPackagePanel.setVisible(true); myScopesPanel.setVisible(true); myPattern.setVisible(false); myClass.setVisible(false); myCategory.setVisible(false); myUniqueIdField.setVisible(false); myMethod.setVisible(false); myDir.setVisible(false); myChangeListLabeledComponent.setVisible(false); myForkCb.setEnabled(true); myForkCb.setModel(new DefaultComboBoxModel(FORK_MODE_ALL)); myForkCb.setSelectedItem(selectedItem); } else if(selectedType == JUnitConfigurationModel.DIR) { myPackagePanel.setVisible(false); myScopesPanel.setVisible(false); myDir.setVisible(true); myPattern.setVisible(false); myClass.setVisible(false); myCategory.setVisible(false); myUniqueIdField.setVisible(false); myChangeListLabeledComponent.setVisible(false); myMethod.setVisible(false); myForkCb.setEnabled(true); myForkCb.setModel(new DefaultComboBoxModel(FORK_MODE_ALL)); myForkCb.setSelectedItem(selectedItem); } else if(selectedType == JUnitConfigurationModel.CLASS) { myPackagePanel.setVisible(false); myScopesPanel.setVisible(false); myPattern.setVisible(false); myDir.setVisible(false); myClass.setVisible(true); myCategory.setVisible(false); myUniqueIdField.setVisible(false); myChangeListLabeledComponent.setVisible(false); myMethod.setVisible(false); myForkCb.setEnabled(true); myForkCb.setModel(getForkModelBasedOnRepeat()); myForkCb.setSelectedItem(selectedItem != JUnitConfiguration.FORK_KLASS ? selectedItem : JUnitConfiguration.FORK_METHOD); } else if(selectedType == JUnitConfigurationModel.METHOD || selectedType == JUnitConfigurationModel.BY_SOURCE_POSITION) { myPackagePanel.setVisible(false); myScopesPanel.setVisible(false); myPattern.setVisible(false); myDir.setVisible(false); myClass.setVisible(true); myCategory.setVisible(false); myUniqueIdField.setVisible(false); myMethod.setVisible(true); myChangeListLabeledComponent.setVisible(false); myForkCb.setEnabled(false); myForkCb.setSelectedItem(JUnitConfiguration.FORK_NONE); } else if(selectedType == JUnitConfigurationModel.CATEGORY) { myPackagePanel.setVisible(false); myScopesPanel.setVisible(true); myDir.setVisible(false); myPattern.setVisible(false); myClass.setVisible(false); myCategory.setVisible(true); myUniqueIdField.setVisible(false); myMethod.setVisible(false); myChangeListLabeledComponent.setVisible(false); myForkCb.setEnabled(true); myForkCb.setModel(new DefaultComboBoxModel(FORK_MODE_ALL)); myForkCb.setSelectedItem(selectedItem); } else if(selectedType == JUnitConfigurationModel.BY_SOURCE_CHANGES) { myPackagePanel.setVisible(false); myScopesPanel.setVisible(false); myDir.setVisible(false); myPattern.setVisible(false); myClass.setVisible(false); myCategory.setVisible(false); myUniqueIdField.setVisible(false); myMethod.setVisible(false); myChangeListLabeledComponent.setVisible(true); myForkCb.setEnabled(true); myForkCb.setModel(new DefaultComboBoxModel(FORK_MODE_ALL)); myForkCb.setSelectedItem(selectedItem); } else if(selectedType == JUnitConfigurationModel.UNIQUE_ID) { myPackagePanel.setVisible(false); myScopesPanel.setVisible(false); myDir.setVisible(false); myPattern.setVisible(false); myClass.setVisible(false); myCategory.setVisible(false); myUniqueIdField.setVisible(true); myMethod.setVisible(false); myChangeListLabeledComponent.setVisible(false); myForkCb.setEnabled(true); myForkCb.setModel(new DefaultComboBoxModel(FORK_MODE_ALL)); myForkCb.setSelectedItem(selectedItem); } else { myPackagePanel.setVisible(false); myScopesPanel.setVisible(true); myPattern.setVisible(true); myDir.setVisible(false); myClass.setVisible(false); myCategory.setVisible(false); myUniqueIdField.setVisible(false); myMethod.setVisible(true); myChangeListLabeledComponent.setVisible(false); myForkCb.setEnabled(true); myForkCb.setModel(new DefaultComboBoxModel(FORK_MODE_ALL)); myForkCb.setSelectedItem(selectedItem); } } private DefaultComboBoxModel getForkModelBasedOnRepeat() { return new DefaultComboBoxModel(RepeatCount.ONCE.equals(myRepeatCb.getSelectedItem()) ? FORK_MODE : FORK_MODE_ALL); } public ModuleDescriptionsComboBox getModulesComponent() { return myModule.getComponent(); } public ConfigurationModuleSelector getModuleSelector() { return myModuleSelector; } private void installDocuments() { for(int i = 0; i < myTestLocations.length; i++) { final LabeledComponent testLocation = getTestLocation(i); final JComponent component = testLocation.getComponent(); final ComponentWithBrowseButton field; Object document; if(component instanceof TextFieldWithBrowseButton) { field = (TextFieldWithBrowseButton) component; document = new PlainDocument(); ((TextFieldWithBrowseButton) field).getTextField().setDocument((Document) document); } else if(component instanceof EditorTextFieldWithBrowseButton) { field = (ComponentWithBrowseButton) component; document = ((EditorTextField) field.getChildComponent()).getDocument(); } else { field = myPatternTextField; document = new PlainDocument(); ((TextFieldWithBrowseButton) field).getTextField().setDocument((Document) document); } myBrowsers[i].setField(field); if(myBrowsers[i] instanceof MethodBrowser) { final EditorTextField childComponent = (EditorTextField) field.getChildComponent(); ((MethodBrowser) myBrowsers[i]).installCompletion(childComponent); document = childComponent.getDocument(); } myModel.setJUnitDocument(i, document); } } public LabeledComponent getTestLocation(final int index) { return myTestLocations[index]; } private void createUIComponents() { myPackage = new LabeledComponent<>(); myPackage.setComponent(new EditorTextFieldWithBrowseButton(myProject, false)); myClass = new LabeledComponent<>(); final TestClassBrowser classBrowser = new TestClassBrowser(myProject); myClass.setComponent(new EditorTextFieldWithBrowseButton(myProject, true, new JavaCodeFragment.VisibilityChecker() { @Override public Visibility isDeclarationVisible(PsiElement declaration, PsiElement place) { try { if(declaration instanceof PsiClass && (classBrowser.getFilter().isAccepted(((PsiClass) declaration)) || classBrowser.findClass(((PsiClass) declaration).getQualifiedName()) != null && place.getParent() != null)) { return Visibility.VISIBLE; } } catch(ClassBrowser.NoFilterException e) { return Visibility.NOT_VISIBLE; } return Visibility.NOT_VISIBLE; } })); myCategory = new LabeledComponent<>(); myCategory.setComponent(new EditorTextFieldWithBrowseButton(myProject, true, new JavaCodeFragment.VisibilityChecker() { @Override public Visibility isDeclarationVisible(PsiElement declaration, PsiElement place) { if(declaration instanceof PsiClass) { return Visibility.VISIBLE; } return Visibility.NOT_VISIBLE; } })); myMethod = new LabeledComponent<>(); final EditorTextFieldWithBrowseButton textFieldWithBrowseButton = new EditorTextFieldWithBrowseButton(myProject, true, JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE, PlainTextLanguage.INSTANCE.getAssociatedFileType()); myMethod.setComponent(textFieldWithBrowseButton); myShortenClasspathModeCombo = new LabeledComponent<>(); } @Override public JComponent getAnchor() { return anchor; } @Override public void setAnchor(JComponent anchor) { this.anchor = anchor; mySearchForTestsLabel.setAnchor(anchor); myTestLabel.setAnchor(anchor); myClass.setAnchor(anchor); myDir.setAnchor(anchor); myMethod.setAnchor(anchor); myPattern.setAnchor(anchor); myPackage.setAnchor(anchor); myCategory.setAnchor(anchor); myUniqueIdField.setAnchor(anchor); myChangeListLabeledComponent.setAnchor(anchor); } public void onTypeChanged(final int newType) { myTypeChooser.setSelectedItem(newType); final IntList enabledFields = ourEnabledFields.get(newType); for(int i = 0; i < myTestLocations.length; i++) { getTestLocation(i).setEnabled(enabledFields.contains(i)); } /*if (newType == JUnitConfigurationModel.PATTERN) { myModule.setEnabled(false); } else */ if(newType != JUnitConfigurationModel.ALL_IN_PACKAGE && newType != JUnitConfigurationModel.PATTERN && newType != JUnitConfigurationModel.CATEGORY && newType != JUnitConfigurationModel .UNIQUE_ID) { myModule.setEnabled(true); } else { onScopeChanged(); } } private void onScopeChanged() { final Integer selectedItem = (Integer) myTypeChooser.getSelectedItem(); final boolean allInPackageAllInProject = (selectedItem == JUnitConfigurationModel.ALL_IN_PACKAGE || selectedItem == JUnitConfigurationModel.PATTERN || selectedItem == JUnitConfigurationModel .CATEGORY || selectedItem == JUnitConfigurationModel.UNIQUE_ID) && myWholeProjectScope.isSelected(); myModule.setEnabled(!allInPackageAllInProject); if(allInPackageAllInProject) { myModule.getComponent().setSelectedItem(null); } } private String getClassName() { return ((LabeledComponent<EditorTextFieldWithBrowseButton>) getTestLocation(JUnitConfigurationModel.CLASS)).getComponent().getText(); } private void setPackage(final PsiPackage aPackage) { if(aPackage == null) { return; } ((LabeledComponent<EditorTextFieldWithBrowseButton>) getTestLocation(JUnitConfigurationModel.ALL_IN_PACKAGE)).getComponent().setText(aPackage.getQualifiedName()); } @Nonnull public JComponent createEditor() { return myWholePanel; } private void applyHelpersTo(final JUnitConfiguration currentState) { myCommonJavaParameters.applyTo(currentState); getModuleSelector().applyTo(currentState); } private static class PackageChooserActionListener extends BrowseModuleValueActionListener { public PackageChooserActionListener(final Project project) { super(project); } protected String showDialog() { final PackageChooserDialog dialog = new PackageChooserDialog(ExecutionBundle.message("choose.package.dialog.title"), getProject()); dialog.show(); final PsiPackage aPackage = dialog.getSelectedPackage(); return aPackage != null ? aPackage.getQualifiedName() : null; } } private class TestsChooserActionListener extends TestClassBrowser { public TestsChooserActionListener(final Project project) { super(project); } @Override protected void onClassChoosen(PsiClass psiClass) { final JTextField textField = myPatternTextField.getTextField(); final String text = textField.getText(); textField.setText(text + (text.length() > 0 ? "||" : "") + psiClass.getQualifiedName()); } @Override protected ClassFilter.ClassFilterWithScope getFilter() throws NoFilterException { try { return TestClassFilter.create(SourceScope.wholeProject(getProject()), null); } catch(JUnitUtil.NoJUnitException ignore) { throw new NoFilterException(new MessagesEx.MessageInfo(getProject(), ignore.getMessage(), ExecutionBundle.message("cannot.browse.test.inheritors.dialog.title"))); } } @Override public void actionPerformed(ActionEvent e) { showDialog(); } } private class TestClassBrowser extends ClassBrowser { public TestClassBrowser(final Project project) { super(project, ExecutionBundle.message("choose.test.class.dialog.title")); } protected void onClassChoosen(final PsiClass psiClass) { setPackage(JUnitUtil.getContainingPackage(psiClass)); } protected PsiClass findClass(final String className) { return getModuleSelector().findClass(className); } protected ClassFilter.ClassFilterWithScope getFilter() throws NoFilterException { final ConfigurationModuleSelector moduleSelector = getModuleSelector(); final Module module = moduleSelector.getModule(); if(module == null) { throw NoFilterException.moduleDoesntExist(moduleSelector); } final ClassFilter.ClassFilterWithScope classFilter; try { final JUnitConfiguration configurationCopy = new JUnitConfiguration(ExecutionBundle.message("default.junit.configuration.name"), getProject(), JUnitConfigurationType.getInstance() .getConfigurationFactories()[0]); applyEditorTo(configurationCopy); classFilter = TestClassFilter.create(SourceScope.modulesWithDependencies(configurationCopy.getModules()), configurationCopy.getConfigurationModule().getModule()); } catch(JUnitUtil.NoJUnitException e) { throw NoFilterException.noJUnitInModule(module); } return classFilter; } } private class CategoryBrowser extends ClassBrowser { public CategoryBrowser(Project project) { super(project, "Category Interface"); } protected PsiClass findClass(final String className) { return myModuleSelector.findClass(className); } protected ClassFilter.ClassFilterWithScope getFilter() throws NoFilterException { final Module module = myModuleSelector.getModule(); final GlobalSearchScope scope; if(module == null) { scope = GlobalSearchScope.allScope(myProject); } else { scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module); } return new ClassFilter.ClassFilterWithScope() { public GlobalSearchScope getScope() { return scope; } public boolean isAccepted(final PsiClass aClass) { return true; } }; } @Override protected void onClassChoosen(PsiClass psiClass) { ((LabeledComponent<EditorTextFieldWithBrowseButton>) getTestLocation(JUnitConfigurationModel.CATEGORY)).getComponent().setText(psiClass.getQualifiedName()); } } }
consulo/consulo-junit
plugin/src/main/java/com/intellij/execution/junit2/configuration/JUnitConfigurable.java
Java
apache-2.0
29,412
package middleware import ( "encoding/base64" "strconv" "strings" "github.com/raintank/raintank-apps/pkg/auth" "gopkg.in/macaron.v1" ) type Context struct { *macaron.Context *auth.SignedInUser ApiKey string } func GetContextHandler() macaron.Handler { return func(c *macaron.Context) { ctx := &Context{ Context: c, SignedInUser: &auth.SignedInUser{}, } c.Map(ctx) } } func RequireAdmin() macaron.Handler { return func(ctx *Context) { if !ctx.IsAdmin { ctx.JSON(403, "Permission denied") } } } func RoleAuth(roles ...auth.RoleType) macaron.Handler { return func(c *Context) { ok := false for _, role := range roles { if role == c.Role { ok = true break } } if !ok { c.JSON(403, "Permission denied") } } } func Auth(adminKey string) macaron.Handler { return func(ctx *Context) { key, err := getApiKey(ctx) if err != nil { ctx.JSON(401, "Invalid Authentication header.") return } if key == "" { ctx.JSON(401, "Unauthorized") return } user, err := auth.Auth(adminKey, key) if err != nil { if err == auth.ErrInvalidApiKey { ctx.JSON(401, "Unauthorized") return } ctx.JSON(500, err) return } // allow admin users to impersonate other orgs. if user.IsAdmin { header := ctx.Req.Header.Get("X-Worldping-Org") if header != "" { orgId, err := strconv.ParseInt(header, 10, 64) if err == nil && orgId != 0 { user.OrgId = orgId } } } ctx.SignedInUser = user ctx.ApiKey = key } } func getApiKey(c *Context) (string, error) { header := c.Req.Header.Get("Authorization") parts := strings.SplitN(header, " ", 2) if len(parts) == 2 && parts[0] == "Bearer" { key := parts[1] return key, nil } if len(parts) == 2 && parts[0] == "Basic" { decoded, err := base64.StdEncoding.DecodeString(parts[1]) if err != nil { return "", err } userAndPass := strings.SplitN(string(decoded), ":", 2) if userAndPass[0] == "api_key" { return userAndPass[1], nil } } return "", nil }
raintank/raintank-apps
vendor/github.com/raintank/worldping-api/pkg/middleware/middleware.go
GO
apache-2.0
2,035
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { HttpModule } from '@angular/http'; import { RecipeServiceProvider } from '../../providers/recipe/recipe.service'; import { Recipe } from '../../providers/recipe/recipe.model'; import { RecipeDetailPage } from '../recipe-detail/recipe-detail'; import { UtilityProvider } from '../../providers/utility/utility'; @Component({ selector: 'page-home', templateUrl: 'home.html', providers: [HttpModule, RecipeServiceProvider,UtilityProvider] }) export class HomePage { recipeList: Recipe[]; recipe: any; constructor(public navCtrl: NavController, public recipeService: RecipeServiceProvider) { this.loadRecipes(); } loadRecipes() { this.recipeService.loadRecipes().subscribe(recipe => this.recipeList = recipe); } viewItem(recipe: any) { this.recipe = recipe; console.log(this.recipe); this.navCtrl.push(RecipeDetailPage, { recipe: recipe }); } filterTime(seconds:string){ return UtilityProvider.filterTime(seconds); } }
gokhankuyucak/AeropressApp
src/pages/home/home.ts
TypeScript
apache-2.0
1,064
package com.google.api.ads.dfp.jaxws.v201511; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Action that can be performed on {@link FirstPartyAudienceSegment} objects to deactivate them. * * * <p>Java class for DeactivateAudienceSegments complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DeactivateAudienceSegments"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201511}AudienceSegmentAction"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DeactivateAudienceSegments") public class DeactivateAudienceSegments extends AudienceSegmentAction { }
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/DeactivateAudienceSegments.java
Java
apache-2.0
984
/* * * Copyright 2017-2018 Nitrite 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.dizitart.no2.objects.data; import lombok.Data; import org.dizitart.no2.IndexType; import org.dizitart.no2.objects.Id; import org.dizitart.no2.objects.Index; import org.dizitart.no2.objects.Indices; import java.util.Date; import java.util.UUID; /** * @author Anindya Chatterjee */ @Data @Indices({ @Index(value = "name", type = IndexType.Fulltext) }) public class PersonEntity { @Id private String uuid; private String name; private String status; private PersonEntity friend; private Date dateCreated; public PersonEntity() { this.uuid = UUID.randomUUID().toString(); this.dateCreated = new Date(); } public PersonEntity(String name) { this.uuid = UUID.randomUUID().toString(); this.name = name; this.dateCreated = new Date(); } }
dizitart/nitrite-database
nitrite/src/test/java/org/dizitart/no2/objects/data/PersonEntity.java
Java
apache-2.0
1,463
package org.devel.reportfx; import de.saxsys.mvvmfx.FluentViewLoader; import javafx.application.Application; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import de.saxsys.mvvmfx.ViewTuple; public class Starter extends Application { public static void main(String... args) { Application.launch(args); } @Override public void start(Stage stage) throws Exception { stage.setTitle("ReportFX"); ViewTuple<MainView, MainViewModel> viewTuple = FluentViewLoader.fxmlView(MainView.class).load(); Parent root = viewTuple.getView(); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); stage.setResizable(false); } }
stefanil/ReportFX
client/src/main/java/org/devel/reportfx/Starter.java
Java
apache-2.0
695
package server import ( "encoding/json" "errors" "fmt" "os" "path/filepath" "strings" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/stringid" "github.com/kubernetes-incubator/cri-o/oci" "github.com/kubernetes-incubator/cri-o/server/apparmor" "github.com/kubernetes-incubator/cri-o/server/seccomp" "github.com/kubernetes-incubator/cri-o/utils" "github.com/opencontainers/runc/libcontainer/label" "github.com/opencontainers/runtime-tools/generate" "golang.org/x/net/context" pb "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" ) const ( seccompUnconfined = "unconfined" seccompRuntimeDefault = "runtime/default" seccompLocalhostPrefix = "localhost/" ) // CreateContainer creates a new container in specified PodSandbox func (s *Server) CreateContainer(ctx context.Context, req *pb.CreateContainerRequest) (res *pb.CreateContainerResponse, err error) { logrus.Debugf("CreateContainerRequest %+v", req) sbID := req.GetPodSandboxId() if sbID == "" { return nil, fmt.Errorf("PodSandboxId should not be empty") } sandboxID, err := s.podIDIndex.Get(sbID) if err != nil { return nil, fmt.Errorf("PodSandbox with ID starting with %s not found: %v", sbID, err) } sb := s.getSandbox(sandboxID) if sb == nil { return nil, fmt.Errorf("specified sandbox not found: %s", sandboxID) } // The config of the container containerConfig := req.GetConfig() if containerConfig == nil { return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig is nil") } name := containerConfig.GetMetadata().GetName() if name == "" { return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig.Name is empty") } attempt := containerConfig.GetMetadata().GetAttempt() containerID, containerName, err := s.generateContainerIDandName(sb.name, name, attempt) if err != nil { return nil, err } // containerDir is the dir for the container bundle. containerDir := filepath.Join(s.runtime.ContainerDir(), containerID) defer func() { if err != nil { s.releaseContainerName(containerName) err1 := os.RemoveAll(containerDir) if err1 != nil { logrus.Warnf("Failed to cleanup container directory: %v", err1) } } }() if _, err = os.Stat(containerDir); err == nil { return nil, fmt.Errorf("container (%s) already exists", containerDir) } if err = os.MkdirAll(containerDir, 0755); err != nil { return nil, err } container, err := s.createSandboxContainer(containerID, containerName, sb, containerDir, containerConfig) if err != nil { return nil, err } if err = s.runtime.CreateContainer(container); err != nil { return nil, err } if err = s.runtime.UpdateStatus(container); err != nil { return nil, err } s.addContainer(container) if err = s.ctrIDIndex.Add(containerID); err != nil { s.removeContainer(container) return nil, err } resp := &pb.CreateContainerResponse{ ContainerId: &containerID, } logrus.Debugf("CreateContainerResponse: %+v", resp) return resp, nil } func (s *Server) createSandboxContainer(containerID string, containerName string, sb *sandbox, containerDir string, containerConfig *pb.ContainerConfig) (*oci.Container, error) { if sb == nil { return nil, errors.New("createSandboxContainer needs a sandbox") } // creates a spec Generator with the default spec. specgen := generate.New() // by default, the root path is an empty string. // here set it to be "rootfs". specgen.SetRootPath("rootfs") args := containerConfig.GetArgs() if args == nil { args = []string{"/bin/sh"} } specgen.SetProcessArgs(args) cwd := containerConfig.GetWorkingDir() if cwd == "" { cwd = "/" } specgen.SetProcessCwd(cwd) envs := containerConfig.GetEnvs() if envs != nil { for _, item := range envs { key := item.GetKey() value := item.GetValue() if key == "" { continue } env := fmt.Sprintf("%s=%s", key, value) specgen.AddProcessEnv(env) } } mounts := containerConfig.GetMounts() for _, mount := range mounts { dest := mount.GetContainerPath() if dest == "" { return nil, fmt.Errorf("Mount.ContainerPath is empty") } src := mount.GetHostPath() if src == "" { return nil, fmt.Errorf("Mount.HostPath is empty") } options := []string{"rw"} if mount.GetReadonly() { options = []string{"ro"} } if mount.GetSelinuxRelabel() { // Need a way in kubernetes to determine if the volume is shared or private if err := label.Relabel(src, sb.mountLabel, true); err != nil && err != syscall.ENOTSUP { return nil, fmt.Errorf("relabel failed %s: %v", src, err) } } specgen.AddBindMount(src, dest, options) } labels := containerConfig.GetLabels() metadata := containerConfig.GetMetadata() annotations := containerConfig.GetAnnotations() if annotations != nil { for k, v := range annotations { specgen.AddAnnotation(k, v) } } // set this container's apparmor profile if it is set by sandbox if s.appArmorEnabled { appArmorProfileName := s.getAppArmorProfileName(sb.annotations, metadata.GetName()) if appArmorProfileName != "" { specgen.SetProcessApparmorProfile(appArmorProfileName) } } if containerConfig.GetLinux().GetSecurityContext().GetPrivileged() { specgen.SetupPrivileged(true) } if containerConfig.GetLinux().GetSecurityContext().GetReadonlyRootfs() { specgen.SetRootReadonly(true) } logPath := containerConfig.GetLogPath() if containerConfig.GetTty() { specgen.SetProcessTerminal(true) } linux := containerConfig.GetLinux() if linux != nil { resources := linux.GetResources() if resources != nil { cpuPeriod := resources.GetCpuPeriod() if cpuPeriod != 0 { specgen.SetLinuxResourcesCPUPeriod(uint64(cpuPeriod)) } cpuQuota := resources.GetCpuQuota() if cpuQuota != 0 { specgen.SetLinuxResourcesCPUQuota(uint64(cpuQuota)) } cpuShares := resources.GetCpuShares() if cpuShares != 0 { specgen.SetLinuxResourcesCPUShares(uint64(cpuShares)) } memoryLimit := resources.GetMemoryLimitInBytes() if memoryLimit != 0 { specgen.SetLinuxResourcesMemoryLimit(uint64(memoryLimit)) } oomScoreAdj := resources.GetOomScoreAdj() specgen.SetLinuxResourcesOOMScoreAdj(int(oomScoreAdj)) } capabilities := linux.GetSecurityContext().GetCapabilities() if capabilities != nil { addCaps := capabilities.GetAddCapabilities() if addCaps != nil { for _, cap := range addCaps { if err := specgen.AddProcessCapability(cap); err != nil { return nil, err } } } dropCaps := capabilities.GetDropCapabilities() if dropCaps != nil { for _, cap := range dropCaps { if err := specgen.DropProcessCapability(cap); err != nil { return nil, err } } } } specgen.SetProcessSelinuxLabel(sb.processLabel) specgen.SetLinuxMountLabel(sb.mountLabel) user := linux.GetSecurityContext().GetRunAsUser() specgen.SetProcessUID(uint32(user)) specgen.SetProcessGID(uint32(user)) groups := linux.GetSecurityContext().GetSupplementalGroups() for _, group := range groups { specgen.AddProcessAdditionalGid(uint32(group)) } } // Join the namespace paths for the pod sandbox container. podInfraState := s.runtime.ContainerStatus(sb.infraContainer) logrus.Debugf("pod container state %+v", podInfraState) ipcNsPath := fmt.Sprintf("/proc/%d/ns/ipc", podInfraState.Pid) if err := specgen.AddOrReplaceLinuxNamespace("ipc", ipcNsPath); err != nil { return nil, err } netNsPath := sb.netNsPath() if netNsPath == "" { // The sandbox does not have a permanent namespace, // it's on the host one. netNsPath = fmt.Sprintf("/proc/%d/ns/net", podInfraState.Pid) } if err := specgen.AddOrReplaceLinuxNamespace("network", netNsPath); err != nil { return nil, err } imageSpec := containerConfig.GetImage() if imageSpec == nil { return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig.Image is nil") } image := imageSpec.GetImage() if image == "" { return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig.Image.Image is empty") } // bind mount the pod shm specgen.AddBindMount(sb.shmPath, "/dev/shm", []string{"rw"}) specgen.AddAnnotation("ocid/name", containerName) specgen.AddAnnotation("ocid/sandbox_id", sb.id) specgen.AddAnnotation("ocid/sandbox_name", sb.infraContainer.Name()) specgen.AddAnnotation("ocid/container_type", containerTypeContainer) specgen.AddAnnotation("ocid/log_path", logPath) specgen.AddAnnotation("ocid/tty", fmt.Sprintf("%v", containerConfig.GetTty())) specgen.AddAnnotation("ocid/image", image) metadataJSON, err := json.Marshal(metadata) if err != nil { return nil, err } specgen.AddAnnotation("ocid/metadata", string(metadataJSON)) labelsJSON, err := json.Marshal(labels) if err != nil { return nil, err } specgen.AddAnnotation("ocid/labels", string(labelsJSON)) annotationsJSON, err := json.Marshal(annotations) if err != nil { return nil, err } specgen.AddAnnotation("ocid/annotations", string(annotationsJSON)) if err = s.setupSeccomp(&specgen, containerName, sb.annotations); err != nil { return nil, err } if err = specgen.SaveToFile(filepath.Join(containerDir, "config.json"), generate.ExportOptions{}); err != nil { return nil, err } // TODO: copy the rootfs into the bundle. // Currently, utils.CreateFakeRootfs is used to populate the rootfs. if err = utils.CreateFakeRootfs(containerDir, image); err != nil { return nil, err } container, err := oci.NewContainer(containerID, containerName, containerDir, logPath, sb.netNs(), labels, annotations, imageSpec, metadata, sb.id, containerConfig.GetTty()) if err != nil { return nil, err } return container, nil } func (s *Server) setupSeccomp(specgen *generate.Generator, cname string, sbAnnotations map[string]string) error { profile, ok := sbAnnotations["security.alpha.kubernetes.io/seccomp/container/"+cname] if !ok { profile, ok = sbAnnotations["security.alpha.kubernetes.io/seccomp/pod"] if !ok { // running w/o seccomp, aka unconfined profile = seccompUnconfined } } if !s.seccompEnabled { if profile != seccompUnconfined { return fmt.Errorf("seccomp is not enabled in your kernel, cannot run with a profile") } logrus.Warn("seccomp is not enabled in your kernel, running container without profile") } if profile == seccompUnconfined { // running w/o seccomp, aka unconfined specgen.Spec().Linux.Seccomp = nil return nil } if profile == seccompRuntimeDefault { return seccomp.LoadProfileFromStruct(s.seccompProfile, specgen) } if !strings.HasPrefix(profile, seccompLocalhostPrefix) { return fmt.Errorf("unknown seccomp profile option: %q", profile) } //file, err := ioutil.ReadFile(filepath.Join(s.seccompProfileRoot, strings.TrimPrefix(profile, seccompLocalhostPrefix))) //if err != nil { //return err //} // TODO(runcom): setup from provided node's seccomp profile // can't do this yet, see https://issues.k8s.io/36997 return nil } func (s *Server) generateContainerIDandName(podName string, name string, attempt uint32) (string, string, error) { var ( err error id = stringid.GenerateNonCryptoID() ) nameStr := fmt.Sprintf("%s-%s-%v", podName, name, attempt) if name == "infra" { nameStr = fmt.Sprintf("%s-%s", podName, name) } if name, err = s.reserveContainerName(id, nameStr); err != nil { return "", "", err } return id, name, err } // getAppArmorProfileName gets the profile name for the given container. func (s *Server) getAppArmorProfileName(annotations map[string]string, ctrName string) string { profile := apparmor.GetProfileNameFromPodAnnotations(annotations, ctrName) if profile == "" { return "" } if profile == apparmor.ProfileRuntimeDefault { // If the value is runtime/default, then return default profile. return s.appArmorProfile } return strings.TrimPrefix(profile, apparmor.ProfileNamePrefix) }
resouer/cri-o
server/container_create.go
GO
apache-2.0
11,852
// Copyright 2011, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v201109; import com.google.api.adwords.lib.AdWordsService; import com.google.api.adwords.lib.AdWordsServiceLogger; import com.google.api.adwords.lib.AdWordsUser; import com.google.api.adwords.v201109.cm.Media; import com.google.api.adwords.v201109.cm.MediaPage; import com.google.api.adwords.v201109.cm.MediaServiceInterface; import com.google.api.adwords.v201109.cm.OrderBy; import com.google.api.adwords.v201109.cm.Predicate; import com.google.api.adwords.v201109.cm.PredicateOperator; import com.google.api.adwords.v201109.cm.Selector; import com.google.api.adwords.v201109.cm.SortOrder; /** * This example gets all videos. To upload a video, see * http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. * * Tags: MediaService.get * * @category adx-exclude * @author api.arogal@gmail (Adam Rogal) */ public class GetAllVideos { public static void main(String[] args) { try { // Log SOAP XML request and response. AdWordsServiceLogger.log(); // Get AdWordsUser from "~/adwords.properties". AdWordsUser user = new AdWordsUser(); // Get the MediaService. MediaServiceInterface mediaService = user.getService(AdWordsService.V201109.MEDIA_SERVICE); // Create selector. Selector selector = new Selector(); selector.setFields(new String[] {"MediaId", "Name"}); selector.setOrdering(new OrderBy[] {new OrderBy("MediaId", SortOrder.ASCENDING)}); // Create predicates. Predicate typePredicate = new Predicate("Type", PredicateOperator.IN, new String[] {"VIDEO"}); selector.setPredicates(new Predicate[] {typePredicate}); // Get all videos. MediaPage page = mediaService.get(selector); // Display videos. if (page.getEntries() != null) { for (Media video : page.getEntries()) { System.out.println("Video with id '" + video.getMediaId() + "' and name '" + video.getName() + "' was found."); } } else { System.out.println("No videos were found."); } } catch (Exception e) { e.printStackTrace(); } } }
cmmanish/OldUITempTest
examples/v201109/GetAllVideos.java
Java
apache-2.0
2,746
/* * Copyright (c) 2011-2013, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.geo.pose; import georegression.struct.se.Se3_F64; import org.ejml.UtilEjml; import org.ejml.ops.MatrixFeatures; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * @author Peter Abeles */ public class TestPnPRodriguesCodec { @Test public void decode_encode() { double param[] = new double[]{0.1,-0.3,4,1,2,3}; PnPRodriguesCodec alg = new PnPRodriguesCodec(); double found[] = new double[6]; Se3_F64 storage = new Se3_F64(); Se3_F64 storage2 = new Se3_F64(); alg.decode(param, storage); alg.encode(storage,found); alg.decode(found,storage2); // multiple parameterization can represent the same model, so test using the model assertTrue(storage.T.isIdentical(storage2.T,1e-8)); assertTrue(MatrixFeatures.isIdentical(storage.R,storage2.R,1e-8)); } @Test public void testCase0() { Se3_F64 a = new Se3_F64(); a.R = UtilEjml.parseMatrix( "1.000000e+00 -5.423439e-14 -3.165003e-13 \n" + "5.420664e-14 1.000000e+00 2.461642e-13 \n" + "3.162678e-13 -2.464418e-13 1.000000e+00",3); PnPRodriguesCodec alg = new PnPRodriguesCodec(); double param[] = new double[6]; alg.encode(a,param); Se3_F64 found = new Se3_F64(); alg.decode(param,found); assertTrue(a.T.isIdentical(found.T,1e-8)); assertTrue(MatrixFeatures.isIdentical(a.R,found.R,1e-8)); } }
intrack/BoofCV-master
main/geo/test/boofcv/alg/geo/pose/TestPnPRodriguesCodec.java
Java
apache-2.0
2,081
package com.nitorcreations.willow.auth; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.singletonMap; import static java.util.Collections.unmodifiableSet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.SimpleAccount; import org.apache.shiro.authz.Permission; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.common.collect.ImmutableMap; import mx.com.inftel.shiro.oauth2.AbstractOAuth2AuthenticatingFilter; public class GitHubOAuthAuthenticatingFilter extends AbstractOAuth2AuthenticatingFilter { private static final String SCOPE = "user:email,read:org"; private final Map<String,? extends Permission> PERMISSIONS; private final GitHubOAuthAccounts accounts; @Inject public GitHubOAuthAuthenticatingFilter(GitHubOAuthConfig config, GitHubOAuthAccounts accounts) throws IOException { setRedirectUri(config.getRedirectUri()); setClientId(config.getClientId()); setClientSecret(config.getClientSecret()); setLoginUrl("/"); this.accounts = accounts; PERMISSIONS = ImmutableMap.of( config.getOrganization() + "." + config.getAdminTeam(), Permissions.ADMIN, config.getOrganization(), Permissions.MONITOR); } @Override public String getName() { return getClass().getName(); } @Override protected String getAuthorizeURL(ServletRequest request, ServletResponse response) throws Exception { return makeStandardAuthorizeURL(request, response, "https://github.com/login/oauth/authorize", SCOPE); } @Override protected JSONObject getOAuth2Principal(ServletRequest request, ServletResponse response) throws Exception { String tokenResponse = httpPost("https://github.com/login/oauth/access_token", "client_id=" + getClientId() + "&client_secret=" + getClientSecret() + "&redirect_uri=" + encodeURL(getRedirectUri()) + "&code=" + encodeURL(request.getParameter("code"))); String token = getAccessToken(tokenResponse); Map<String,String> headers = singletonMap("Authorization", "token " + token); JSONArray memberOf = JSONTool.toArray(getOrganizations(headers), getTeams(headers)); String loginId = new JSONObject(httpGet("https://api.github.com/user", headers)).getString("login"); JSONObject ret = new JSONObject() .put("login", loginId) .put("member_of", memberOf) .put("token", token); SimpleAccount acco = doGetAuthenticationInfo(ret); accounts.add(acco); return ret; } @Override protected String getOAuth2Credentials(JSONObject principal) throws Exception { return principal.getString("login"); } private String getAccessToken(String response) throws Exception { for(String param : response.split("&")) { if(param.startsWith("access_token=")) { return decodeURL(param.substring(param.indexOf('=') + 1)); } } throw new IllegalStateException("access_token param not sent by idp"); } private List<String> getOrganizations(Map<String,String> headers) throws Exception { JSONArray organizations = new JSONArray(httpGet("https://api.github.com/user/orgs", headers)); List<String> names = new ArrayList<>(); for(int i = 0; i < organizations.length(); i++) { names.add(organizations.getJSONObject(i).getString("login")); } return Collections.unmodifiableList(names); } private List<String> getTeams(Map<String,String> headers) throws Exception { JSONArray teams = new JSONArray(httpGet("https://api.github.com/user/teams", headers)); List<String> names = new ArrayList<>(); for(int i = 0; i < teams.length(); i++) { JSONObject team = teams.getJSONObject(i); names.add(team.getJSONObject("organization").getString("login") + "." + team.getString("name")); } return Collections.unmodifiableList(names); } private String httpGet(String url, Map<String, String> headers) throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); for(Map.Entry<String,String> header : headers.entrySet()) { conn.setRequestProperty(header.getKey(), header.getValue()); } return readResponseBody(conn); } private String httpPost(String url, String data) throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); try(OutputStream out = conn.getOutputStream()) { out.write(data.getBytes(UTF_8)); } return readResponseBody(conn); } @SuppressFBWarnings(value={"RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE"}, justification="null check in try-with-resources magic bytecode") private String readResponseBody(HttpURLConnection conn) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; try(InputStream in = conn.getResponseCode() == 200 ? conn.getInputStream() : conn.getErrorStream()) { for(int i = in.read(buf); i != -1; i = in.read(buf)) { baos.write(buf, 0, i); } } String body = new String(baos.toByteArray(), UTF_8); if(conn.getResponseCode() != 200) { throw new IllegalStateException(String.format("idp responded with HTTP %s %s: %s", conn.getResponseCode(), conn.getResponseMessage(), body)); } return body; } public SimpleAccount doGetAuthenticationInfo(JSONObject user) throws AuthenticationException { try { String userId = user.getString("login"); Set<String> memberOf = JSONTool.toStringSet(user.getJSONArray("member_of")); return new SimpleAccount(userId, userId, getName(), memberOf, memberShipsToPermissions(memberOf)); } catch (JSONException e) { throw new AuthenticationException(e); } } protected Set<Permission> memberShipsToPermissions(Set<String> organizations) { Set<Permission> permissions = new HashSet<>(); for(String team : organizations) { Permission permission = PERMISSIONS.get(team); if(permission != null) { permissions.add(permission); } } return unmodifiableSet(permissions); } }
NitorCreations/willow
willow-servers/src/main/java/com/nitorcreations/willow/auth/GitHubOAuthAuthenticatingFilter.java
Java
apache-2.0
6,779
/* First created by JCasGen Sat Apr 11 19:49:33 EDT 2015 */ package edu.cmu.lti.oaqa.type.answer; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** A Named Entity type that represents the type of the answer being sought. * Updated by JCasGen Sun Apr 19 19:46:49 EDT 2015 * @generated */ public class AnswerType_Type extends Annotation_Type { /** @generated * @return the generator for this type */ @Override protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (AnswerType_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = AnswerType_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new AnswerType(addr, AnswerType_Type.this); AnswerType_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new AnswerType(addr, AnswerType_Type.this); } }; /** @generated */ @SuppressWarnings ("hiding") public final static int typeIndexID = AnswerType.typeIndexID; /** @generated @modifiable */ @SuppressWarnings ("hiding") public final static boolean featOkTst = JCasRegistry.getFeatOkTst("edu.cmu.lti.oaqa.type.answer.AnswerType"); /** @generated */ final Feature casFeat_label; /** @generated */ final int casFeatCode_label; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getLabel(int addr) { if (featOkTst && casFeat_label == null) jcas.throwFeatMissing("label", "edu.cmu.lti.oaqa.type.answer.AnswerType"); return ll_cas.ll_getStringValue(addr, casFeatCode_label); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setLabel(int addr, String v) { if (featOkTst && casFeat_label == null) jcas.throwFeatMissing("label", "edu.cmu.lti.oaqa.type.answer.AnswerType"); ll_cas.ll_setStringValue(addr, casFeatCode_label, v);} /** @generated */ final Feature casFeat_targetType; /** @generated */ final int casFeatCode_targetType; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public int getTargetType(int addr) { if (featOkTst && casFeat_targetType == null) jcas.throwFeatMissing("targetType", "edu.cmu.lti.oaqa.type.answer.AnswerType"); return ll_cas.ll_getRefValue(addr, casFeatCode_targetType); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setTargetType(int addr, int v) { if (featOkTst && casFeat_targetType == null) jcas.throwFeatMissing("targetType", "edu.cmu.lti.oaqa.type.answer.AnswerType"); ll_cas.ll_setRefValue(addr, casFeatCode_targetType, v);} /** initialize variables to correspond with Cas Type and Features * @generated * @param jcas JCas * @param casType Type */ public AnswerType_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_label = jcas.getRequiredFeatureDE(casType, "label", "uima.cas.String", featOkTst); casFeatCode_label = (null == casFeat_label) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_label).getCode(); casFeat_targetType = jcas.getRequiredFeatureDE(casType, "targetType", "uima.tcas.Annotation", featOkTst); casFeatCode_targetType = (null == casFeat_targetType) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_targetType).getCode(); } }
oaqa/baseqa
src/main/java/edu/cmu/lti/oaqa/type/answer/AnswerType_Type.java
Java
apache-2.0
4,196
""" Simple demo of a scatter plot. """ import numpy as np import matplotlib.pyplot as plt N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radii plt.scatter(x, y, s=area, c=colors, alpha=0.5) plt.show()
ArmstrongYang/StudyShare
Python-matplotlib/scatter_demo.py
Python
apache-2.0
295
package com.planet_ink.coffee_mud.Abilities.Traps; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2016 Bo Zimmerman 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. */ public class Trap_CaveIn extends StdTrap { @Override public String ID() { return "Trap_CaveIn"; } private final static String localizedName = CMLib.lang().L("cave-in"); @Override public String name() { return localizedName; } @Override protected int canAffectCode() { return Ability.CAN_ROOMS; } @Override protected int canTargetCode() { return 0; } @Override protected int trapLevel() { return 22; } @Override public String requiresToSet() { return "100 pounds of wood"; } @Override public int baseRejuvTime(int level) { return 6; } @Override public List<Item> getTrapComponents() { final List<Item> V=new Vector<Item>(); for(int i=0;i<100;i++) V.add(CMLib.materials().makeItemResource(RawMaterial.RESOURCE_WOOD)); return V; } @Override public Trap setTrap(MOB mob, Physical P, int trapBonus, int qualifyingClassLevel, boolean perm) { if(P==null) return null; if(mob!=null) { final Item I=findMostOfMaterial(mob.location(),RawMaterial.MATERIAL_WOODEN); if(I!=null) super.destroyResources(mob.location(),I.material(),100); } return super.setTrap(mob,P,trapBonus,qualifyingClassLevel,perm); } @Override public boolean canSetTrapOn(MOB mob, Physical P) { if(!super.canSetTrapOn(mob,P)) return false; if(mob!=null) { final Item I=findMostOfMaterial(mob.location(),RawMaterial.MATERIAL_WOODEN); if((I==null) ||(super.findNumberOfResource(mob.location(),I.material())<100)) { mob.tell(L("You'll need to set down at least 100 pounds of wood first.")); return false; } } if(P instanceof Room) { final Room R=(Room)P; if(R.domainType()!=Room.DOMAIN_INDOORS_CAVE) { if(mob!=null) mob.tell(L("You can only set this trap in caves.")); return false; } } return true; } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((sprung) &&(affected!=null) &&(!disabled()) &&(tickDown>=0)) { if(((msg.targetMinor()==CMMsg.TYP_LEAVE) ||(msg.targetMinor()==CMMsg.TYP_ENTER) ||(msg.targetMinor()==CMMsg.TYP_FLEE)) &&(msg.amITarget(affected))) { msg.source().tell(L("The cave-in prevents entry or exit from here.")); return false; } } return super.okMessage(myHost,msg); } @Override public void spring(MOB target) { if((target!=invoker())&&(target.location()!=null)) { if((doesSaveVsTraps(target)) ||(invoker().getGroupMembers(new HashSet<MOB>()).contains(target))) target.location().show(target,null,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> avoid(s) setting off a cave-in!")); else if(target.location().show(target,target,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> trigger(s) a cave-in!"))) { super.spring(target); if((affected!=null) &&(affected instanceof Room)) { final Room R=(Room)affected; for(int i=0;i<R.numInhabitants();i++) { final MOB M=R.fetchInhabitant(i); if((M!=null)&&(M!=invoker())) if(invoker().mayIFight(M)) { final int damage=CMLib.dice().roll(trapLevel()+abilityCode(),20,1); CMLib.combat().postDamage(invoker(),M,this,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_JUSTICE,Weapon.TYPE_BASHING,L("The cave-in <DAMAGE> <T-NAME>!")); } } } } } } }
oriontribunal/CoffeeMud
com/planet_ink/coffee_mud/Abilities/Traps/Trap_CaveIn.java
Java
apache-2.0
4,993
/* * Copyright 2018 Mirko Sertic * * 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 de.mirkosertic.bytecoder.backend.wasm.ast; import de.mirkosertic.bytecoder.ssa.Expression; public class I32Or extends BinaryExpression { I32Or(final WASMValue left, final WASMValue right, final Expression expression) { super(left, right,"i32.or", (byte) 0x72, expression); } }
mirkosertic/Bytecoder
core/src/main/java/de/mirkosertic/bytecoder/backend/wasm/ast/I32Or.java
Java
apache-2.0
902
import { Routes } from '@angular/router'; import { EditorComponent } from './editor/editor.component' export const routes: Routes = [ { path: 'config/:id', component: EditorComponent } ];
jianzhichun/mongodb-spring-cloud-config-server
src/main/frontend/src/app/app.routes.ts
TypeScript
apache-2.0
211
package com.coolweather.android.gson; /** * Created by LanQ on 2017/8/21 0021. */ public class AQI { public AQICity city; public class AQICity{ public String aqi; public String pm25; } }
lq2677/myweather
app/src/main/java/com/coolweather/android/gson/AQI.java
Java
apache-2.0
223
/** * Copyright (C) 2016 - 2030 youtongluan. * * 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.yx.validate; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.yx.annotation.spec.ParamSpec; import org.yx.annotation.spec.Specs; import org.yx.util.CollectionUtil; public final class FieldParameterHolder { private static final ConcurrentMap<Class<?>, List<FieldParameterInfo>> map = new ConcurrentHashMap<>(); public static void put(Class<?> clz, List<FieldParameterInfo> infos) { if (clz == null || infos == null || infos.isEmpty()) { return; } map.put(clz, infos); } public static Set<Class<?>> keys() { return new HashSet<>(map.keySet()); } public static List<FieldParameterInfo> get(Class<?> clz) { return map.get(clz); } public static Map<Field, FieldParameterInfo> getFieldParameterMap(Class<?> clz) { List<FieldParameterInfo> infos = get(clz); if (infos == null) { return Collections.emptyMap(); } Map<Field, FieldParameterInfo> infoMap = new HashMap<>(); for (FieldParameterInfo info : infos) { infoMap.put(info.getField(), info); } return infoMap; } public static void registerFieldInfo(final Class<?> clazz) { if (clazz.isArray()) { registerFieldInfo(clazz.getComponentType()); return; } if (!Validators.supportComplex(clazz)) { return; } if (get(clazz) != null) { return; } List<FieldParameterInfo> list = new ArrayList<>(); Class<?> tempClz = clazz; while (tempClz != null && !tempClz.getName().startsWith("java.")) { Field[] fs = tempClz.getDeclaredFields(); for (Field f : fs) { if (Modifier.isStatic(f.getModifiers())) { continue; } ParamSpec p = Specs.extractParamField(f); if (p == null) { continue; } FieldParameterInfo info = new FieldParameterInfo(p, f); if (!info.maybeCheck()) { continue; } list.add(info); if (info.isComplex()) { registerFieldInfo(info.getParamType()); } } tempClz = tempClz.getSuperclass(); } if (list.size() > 0) { put(clazz, CollectionUtil.unmodifyList(list.toArray(new FieldParameterInfo[list.size()]))); } } }
youtongluan/sumk
src/main/java/org/yx/validate/FieldParameterHolder.java
Java
apache-2.0
2,939
package eu.ensure.ppe; import org.gautelis.vopn.lang.Number; import org.gautelis.vopn.statistics.MovingAverage; import eu.ensure.ppe.model.Consequence; import java.util.Collection; import java.util.LinkedList; public class AggregationLevelScore { public static final double FAILURE_SCORE = 0.0; final String id; // Id of aggregation final String name; final double score; final double stdDev; final double cv; final long datasetSize; final Collection<String> storyLine; final Collection<Consequence> consequences; AggregationLevelScore(String aggrId, String aggrName, MovingAverage stats, Collection<String> storyLine, Collection<Consequence> consequences) { this.id = aggrId; this.name = aggrName; this.storyLine = storyLine; if (null == consequences) { this.consequences = new LinkedList<Consequence>(); } else { this.consequences = consequences; } // this.score = Number.roundTwoDecimals(stats.getAverage()); this.stdDev = Number.roundTwoDecimals(stats.getStdDev()); this.cv = Number.roundTwoDecimals(stats.getCV()); this.datasetSize = stats.getCount(); } public String getId() { return id; } public String getName() { return name; } public double getScore() { return score; } public double getStdDev() { return stdDev; } public double getCV() { return cv; } public long getDatasetSize() { return datasetSize; } public Collection<String> getStoryLine() { return storyLine; } public Collection<Consequence> getConsequences() { return consequences; } }
FrodeRanders/ensure
ppe/src/main/java/eu/ensure/ppe/AggregationLevelScore.java
Java
apache-2.0
1,778
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iot1clickprojects.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iot1click-projects-2018-05-14/DescribePlacement" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribePlacementRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the placement within a project. * </p> */ private String placementName; /** * <p> * The project containing the placement to be described. * </p> */ private String projectName; /** * <p> * The name of the placement within a project. * </p> * * @param placementName * The name of the placement within a project. */ public void setPlacementName(String placementName) { this.placementName = placementName; } /** * <p> * The name of the placement within a project. * </p> * * @return The name of the placement within a project. */ public String getPlacementName() { return this.placementName; } /** * <p> * The name of the placement within a project. * </p> * * @param placementName * The name of the placement within a project. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribePlacementRequest withPlacementName(String placementName) { setPlacementName(placementName); return this; } /** * <p> * The project containing the placement to be described. * </p> * * @param projectName * The project containing the placement to be described. */ public void setProjectName(String projectName) { this.projectName = projectName; } /** * <p> * The project containing the placement to be described. * </p> * * @return The project containing the placement to be described. */ public String getProjectName() { return this.projectName; } /** * <p> * The project containing the placement to be described. * </p> * * @param projectName * The project containing the placement to be described. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribePlacementRequest withProjectName(String projectName) { setProjectName(projectName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPlacementName() != null) sb.append("PlacementName: ").append(getPlacementName()).append(","); if (getProjectName() != null) sb.append("ProjectName: ").append(getProjectName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribePlacementRequest == false) return false; DescribePlacementRequest other = (DescribePlacementRequest) obj; if (other.getPlacementName() == null ^ this.getPlacementName() == null) return false; if (other.getPlacementName() != null && other.getPlacementName().equals(this.getPlacementName()) == false) return false; if (other.getProjectName() == null ^ this.getProjectName() == null) return false; if (other.getProjectName() != null && other.getProjectName().equals(this.getProjectName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPlacementName() == null) ? 0 : getPlacementName().hashCode()); hashCode = prime * hashCode + ((getProjectName() == null) ? 0 : getProjectName().hashCode()); return hashCode; } @Override public DescribePlacementRequest clone() { return (DescribePlacementRequest) super.clone(); } }
jentfoo/aws-sdk-java
aws-java-sdk-iot1clickprojects/src/main/java/com/amazonaws/services/iot1clickprojects/model/DescribePlacementRequest.java
Java
apache-2.0
5,307
using System; using System.Collections.Generic; namespace PMS.Data.Models { public partial class Status { public Status() { Issue = new HashSet<Issue>(); } public int Id { get; set; } public string Name { get; set; } public short Priority { get; set; } public ICollection<Issue> Issue { get; set; } } }
ntgnst/ProjectManagementSystem
PMS.Data/Models/Status.cs
C#
apache-2.0
389
/* * Copyright 2009-2015 University of Hildesheim, Software Systems Engineering * * 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.ssehub.easy.basics.modelManagement; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.List; /** * Stores model information objects of the same version. * * @param <M> the specific type of model * * @author Holger Eichelberger */ public class VersionedModelInfos <M extends IModel> { private Version version; private List<ModelInfo<M>> infos = new ArrayList<ModelInfo<M>>(); /** * Creates a new versioned model information container. * * @param version the version of this container (may be <b>null</b>) */ public VersionedModelInfos(Version version) { this.version = version; } /** * Adds a model information object. * * @param info the object to be added * @throws IllegalArgumentException if the version of <code>info</code> does * not match {@link #version} or the name of <code>info</code> does not match * the name of the first stored model information object (if there is any) */ public void add(ModelInfo<M> info) { assert null != info; if (!Version.equals(info.getVersion(), version)) { throw new IllegalArgumentException("versions do not match"); } if (!infos.isEmpty()) { ModelInfo<M> first = infos.get(0); if (!first.getName().equals(info.getName())) { throw new IllegalArgumentException("names do not match"); } } for (int i = 0; i < infos.size(); i++) { ModelInfo<M> tmp = infos.get(i); if (isSame(tmp.getLocation(), info.getLocation()) && tmp.getLoader() == info.getLoader()) { throw new IllegalArgumentException("URI and loader match"); } } // multiple equal URIs may exist due to different loaders -> any shall be fine infos.add(info); } /** * Checks two URIs for equality. * * @param uri1 the first URI (may be <b>null</b>) * @param uri2 the second URI (may be <b>null</b>) * @return <code>true</code> if both are the same, <code>false</code> else */ public static final boolean isSame(URI uri1, URI uri2) { return (null == uri1 && uri1 == uri2) || (null != uri1 && uri1.equals(uri2)); } /** * Returns the specified model information object. * * @param index the index of the object to be returned * @return the specified object * @throws IndexOutOfBoundsException if <code>index&lt;0 * || index&gt;={@link #size()}</code> */ public ModelInfo<M> get(int index) { return infos.get(index); } /** * Returns the model information objects with <code>model</code> as resolved model. * * @param model the (resolved) model to search for * @return the model information object or <b>null</b> if there is none */ public ModelInfo<M> get(M model) { ModelInfo<M> result = null; int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> tmp = infos.get(i); if (tmp.getResolved() == model) { result = tmp; } } return result; } /** * Returns the model information objects with <code>uri</code> as location. * * @param uri the URI to search for * @return the model information object or <b>null</b> if there is none */ public ModelInfo<M> get(URI uri) { ModelInfo<M> result = null; int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> tmp = infos.get(i); if ((null == uri && tmp.getLocation() == uri) || (null != uri && uri.equals(tmp.getLocation()))) { result = tmp; } } return result; } /** * Returns the number of contained version information objects. * * @return the number of version information objects */ public int size() { return infos.size(); } /** * Removes the specified model information object. * @param index the index of the object to be returned * @return the removed object * @throws IndexOutOfBoundsException if <code>index&lt;0 * || index&gt;={@link #size()}</code> */ public ModelInfo<M> remove(int index) { return infos.remove(index); } /** * Removes all stored model information objects. */ public void clear() { infos.clear(); } /** * Removes the specified model information object. * @param info the information object to be removed * @return <code>true</code> if successful <code>false</code> else */ public boolean remove(ModelInfo<M> info) { return infos.remove(info); } /** * Returns the version all information objects in this instance * are assigned to. * * @return the version */ public Version getVersion() { return version; } /** * Returns the model information with the exact match to <code>uri</code>. * * @param uri the URI to match with (may be <b>null</b> then the first * information object is returned) * @return the matching model information (or <b>null</b> if none matches) */ public List<ModelInfo<M>> getByEqualUri(URI uri) { List<ModelInfo<M>> result = null; if (null != uri) { uri = uri.normalize(); int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> info = infos.get(i); if (null != info.getLocation() && uri.equals(info.getLocation())) { if (null == result) { result = new ArrayList<ModelInfo<M>>(); } result.add(info); } } } return result; } /** * Returns the model information with the closest match * to <code>uri</code>, i.e. in closest in the same hierarchy path. * * @param uri the URI to match with (may be <b>null</b> then the first * information object is returned) * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ public ModelInfo<M> getByClosestUri(URI uri, List<String> modelPath) { return getByClosestUri(infos, uri, modelPath); } /** * Returns the model information from <code>infos</code> with the closest match * to <code>uri</code>, i.e. in closest in the same hierarchy path. * * @param <M> the model type * @param infos the information objects to be considered * @param uri the URI to match with (may be <b>null</b> then the first * information object is returned) * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ public static <M extends IModel> ModelInfo<M> getByClosestUri(List<ModelInfo<M>> infos, URI uri, List<String> modelPath) { ModelInfo<M> result = null; int size = infos.size(); if (size > 0) { if (null == uri/* || null == version*/) { result = infos.get(0); } else { // precedence to same file for (int i = 0; null == result && i < size; i++) { ModelInfo<M> info = infos.get(i); if (isSame(uri, info.getLocation())) { result = info; } } // precedence to own hierarchy String searchUriText = pathWithoutLastFragment(uri.normalize()); if (null == result) { // search according to hierarchical IVML convention result = search(infos, searchUriText, modelPath); // this may fail, in particular for parent projects imported according to EASy convention if (null == result) { result = searchOnParentLevel(infos, uri, modelPath); } // search in folders on the same level if (null == result) { result = searchOnSameFolderLevel(infos, uri, modelPath); } } // containment in model path if (null != modelPath) { for (int i = 0; null == result && i < size; i++) { ModelInfo<M> info = infos.get(i); for (int m = 0; null == result && m < modelPath.size(); m++) { if (isMatching(info.getLocation().toString(), modelPath.get(m), false)) { result = info; } } } } } } return result; } /** * Searches for the best match according to the IVML search conventions, first down along the given * URI, then up along the hierarchy. * * @param <M> the model type * @param infos the information objects to be considered * @param searchUriText the search folder URI as text * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ private static <M extends IModel> ModelInfo<M> search(List<ModelInfo<M>> infos, String searchUriText, List<String> modelPath) { ModelInfo<M> result = null; int matchLength = 0; // 0 == b: down, 1 == b up in URI hierarchy for (int b = 0; null == result && 0 == matchLength && b < 2; b++) { int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> info = infos.get(i); URI infoUri = info.getLocation(); if (null == infoUri) { continue; } String infoUriText = pathWithoutLastFragment(infoUri); if (isMatching(searchUriText, modelPath, infoUriText, 0 == b)) { // the first match is a candidate boolean isBestMatch = (0 == matchLength); // down, then minimize match length isBestMatch |= (0 == b && infoUriText.length() < matchLength); // up, then maximize match length isBestMatch |= (1 == b && infoUriText.length() > matchLength); if (isBestMatch) { result = infos.get(i); matchLength = infoUriText.length(); } } } } return result; } /** * Searches for the best match within the parent-parent folders of <code>uri</code> if that folder starts with * ".". This enables cross-links among parent models according to the convention EASy places imported IVML files. * * @param <M> the model type * @param infos the information objects to be considered * @param uri the URI to start searching * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ private static <M extends IModel> ModelInfo<M> searchOnParentLevel(List<ModelInfo<M>> infos, URI uri, List<String> modelPath) { ModelInfo<M> result = null; if (isFileScheme(uri)) { File uriFile = new File(uri); File uriParent = uriFile.getParentFile(); File parent = uriParent; // step two levels up... // uri = EASy/.core/core.ivml; uri-parent = EASy/.core; uri-parent-parent = EASy if (null != parent) { if (parent.getName().startsWith(".")) { // do not consider other parents, EASy-folder not known here! parent = parent.getParentFile(); } else { parent = null; } } if (null != parent) { File[] siblings = parent.listFiles(); if (null != siblings) { for (int s = 0; null == result && s < siblings.length; s++) { File sibling = siblings[s]; if (sibling.isDirectory() && !sibling.equals(uriParent)) { URI siblingUri = sibling.toURI().normalize(); result = search(infos, siblingUri.toString(), modelPath); } } } } } return result; } /** * Search in folders on the level of the parent folder of <code>uri</code>. * * @param <M> the model type * @param infos the information objects to be considered * @param uri the URI to start searching * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information but only if this is unique */ private static <M extends IModel> ModelInfo<M> searchOnSameFolderLevel(List<ModelInfo<M>> infos, URI uri, List<String> modelPath) { ModelInfo<M> result = null; if (isFileScheme(uri)) { List<ModelInfo<M>> tmp = new ArrayList<ModelInfo<M>>(); File uriFile = new File(uri).getParentFile(); File searchFolder = uriFile.getParentFile(); if (null != searchFolder) { File[] files = searchFolder.listFiles(); for (int f = 0; null != files && f < files.length; f++) { File file = files[f]; if (file.isDirectory() && !file.equals(uriFile)) { String searchUriText = file.toURI().normalize().toString(); ModelInfo<M> searchResult = search(infos, searchUriText, modelPath); if (null != searchResult) { tmp.add(searchResult); } } } } if (1 == tmp.size()) { result = tmp.get(0); } // else -> result = null; // if not found or multiple are found } return result; } /** * Returns whether the given URI is a file (file scheme). * * @param uri the URI to test for * @return <code>true</code> if it is a file, <code>false</code> else */ public static boolean isFileScheme(URI uri) { return "file".equals(uri.getScheme()); } /** * Checks whether the <code>searchUriText</code> (with precedence) ore one of the * <code>modelPath</code> URI paths match <code>importUri</code>, i.e. whether * <code>importUri</code> is an appropriate URI for import. * * @param searchUriText the textual URI of the model stating the import * @param modelPath additional URI paths, may be <b>null</b> * @param importUriText the URI path of the model being considered for import * @param contained prefer contained or containing URIs * @return <code>true</code> if the specified data match, <code>false</code> if not */ private static boolean isMatching(String searchUriText, List<String> modelPath, String importUriText, boolean contained) { boolean matches = isMatching(searchUriText, importUriText, contained); if (!matches && null != modelPath) { int size = modelPath.size(); for (int p = 0; !matches && p < size; p++) { matches = isMatching(searchUriText, modelPath.get(p), contained); } } return matches; } /** * Checks whether the <code>searchUriText</code> and <code>importUri</code> match. * * @param searchUriText the textual URI of the model stating the import * @param importUriText the URI path of the model being considered for import * @param contained prefer contained or containing URIs * @return <code>true</code> if the specified data match, <code>false</code> if not */ private static boolean isMatching(String searchUriText, String importUriText, boolean contained) { return contained ? importUriText.startsWith(searchUriText) : searchUriText.startsWith(importUriText); } /** * Returns the prefix path of the given <code>uri</code> without the last fragment. * * @param uri the URI to be considered * @return the prefix path if possible, the <code>uri</code> else */ public static String pathWithoutLastFragment(URI uri) { String uriText = uri.toString(); int pos = uriText.lastIndexOf('/'); if (pos > 0) { uriText = uriText.substring(0, pos + 1); } return uriText; } /** * Adds all model information objects to the given <code>list</code>. * * @param list the list to be modified as a side effect (may be <b>null</b> * then a list is created) * @return <code>list</code> or the created list */ public List<ModelInfo<M>> toList(List<ModelInfo<M>> list) { if (null == list) { list = new ArrayList<ModelInfo<M>>(); } for (int i = 0; i < infos.size(); i++) { list.add(infos.get(i)); } return list; } /** * Returns the textual representation of this instance. * * @return the textual representation */ public String toString() { return version + " " + infos; } /** * Finds a model information object based on a give URI. * * @param uri the URI to find the information object * @return the information object or <b>null</b> if not found */ public ModelInfo<M> find(URI uri) { ModelInfo<M> result = null; if (null != uri) { int size = infos.size(); for (int i = 0; null == result && i < size; i++) { ModelInfo<M> info = infos.get(i); if (uri.equals(info.getLocation())) { result = info; } } } return result; } /** * Retrieves the version model information container with the specified version. * * @param <M> the specific type of model * * @param infos a list of model information containers (may be <b>null</b>) * @param version the version to retrieve * @return the first matching container */ public static <M extends IModel> VersionedModelInfos<M> find(List<VersionedModelInfos<M>> infos, Version version) { VersionedModelInfos<M> result = null; if (null != infos) { for (int i = 0; null == result && i < infos.size(); i++) { VersionedModelInfos<M> info = infos.get(i); if (Version.equals(info.getVersion(), version)) { result = info; } } } return result; } /** * Returns the model information object with highest version number from <code>list</code>. * Unspecified versions are treated as implicit minimum. * * @param <M> the actual model type * @param list the list of model information objects to determine the maximum from (may be <b>null</b>) * @return the maximum version */ public static <M extends IModel> ModelInfo<M> maxVersion(List<ModelInfo<M>> list) { ModelInfo<M> result = null; if (null != list) { Version highest = null; for (int i = 0, n = list.size(); i < n; i++) { ModelInfo<M> tmp = list.get(i); Version tmpVersion = tmp.getVersion(); if (null == result || Version.compare(tmpVersion, highest) > 0) { result = tmp; highest = tmpVersion; } } } return result; } }
SSEHUB/EASyProducer
Plugins/VarModel/Utils/src/net/ssehub/easy/basics/modelManagement/VersionedModelInfos.java
Java
apache-2.0
21,315
package com.sap.cloud.lm.sl.cf.core.liquibase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import com.sap.cloud.lm.sl.cf.core.model.CloudTarget; import com.sap.cloud.lm.sl.cf.core.util.ConfigurationEntriesUtil; public class TransformFilterColumnTest { private TransformFilterColumn transformFilterColumn = new TransformFilterColumn(); @Test public void testSplitTargetSpaceValue() { CloudTarget targetSpace = ConfigurationEntriesUtil.splitTargetSpaceValue("org space"); assertEquals("org", targetSpace.getOrg()); assertEquals("space", targetSpace.getSpace()); targetSpace = ConfigurationEntriesUtil.splitTargetSpaceValue("orgspace"); assertEquals("", targetSpace.getOrg()); assertEquals("orgspace", targetSpace.getSpace()); targetSpace = ConfigurationEntriesUtil.splitTargetSpaceValue("org test space sap"); assertEquals("org", targetSpace.getOrg()); assertEquals("test space sap", targetSpace.getSpace()); targetSpace = ConfigurationEntriesUtil.splitTargetSpaceValue(""); assertEquals("", targetSpace.getOrg()); assertEquals("", targetSpace.getSpace()); } @Test public void testTransformData() { Map<Long, String> retrievedData = new HashMap<Long, String>(); retrievedData.put(1l, "{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":\"org space\"}"); retrievedData.put(2l, "{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":\"orgspace\"}"); retrievedData.put(3l, "{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":\"org test space sap\"}"); Map<Long, String> transformedData = transformFilterColumn.transformData(retrievedData); assertEquals("{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":{\"space\":\"space\",\"org\":\"org\"}}", transformedData.get(1l)); transformedData = transformFilterColumn.transformData(retrievedData); assertEquals("{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":{\"space\":\"orgspace\",\"org\":\"\"}}", transformedData.get(2l)); transformedData = transformFilterColumn.transformData(retrievedData); assertEquals("{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":{\"space\":\"test space sap\",\"org\":\"org\"}}", transformedData.get(3l)); } @Test public void testTransformDataEmptyContent() { Map<Long, String> retrievedData = new HashMap<Long, String>(); Map<Long, String> transformedData = null; retrievedData.put(1l, "{\"requiredContent\":{\"type\":\"com.acme.plugin\"}}"); transformedData = transformFilterColumn.transformData(retrievedData); assertTrue(transformedData.isEmpty()); retrievedData.put(1l, "{}"); transformedData = transformFilterColumn.transformData(retrievedData); assertTrue(transformedData.isEmpty()); retrievedData.put(1l, ""); transformedData = transformFilterColumn.transformData(retrievedData); assertTrue(transformedData.isEmpty()); } }
boyan-velinov/cf-mta-deploy-service
com.sap.cloud.lm.sl.cf.core/src/test/java/com/sap/cloud/lm/sl/cf/core/liquibase/TransformFilterColumnTest.java
Java
apache-2.0
3,357
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.runtime.match; import org.apache.flink.cep.EventComparator; import org.apache.flink.table.dataformat.BaseRow; import org.apache.flink.table.generated.GeneratedRecordComparator; import org.apache.flink.table.generated.RecordComparator; /** * An implementation of {@link EventComparator} based on a generated {@link RecordComparator}. */ public class BaseRowEventComparator implements EventComparator<BaseRow> { private static final long serialVersionUID = 1L; private final GeneratedRecordComparator generatedComparator; private transient RecordComparator comparator; public BaseRowEventComparator(GeneratedRecordComparator generatedComparator) { this.generatedComparator = generatedComparator; } @Override public int compare(BaseRow row1, BaseRow row2) { if (comparator == null) { comparator = generatedComparator.newInstance( Thread.currentThread().getContextClassLoader()); } return comparator.compare(row1, row2); } }
shaoxuan-wang/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/match/BaseRowEventComparator.java
Java
apache-2.0
1,790
<?php /** * Created by JetBrains PhpStorm. * User: occul_000 * Date: 03/03/13 * Time: 19:45 * To change this template use File | Settings | File Templates. */ ?> <!DOCTYPE html> <html> <head> <title>AnfShift</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link rel="stylesheet" href="../docs/assets/css/bootstrap.css"> <meta charset="utf-8"> <link rel="stylesheet" href="../docs/assets/css/style.css"> </head> <body> <header> <div class="navbar navbar-static-top"> <div class="navbar-inner"> <div class="container"> <a class="brand" href="#">Abercrombie & Fitch</a> <ul class="nav pull-right"> <a href="login.php" class="btn btn-large btn-primary">Sign in</a> </ul> </div> </div> </div> </header> <section> <div class="container"> <div class="info"> <h3>Exchange shift,</h3> <h3>Open shift.</h3> <p class="lead">only for associates</p> </div> <div class="container-form"> <form class="form-horizontal" action="../controller/check_register.php" method="POST" > <div class="control-group"> <div class="controls"> <input type="text" name="firstname" placeholder="Firstname" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="text" name="lastname" placeholder="Lastname" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="email" name="email" placeholder="E-mail" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="password" name="password" placeholder="Password" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="password" name="confirmPassword" placeholder="Confirm Password" required> </div> </div> <div class="control-group"> <div class="controls"> <select name="job" required> <option value="cashier">Cashier</option> <option value="impact_1">Impact 1</option> <option value="impact_2">Impact 2</option> <option value="model">Model</option> <option value="ops">OPS</option> <option value="stylist">Stylist</option> </select> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn btn-large btn-success">Sign up</button> </div> </div> </form> </div> </div> </body> </html>
GuillaumeOcculy/anfshift_paris
view/register.php
PHP
apache-2.0
2,939
 using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nest { [JsonObject] public class ClusterIndicesStats { [JsonProperty("completion")] public CompletionStats Completion { get; internal set; } [JsonProperty("count")] public long Count { get; internal set; } [JsonProperty("docs")] public DocStats Documents { get; internal set; } [JsonProperty("fielddata")] public FielddataStats Fielddata { get; internal set; } [JsonProperty("percolate")] public PercolateStats Percolate { get; internal set; } [JsonProperty("query_cache")] public QueryCacheStats QueryCache { get; internal set; } [JsonProperty("segments")] public SegmentsStats Segments { get; internal set; } [JsonProperty("shards")] public ClusterIndicesShardsStats Shards { get; internal set; } [JsonProperty("store")] public StoreStats Store { get; internal set; } } [JsonObject] public class ClusterIndicesShardsStats { [JsonProperty("total")] public double Total { get; internal set; } [JsonProperty("primaries")] public double Primaries { get; internal set; } [JsonProperty("replication")] public double Replication { get; internal set; } [JsonProperty("index")] public ClusterIndicesShardsIndexStats Index { get; internal set; } } [JsonObject] public class ClusterIndicesShardsIndexStats { [JsonProperty("shards")] public ClusterShardMetrics Shards { get; internal set; } [JsonProperty("primaries")] public ClusterShardMetrics Primaries { get; internal set; } [JsonProperty("replication")] public ClusterShardMetrics Replication { get; internal set; } } [JsonObject] public class ClusterShardMetrics { [JsonProperty("min")] public double Min { get; internal set; } [JsonProperty("max")] public double Max { get; internal set; } [JsonProperty("avg")] public double Avg { get; internal set; } } }
jonyadamit/elasticsearch-net
src/Nest/Cluster/ClusterStats/ClusterIndicesStats.cs
C#
apache-2.0
1,939
package com.log999.task; public class TestUtil { public static void sleepMs(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { // ignore } } }
bitsetd4d/log999-large-log-viewer
src/test/java/com/log999/task/TestUtil.java
Java
apache-2.0
220
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.api.command.admin.host; import java.util.ArrayList; import java.util.List; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; import com.cloud.exception.DiscoveryException; import com.cloud.host.Host; import com.cloud.user.Account; @APICommand(name = "addHost", description="Adds a new host.", responseObject=HostResponse.class) public class AddHostCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddHostCmd.class.getName()); private static final String s_name = "addhostresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType=ClusterResponse.class, description="the cluster ID for the host") private Long clusterId; @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, description="the cluster name for the host") private String clusterName; @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="the password for the host") private String password; @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, required=true, description="the Pod ID for the host") private Long podId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the host URL") private String url; @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="the username for the host") private String username; @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, required=true, description="the Zone ID for the host") private Long zoneId; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, required=true, description="hypervisor type of the host") private String hypervisor; @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Host for allocation of new resources") private String allocationState; @Parameter(name=ApiConstants.HOST_TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="list of tags to be added to the host") private List<String> hostTags; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getClusterId() { return clusterId; } public String getClusterName() { return clusterName; } public String getPassword() { return password; } public Long getPodId() { return podId; } public String getUrl() { return url; } public String getUsername() { return username; } public Long getZoneId() { return zoneId; } public String getHypervisor() { return hypervisor; } public List<String> getHostTags() { return hostTags; } public String getAllocationState() { return allocationState; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } @Override public void execute(){ try { List<? extends Host> result = _resourceService.discoverHosts(this); ListResponse<HostResponse> response = new ListResponse<HostResponse>(); List<HostResponse> hostResponses = new ArrayList<HostResponse>(); if (result != null && result.size() > 0) { for (Host host : result) { HostResponse hostResponse = _responseGenerator.createHostResponse(host); hostResponses.add(hostResponse); } } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add host"); } response.setResponses(hostResponses); response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } }
mufaddalq/cloudstack-datera-driver
api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java
Java
apache-2.0
5,997
// Copyright 2015 PLUMgrid // // 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 iovplug type Config struct { Subnet string Socket string Interface string Gateway string }
drzaeus77/docker-plugin
iovplug/config.go
GO
apache-2.0
694
sap.ui.define([ "sap/ui/core/UIComponent", "sap/ui/core/mvc/Controller", "sap/ui/core/routing/History", "sap/ui/model/json/JSONModel" ], function (UIComponent, Controller, History, JSONModel) { "use strict"; return Controller.extend("sap.ui.core.sample.odata.v4.MusicArtists.PublicationObjectPage", { _onObjectMatched : function (oEvent) { var oEventArguments = oEvent.getParameter("arguments"), oView = this.getView(), oPublicationContext = oView.getModel() .bindContext("/" + oEventArguments.artistPath + "/" + oEventArguments.publicationPath) .getBoundContext(); oView.setBindingContext(oPublicationContext); oPublicationContext.requestObject("IsActiveEntity").then(function (bIsActiveEntity) { oView.getModel("ui-op").setProperty("/bEditMode", !bIsActiveEntity); }); }, onBack : function () { var sPreviousHash = History.getInstance().getPreviousHash(); this.getView().getModel("ui-op").setProperty("/bEditMode", false); if (sPreviousHash !== undefined) { window.history.go(-1); } else { this.getOwnerComponent().getRouter().navTo("masterList", null, true); } }, onInit : function () { var oRouter = UIComponent.getRouterFor(this); oRouter.getRoute("publicationObjectPage") .attachPatternMatched(this._onObjectMatched, this); this.getView().setModel(new JSONModel({bEditMode : false}), "ui-op"); } }); });
SAP/openui5
src/sap.ui.core/test/sap/ui/core/demokit/sample/odata/v4/MusicArtists/PublicationObjectPage.controller.js
JavaScript
apache-2.0
1,423
var autils = require('../../AUtils'); var osTool = require('../../osTools'); var shelljs = require('shelljs'); var GenericDiffReporterBase = require('../GenericDiffReporterBase'); class Reporter extends GenericDiffReporterBase { constructor() { super("BeyondCompare"); var app = null; if (osTool.platform.isMac) { try { app = shelljs.ls('/Applications/Beyond Compare.app/Contents/MacOS/bcomp')[0]; } catch (err) { console.error(err); } app = app || autils.searchForExecutable("bcomp"); } else if (osTool.platform.isWindows) { app = autils.searchForExecutable("Beyond Compare 4", "BCompare.exe") || autils.searchForExecutable("Beyond Compare 3", "BCompare.exe"); } app = app || autils.searchForExecutable("bcomp"); this.exePath = app; } } module.exports = Reporter;
approvals/Approvals.NodeJS
lib/Reporting/Reporters/beyondcompareReporter.js
JavaScript
apache-2.0
860
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.black; import static com.opengamma.engine.value.ValueRequirementNames.POSITION_GAMMA; import java.util.Collections; import java.util.Set; import org.threeten.bp.Instant; import com.google.common.collect.Iterables; import com.opengamma.analytics.financial.forex.method.FXMatrix; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitor; import com.opengamma.analytics.financial.provider.calculator.blackstirfutures.PositionGammaSTIRFutureOptionCalculator; import com.opengamma.analytics.financial.provider.description.interestrate.BlackSTIRFuturesProviderInterface; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.CompiledFunctionDefinition; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueSpecification; /** * Calculates the position gamma of interest rate future options using a Black surface and curves constructed using the discounting method. */ public class BlackDiscountingPositionGammaIRFutureOptionFunction extends BlackDiscountingIRFutureOptionFunction { /** The position gamma calculator */ private static final InstrumentDerivativeVisitor<BlackSTIRFuturesProviderInterface, Double> CALCULATOR = PositionGammaSTIRFutureOptionCalculator .getInstance(); /** * Sets the value requirement to {@link com.opengamma.engine.value.ValueRequirementNames#POSITION_GAMMA}. */ public BlackDiscountingPositionGammaIRFutureOptionFunction() { super(POSITION_GAMMA); } @Override public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) { return new BlackDiscountingCompiledFunction(getTargetToDefinitionConverter(context), getDefinitionToDerivativeConverter(context), true) { @Override protected Set<ComputedValue> getValues(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues, final InstrumentDerivative derivative, final FXMatrix fxMatrix) { final BlackSTIRFuturesProviderInterface blackData = getBlackSurface(executionContext, inputs, target, fxMatrix); final double positionGamma = derivative.accept(CALCULATOR, blackData); final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues); final ValueProperties properties = desiredValue.getConstraints().copy().get(); final ValueSpecification spec = new ValueSpecification(POSITION_GAMMA, target.toSpecification(), properties); return Collections.singleton(new ComputedValue(spec, positionGamma)); } }; } }
McLeodMoores/starling
projects/financial/src/main/java/com/opengamma/financial/analytics/model/black/BlackDiscountingPositionGammaIRFutureOptionFunction.java
Java
apache-2.0
3,204
// Copyright 2016 The Oklog 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 ulid import ( "bufio" "bytes" "database/sql/driver" "encoding/binary" "errors" "io" "math" "math/bits" "math/rand" "time" ) /* An ULID is a 16 byte Universally Unique Lexicographically Sortable Identifier The components are encoded as 16 octets. Each component is encoded with the MSB first (network byte order). 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32_bit_uint_time_high | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 16_bit_uint_time_low | 16_bit_uint_random | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32_bit_uint_random | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32_bit_uint_random | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ type ULID [16]byte var ( // ErrDataSize is returned when parsing or unmarshaling ULIDs with the wrong // data size. ErrDataSize = errors.New("ulid: bad data size when unmarshaling") // ErrInvalidCharacters is returned when parsing or unmarshaling ULIDs with // invalid Base32 encodings. ErrInvalidCharacters = errors.New("ulid: bad data characters when unmarshaling") // ErrBufferSize is returned when marshalling ULIDs to a buffer of insufficient // size. ErrBufferSize = errors.New("ulid: bad buffer size when marshaling") // ErrBigTime is returned when constructing an ULID with a time that is larger // than MaxTime. ErrBigTime = errors.New("ulid: time too big") // ErrOverflow is returned when unmarshaling a ULID whose first character is // larger than 7, thereby exceeding the valid bit depth of 128. ErrOverflow = errors.New("ulid: overflow when unmarshaling") // ErrMonotonicOverflow is returned by a Monotonic entropy source when // incrementing the previous ULID's entropy bytes would result in overflow. ErrMonotonicOverflow = errors.New("ulid: monotonic entropy overflow") // ErrScanValue is returned when the value passed to scan cannot be unmarshaled // into the ULID. ErrScanValue = errors.New("ulid: source value must be a string or byte slice") ) // MonotonicReader is an interface that should yield monotonically increasing // entropy into the provided slice for all calls with the same ms parameter. If // a MonotonicReader is provided to the New constructor, its MonotonicRead // method will be used instead of Read. type MonotonicReader interface { io.Reader MonotonicRead(ms uint64, p []byte) error } // New returns an ULID with the given Unix milliseconds timestamp and an // optional entropy source. Use the Timestamp function to convert // a time.Time to Unix milliseconds. // // ErrBigTime is returned when passing a timestamp bigger than MaxTime. // Reading from the entropy source may also return an error. // // Safety for concurrent use is only dependent on the safety of the // entropy source. func New(ms uint64, entropy io.Reader) (id ULID, err error) { if err = id.SetTime(ms); err != nil { return id, err } switch e := entropy.(type) { case nil: return id, err case MonotonicReader: err = e.MonotonicRead(ms, id[6:]) default: _, err = io.ReadFull(e, id[6:]) } return id, err } // MustNew is a convenience function equivalent to New that panics on failure // instead of returning an error. func MustNew(ms uint64, entropy io.Reader) ULID { id, err := New(ms, entropy) if err != nil { panic(err) } return id } // Parse parses an encoded ULID, returning an error in case of failure. // // ErrDataSize is returned if the len(ulid) is different from an encoded // ULID's length. Invalid encodings produce undefined ULIDs. For a version that // returns an error instead, see ParseStrict. func Parse(ulid string) (id ULID, err error) { return id, parse([]byte(ulid), false, &id) } // ParseStrict parses an encoded ULID, returning an error in case of failure. // // It is like Parse, but additionally validates that the parsed ULID consists // only of valid base32 characters. It is slightly slower than Parse. // // ErrDataSize is returned if the len(ulid) is different from an encoded // ULID's length. Invalid encodings return ErrInvalidCharacters. func ParseStrict(ulid string) (id ULID, err error) { return id, parse([]byte(ulid), true, &id) } func parse(v []byte, strict bool, id *ULID) error { // Check if a base32 encoded ULID is the right length. if len(v) != EncodedSize { return ErrDataSize } // Check if all the characters in a base32 encoded ULID are part of the // expected base32 character set. if strict && (dec[v[0]] == 0xFF || dec[v[1]] == 0xFF || dec[v[2]] == 0xFF || dec[v[3]] == 0xFF || dec[v[4]] == 0xFF || dec[v[5]] == 0xFF || dec[v[6]] == 0xFF || dec[v[7]] == 0xFF || dec[v[8]] == 0xFF || dec[v[9]] == 0xFF || dec[v[10]] == 0xFF || dec[v[11]] == 0xFF || dec[v[12]] == 0xFF || dec[v[13]] == 0xFF || dec[v[14]] == 0xFF || dec[v[15]] == 0xFF || dec[v[16]] == 0xFF || dec[v[17]] == 0xFF || dec[v[18]] == 0xFF || dec[v[19]] == 0xFF || dec[v[20]] == 0xFF || dec[v[21]] == 0xFF || dec[v[22]] == 0xFF || dec[v[23]] == 0xFF || dec[v[24]] == 0xFF || dec[v[25]] == 0xFF) { return ErrInvalidCharacters } // Check if the first character in a base32 encoded ULID will overflow. This // happens because the base32 representation encodes 130 bits, while the // ULID is only 128 bits. // // See https://github.com/oklog/ulid/issues/9 for details. if v[0] > '7' { return ErrOverflow } // Use an optimized unrolled loop (from https://github.com/RobThree/NUlid) // to decode a base32 ULID. // 6 bytes timestamp (48 bits) (*id)[0] = (dec[v[0]] << 5) | dec[v[1]] (*id)[1] = (dec[v[2]] << 3) | (dec[v[3]] >> 2) (*id)[2] = (dec[v[3]] << 6) | (dec[v[4]] << 1) | (dec[v[5]] >> 4) (*id)[3] = (dec[v[5]] << 4) | (dec[v[6]] >> 1) (*id)[4] = (dec[v[6]] << 7) | (dec[v[7]] << 2) | (dec[v[8]] >> 3) (*id)[5] = (dec[v[8]] << 5) | dec[v[9]] // 10 bytes of entropy (80 bits) (*id)[6] = (dec[v[10]] << 3) | (dec[v[11]] >> 2) (*id)[7] = (dec[v[11]] << 6) | (dec[v[12]] << 1) | (dec[v[13]] >> 4) (*id)[8] = (dec[v[13]] << 4) | (dec[v[14]] >> 1) (*id)[9] = (dec[v[14]] << 7) | (dec[v[15]] << 2) | (dec[v[16]] >> 3) (*id)[10] = (dec[v[16]] << 5) | dec[v[17]] (*id)[11] = (dec[v[18]] << 3) | dec[v[19]]>>2 (*id)[12] = (dec[v[19]] << 6) | (dec[v[20]] << 1) | (dec[v[21]] >> 4) (*id)[13] = (dec[v[21]] << 4) | (dec[v[22]] >> 1) (*id)[14] = (dec[v[22]] << 7) | (dec[v[23]] << 2) | (dec[v[24]] >> 3) (*id)[15] = (dec[v[24]] << 5) | dec[v[25]] return nil } // MustParse is a convenience function equivalent to Parse that panics on failure // instead of returning an error. func MustParse(ulid string) ULID { id, err := Parse(ulid) if err != nil { panic(err) } return id } // MustParseStrict is a convenience function equivalent to ParseStrict that // panics on failure instead of returning an error. func MustParseStrict(ulid string) ULID { id, err := ParseStrict(ulid) if err != nil { panic(err) } return id } // Bytes returns bytes slice representation of ULID. func (id ULID) Bytes() []byte { return id[:] } // String returns a lexicographically sortable string encoded ULID // (26 characters, non-standard base 32) e.g. 01AN4Z07BY79KA1307SR9X4MV3. // Format: tttttttttteeeeeeeeeeeeeeee where t is time and e is entropy. func (id ULID) String() string { ulid := make([]byte, EncodedSize) _ = id.MarshalTextTo(ulid) return string(ulid) } // MarshalBinary implements the encoding.BinaryMarshaler interface by // returning the ULID as a byte slice. func (id ULID) MarshalBinary() ([]byte, error) { ulid := make([]byte, len(id)) return ulid, id.MarshalBinaryTo(ulid) } // MarshalBinaryTo writes the binary encoding of the ULID to the given buffer. // ErrBufferSize is returned when the len(dst) != 16. func (id ULID) MarshalBinaryTo(dst []byte) error { if len(dst) != len(id) { return ErrBufferSize } copy(dst, id[:]) return nil } // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface by // copying the passed data and converting it to an ULID. ErrDataSize is // returned if the data length is different from ULID length. func (id *ULID) UnmarshalBinary(data []byte) error { if len(data) != len(*id) { return ErrDataSize } copy((*id)[:], data) return nil } // Encoding is the base 32 encoding alphabet used in ULID strings. const Encoding = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" // MarshalText implements the encoding.TextMarshaler interface by // returning the string encoded ULID. func (id ULID) MarshalText() ([]byte, error) { ulid := make([]byte, EncodedSize) return ulid, id.MarshalTextTo(ulid) } // MarshalTextTo writes the ULID as a string to the given buffer. // ErrBufferSize is returned when the len(dst) != 26. func (id ULID) MarshalTextTo(dst []byte) error { // Optimized unrolled loop ahead. // From https://github.com/RobThree/NUlid if len(dst) != EncodedSize { return ErrBufferSize } // 10 byte timestamp dst[0] = Encoding[(id[0]&224)>>5] dst[1] = Encoding[id[0]&31] dst[2] = Encoding[(id[1]&248)>>3] dst[3] = Encoding[((id[1]&7)<<2)|((id[2]&192)>>6)] dst[4] = Encoding[(id[2]&62)>>1] dst[5] = Encoding[((id[2]&1)<<4)|((id[3]&240)>>4)] dst[6] = Encoding[((id[3]&15)<<1)|((id[4]&128)>>7)] dst[7] = Encoding[(id[4]&124)>>2] dst[8] = Encoding[((id[4]&3)<<3)|((id[5]&224)>>5)] dst[9] = Encoding[id[5]&31] // 16 bytes of entropy dst[10] = Encoding[(id[6]&248)>>3] dst[11] = Encoding[((id[6]&7)<<2)|((id[7]&192)>>6)] dst[12] = Encoding[(id[7]&62)>>1] dst[13] = Encoding[((id[7]&1)<<4)|((id[8]&240)>>4)] dst[14] = Encoding[((id[8]&15)<<1)|((id[9]&128)>>7)] dst[15] = Encoding[(id[9]&124)>>2] dst[16] = Encoding[((id[9]&3)<<3)|((id[10]&224)>>5)] dst[17] = Encoding[id[10]&31] dst[18] = Encoding[(id[11]&248)>>3] dst[19] = Encoding[((id[11]&7)<<2)|((id[12]&192)>>6)] dst[20] = Encoding[(id[12]&62)>>1] dst[21] = Encoding[((id[12]&1)<<4)|((id[13]&240)>>4)] dst[22] = Encoding[((id[13]&15)<<1)|((id[14]&128)>>7)] dst[23] = Encoding[(id[14]&124)>>2] dst[24] = Encoding[((id[14]&3)<<3)|((id[15]&224)>>5)] dst[25] = Encoding[id[15]&31] return nil } // Byte to index table for O(1) lookups when unmarshaling. // We use 0xFF as sentinel value for invalid indexes. var dec = [...]byte{ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 0x15, 0xFF, 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 0x15, 0xFF, 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, } // EncodedSize is the length of a text encoded ULID. const EncodedSize = 26 // UnmarshalText implements the encoding.TextUnmarshaler interface by // parsing the data as string encoded ULID. // // ErrDataSize is returned if the len(v) is different from an encoded // ULID's length. Invalid encodings produce undefined ULIDs. func (id *ULID) UnmarshalText(v []byte) error { return parse(v, false, id) } // Time returns the Unix time in milliseconds encoded in the ULID. // Use the top level Time function to convert the returned value to // a time.Time. func (id ULID) Time() uint64 { return uint64(id[5]) | uint64(id[4])<<8 | uint64(id[3])<<16 | uint64(id[2])<<24 | uint64(id[1])<<32 | uint64(id[0])<<40 } // maxTime is the maximum Unix time in milliseconds that can be // represented in an ULID. var maxTime = ULID{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}.Time() // MaxTime returns the maximum Unix time in milliseconds that // can be encoded in an ULID. func MaxTime() uint64 { return maxTime } // Now is a convenience function that returns the current // UTC time in Unix milliseconds. Equivalent to: // Timestamp(time.Now().UTC()) func Now() uint64 { return Timestamp(time.Now().UTC()) } // Timestamp converts a time.Time to Unix milliseconds. // // Because of the way ULID stores time, times from the year // 10889 produces undefined results. func Timestamp(t time.Time) uint64 { return uint64(t.Unix())*1000 + uint64(t.Nanosecond()/int(time.Millisecond)) } // Time converts Unix milliseconds in the format // returned by the Timestamp function to a time.Time. func Time(ms uint64) time.Time { s := int64(ms / 1e3) ns := int64((ms % 1e3) * 1e6) return time.Unix(s, ns) } // SetTime sets the time component of the ULID to the given Unix time // in milliseconds. func (id *ULID) SetTime(ms uint64) error { if ms > maxTime { return ErrBigTime } (*id)[0] = byte(ms >> 40) (*id)[1] = byte(ms >> 32) (*id)[2] = byte(ms >> 24) (*id)[3] = byte(ms >> 16) (*id)[4] = byte(ms >> 8) (*id)[5] = byte(ms) return nil } // Entropy returns the entropy from the ULID. func (id ULID) Entropy() []byte { e := make([]byte, 10) copy(e, id[6:]) return e } // SetEntropy sets the ULID entropy to the passed byte slice. // ErrDataSize is returned if len(e) != 10. func (id *ULID) SetEntropy(e []byte) error { if len(e) != 10 { return ErrDataSize } copy((*id)[6:], e) return nil } // Compare returns an integer comparing id and other lexicographically. // The result will be 0 if id==other, -1 if id < other, and +1 if id > other. func (id ULID) Compare(other ULID) int { return bytes.Compare(id[:], other[:]) } // Scan implements the sql.Scanner interface. It supports scanning // a string or byte slice. func (id *ULID) Scan(src interface{}) error { switch x := src.(type) { case nil: return nil case string: return id.UnmarshalText([]byte(x)) case []byte: return id.UnmarshalBinary(x) } return ErrScanValue } // Value implements the sql/driver.Valuer interface, returning the ULID as a // slice of bytes, by invoking MarshalBinary. If your use case requires a string // representation instead, you can create a wrapper type that calls String() // instead. // // type stringValuer ulid.ULID // // func (v stringValuer) Value() (driver.Value, error) { // return ulid.ULID(v).String(), nil // } // // // Example usage. // db.Exec("...", stringValuer(id)) // // All valid ULIDs, including zero-value ULIDs, return a valid Value with a nil // error. If your use case requires zero-value ULIDs to return a non-nil error, // you can create a wrapper type that special-cases this behavior. // // var zeroValueULID ulid.ULID // // type invalidZeroValuer ulid.ULID // // func (v invalidZeroValuer) Value() (driver.Value, error) { // if ulid.ULID(v).Compare(zeroValueULID) == 0 { // return nil, fmt.Errorf("zero value") // } // return ulid.ULID(v).Value() // } // // // Example usage. // db.Exec("...", invalidZeroValuer(id)) // func (id ULID) Value() (driver.Value, error) { return id.MarshalBinary() } // Monotonic returns an entropy source that is guaranteed to yield // strictly increasing entropy bytes for the same ULID timestamp. // On conflicts, the previous ULID entropy is incremented with a // random number between 1 and `inc` (inclusive). // // The provided entropy source must actually yield random bytes or else // monotonic reads are not guaranteed to terminate, since there isn't // enough randomness to compute an increment number. // // When `inc == 0`, it'll be set to a secure default of `math.MaxUint32`. // The lower the value of `inc`, the easier the next ULID within the // same millisecond is to guess. If your code depends on ULIDs having // secure entropy bytes, then don't go under this default unless you know // what you're doing. // // The returned type isn't safe for concurrent use. func Monotonic(entropy io.Reader, inc uint64) *MonotonicEntropy { m := MonotonicEntropy{ Reader: bufio.NewReader(entropy), inc: inc, } if m.inc == 0 { m.inc = math.MaxUint32 } if rng, ok := entropy.(*rand.Rand); ok { m.rng = rng } return &m } // MonotonicEntropy is an opaque type that provides monotonic entropy. type MonotonicEntropy struct { io.Reader ms uint64 inc uint64 entropy uint80 rand [8]byte rng *rand.Rand } // MonotonicRead implements the MonotonicReader interface. func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error) { if !m.entropy.IsZero() && m.ms == ms { err = m.increment() m.entropy.AppendTo(entropy) } else if _, err = io.ReadFull(m.Reader, entropy); err == nil { m.ms = ms m.entropy.SetBytes(entropy) } return err } // increment the previous entropy number with a random number // of up to m.inc (inclusive). func (m *MonotonicEntropy) increment() error { if inc, err := m.random(); err != nil { return err } else if m.entropy.Add(inc) { return ErrMonotonicOverflow } return nil } // random returns a uniform random value in [1, m.inc), reading entropy // from m.Reader. When m.inc == 0 || m.inc == 1, it returns 1. // Adapted from: https://golang.org/pkg/crypto/rand/#Int func (m *MonotonicEntropy) random() (inc uint64, err error) { if m.inc <= 1 { return 1, nil } // Fast path for using a underlying rand.Rand directly. if m.rng != nil { // Range: [1, m.inc) return 1 + uint64(m.rng.Int63n(int64(m.inc))), nil } // bitLen is the maximum bit length needed to encode a value < m.inc. bitLen := bits.Len64(m.inc) // byteLen is the maximum byte length needed to encode a value < m.inc. byteLen := uint(bitLen+7) / 8 // msbitLen is the number of bits in the most significant byte of m.inc-1. msbitLen := uint(bitLen % 8) if msbitLen == 0 { msbitLen = 8 } for inc == 0 || inc >= m.inc { if _, err = io.ReadFull(m.Reader, m.rand[:byteLen]); err != nil { return 0, err } // Clear bits in the first byte to increase the probability // that the candidate is < m.inc. m.rand[0] &= uint8(int(1<<msbitLen) - 1) // Convert the read bytes into an uint64 with byteLen // Optimized unrolled loop. switch byteLen { case 1: inc = uint64(m.rand[0]) case 2: inc = uint64(binary.LittleEndian.Uint16(m.rand[:2])) case 3, 4: inc = uint64(binary.LittleEndian.Uint32(m.rand[:4])) case 5, 6, 7, 8: inc = uint64(binary.LittleEndian.Uint64(m.rand[:8])) } } // Range: [1, m.inc) return 1 + inc, nil } type uint80 struct { Hi uint16 Lo uint64 } func (u *uint80) SetBytes(bs []byte) { u.Hi = binary.BigEndian.Uint16(bs[:2]) u.Lo = binary.BigEndian.Uint64(bs[2:]) } func (u *uint80) AppendTo(bs []byte) { binary.BigEndian.PutUint16(bs[:2], u.Hi) binary.BigEndian.PutUint64(bs[2:], u.Lo) } func (u *uint80) Add(n uint64) (overflow bool) { lo, hi := u.Lo, u.Hi if u.Lo += n; u.Lo < lo { u.Hi++ } return u.Hi < hi } func (u uint80) IsZero() bool { return u.Hi == 0 && u.Lo == 0 }
oklog/ulid
ulid.go
GO
apache-2.0
20,673